CVE-2022-37246 (published 2022-09-21T15:15Z)

Craft CMS 4.2.0.1 is affected by Cross Site Scripting (XSS) in the file src/web/assets/cp/src/js/BaseElementSelectInput.js and in specific on the line label: elementInfo.label.

CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/craftcms/cms
commit_details: repo_url: https://github.com/craftcms/cms
author: brandonkelly
author_date: 2022-07-28 15:54:03-07:00
msg: Fixed an XSS vulnerability
repository: repo_url: https://github.com/craftcms/cms
repo_name: craftcms/cms
description: Build bespoke content experiences with Craft.
repo_language: PHP
owner: craftcms
file_changes: filename: CHANGELOG.md
change_type: ModificationType.MODIFY
diff: @@ -9,6 +9,9 @@
 ### Fixed
 - Fixed a bug where system messages provided by Yii weren’t getting translated in some cases. ([#11712](https://github.com/craftcms/cms/issues/11712))
 
+### Security
+- Fixed an XSS vulnerability.
+
 ## 3.7.49 - 2022-07-26
 
 ### Added

programming_language: Markdown
filename: cp.js
change_type: ModificationType.MODIFY
diff: @@ -1,2 +1,2 @@
-!function(){var t={7452:function(){Craft.AdminTable=Garnish.Base.extend({settings:null,totalItems:null,sorter:null,$noItems:null,$table:null,$tbody:null,$deleteBtns:null,init:function(t){this.setSettings(t,Craft.AdminTable.defaults),this.settings.allowDeleteAll||(this.settings.minItems=1),this.$noItems=$(this.settings.noItemsSelector),this.$table=$(this.settings.tableSelector),this.$tbody=this.$table.children("tbody"),this.totalItems=this.$tbody.children().length,this.settings.sortable&&(this.sorter=new Craft.DataTableSorter(this.$table,{onSortChange:this.reorderItems.bind(this)})),this.$deleteBtns=this.$table.find(".delete:not(.disabled)"),this.addListener(this.$deleteBtns,"click","handleDeleteBtnClick"),this.updateUI()},addRow:function(t){if(!(this.settings.maxItems&&this.totalItems>=this.settings.maxItems)){var e=$(t).appendTo(this.$tbody),i=e.find(".delete");this.settings.sortable&&this.sorter.addItems(e),this.$deleteBtns=this.$deleteBtns.add(i),this.addListener(i,"click","handleDeleteBtnClick"),this.totalItems++,this.updateUI()}},reorderItems:function(){var t=this;if(this.settings.sortable){for(var e=[],i=0;i<this.sorter.$items.length;i++){var s=$(this.sorter.$items[i]).attr(this.settings.idAttribute);e.push(s)}var a={ids:JSON.stringify(e)};Craft.postActionRequest(this.settings.reorderAction,a,(function(i,s){"success"===s&&(i.success?(t.onReorderItems(e),Craft.cp.displayNotice(Craft.t("app",t.settings.reorderSuccessMessage))):Craft.cp.displayError(Craft.t("app",t.settings.reorderFailMessage)))}))}},handleDeleteBtnClick:function(t){if(!(this.settings.minItems&&this.totalItems<=this.settings.minItems)){var e=$(t.target).closest("tr");this.confirmDeleteItem(e)&&this.deleteItem(e)}},confirmDeleteItem:function(t){var e=this.getItemName(t);return confirm(Craft.t("app",this.settings.confirmDeleteMessage,{name:e}))},deleteItem:function(t){var e=this,i={id:this.getItemId(t)};Craft.postActionRequest(this.settings.deleteAction,i,(function(i,s){"success"===s&&e.handleDeleteItemResponse(i,t)}))},handleDeleteItemResponse:function(t,e){var i=this.getItemId(e),s=this.getItemName(e);t.success?(this.sorter&&this.sorter.removeItems(e),e.remove(),this.totalItems--,this.updateUI(),this.onDeleteItem(i),Craft.cp.displayNotice(Craft.t("app",this.settings.deleteSuccessMessage,{name:s}))):Craft.cp.displayError(Craft.t("app",this.settings.deleteFailMessage,{name:s}))},onReorderItems:function(t){this.settings.onReorderItems(t)},onDeleteItem:function(t){this.settings.onDeleteItem(t)},getItemId:function(t){return t.attr(this.settings.idAttribute)},getItemName:function(t){return Craft.escapeHtml(t.attr(this.settings.nameAttribute))},updateUI:function(){if(0===this.totalItems?(this.$table.hide(),this.$noItems.removeClass("hidden")):(this.$table.show(),this.$noItems.addClass("hidden")),this.settings.sortable){var t=this.$table.find(".move");1===this.totalItems?t.addClass("disabled"):t.removeClass("disabled")}this.settings.minItems&&this.totalItems<=this.settings.minItems?this.$deleteBtns.addClass("disabled"):this.$deleteBtns.removeClass("disabled"),this.settings.newItemBtnSelector&&(this.settings.maxItems&&this.totalItems>=this.settings.maxItems?$(this.settings.newItemBtnSelector).addClass("hidden"):$(this.settings.newItemBtnSelector).removeClass("hidden"))}},{defaults:{tableSelector:null,noItemsSelector:null,newItemBtnSelector:null,idAttribute:"data-id",nameAttribute:"data-name",sortable:!1,allowDeleteAll:!0,minItems:0,maxItems:null,reorderAction:null,deleteAction:null,reorderSuccessMessage:Craft.t("app","New order saved."),reorderFailMessage:Craft.t("app","Couldn’t save new order."),confirmDeleteMessage:Craft.t("app","Are you sure you want to delete “{name}”?"),deleteSuccessMessage:Craft.t("app","“{name}” deleted."),deleteFailMessage:Craft.t("app","Couldn’t delete “{name}”."),onReorderItems:$.noop,onDeleteItem:$.noop}})},76:function(){Craft.AssetEditor=Craft.BaseElementEditor.extend({$filenameInput:null,originalBasename:null,originalExtension:null,reloadIndex:!1,init:function(t,e){var i=this;this.on("updateForm",(function(){i.addListener(i.$sidebar.find(".preview-thumb-container .edit-btn"),"click","showImageEditor"),i.addListener(i.$sidebar.find(".preview-thumb-container .preview-btn"),"click","showImagePreview"),i.$filenameInput=i.$sidebar.find(".filename"),i.addListener(i.$filenameInput,"focus","selectFilename")})),this.on("closeSlideout",(function(){i.reloadIndex&&(i.settings.elementIndex?i.settings.elementIndex.updateElements():i.settings.input&&i.settings.input.refreshThumbnail(i.$element.data("id")))})),this.base(t,e),this.settings.validators.push((function(){return i.validateExtension()}))},showImageEditor:function(){var t=this;new Craft.AssetImageEditor(this.$element.data("id"),{onSave:function(){t.reloadIndex=!0,t.load()}})},showImagePreview:function(){var t={};this.$element.data("image-width")&&(t.startingWidth=this.$element.data("image-width"),t.startingHeight=this.$element.data("image-height")),new Craft.PreviewFileModal(this.$element.data("id"),null,t)},selectFilename:function(){var t=this;if(void 0!==this.$filenameInput[0].selectionStart){var e=this._parseFilename(),i=e.basename,s=e.extension;null===this.originalBasename&&(this.originalBasename=i,this.originalExtension=s),this.$filenameInput[0].selectionStart=0,this.$filenameInput[0].selectionEnd=i.length,this.$filenameInput.one("mouseup.keepselection",(function(t){t.preventDefault()})),setTimeout((function(){t.$filenameInput.off("mouseup.keepselection")}),500)}},validateExtension:function(){if(null===this.originalBasename)return!0;var t=this._parseFilename(),e=t.basename,i=t.extension;return i===this.originalExtension||(i?confirm(Craft.t("app","Are you sure you want to change the extension from “.{oldExt}” to “.{newExt}”?",{oldExt:this.originalExtension,newExt:i})):this.originalFilename!==e?(this.$filenameInput.val("".concat(Craft.rtrim(e,"."),".").concat(this.originalExtension)),!0):confirm(Craft.t("app","Are you sure you want to remove the extension “.{ext}”?",{ext:this.originalExtension})))},_parseFilename:function(){var t=this.$filenameInput.val().split("."),e=t.length>1?t.pop():null;return{basename:t.join("."),extension:e}}}),Craft.registerElementEditorClass("craft\\elements\\Asset",Craft.AssetEditor)},6872:function(){Craft.AssetImageEditor=Garnish.Modal.extend({$body:null,$footer:null,$imageTools:null,$buttons:null,$cancelBtn:null,$replaceBtn:null,$saveBtn:null,$editorContainer:null,$straighten:null,$croppingCanvas:null,$spinnerCanvas:null,canvas:null,image:null,viewport:null,focalPoint:null,grid:null,croppingCanvas:null,clipper:null,croppingRectangle:null,cropperHandles:null,cropperGrid:null,croppingShade:null,imageStraightenAngle:0,viewportRotation:0,originalWidth:0,originalHeight:0,imageVerticeCoords:null,zoomRatio:1,animationInProgress:!1,currentView:"",assetId:null,cacheBust:null,draggingCropper:!1,scalingCropper:!1,draggingFocal:!1,previousMouseX:0,previousMouseY:0,shiftKeyHeld:!1,editorHeight:0,editorWidth:0,cropperState:!1,scaleFactor:1,flipData:{},focalPointState:!1,spinnerInterval:null,maxImageSize:null,lastLoadedDimensions:null,imageIsLoading:!1,mouseMoveEvent:null,croppingConstraint:!1,constraintOrientation:"landscape",showingCustomConstraint:!1,renderImage:null,renderCropper:null,init:function(t,e){this.cacheBust=Date.now(),this.setSettings(e,Craft.AssetImageEditor.defaults),null===this.settings.allowDegreeFractions&&(this.settings.allowDegreeFractions=Craft.isImagick),this.assetId=t,this.flipData={x:0,y:0},this.$container=$('<form class="modal fitted imageeditor"></form>').appendTo(Garnish.$bod),this.$body=$('<div class="body"></div>').appendTo(this.$container),this.$footer=$('<div class="footer"/>').appendTo(this.$container),this.base(this.$container,this.settings),this.$buttons=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn cancel",text:Craft.t("app","Cancel")}).appendTo(this.$buttons),this.$replaceBtn=$("<button/>",{type:"button",class:"btn submit save replace",text:Craft.t("app","Save")}).appendTo(this.$buttons),this.settings.allowSavingAsNew&&(this.$saveBtn=$("<button/>",{type:"button",class:"btn submit save copy",text:Craft.t("app","Save as a new asset")}).appendTo(this.$buttons),this.addListener(this.$saveBtn,"activate",this.saveImage)),this.addListener(this.$replaceBtn,"activate",this.saveImage),this.addListener(this.$cancelBtn,"activate",this.hide),this.removeListener(this.$shade,"click"),this.maxImageSize=this.getMaxImageSize(),Craft.postActionRequest("assets/image-editor",{assetId:t},this.loadEditor.bind(this))},getMaxImageSize:function(){var t=Garnish.$doc.get(0).documentElement.clientWidth,e=Garnish.$doc.get(0).documentElement.clientHeight;return Math.max(e,t)*(window.devicePixelRatio>1?2:1)},loadEditor:function(t){var e=this;t.html||alert(Craft.t("app","Could not load the image editor.")),this.$body.html(t.html),this.$tabs=$(".tabs li",this.$body),this.$viewsContainer=$(".views",this.$body),this.$views=$("> div",this.$viewsContainer),this.$imageTools=$(".image-container .image-tools",this.$body),this.$editorContainer=$(".image-container .image",this.$body),this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this._showSpinner(),this.updateSizeAndPosition(),this.canvas=new fabric.StaticCanvas("image-canvas"),this.$croppingCanvas=$("#cropping-canvas",this.$editorContainer),this.$croppingCanvas.width(this.editorWidth),this.$croppingCanvas.height(this.editorHeight),this.canvas.enableRetinaScaling=!0,this.renderImage=function(){Garnish.requestAnimationFrame(e.canvas.renderAll.bind(e.canvas))};var i=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});fabric.Image.fromURL(i,(function(i){e.image=i,e.image.set({originX:"center",originY:"center",left:e.editorWidth/2,top:e.editorHeight/2}),e.canvas.add(e.image),e.originalHeight=e.image.getHeight(),e.originalWidth=e.image.getWidth(),e.zoomRatio=1,e.lastLoadedDimensions=e.getScaledImageDimensions(),e._setFittedImageVerticeCoordinates(),e._repositionEditorElements();var s={imageDimensions:e.getScaledImageDimensions(),offsetX:0,offsetY:0},a=!1;if(t.focalPoint){var n=t.focalPoint,r=s.imageDimensions.width*n.x,o=s.imageDimensions.height*n.y;s.offsetX=r-s.imageDimensions.width/2,s.offsetY=o-s.imageDimensions.height/2,a=!0}e.storeFocalPointState(s),a&&e._createFocalPoint(),e._createViewport(),e.storeCropperState(),e._addControlListeners(),e.addListener(e.$croppingCanvas,"mousemove,touchmove",e._handleMouseMove),e.addListener(e.$croppingCanvas,"mousedown,touchstart",e._handleMouseDown),e.addListener(e.$croppingCanvas,"mouseup,touchend",e._handleMouseUp),e.addListener(e.$croppingCanvas,"mouseout,touchcancel",e._handleMouseOut),e._hideSpinner(),e.renderImage(),e.$tabs.first().trigger("click")}))},_reloadImage:function(){var t=this;if(!this.imageIsLoading){this.imageIsLoading=!0,this.maxImageSize=this.getMaxImageSize();var e=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});this.image.setSrc(e,(function(e){t.originalHeight=e.getHeight(),t.originalWidth=e.getWidth(),t.lastLoadedDimensions={width:t.originalHeight,height:t.originalWidth},t.updateSizeAndPosition(),t.renderImage(),t.imageIsLoading=!1}))}},updateSizeAndPosition:function(){if(this.$container){var t=window.innerWidth,e=window.innerHeight;this.$container.css({width:t,"min-width":t,left:0,height:e,"min-height":e,top:0}),this.$body.css({height:e-62}),t<e?this.$container.addClass("vertical"):this.$container.removeClass("vertical"),this.$spinnerCanvas&&this.$spinnerCanvas.css({left:this.$spinnerCanvas.parent().width()/2-this.$spinnerCanvas.width()/2+"px",top:this.$spinnerCanvas.parent().height()/2-this.$spinnerCanvas.height()/2+"px"}),this.$editorContainer&&this.image&&this._repositionEditorElements()}},_repositionEditorElements:function(){var t={width:this.editorWidth,height:this.editorHeight};this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this.canvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var e=this.getScaledImageDimensions();if("crop"===this.currentView){this.zoomRatio=this.getZoomToFitRatio(this.getScaledImageDimensions());var i=this._getBoundingRectangle(this.imageVerticeCoords);this._setFittedImageVerticeCoordinates(),this._repositionCropper(i)}else this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor;this._repositionImage(t),this._repositionViewport(),this._repositionFocalPoint(t),this._zoomImage(),this.renderImage(),(e.width/this.lastLoadedDimensions.width>1.5||e.height/this.lastLoadedDimensions.height>1.5)&&this._reloadImage()},_repositionImage:function(t){this.image.set({left:this.image.left-(t.width-this.editorWidth)/2,top:this.image.top-(t.height-this.editorHeight)/2})},_createViewport:function(){this.viewport=new fabric.Rect({width:this.image.width,height:this.image.height,fill:"rgba(127,0,0,1)",originX:"center",originY:"center",globalCompositeOperation:"destination-in",left:this.image.left,top:this.image.top}),this.canvas.add(this.viewport),this.renderImage()},_createFocalPoint:function(){var t=this.focalPointState,e=this.getScaledImageDimensions().width/t.imageDimensions.width,i=t.offsetX*e*this.zoomRatio*this.scaleFactor,s=t.offsetY*e*this.zoomRatio*this.scaleFactor;i+=this.image.left,s+=this.image.top;var a=0,n=0;this.viewport&&0===t.offsetX&&0===t.offsetY&&("crop"!==this.currentView?(a=this.viewport.left-this.image.left,n=this.viewport.top-this.image.top):(a=this.clipper.left-this.image.left,n=this.clipper.top-this.image.top),i+=a,s+=n,t.offsetX+=a/(e*this.zoomRatio*this.scaleFactor),t.offsetY+=n/(e*this.zoomRatio*this.scaleFactor)),this.focalPoint=new fabric.Group([new fabric.Circle({radius:8,fill:"rgba(0,0,0,0.5)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"}),new fabric.Circle({radius:1,fill:"rgba(255,255,255,0)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"})],{originX:"center",originY:"center",left:i,top:s}),this.storeFocalPointState(t),this.canvas.add(this.focalPoint)},toggleFocalPoint:function(){this.focalPoint?(this.canvas.remove(this.focalPoint),this.focalPoint=null):this._createFocalPoint(),this.renderImage()},_repositionViewport:function(){if(this.viewport){var t={left:this.editorWidth/2,top:this.editorHeight/2};if("crop"===this.currentView)t.width=this.editorWidth,t.height=this.editorHeight;else if(this.cropperState){var e=this.cropperState,i=this.getScaledImageDimensions().width/e.imageDimensions.width;t.width=e.width*i*this.zoomRatio,t.height=e.height*i*this.zoomRatio,this.image.set({left:this.editorWidth/2-e.offsetX*i,top:this.editorHeight/2-e.offsetY*i})}else $.extend(t,this.getScaledImageDimensions());this.viewport.set(t)}},_repositionFocalPoint:function(t){if(this.focalPoint){var e=this.focalPoint.left-this.editorWidth/2,i=this.focalPoint.top-this.editorHeight/2,s=this.image.width,a=this.getScaledImageDimensions().width*this.zoomRatio/s/this.scaleFactor;e-=(t.width-this.editorWidth)/2,i-=(t.height-this.editorHeight)/2,e*=a,i*=a,this.focalPoint.set({left:this.editorWidth/2+e,top:this.editorHeight/2+i})}},hasOrientationChanged:function(){return this.viewportRotation%180!=0},getScaledImageDimensions:function(){return void 0===this.getScaledImageDimensions._&&(this.getScaledImageDimensions._={}),this.getScaledImageDimensions._.imageRatio=this.originalHeight/this.originalWidth,this.getScaledImageDimensions._.editorRatio=this.editorHeight/this.editorWidth,this.getScaledImageDimensions._.dimensions={},this.getScaledImageDimensions._.imageRatio>this.getScaledImageDimensions._.editorRatio?(this.getScaledImageDimensions._.dimensions.height=Math.min(this.editorHeight,this.originalHeight),this.getScaledImageDimensions._.dimensions.width=Math.round(this.originalWidth/(this.originalHeight/this.getScaledImageDimensions._.dimensions.height))):(this.getScaledImageDimensions._.dimensions.width=Math.min(this.editorWidth,this.originalWidth),this.getScaledImageDimensions._.dimensions.height=Math.round(this.originalHeight*(this.getScaledImageDimensions._.dimensions.width/this.originalWidth))),this.getScaledImageDimensions._.dimensions},_zoomImage:function(){void 0===this._zoomImage._&&(this._zoomImage._={}),this._zoomImage._.imageDimensions=this.getScaledImageDimensions(),this.image.set({width:this._zoomImage._.imageDimensions.width*this.zoomRatio,height:this._zoomImage._.imageDimensions.height*this.zoomRatio})},_addControlListeners:function(){var t=this;this.addListener(this.$tabs,"click",this._handleTabClick),this.addListener($(".focal-point"),"click",this.toggleFocalPoint),this.addListener($(".rotate-left"),"click",(function(){this.rotateImage(-90)})),this.addListener($(".rotate-right"),"click",(function(){this.rotateImage(90)})),this.addListener($(".flip-vertical"),"click",(function(){this.flipImage("y")})),this.addListener($(".flip-horizontal"),"click",(function(){this.flipImage("x")})),this.straighteningInput=new Craft.SlideRuleInput("slide-rule",{onStart:function(){t._showGrid()},onChange:function(e){t.straighten(e)},onEnd:function(){t._hideGrid(),t._cleanupFocalPointAfterStraighten()}}),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!0)})),this.addListener(Garnish.$doc,"keyup",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!1)})),this.addListener($(".constraint-buttons .constraint",this.$container),"click",this._handleConstraintClick),this.addListener($(".orientation input",this.$container),"click",this._handleOrientationClick),this.addListener($(".constraint-buttons .custom-input input",this.$container),"keyup",this._applyCustomConstraint)},_handleConstraintClick:function(t){var e=$(t.currentTarget).data("constraint"),i=$(t.currentTarget);if(i.siblings().removeClass("active"),i.addClass("active"),"custom"==e)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(e),this.enforceCroppingConstraint()},_handleOrientationClick:function(t){if(t.currentTarget.value!==this.constraintOrientation){this.constraintOrientation=t.currentTarget.value;for(var e=$(".constraint.flip",this.$container),i=0;i<e.length;i++){var s=$(e[i]);s.data("constraint",1/s.data("constraint")),s.html(s.html().split(":").reverse().join(":"))}e.filter(".active").click()}},_applyCustomConstraint:function(){var t=this._getCustomConstraint();t.w>0&&t.h>0&&(this.setCroppingConstraint(t.w/t.h),this.enforceCroppingConstraint())},_getCustomConstraint:function(){var t=parseFloat($(".custom-constraint-w").val()),e=parseFloat($(".custom-constraint-h").val());return{w:isNaN(t)?0:t,h:isNaN(e)?0:e}},_setCustomConstraint:function(t,e){$(".custom-constraint-w").val(parseFloat(t)),$(".custom-constraint-h").val(parseFloat(e))},_hideCustomConstraint:function(){this.showingCustomConstraint=!1,$(".constraint.custom .custom-input",this.$container).addClass("hidden"),$(".constraint.custom .custom-label",this.$container).removeClass("hidden"),$(".orientation",this.$container).removeClass("hidden")},_showCustomConstraint:function(){this.showingCustomConstraint||(this.showingCustomConstraint=!0,$(".constraint.custom .custom-input",this.$container).removeClass("hidden"),$(".constraint.custom .custom-label",this.$container).addClass("hidden"),$(".orientation",this.$container).addClass("hidden"))},_handleTabClick:function(t){if(!this.animationInProgress){var e=$(t.currentTarget),i=e.data("view");this.$tabs.removeClass("selected"),e.addClass("selected"),this.showView(i)}},showView:function(t){this.currentView!==t&&(this.$views.addClass("hidden"),this.$views.filter('[data-view="'+t+'"]').removeClass("hidden"),"rotate"===t?this.enableSlider():this.disableSlider(),this.updateSizeAndPosition(),"crop"===this.currentView&&"crop"!==t?this.disableCropMode():"crop"!==this.currentView&&"crop"===t&&this.enableCropMode(),this.currentView=t)},storeCropperState:function(t){void 0===this.storeCropperState._&&(this.storeCropperState._={}),t?this.cropperState=t:this.clipper?(this.storeCropperState._.zoomFactor=1/this.zoomRatio,this.cropperState={offsetX:(this.clipper.left-this.image.left)*this.storeCropperState._.zoomFactor,offsetY:(this.clipper.top-this.image.top)*this.storeCropperState._.zoomFactor,height:this.clipper.height*this.storeCropperState._.zoomFactor,width:this.clipper.width*this.storeCropperState._.zoomFactor,imageDimensions:this.getScaledImageDimensions()}):(this.storeCropperState._.dimensions=this.getScaledImageDimensions(),this.cropperState={offsetX:0,offsetY:0,height:this.storeCropperState._.dimensions.height,width:this.storeCropperState._.dimensions.width,imageDimensions:this.storeCropperState._.dimensions})},storeFocalPointState:function(t){void 0===this.storeFocalPointState._&&(this.storeFocalPointState._={}),t?this.focalPointState=t:this.focalPoint&&(this.storeFocalPointState._.zoomFactor=1/this.zoomRatio,this.focalPointState={offsetX:(this.focalPoint.left-this.image.left)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,offsetY:(this.focalPoint.top-this.image.top)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,imageDimensions:this.getScaledImageDimensions()})},rotateImage:function(t){var e=this;if(!this.animationInProgress){if(90!==t&&-90!==t)return!1;this.animationInProgress=!0,this.viewportRotation+=t,this.viewportRotation=parseInt((this.viewportRotation+360)%360,10);var i,s=this.image.angle+t,a=this.getScaledImageDimensions();i=this.hasOrientationChanged()?this.getZoomToCoverRatio({height:a.width,width:a.height}):this.getZoomToCoverRatio(a),this.zoomRatio>i&&(i=this.zoomRatio);var n={angle:90===t?"+=90":"-=90"},r={angle:s,width:a.width*i,height:a.height*i},o=1;this.scaleFactor<1?(o=1/this.scaleFactor,this.scaleFactor=1):(this.viewport.width>this.editorHeight?o=this.editorHeight/this.viewport.width:this.viewport.height>this.editorWidth&&(o=this.editorWidth/this.viewport.height),this.scaleFactor=o),o<1&&(r.width*=o,r.height*=o);var l=this.cropperState,h=l.offsetX,d=l.offsetY,c=t*(Math.PI/180),u=h*Math.cos(c)-d*Math.sin(c),p=h*Math.sin(c)+d*Math.cos(c),g=a.width/l.imageDimensions.width,f=u*g*this.zoomRatio*this.scaleFactor,m=p*g*this.zoomRatio*this.scaleFactor;r.left=this.editorWidth/2-f,r.top=this.editorHeight/2-m,l.offsetX=u,l.offsetY=p;var v=l.width;l.width=l.height,l.height=v,this.storeCropperState(l),this.focalPoint&&this.canvas.remove(this.focalPoint),this.viewport.animate(n,{duration:this.settings.animationDuration,onComplete:function(){var t=e.viewport.height*o;e.viewport.height=e.viewport.width*o,e.viewport.width=t,e.viewport.set({angle:0})}}),this.image.animate(r,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){var i=parseFloat((e.image.angle+360)%360);e.image.set({angle:i}),e.animationInProgress=!1,e.focalPoint?(e._adjustFocalPointByAngle(t),e.straighten(e.straighteningInput),e.canvas.add(e.focalPoint)):e._resetFocalPointPosition()}})}},flipImage:function(t){var e=this;if(!this.animationInProgress){this.animationInProgress=!0,this.hasOrientationChanged()&&(t="y"===t?"x":"y"),this.focalPoint?this.canvas.remove(this.focalPoint):this._resetFocalPointPosition();var i={x:this.editorWidth/2,y:this.editorHeight/2};this.straighteningInput.setValue(-this.imageStraightenAngle),this.imageStraightenAngle=-this.imageStraightenAngle;var s,a,n={angle:this.viewportRotation+this.imageStraightenAngle},r=this.cropperState,o=this.focalPointState;"y"===t&&this.hasOrientationChanged()||"y"!==t&&!this.hasOrientationChanged()?(r.offsetX=-r.offsetX,o.offsetX=-o.offsetX,a=this.image.left-i.x,n.left=i.x-a):(r.offsetY=-r.offsetY,o.offsetY=-o.offsetY,s=this.image.top-i.y,n.top=i.y-s),"y"===t?(n.scaleY=-1*this.image.scaleY,this.flipData.y=1-this.flipData.y):(n.scaleX=-1*this.image.scaleX,this.flipData.x=1-this.flipData.x),this.storeCropperState(r),this.storeFocalPointState(o),this.image.animate(n,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){e.animationInProgress=!1,e.focalPoint&&(e._adjustFocalPointByAngle(0),e.canvas.add(e.focalPoint))}})}},straighten:function(t){if(!this.animationInProgress){this.animationInProgress=!0;var e=this.image.angle;this.imageStraightenAngle=(this.settings.allowDegreeFractions?parseFloat(t.value):Math.round(parseFloat(t.value)))%360,this.image.set({angle:this.viewportRotation+this.imageStraightenAngle}),this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor,this._zoomImage(),this.cropperState&&this._adjustEditorElementsOnStraighten(e),this.renderImage(),this.animationInProgress=!1}},_adjustEditorElementsOnStraighten:function(t){var e,i,s,a,n,r=this.getScaledImageDimensions(),o=this.image.angle-t,l=this.cropperState,h=this.zoomRatio,d=1;do{var c=l.offsetX,u=l.offsetY,p=o*(Math.PI/180);s=c*Math.cos(p)-u*Math.sin(p),a=c*Math.sin(p)+u*Math.cos(p),e=s*h*(n=r.width/l.imageDimensions.width),i=a*h*n;var g=this.getImageVerticeCoords(h),f={width:this.viewport.width,height:this.viewport.height,left:this.editorWidth/2-this.viewport.width/2+e,top:this.editorHeight/2-this.viewport.height/2+i};h*=d=this._getZoomRatioToFitRectangle(f,g)}while(1!==d);this.image.set({left:this.editorWidth/2-e,top:this.editorHeight/2-i}),l.offsetX=s,l.offsetY=a,l.width=this.viewport.width/h/n,l.height=this.viewport.height/h/n,this.storeCropperState(l),this.zoomRatio=h,this.focalPoint?(this._adjustFocalPointByAngle(o),this._isCenterInside(this.focalPoint,this.viewport)?this.focalPoint.set({opacity:1}):this.focalPoint.set({opacity:0})):0!==o&&this._resetFocalPointPosition(),this._zoomImage()},_cleanupFocalPointAfterStraighten:function(){if(this.focalPoint&&!this._isCenterInside(this.focalPoint,this.viewport)){this.focalPoint.set({opacity:1});var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t),this.toggleFocalPoint()}},_resetFocalPointPosition:function(){var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t)},_isCenterInside:function(t,e){return t.left>e.left-e.width/2&&t.top>e.top-e.height/2&&t.left<e.left+e.width/2&&t.top<e.top+e.height/2},_adjustFocalPointByAngle:function(t){var e=t*(Math.PI/180),i=this.focalPointState,s=i.offsetX,a=i.offsetY,n=s*Math.cos(e)-a*Math.sin(e),r=s*Math.sin(e)+a*Math.cos(e),o=this.getScaledImageDimensions().width/i.imageDimensions.width,l=n*o*this.zoomRatio,h=r*o*this.zoomRatio;this.focalPoint.left=this.image.left+l,this.focalPoint.top=this.image.top+h,i.offsetX=n,i.offsetY=r,this.storeFocalPointState(i)},_getZoomRatioToFitRectangle:function(t,e){for(var i,s,a=this._getRectangleVertices(t),n=0;n<a.length&&(i=a[n],this.arePointsInsideRectangle([i],e));n++)i=!1;if(i){var r=this._getEdgeCrossed(e,i),o={x:t.left+t.width/2,y:t.top+t.height/2},l=Math.abs((r[1].y-r[0].y)*i.x-(r[1].x-r[0].x)*i.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2)),h=Math.abs((r[1].y-r[0].y)*o.x-(r[1].x-r[0].x)*o.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2));s=(l+h)/h}else s=1;return s},saveImage:function(t){var e=this,i=$(t.currentTarget);if(i.hasClass("disabled"))return!1;$(".btn",this.$buttons).addClass("disabled"),this.$buttons.append('<div class="spinner"></div>');var s={assetId:this.assetId,viewportRotation:this.viewportRotation,imageRotation:this.imageStraightenAngle,replace:i.hasClass("replace")?1:0};if(this.cropperState){var a={};a.height=this.cropperState.height,a.width=this.cropperState.width,a.offsetX=this.cropperState.offsetX,a.offsetY=this.cropperState.offsetY,s.imageDimensions=this.cropperState.imageDimensions,s.cropData=a}else s.imageDimensions=this.getScaledImageDimensions();this.focalPoint&&(s.focalPoint=this.focalPointState),s.flipData=this.flipData,s.zoom=this.zoomRatio,Craft.postActionRequest("assets/save-image",s,(function(t){e.$buttons.find(".btn").removeClass("disabled").end().find(".spinner").remove(),t.error?alert(t.error):(e.onSave(),e.hide(),Craft.cp.runQueue())}))},getZoomToCoverRatio:function(t){var e=Math.abs(this.imageStraightenAngle)*(Math.PI/180),i=Math.sin(e)*t.height+Math.cos(e)*t.width,s=Math.sin(e)*t.width+Math.cos(e)*t.height;return Math.max(i/t.width,s/t.height)},getZoomToFitRatio:function(t){var e=this._getImageBoundingBox(t),i=1;if(e.height>this.editorHeight||e.width>this.editorWidth){var s=this.editorHeight/e.height,a=this.editorWidth/e.width;i=Math.min(a,s)}return i},getCombinedZoomRatio:function(t){return this.getZoomToCoverRatio(t)/this.getZoomToFitRatio(t)},_showGrid:function(){if(!this.grid){var t,e={strokeWidth:1,stroke:"rgba(255,255,255,0.5)"},i=this.viewport.width,s=this.viewport.height,a=i/9,n=s/9,r=[new fabric.Rect({strokeWidth:2,stroke:"rgba(255,255,255,1)",originX:"center",originY:"center",width:i,height:s,left:i/2,top:s/2,fill:"rgba(255,255,255,0)"})];for(t=1;t<=8;t++)r.push(new fabric.Line([t*a,0,t*a,s],e));for(t=1;t<=8;t++)r.push(new fabric.Line([0,t*n,i,t*n],e));this.grid=new fabric.Group(r,{left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",angle:this.viewport.angle}),this.canvas.add(this.grid),this.renderImage()}},_hideGrid:function(){this.canvas.remove(this.grid),this.grid=null,this.renderImage()},onFadeOut:function(){this.destroy()},show:function(){this.base(),Garnish.$bod.addClass("no-scroll")},hide:function(){this.removeAllListeners(),this.straighteningInput.removeAllListeners(),Garnish.$bod.removeClass("no-scroll"),this.base()},onSave:function(){this.settings.onSave(),this.trigger("save")},enableSlider:function(){this.$imageTools.removeClass("hidden")},disableSlider:function(){this.$imageTools.addClass("hidden")},enableCropMode:function(){var t=this,e=this.getScaledImageDimensions();this.zoomRatio=this.getZoomToFitRatio(e);var i={width:this.editorWidth,height:this.editorHeight},s={width:e.width*this.zoomRatio,height:e.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2};this._editorModeTransition((function(){t._setFittedImageVerticeCoordinates();var e=t.cropperState,i=t.getScaledImageDimensions(),s=i.width/e.imageDimensions.width,a={left:t.image.left+e.offsetX*s*t.zoomRatio,top:t.image.top+e.offsetY*s*t.zoomRatio,width:e.width*s*t.zoomRatio,height:e.height*s*t.zoomRatio};t._showCropper(a),t.focalPoint&&(s=i.width/t.focalPointState.imageDimensions.width,t.focalPoint.left=t.image.left+t.focalPointState.offsetX*s*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*s*t.zoomRatio,t.canvas.add(t.focalPoint))}),s,i)},disableCropMode:function(){var t=this,e={};this._hideCropper();var i=this.getScaledImageDimensions(),s=this.getZoomToCoverRatio(i)*this.scaleFactor,a=s/this.zoomRatio;this.zoomRatio=s;var n={width:i.width*this.zoomRatio,height:i.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},r=(this.clipper.left-this.image.left)*a,o=(this.clipper.top-this.image.top)*a;n.left=this.editorWidth/2-r,n.top=this.editorHeight/2-o,e.height=this.clipper.height*a,e.width=this.clipper.width*a,(!this.focalPoint||this.focalPoint&&!this._isCenterInside(this.focalPoint,this.clipper))&&(this.focalPoint&&this.toggleFocalPoint(),this._resetFocalPointPosition()),this._editorModeTransition((function(){if(t.focalPoint){var e=t.getScaledImageDimensions().width/t.focalPointState.imageDimensions.width;t.focalPoint.left=t.image.left+t.focalPointState.offsetX*e*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*e*t.zoomRatio,t.canvas.add(t.focalPoint)}}),n,e)},_editorModeTransition:function(t,e,i){var s=this;this.animationInProgress||(this.animationInProgress=!0,this.focalPoint&&(this.canvas.remove(this.focalPoint),this.renderImage()),this.image.animate(e,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){t(),s.animationInProgress=!1,s.renderImage()}}),this.viewport.animate(i,{duration:this.settings.animationDuration}))},_showSpinner:function(){this.$spinnerCanvas=$('<canvas id="spinner-canvas"></canvas>').appendTo($(".image",this.$container));var t=document.getElementById("spinner-canvas").getContext("2d"),e=new Date,i=t.canvas.width,s=t.canvas.height;this.spinnerInterval=window.setInterval((function(){var a=parseInt((new Date-e)/1e3*16)/16;t.save(),t.clearRect(0,0,i,s),t.translate(i/2,s/2),t.rotate(2*Math.PI*a);for(var n=0;n<16;n++)t.beginPath(),t.rotate(2*Math.PI/16),t.moveTo(i/10,0),t.lineTo(i/4,0),t.lineWidth=i/30,t.strokeStyle="rgba(255,255,255,"+n/16+")",t.stroke();t.restore()}),1e3/30)},_hideSpinner:function(){window.clearInterval(this.spinnerInterval),this.$spinnerCanvas.remove(),this.$spinnerCanvas=null},_showCropper:function(t){this._setupCropperLayer(t),this._redrawCropperElements(),this.renderCropper()},_hideCropper:function(){this.clipper&&(this.croppingCanvas.remove(this.clipper),this.croppingCanvas.remove(this.croppingShade),this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle),this.croppingCanvas=null,this.renderCropper=null)},_setupCropperLayer:function(t){var e=this;this.croppingCanvas=new fabric.StaticCanvas("cropping-canvas",{backgroundColor:"rgba(0,0,0,0)",hoverCursor:"default",selection:!1}),this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight}),this.renderCropper=function(){return Garnish.requestAnimationFrame(e.croppingCanvas.renderAll.bind(e.croppingCanvas))},$("#cropping-canvas",this.$editorContainer).css({position:"absolute",top:0,left:0}),this.croppingShade=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:this.editorWidth,height:this.editorHeight,fill:"rgba(0,0,0,0.7)"});var i=this.getScaledImageDimensions(),s=0===this.imageStraightenAngle?1:1.2*this.getCombinedZoomRatio(i),a=i.width/s,n=i.height/s;if(this.hasOrientationChanged()){var r=n;n=a,a=r}this.clipper=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:a,height:n,stroke:"black",fill:"rgba(128,0,0,1)",strokeWidth:0}),t&&this.clipper.set(t),this.clipper.globalCompositeOperation="destination-out",this.croppingCanvas.add(this.croppingShade),this.croppingCanvas.add(this.clipper)},_redrawCropperElements:function(){void 0===this._redrawCropperElements._&&(this._redrawCropperElements._={}),this.cropperHandles&&(this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle)),this._redrawCropperElements._.lineOptions={strokeWidth:4,stroke:"rgb(255,255,255)",fill:!1},this._redrawCropperElements._.gridOptions={strokeWidth:2,stroke:"rgba(255,255,255,0.5)"},this._redrawCropperElements._.pathGroup=[new fabric.Path("M 0,10 L 0,0 L 10,0",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width-8)+",0 L "+(this.clipper.width+4)+",0 L "+(this.clipper.width+4)+",10",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width+4)+","+(this.clipper.height-8)+" L"+(this.clipper.width+4)+","+(this.clipper.height+4)+" L "+(this.clipper.width-8)+","+(this.clipper.height+4),this._redrawCropperElements._.lineOptions),new fabric.Path("M 10,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height-8),this._redrawCropperElements._.lineOptions)],this.cropperHandles=new fabric.Group(this._redrawCropperElements._.pathGroup,{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this.croppingRectangle=new fabric.Rect({left:this.clipper.left,top:this.clipper.top,width:this.clipper.width,height:this.clipper.height,fill:"rgba(0,0,0,0)",stroke:"rgba(255,255,255,0.8)",strokeWidth:2,originX:"center",originY:"center"}),this.cropperGrid=new fabric.Group([new fabric.Line([.33*this.clipper.width,0,.33*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([.66*this.clipper.width,0,.66*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.33*this.clipper.height,this.clipper.width,.33*this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.66*this.clipper.height,this.clipper.width,.66*this.clipper.height],this._redrawCropperElements._.gridOptions)],{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this._redrawCropperElements._.cropTextTop=this.croppingRectangle.top+this.clipper.height/2+12,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0)",this._redrawCropperElements._.cropTextTop+12>this.editorHeight-2&&(this._redrawCropperElements._.cropTextTop-=24,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0.5)"),this.croppingCanvas.add(this.cropperHandles),this.croppingCanvas.add(this.cropperGrid),this.croppingCanvas.add(this.croppingRectangle)},_repositionCropper:function(t){if(this.croppingCanvas){var e=this.clipper.left-this.croppingCanvas.width/2,i=this.clipper.top-this.croppingCanvas.height/2;this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var s=this._getBoundingRectangle(this.imageVerticeCoords).width/t.width;this.clipper.width=Math.round(this.clipper.width*s),this.clipper.height=Math.round(this.clipper.height*s),this.clipper.left=this.editorWidth/2+e*s,this.clipper.top=this.editorHeight/2+i*s,this.croppingShade.set({width:this.editorWidth,height:this.editorHeight,left:this.editorWidth/2,top:this.editorHeight/2}),this._redrawCropperElements(),this.renderCropper()}},_getBoundingRectangle:function(t){return{width:Math.max(t.a.x,t.b.x,t.c.x,t.d.x)-Math.min(t.a.x,t.b.x,t.c.x,t.d.x),height:Math.max(t.a.y,t.b.y,t.c.y,t.d.y)-Math.min(t.a.y,t.b.y,t.c.y,t.d.y)}},_handleMouseDown:function(t){var e=this.focalPoint&&this._isMouseOver(t,this.focalPoint),i=this.croppingCanvas&&this._isMouseOver(t,this.clipper),s=this.croppingCanvas&&this._cropperHandleHitTest(t);(s||i||e)&&(this.previousMouseX=t.pageX,this.previousMouseY=t.pageY,e?this.draggingFocal=!0:s?this.scalingCropper=s:i&&(this.draggingCropper=!0))},_handleMouseMove:function(t){null!==this.mouseMoveEvent&&Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this)),this.mouseMoveEvent=t},_handleMouseMoveInternal:function(){null!==this.mouseMoveEvent&&(this.focalPoint&&this.draggingFocal?(this._handleFocalDrag(this.mouseMoveEvent),this.storeFocalPointState(),this.renderImage()):this.draggingCropper||this.scalingCropper?(this.draggingCropper?this._handleCropperDrag(this.mouseMoveEvent):this._handleCropperResize(this.mouseMoveEvent),this._redrawCropperElements(),this.storeCropperState(),this.renderCropper()):this._setMouseCursor(this.mouseMoveEvent),this.previousMouseX=this.mouseMoveEvent.pageX,this.previousMouseY=this.mouseMoveEvent.pageY,this.mouseMoveEvent=null)},_handleMouseUp:function(t){this.draggingCropper=!1,this.scalingCropper=!1,this.draggingFocal=!1},_handleMouseOut:function(t){this._handleMouseUp(t),this.mouseMoveEvent=t,this._handleMouseMoveInternal()},_handleCropperDrag:function(t){if(void 0===this._handleCropperDrag._&&(this._handleCropperDrag._={}),this._handleCropperDrag._.deltaX=t.pageX-this.previousMouseX,this._handleCropperDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleCropperDrag._.deltaX&&0===this._handleCropperDrag._.deltaY)return!1;if(this._handleCropperDrag._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.deltaX,this._handleCropperDrag._.deltaY),!this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)){for(this._handleCropperDrag._.dxi=0,this._handleCropperDrag._.dyi=0,this._handleCropperDrag._.xStep=this._handleCropperDrag._.deltaX>0?-1:1,this._handleCropperDrag._.yStep=this._handleCropperDrag._.deltaY>0?-1:1,this._handleCropperDrag._.furthest=0,this._handleCropperDrag._.furthestDeltas={},this._handleCropperDrag._.dxi=Math.min(Math.abs(this._handleCropperDrag._.deltaX),10);this._handleCropperDrag._.dxi>=0;this._handleCropperDrag._.dxi--)for(this._handleCropperDrag._.dyi=Math.min(Math.abs(this._handleCropperDrag._.deltaY),10);this._handleCropperDrag._.dyi>=0;this._handleCropperDrag._.dyi--)this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)),this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)&&this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi>this._handleCropperDrag._.furthest&&(this._handleCropperDrag._.furthest=this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi,this._handleCropperDrag._.furthestDeltas={x:this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),y:this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)});if(0==this._handleCropperDrag._.furthest)return;this._handleCropperDrag._.deltaX=this._handleCropperDrag._.furthestDeltas.x,this._handleCropperDrag._.deltaY=this._handleCropperDrag._.furthestDeltas.y}this.clipper.set({left:this.clipper.left+this._handleCropperDrag._.deltaX,top:this.clipper.top+this._handleCropperDrag._.deltaY})},_handleFocalDrag:function(t){if(void 0===this._handleFocalDrag._&&(this._handleFocalDrag._={}),this.focalPoint){if(this._handleFocalDrag._.deltaX=t.pageX-this.previousMouseX,this._handleFocalDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleFocalDrag._.deltaX&&0===this._handleFocalDrag._.deltaY)return;if(this._handleFocalDrag._.newX=this.focalPoint.left+this._handleFocalDrag._.deltaX,this._handleFocalDrag._.newY=this.focalPoint.top+this._handleFocalDrag._.deltaY,"crop"===this.currentView){if(!this.arePointsInsideRectangle([{x:this._handleFocalDrag._.newX,y:this._handleFocalDrag._.newY}],this.imageVerticeCoords))return}else if(!(this.viewport.left-this.viewport.width/2-this._handleFocalDrag._.newX<0&&this.viewport.left+this.viewport.width/2-this._handleFocalDrag._.newX>0&&this.viewport.top-this.viewport.height/2-this._handleFocalDrag._.newY<0&&this.viewport.top+this.viewport.height/2-this._handleFocalDrag._.newY>0))return;this.focalPoint.set({left:this.focalPoint.left+this._handleFocalDrag._.deltaX,top:this.focalPoint.top+this._handleFocalDrag._.deltaY})}},setCroppingConstraint:function(t){switch(this.updateSizeAndPosition(),t){case"none":this.croppingConstraint=!1;break;case"original":this.croppingConstraint=this.originalWidth/this.originalHeight;break;case"current":this.croppingConstraint=this.clipper.width/this.clipper.height;break;case"custom":break;default:this.croppingConstraint=parseFloat(t)}},enforceCroppingConstraint:function(){var t=this;void 0===this.enforceCroppingConstraint._&&(this.enforceCroppingConstraint._={}),!this.animationInProgress&&this.croppingConstraint&&(this.animationInProgress=!0,this.enforceCroppingConstraint._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this.clipper.width>this.clipper.height*this.croppingConstraint?(this.enforceCroppingConstraint._.previousHeight=this.enforceCroppingConstraint._.rectangle.height,this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.top-=(this.enforceCroppingConstraint._.rectangle.height-this.enforceCroppingConstraint._.previousHeight)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.height=this.enforceCroppingConstraint._.rectangle.width/this.croppingConstraint)):(this.enforceCroppingConstraint._.previousWidth=this.enforceCroppingConstraint._.rectangle.width,this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.left-=(this.enforceCroppingConstraint._.rectangle.width-this.enforceCroppingConstraint._.previousWidth)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.width=this.enforceCroppingConstraint._.rectangle.height*this.croppingConstraint)),this.enforceCroppingConstraint._.properties={height:this.enforceCroppingConstraint._.rectangle.height,width:this.enforceCroppingConstraint._.rectangle.width},this.clipper.animate(this.enforceCroppingConstraint._.properties,{onChange:function(){t._redrawCropperElements(),t.croppingCanvas.renderAll()},duration:this.settings.animationDuration,onComplete:function(){t._redrawCropperElements(),t.animationInProgress=!1,t.renderCropper(),t.storeCropperState()}}))},_handleCropperResize:function(t){void 0===this._handleCropperResize._&&(this._handleCropperResize._={}),this._handleCropperResize._.deltaX=t.pageX-this.previousMouseX,this._handleCropperResize._.deltaY=t.pageY-this.previousMouseY,"b"!==this.scalingCropper&&"t"!==this.scalingCropper||(this._handleCropperResize._.deltaX=0),"l"!==this.scalingCropper&&"r"!==this.scalingCropper||(this._handleCropperResize._.deltaY=0),0===this._handleCropperResize._.deltaX&&0===this._handleCropperResize._.deltaY||(this._handleCropperResize._.startingRectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperResize._.rectangle=this._calculateNewCropperSizeByDeltas(this._handleCropperResize._.startingRectangle,this._handleCropperResize._.deltaX,this._handleCropperResize._.deltaY,this.scalingCropper),this._handleCropperResize._.rectangle.height<30||this._handleCropperResize._.rectangle.width<30||this.arePointsInsideRectangle(this._getRectangleVertices(this._handleCropperResize._.rectangle),this.imageVerticeCoords)&&(this.clipper.set({top:this._handleCropperResize._.rectangle.top+this._handleCropperResize._.rectangle.height/2,left:this._handleCropperResize._.rectangle.left+this._handleCropperResize._.rectangle.width/2,width:this._handleCropperResize._.rectangle.width,height:this._handleCropperResize._.rectangle.height}),this._redrawCropperElements()))},_calculateNewCropperSizeByDeltas:function(t,e,i,s){if(void 0===this._calculateNewCropperSizeByDeltas._&&(this._calculateNewCropperSizeByDeltas._={}),this._calculateNewCropperSizeByDeltas._.topDelta=0,this._calculateNewCropperSizeByDeltas._.leftDelta=0,this._calculateNewCropperSizeByDeltas._.rectangle=t,this._calculateNewCropperSizeByDeltas._.deltaX=e,this._calculateNewCropperSizeByDeltas._.deltaY=i,this.croppingConstraint){switch(this._calculateNewCropperSizeByDeltas._.change=0,s){case"t":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaY;break;case"b":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"r":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"l":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"br":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX}switch(this.croppingConstraint>1?(this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this.croppingConstraint):(this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this.croppingConstraint),this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX,s){case"t":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"b":this._calculateNewCropperSizeByDeltas._.rectangle.left+=-this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"r":this._calculateNewCropperSizeByDeltas._.rectangle.top+=-this._calculateNewCropperSizeByDeltas._.deltaY/2;break;case"l":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY/2,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"tl":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX}}else!this.shiftKeyHeld||"tl"!==s&&"tr"!==s&&"bl"!==s&&"br"!==s||(this._calculateNewCropperSizeByDeltas._.ratio,Math.abs(e)>Math.abs(i)?(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaY*="tr"===s||"bl"===s?-1:1):(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaX*="tr"===s||"bl"===s?-1:1)),s.match(/t/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.top+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.height-=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/b/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/r/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX),s.match(/l/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.left+=this._calculateNewCropperSizeByDeltas._.deltaX,this._calculateNewCropperSizeByDeltas._.rectangle.width-=this._calculateNewCropperSizeByDeltas._.deltaX);return this._calculateNewCropperSizeByDeltas._.rectangle.top=this._calculateNewCropperSizeByDeltas._.rectangle.top,this._calculateNewCropperSizeByDeltas._.rectangle.left=this._calculateNewCropperSizeByDeltas._.rectangle.left,this._calculateNewCropperSizeByDeltas._.rectangle.width=this._calculateNewCropperSizeByDeltas._.rectangle.width,this._calculateNewCropperSizeByDeltas._.rectangle.height=this._calculateNewCropperSizeByDeltas._.rectangle.height,this._calculateNewCropperSizeByDeltas._.rectangle},_setMouseCursor:function(t){void 0===this._setMouseCursor._&&(this._setMouseCursor._={}),Garnish.isMobileBrowser(!0)||(this._setMouseCursor._.cursor="default",this._setMouseCursor._.handle=this.croppingCanvas&&this._cropperHandleHitTest(t),this.focalPoint&&this._isMouseOver(t,this.focalPoint)?this._setMouseCursor._.cursor="pointer":this._setMouseCursor._.handle?"t"===this._setMouseCursor._.handle||"b"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ns-resize":"l"===this._setMouseCursor._.handle||"r"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ew-resize":"tl"===this._setMouseCursor._.handle||"br"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="nwse-resize":"bl"!==this._setMouseCursor._.handle&&"tr"!==this._setMouseCursor._.handle||(this._setMouseCursor._.cursor="nesw-resize"):this.croppingCanvas&&this._isMouseOver(t,this.clipper)&&(this._setMouseCursor._.cursor="move"),$(".body").css("cursor",this._setMouseCursor._.cursor))},_cropperHandleHitTest:function(t){if(void 0===this._cropperHandleHitTest._&&(this._cropperHandleHitTest._={}),this._cropperHandleHitTest._.parentOffset=this.$croppingCanvas.offset(),this._cropperHandleHitTest._.mouseX=t.pageX-this._cropperHandleHitTest._.parentOffset.left,this._cropperHandleHitTest._.mouseY=t.pageY-this._cropperHandleHitTest._.parentOffset.top,this._cropperHandleHitTest._.lb=this.clipper.left-this.clipper.width/2,this._cropperHandleHitTest._.rb=this._cropperHandleHitTest._.lb+this.clipper.width,this._cropperHandleHitTest._.tb=this.clipper.top-this.clipper.height/2,this._cropperHandleHitTest._.bb=this._cropperHandleHitTest._.tb+this.clipper.height,this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tl";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+3&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"bl"}if(this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-13&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tr";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"br"}return this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+3&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"l":this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+1&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-5&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"r":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+4&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-2&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10?"t":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-4&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10&&"b"},_isMouseOver:function(t,e){return void 0===this._isMouseOver._&&(this._isMouseOver._={}),this._isMouseOver._.parentOffset=this.$croppingCanvas.offset(),this._isMouseOver._.mouseX=t.pageX-this._isMouseOver._.parentOffset.left,this._isMouseOver._.mouseY=t.pageY-this._isMouseOver._.parentOffset.top,this._isMouseOver._.lb=e.left-e.width/2,this._isMouseOver._.rb=this._isMouseOver._.lb+e.width,this._isMouseOver._.tb=e.top-e.height/2,this._isMouseOver._.bb=this._isMouseOver._.tb+e.height,this._isMouseOver._.mouseX>=this._isMouseOver._.lb&&this._isMouseOver._.mouseX<=this._isMouseOver._.rb&&this._isMouseOver._.mouseY>=this._isMouseOver._.tb&&this._isMouseOver._.mouseY<=this._isMouseOver._.bb},_getRectangleVertices:function(t,e,i){return void 0===this._getRectangleVertices._&&(this._getRectangleVertices._={}),void 0===e&&(e=0),void 0===i&&(i=0),this._getRectangleVertices._.topLeft={x:t.left+e,y:t.top+i},this._getRectangleVertices._.topRight={x:this._getRectangleVertices._.topLeft.x+t.width,y:this._getRectangleVertices._.topLeft.y},this._getRectangleVertices._.bottomRight={x:this._getRectangleVertices._.topRight.x,y:this._getRectangleVertices._.topRight.y+t.height},this._getRectangleVertices._.bottomLeft={x:this._getRectangleVertices._.topLeft.x,y:this._getRectangleVertices._.bottomRight.y},[this._getRectangleVertices._.topLeft,this._getRectangleVertices._.topRight,this._getRectangleVertices._.bottomRight,this._getRectangleVertices._.bottomLeft]},_setFittedImageVerticeCoordinates:function(){this.imageVerticeCoords=this.getImageVerticeCoords("fit")},getImageVerticeCoords:function(t){var e,i=-1*((this.hasOrientationChanged()?90:0)+this.imageStraightenAngle)*(Math.PI/180),s=this.getScaledImageDimensions();e="number"==typeof t?t:"cover"===t?this.getZoomToCoverRatio(s):this.getZoomToFitRatio(s);var a=s.height*e,n=s.width*e,r=Math.cos(i)*a,o=Math.sin(i)*n,l=Math.cos(i)*n,h=Math.sin(i)*a,d=(this.editorHeight-(r+o))/2,c=(this.editorWidth-(h+l))/2;return{a:{x:c+l,y:d},b:{x:this.editorWidth-c,y:d+r},c:{x:c+h,y:this.editorHeight-d},d:{x:c,y:d+o}}},_debug:function(t){this.canvas.remove(this.debugger),this.debugger=t,this.canvas.add(this.debugger)},arePointsInsideRectangle:function(t,e){for(void 0===this.arePointsInsideRectangle._&&(this.arePointsInsideRectangle._={}),this.arePointsInsideRectangle._.ab=this._getVector(e.a,e.b),this.arePointsInsideRectangle._.bc=this._getVector(e.b,e.c),this.arePointsInsideRectangle._.scalarAbAb=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ab),this.arePointsInsideRectangle._.scalarBcBc=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bc),this.arePointsInsideRectangle._.i=0;this.arePointsInsideRectangle._.i<t.length;this.arePointsInsideRectangle._.i++)if(this.arePointsInsideRectangle._.point=t[this.arePointsInsideRectangle._.i],this.arePointsInsideRectangle._.ap=this._getVector(e.a,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.bp=this._getVector(e.b,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.scalarAbAp=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ap),this.arePointsInsideRectangle._.scalarBcBp=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bp),this.arePointsInsideRectangle._.projectsOnAB=0<=this.arePointsInsideRectangle._.scalarAbAp&&this.arePointsInsideRectangle._.scalarAbAp<=this.arePointsInsideRectangle._.scalarAbAb,this.arePointsInsideRectangle._.projectsOnBC=0<=this.arePointsInsideRectangle._.scalarBcBp&&this.arePointsInsideRectangle._.scalarBcBp<=this.arePointsInsideRectangle._.scalarBcBc,!this.arePointsInsideRectangle._.projectsOnAB||!this.arePointsInsideRectangle._.projectsOnBC)return!1;return!0},_getVector:function(t,e){return{x:e.x-t.x,y:e.y-t.y}},_getScalarProduct:function(t,e){return t.x*e.x+t.y*e.y},_getVectorMagnitude:function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},_getAngleBetweenVectors:function(t,e){return Math.round(180*Math.acos(Math.min(1,this._getScalarProduct(t,e)/(this._getVectorMagnitude(t)*this._getVectorMagnitude(e))))/Math.PI*100)/100},_getEdgeCrossed:function(t,e){for(var i=[[t.a,t.b],[t.b,t.c],[t.c,t.d],[t.d,t.a]],s={x:this.editorWidth/2,y:this.editorHeight/2},a=180,n=null,r=0;r<i.length;r++){var o=i[r],l=this._getVector(o[0],s),h=this._getVector(o[0],o[1]),d=this._getVector(o[0],e),c=Math.abs(this._getAngleBetweenVectors(l,d)-(this._getAngleBetweenVectors(l,h)+this._getAngleBetweenVectors(h,d)));c<a&&(a=c,n=o)}return n},_getImageBoundingBox:function(t){var e={},i=Math.abs(this.imageStraightenAngle)*(Math.PI/180),s=t.height/t.width;if(e.height=t.width*(Math.sin(i)+Math.cos(i)*s),e.width=t.width*(Math.cos(i)+Math.sin(i)*s),this.hasOrientationChanged()){var a=e.width;e.width=e.height,e.height=a}return e}},{defaults:{animationDuration:100,allowSavingAsNew:!0,onSave:$.noop,allowDegreeFractions:null}})},2495:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}Craft.AssetIndex=Craft.BaseElementIndex.extend({$includeSubfoldersContainer:null,$includeSubfoldersCheckbox:null,showingIncludeSubfoldersCheckbox:!1,$uploadButton:null,$uploadInput:null,$progressBar:null,$folders:null,uploader:null,promptHandler:null,progressBar:null,_uploadTotalFiles:0,_uploadFileProgress:{},_currentUploaderSettings:{},_assetDrag:null,_folderDrag:null,_expandDropTargetFolderTimeout:null,_tempExpandedFolders:[],_fileConflictTemplate:{choices:[{value:"keepBoth",title:Craft.t("app","Keep both")},{value:"replace",title:Craft.t("app","Replace it")}]},_folderConflictTemplate:{choices:[{value:"replace",title:Craft.t("app","Replace the folder (all existing files will be deleted)")},{value:"merge",title:Craft.t("app","Merge the folder (any conflicting files will be replaced)")}]},init:function(t,e,i){this.base(t,e,i),"index"===this.settings.context?(this._folderDrag||this._initIndexPageMode(),this.addListener(Garnish.$win,"resize,scroll","_positionProgressBar")):(this.addListener(this.$main,"scroll","_positionProgressBar"),this.settings.modal&&this.settings.modal.on("updateSizeAndPosition",this._positionProgressBar.bind(this)))},initSources:function(){return"index"!==this.settings.context||this._folderDrag||this._initIndexPageMode(),this.base()},initSource:function(t){this.base(t),this._createFolderContextMenu(t),"index"===this.settings.context&&(this._folderDrag&&this._getSourceLevel(t)>1&&t.data("folder-id")&&this._folderDrag.addItems(t.parent()),this._assetDrag&&this._assetDrag.updateDropTargets())},deinitSource:function(t){this.base(t);var e=t.data("contextmenu");e&&e.destroy(),"index"===this.settings.context&&(this._folderDrag&&this._getSourceLevel(t)>1&&this._folderDrag.removeItems(t.parent()),this._assetDrag&&this._assetDrag.updateDropTargets())},_getSourceLevel:function(t){return t.parentsUntil("nav","ul").length},_initIndexPageMode:function(){var t=this;this._folderDrag||(this.settings.selectable=!0,this.settings.multiSelect=!0,this._assetDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,filter:function(){return t.view.getSelectedElements().has("div.element[data-movable]")},helper:function(e){return t._getFileDragHelper(e)},dropTargets:function(){var e;e=t._assetDrag.$draggee&&t._assetDrag.$draggee.has(".element[data-peer-file]").length?"data-can-move-peer-files-to":"data-can-move-to";for(var i=[],s=0;s<t.$sources.length;s++){var a=t.$sources.eq(s);Garnish.hasAttr(a,e)&&i.push(a)}return i},onDragStart:this._onDragStart.bind(this),onDropTargetChange:this._onDropTargetChange.bind(this),onDragStop:this._onFileDragStop.bind(this),helperBaseZindex:800}),this._folderDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,helper:function(e){var i=$('<div class="sidebar drag-helper"/>'),s=$("<nav/>").appendTo(i),a=$("<ul/>").appendTo(s);return e.appendTo(a).removeClass("expanded"),e.children("a").addClass("sel"),e.css({"padding-top":t._folderDrag.$draggee.css("padding-top"),"padding-right":t._folderDrag.$draggee.css("padding-right"),"padding-bottom":t._folderDrag.$draggee.css("padding-bottom"),"padding-left":t._folderDrag.$draggee.css("padding-left")}),i},dropTargets:function(){var e=[],i=[];t._folderDrag.$draggee.find("a[data-key]").each((function(){i.push($(this).data("key"))}));for(var s=0;s<t.$sources.length;s++){var a=t.$sources.eq(s),n=a.data("key");t._getFolderUidFromSourceKey(n)&&(Craft.inArray(n,i)||e.push(a))}return e},onDragStart:this._onDragStart.bind(this),onDropTargetChange:this._onDropTargetChange.bind(this),onDragStop:this._onFolderDragStop.bind(this)}))},_onFileDragStop:function(){var t=this;if(this._assetDrag.$activeDropTarget&&this._assetDrag.$activeDropTarget[0]!==this.$source[0]){for(var e=this.$source,i=this._assetDrag.$activeDropTarget.data("folder-id"),s=[],a=0;a<this._assetDrag.$draggee.length;a++){var n=Craft.getElementInfo(this._assetDrag.$draggee[a]).id;s.push(n)}if(s.length){this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(s.length),this.progressBar.showProgressBar();var r=[];for(a=0;a<s.length;a++)r.push({action:"assets/move-asset",params:{assetId:s[a],folderId:i}});return void this._performBatchRequests(r,(function a(n){t.promptHandler.resetPrompts();for(var r=0;r<n.length;r++){var o=n[r];o.conflict&&t.promptHandler.addPrompt({assetId:o.assetId,suggestedFilename:o.suggestedFilename,prompt:{message:o.conflict,choices:t._fileConflictTemplate.choices}}),o.error&&alert(o.error)}t.setIndexAvailable(),t.progressBar.hideProgressBar();var l=!1,h=function(){this.sourceSelect.selectItem(e),this._totalVisible-=this._assetDrag.$draggee.length;for(var t=0;t<s.length;t++)$("[data-id="+s[t]+"]").remove();this.view.deselectAllElements(),this._collapseExtraExpandedFolders(i),l&&this.updateElements()};t.promptHandler.getPromptCount()?(t._assetDrag.fadeOutHelpers(),t.promptHandler.showBatchPrompts((function(e){for(var s=[],n=0;n<e.length;n++)"cancel"!==e[n].choice?("keepBoth"===e[n].choice&&s.push({action:"assets/move-asset",params:{folderId:i,assetId:e[n].assetId,filename:e[n].suggestedFilename}}),"replace"===e[n].choice&&s.push({action:"assets/move-asset",params:{folderId:i,assetId:e[n].assetId,force:!0}})):l=!0;0===s.length?h.apply(t):(t.setIndexBusy(),t.progressBar.resetProgressBar(),t.progressBar.setItemCount(t.promptHandler.getPromptCount()),t.progressBar.showProgressBar(),t._performBatchRequests(s,a))}))):(h.apply(t),t._assetDrag.fadeOutHelpers())}))}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._assetDrag.returnHelpersToDraggees()},_onFolderDragStop:function(){var t=this;if(this._folderDrag.$activeDropTarget&&0===this._folderDrag.$activeDropTarget.siblings("ul").children("li").filter(this._folderDrag.$draggee).length){var e=this._folderDrag.$activeDropTarget.data("folder-id");this._collapseExtraExpandedFolders(e);for(var i=[],s=0;s<this._folderDrag.$draggee.length;s++){var a=this._folderDrag.$draggee.eq(s).children("a").data("folder-id");if(a!=e){i.push(a);break}}if(i.length){i.sort(),i.reverse(),this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(i.length),this.progressBar.showProgressBar();var n=[];for(s=0;s<i.length;s++)n.push({action:"assets/move-folder",params:{folderId:i[s],parentId:e}});this.requestId++;var r=[],o="";return void this._performBatchRequests(n,(function e(s){t.promptHandler.resetPrompts();for(var a=0;a<s.length;a++){var n=s[a];n.success&&(n.transferList&&(r=n.transferList),n.newFolderId&&(o=t._folderDrag.$activeDropTarget.data("key")+"/folder:"+n.newFolderUid)),n.conflict&&(n.prompt={message:n.conflict,choices:t._folderConflictTemplate.choices},t.promptHandler.addPrompt(n)),n.error&&alert(n.error)}t.promptHandler.getPromptCount()?(t.promptHandler.showBatchPrompts((function(s){t.promptHandler.resetPrompts();for(var a=[],l={},h=0;h<s.length;h++)"cancel"!==s[h].choice&&("replace"===s[h].choice&&(l.force=!0),"merge"===s[h].choice&&(l.merge=!0),l.folderId=n.folderId,l.parentId=n.parentId,a.push({action:"assets/move-folder",params:l}));0===a.length?t._performActualFolderMove(r,i,o):(t.setIndexBusy(),t.progressBar.resetProgressBar(),t.progressBar.setItemCount(t.promptHandler.getPromptCount()),t.progressBar.showProgressBar(),t._performBatchRequests(a,e))})),t.setIndexAvailable(),t.progressBar.hideProgressBar()):t._performActualFolderMove(r,i,o)}))}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._folderDrag.returnHelpersToDraggees()},_performActualFolderMove:function(t,e,i){var s=this;this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(1),this.progressBar.showProgressBar();var a=function(t){for(var e=0,a=t.length,n=0;n<t.length;n++)Craft.postActionRequest("assets/delete-folder",{folderId:t[n]},(function(){++e===a&&(s.setIndexAvailable(),s.progressBar.hideProgressBar(),s._folderDrag.returnHelpersToDraggees(),s.setInstanceState("selectedSource",i),s.refreshSources())}))};if(t.length>0){for(var n=[],r=0;r<t.length;r++)n.push({action:"assets/move-asset",params:t[r]});this._performBatchRequests(n,(function(){a(e)}))}else a(e)},_getRootSource:function(t){for(var e;(e=this._getParentSource(t))&&e.length;)t=e;return t},_getParentSource:function(t){if(this._getSourceLevel(t)>1)return t.parent().parent().siblings("a")},_selectSourceByFolderId:function(t){for(var e=this._getSourceByKey(t),i=e.parent().parents("li"),s=0;s<i.length;s++){var a=$(i[s]);a.hasClass("expanded")||a.children(".toggle").trigger("click")}this.selectSource(e),this.updateElements()},afterInit:function(){var t=this;this.$uploadButton||(this.$uploadButton=$("<button/>",{type:"button",class:"btn submit","data-icon":"upload",style:"position: relative; overflow: hidden;",text:Craft.t("app","Upload files")}),this.addButton(this.$uploadButton),this.$uploadInput=$('<input type="file" multiple="multiple" name="assets-upload" />').hide().insertBefore(this.$uploadButton)),this.promptHandler=new Craft.PromptHandler,this.progressBar=new Craft.ProgressBar(this.$main,!0);var e={url:Craft.getActionUrl("assets/upload"),fileInput:this.$uploadInput,dropZone:this.$container};e.events={fileuploadstart:this._onUploadStart.bind(this),fileuploadprogressall:this._onUploadProgress.bind(this),fileuploaddone:this._onUploadComplete.bind(this),fileuploadfail:this._onUploadFailure.bind(this)},this.settings.criteria&&void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),this._currentUploaderSettings=e,this.uploader=new Craft.Uploader(this.$uploadButton,e),this.$uploadButton.on("click",(function(){t.$uploadButton.hasClass("disabled")||t.isIndexBusy||t.$uploadButton.parent().find("input[name=assets-upload]").trigger("click")})),this.base()},getDefaultSourceKey:function(){var e=this;if("index"===this.settings.context&&void 0!==window.defaultSource){var i=function(){var t=window.defaultSource.split("/"),i=e.$sources.toArray().find((function(e){return $(e).data("volume-handle")===t[0]}));if(i){for(var s=$(i),a=function(i){var a=e._getChildSources(s).toArray().find((function(e){return $("> .label",e).text()===t[i]}));if(!a)return"break";e._expandSource(s),s=$(a)},n=1;n<t.length&&"break"!==a(n);n++);return{v:s.data("key")}}}();if("object"===t(i))return i.v}return this.base()},onSelectSource:function(){var t=this._getSourceByKey(this.sourceKey);t.data("folder-id")&&Garnish.hasAttr(this.$source,"data-can-upload")?(this.uploader.setParams({folderId:this.$source.attr("data-folder-id")}),this.$uploadButton.removeClass("disabled")):this.$uploadButton.addClass("disabled"),t.length&&"index"===this.settings.context&&this._updateUrl(t),this.base()},_updateUrl:function(t){if("undefined"!=typeof history){for(var e,i=[],s=t;(e=this._getParentSource(s))&&e.length;)i.unshift(s),s=e;var a="assets";s.data("volume-handle")&&(a+="/"+s.data("volume-handle"),i.forEach((function(t){a+="/"+t.children(".label").text()}))),history.replaceState({},"",Craft.getUrl(a))}},_getFolderUidFromSourceKey:function(t){var e=t.match(/\bfolder:([0-9a-f\-]+)$/);return e?e[1]:null},startSearching:function(){if(!this.settings.hideSidebar&&this.$source.siblings("ul").length){if(null===this.$includeSubfoldersContainer){var t="includeSubfolders-"+Math.floor(1e9*Math.random());this.$includeSubfoldersContainer=$('<div style="margin-bottom: -25px; opacity: 0;"/>').insertAfter(this.$search);var e=$('<div style="padding-top: 5px;"/>').appendTo(this.$includeSubfoldersContainer);this.$includeSubfoldersCheckbox=$('<input type="checkbox" id="'+t+'" class="checkbox"/>').appendTo(e),$('<label class="light smalltext" for="'+t+'"/>').text(" "+Craft.t("app","Search in subfolders")).appendTo(e),this.addListener(this.$includeSubfoldersCheckbox,"change",(function(){this.setSelecetedSourceState("includeSubfolders",this.$includeSubfoldersCheckbox.prop("checked")),this.updateElements()}))}else this.$includeSubfoldersContainer.velocity("stop");var i=this.getSelectedSourceState("includeSubfolders",!1);this.$includeSubfoldersCheckbox.prop("checked",i),this.$includeSubfoldersContainer.velocity({marginBottom:0,opacity:1},"fast"),this.showingIncludeSubfoldersCheckbox=!0}this.base()},stopSearching:function(){this.showingIncludeSubfoldersCheckbox&&(this.$includeSubfoldersContainer.velocity("stop"),this.$includeSubfoldersContainer.velocity({marginBottom:-25,opacity:0},"fast"),this.showingIncludeSubfoldersCheckbox=!1),this.base()},getViewParams:function(){var t=this.base();return this.showingIncludeSubfoldersCheckbox&&this.$includeSubfoldersCheckbox.prop("checked")&&(t.criteria.includeSubfolders=!0),t},_onUploadStart:function(){this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar(),this.promptHandler.resetPrompts()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){var i=e.result,s=e.files[0].name,a=!0;i.success||i.conflict?(this.selectElementAfterUpdate(i.assetId),i.conflict&&(i.prompt={message:Craft.t("app",i.conflict,{file:i.filename}),choices:this._fileConflictTemplate.choices},this.promptHandler.addPrompt(i)),Craft.cp.runQueue()):(i.error?alert(Craft.t("app","Upload failed. The error message was: “{error}”",{error:i.error})):alert(Craft.t("app","Upload failed for {filename}.",{filename:s})),a=!1),this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.setIndexAvailable(),this.promptHandler.getPromptCount()?this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this)):a&&this._updateAfterUpload())},_onUploadFailure:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.progressBar.hideProgressBar(),this.setIndexAvailable())},_updateAfterUpload:function(){"index"!==this.settings.context&&(this.clearSearch(),this.setSortAttribute("dateCreated"),this.setSortDirection("desc")),this.updateElements()},_uploadFollowup:function(t){var e=this;this.setIndexBusy(),this.progressBar.resetProgressBar(),this.promptHandler.resetPrompts(),this.progressBar.setItemCount(t.length),this.progressBar.showProgressBar(),function t(i,s,a){var n={},r=null,o=function(n,r){"success"===r&&n.assetId?e.selectElementAfterUpdate(n.assetId):n.error&&alert(n.error),s++,e.progressBar.incrementProcessedItemCount(1),e.progressBar.updateProgressBar(),s===i.length?a():t(i,s,a)};"replace"===i[s].choice?(r="assets/replace-file",n.sourceAssetId=i[s].assetId,i[s].conflictingAssetId?n.assetId=i[s].conflictingAssetId:n.targetFilename=i[s].filename):"cancel"===i[s].choice&&(r="assets/delete-asset",n.assetId=i[s].assetId),r?Craft.postActionRequest(r,n,o):o({assetId:i[s].assetId},"success")}(t,0,(function(){e.progressBar.hideProgressBar(),e.setIndexAvailable(),e._updateAfterUpload()}))},onUpdateElements:function(){var t=this;this._onUpdateElements(!1,this.view.getAllElements()),this.view.on("appendElements",(function(e){t._onUpdateElements(!0,e.newElements)})),this.base()},_onUpdateElements:function(t,e){"index"===this.settings.context&&(t||this._assetDrag.removeAllItems(),this._assetDrag.addItems(e.has("div.element[data-movable]"))),this.base(t,e),this.removeListener(this.$elements,"keydown"),this.addListener(this.$elements,"keydown",this._onKeyDown.bind(this)),this.view.elementSelect.on("focusItem",this._onElementFocus.bind(this))},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var e=this.view.elementSelect.$focusedItem.find(".element");e.length&&this._loadPreview(e)}return t.stopPropagation(),!1}},_onElementFocus:function(t){var e=$(t.item).find(".element");Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.view.elementSelect,e)},_onDragStart:function(){this._tempExpandedFolders=[]},_getFileDragHelper:function(t){var e,i;switch(this.getSelectedSourceState("mode")){case"table":e=$('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),i=$('<div class="tableview"/>').appendTo(e);var s=$('<table class="data"/>').appendTo(i),a=$("<tbody/>").appendTo(s);t.appendTo(a),this._$firstRowCells=this.view.$table.children("tbody").children("tr:first").children();for(var n=t.children(),r=0;r<n.length;r++){var o=$(n[r]);if(o.hasClass("checkbox-cell"))o.remove(),e.css("margin-"+Craft.left,19);else{var l=$(this._$firstRowCells[r]),h=l.width();l.width(h),o.width(h)}}return e;case"thumbs":return e=$('<div class="elements thumbviewhelper"/>').appendTo(Garnish.$bod),i=$('<ul class="thumbsview"/>').appendTo(e),t.appendTo(i),e}return $()},_onDropTargetChange:function(t){if(clearTimeout(this._expandDropTargetFolderTimeout),t){var e=t.data("folder-id");e?(this.dropTargetFolder=this._getSourceByKey(e),this._hasSubfolders(this.dropTargetFolder)&&!this._isExpanded(this.dropTargetFolder)&&(this._expandDropTargetFolderTimeout=setTimeout(this._expandFolder.bind(this),500))):this.dropTargetFolder=null}t&&t[0]!==this.$source[0]?this.$source.removeClass("sel"):this.$source.addClass("sel")},_collapseExtraExpandedFolders:function(t){var e;clearTimeout(this._expandDropTargetFolderTimeout),t&&(e=this._getSourceByKey(t).parents("li").children("a"));for(var i=this._tempExpandedFolders.length-1;i>=0;i--){var s=this._tempExpandedFolders[i];void 0!==e&&0!==e.filter('[data-key="'+s.data("key")+'"]').length||(this._collapseFolder(s),this._tempExpandedFolders.splice(i,1))}},_getSourceByKey:function(t){return this.$sources.filter('[data-key$="'+t+'"]')},_hasSubfolders:function(t){return t.siblings("ul").find("li").length},_isExpanded:function(t){return t.parent("li").hasClass("expanded")},_expandFolder:function(){this._collapseExtraExpandedFolders(this.dropTargetFolder.data("folder-id")),this.dropTargetFolder.siblings(".toggle").trigger("click"),this._tempExpandedFolders.push(this.dropTargetFolder)},_collapseFolder:function(t){t.parent().hasClass("expanded")&&t.siblings(".toggle").trigger("click")},_createFolderContextMenu:function(t){var e=this;if(this._getFolderUidFromSourceKey(t.data("key"))){var i=[{label:Craft.t("app","New subfolder"),onClick:function(){e._createSubfolder(t)}}];"index"===this.settings.context&&this._getSourceLevel(t)>1&&(i.push({label:Craft.t("app","Rename folder"),onClick:function(){e._renameFolder(t)}}),i.push({label:Craft.t("app","Delete folder"),onClick:function(){e._deleteFolder(t)}})),new Garnish.ContextMenu(t,i,{menuClass:"menu"})}},_createSubfolder:function(t){var e=this,i=prompt(Craft.t("app","Enter the name of the folder"));if(i){var s={parentId:t.data("folder-id"),folderName:i};this.setIndexBusy(),Craft.postActionRequest("assets/create-folder",s,(function(i,s){if(e.setIndexAvailable(),"success"===s&&i.success){e._prepareParentForChildren(t);var a=$('<li><a data-key="'+t.data("key")+"/folder:"+i.folderUid+'"'+(Garnish.hasAttr(t,"data-has-thumbs")?" data-has-thumbs":"")+' data-folder-id="'+i.folderId+'"'+(Garnish.hasAttr(t,"data-can-upload")?" data-can-upload":"")+(Garnish.hasAttr(t,"data-can-move-to")?" data-can-move-to":"")+(Garnish.hasAttr(t,"data-can-move-peer-files-to")?" data-can-move-peer-files-to":"")+">"+i.folderName+"</a></li>"),n=a.children("a:first");e._appendSubfolder(t,a),e.initSource(n)}"success"===s&&i.error&&alert(i.error)}))}},_deleteFolder:function(t){var e=this;if(confirm(Craft.t("app","Really delete folder “{folder}”?",{folder:$.trim(t.text())}))){var i={folderId:t.data("folder-id")};this.setIndexBusy(),Craft.postActionRequest("assets/delete-folder",i,(function(i,s){if(e.setIndexAvailable(),"success"===s&&i.success){var a=e._getParentSource(t);e.deinitSource(t),t.parent().remove(),e._cleanUpTree(a)}"success"===s&&i.error&&alert(i.error)}))}},_renameFolder:function(t){var e=this,i=t.children(".label"),s=Craft.trim(i.text()),a=prompt(Craft.t("app","Rename folder"),s);a&&a!==s&&(this.setIndexBusy(),Craft.sendActionRequest("POST","assets/rename-folder",{data:{folderId:t.data("folder-id"),newName:a}}).then((function(s){s.data.success?(i.text(s.data.newName),t.data("key")===e.$source.data("key")&&(e.updateElements(),"index"===e.settings.context&&e._updateUrl(t))):s.data.error&&alert(s.data.error)})).finally((function(){e.setIndexAvailable()})))},_prepareParentForChildren:function(t){this._hasSubfolders(t)||(t.parent().addClass("expanded").append('<div class="toggle"></div><ul></ul>'),this.initSourceToggle(t))},_appendSubfolder:function(t,e){for(var i=t.siblings("ul").children("li"),s=$.trim(e.children("a:first").text()),a=!1,n=0;n<i.length;n++){var r=$(i[n]);if($.trim(r.children("a:first").text())>s){r.before(e),a=!0;break}}a||t.siblings("ul").append(e)},_cleanUpTree:function(t){null!==t&&0===t.siblings("ul").children("li").length&&(this.deinitSourceToggle(t),t.siblings("ul").remove(),t.siblings(".toggle").remove(),t.parent().removeClass("expanded"))},_positionProgressBar:function(){this.progressBar||(this.progressBar=new Craft.ProgressBar(this.$main,!0));var t=$(),e=0,i=0;"index"===this.settings.context?(t=this.progressBar.$progressBar.closest("#content"),e=Garnish.$win.scrollTop()):(t=this.progressBar.$progressBar.closest(".main"),e=this.$main.scrollTop());var s=e-t.offset().top,a=Garnish.$win.height();i=t.height()>a?a/2-6+s:t.height()/2-6,"index"!==this.settings.context&&(i=e+(t.height()/2-6)),this.progressBar.$progressBar.css({top:i})},_performBatchRequests:function(t,e){for(var i=this,s=[],a=t.length;t.length;){var n=t.shift();Craft.sendActionRequest("POST",n.action,{data:n.params}).then((function(t){s.push(t.data)})).finally((function(){i.progressBar.incrementProcessedItemCount(1),i.progressBar.updateProgressBar(),0==--a&&(Craft.cp.runQueue(),e(s))}))}}}),Craft.registerElementIndexClass("craft\\elements\\Asset",Craft.AssetIndex)},5077:function(){Craft.AssetSelectInput=Craft.BaseElementSelectInput.extend({requestId:0,hud:null,$uploadBtn:null,uploader:null,progressBar:null,init:function(){this.base.apply(this,arguments),this.settings.canUpload&&this._attachUploader(),this.addListener(this.$elementsContainer,"keydown",this._onKeyDown.bind(this)),this.elementSelect.on("focusItem",this._onElementFocus.bind(this))},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var e=this.elementSelect.$focusedItem;e.length&&this._loadPreview(e)}return t.stopPropagation(),!1}},_onElementFocus:function(t){var e=$(t.item);Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.elementSelect,e)},createElementEditor:function(t){return this.base(t,{params:{defaultFieldLayoutId:this.settings.defaultFieldLayoutId},input:this})},_attachUploader:function(){var t=this;this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var e={url:Craft.getActionUrl("assets/upload"),dropZone:this.$container,formData:{fieldId:this.settings.fieldId}};this.settings.sourceElementId&&(e.formData.elementId=this.settings.sourceElementId),this.settings.criteria.siteId&&(e.formData.siteId=this.settings.criteria.siteId),this.$addElementBtn&&(this.$uploadBtn=$("<button/>",{type:"button",class:"btn dashed","data-icon":"upload","aria-label":1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files"),"aria-describedby":this.settings.describedBy,text:1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files")}).insertAfter(this.$addElementBtn),e.fileInput=$("<input/>",{type:"file",class:"hidden",multiple:1!=this.settings.limit}).insertAfter(this.$uploadBtn),Garnish.$win.trigger("resize")),void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(e.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),e.canAddMoreFiles=this.canAddMoreFiles.bind(this),e.events={},e.events.fileuploadstart=this._onUploadStart.bind(this),e.events.fileuploadprogressall=this._onUploadProgress.bind(this),e.events.fileuploaddone=this._onUploadComplete.bind(this),e.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,e),this.$uploadBtn&&this.$uploadBtn.on("click",(function(e){t.$uploadBtn.next("input[type=file]").trigger("click")}))},refreshThumbnail:function(t){var e=this,i={elementId:t,siteId:this.settings.criteria.siteId,size:this.settings.viewMode};Craft.postActionRequest("elements/get-element-html",i,(function(i){if(i.error)alert(i.error);else{var s=e.$elements.filter('[data-id="'+t+'"]');s.find(".elementthumb").replaceWith($(i.html).find(".elementthumb")),e.thumbLoader.load(s)}}))},selectUploadedFile:function(t){if(this.canAddMoreElements()){var e=t.$element;e.addClass("removable"),e.prepend('<input type="hidden" name="'+this.settings.name+'[]" value="'+t.id+'"><a class="delete icon" title="'+Craft.t("app","Remove")+'"></a>'),e.appendTo(this.$elementsContainer);var i=-(e.outerWidth()+10);this.$addElementBtn.css("margin-"+Craft.left,i+"px");var s={};s["margin-"+Craft.left]=0,this.$addElementBtn.velocity(s,"fast"),this.addElements(e),delete this.modal}},_onUploadStart:function(){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){var i=this;if(e.result.error)alert(e.result.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading");else{var s={elementId:e.result.assetId,siteId:this.settings.criteria.siteId,size:this.settings.viewMode};Craft.postActionRequest("elements/get-element-html",s,(function(t){if(t.error)alert(t.error);else{var e=$(t.html);Craft.appendHeadHtml(t.headHtml),i.selectUploadedFile(Craft.getElementInfo(e))}i.uploader.isLastUpload()&&(i.progressBar.hideProgressBar(),i.$container.removeClass("uploading"),window.draftEditor&&window.draftEditor.checkForm())})),Craft.cp.runQueue()}},_onUploadFailure:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},canAddMoreFiles:function(t){return!this.settings.limit||this.$elements.length+t<this.settings.limit}})},4606:function(){Craft.AssetSelectorModal=Craft.BaseElementSelectorModal.extend({$selectTransformBtn:null,_selectedTransform:null,init:function(t,e){e=$.extend({},Craft.AssetSelectorModal.defaults,e),this.base(t,e),e.transforms.length&&this.createSelectTransformButton(e.transforms)},createSelectTransformButton:function(t){if(t&&t.length){var e=$('<div class="btngroup"/>').appendTo(this.$primaryButtons);this.$selectBtn.appendTo(e),this.$selectTransformBtn=$("<button/>",{type:"button",class:"btn menubtn disabled",text:Craft.t("app","Select transform")}).appendTo(e);for(var i=$('<div class="menu" data-align="right"></div>').insertAfter(this.$selectTransformBtn),s=$("<ul></ul>").appendTo(i),a=0;a<t.length;a++)$('<li><a data-transform="'+t[a].handle+'">'+t[a].name+"</a></li>").appendTo(s);var n=new Garnish.MenuBtn(this.$selectTransformBtn,{onOptionSelect:this.onSelectTransform.bind(this)});n.disable(),this.$selectTransformBtn.data("menuButton",n)}},onSelectionChange:function(t){var e=this.elementIndex.getSelectedElements(),i=!1;if(e.length&&this.settings.transforms.length){i=!0;for(var s=0;s<e.length&&$(".element.hasthumb:first",e[s]).length;s++);}var a=null;this.$selectTransformBtn&&(a=this.$selectTransformBtn.data("menuButton")),i?(a&&a.enable(),this.$selectTransformBtn.removeClass("disabled")):this.$selectTransformBtn&&(a&&a.disable(),this.$selectTransformBtn.addClass("disabled")),this.base()},onSelectTransform:function(t){var e=$(t).data("transform");this.selectImagesWithTransform(e)},selectImagesWithTransform:function(t){var e=this;void 0===Craft.AssetSelectorModal.transformUrls[t]&&(Craft.AssetSelectorModal.transformUrls[t]={});for(var i=this.elementIndex.getSelectedElements(),s=[],a=0;a<i.length;a++){var n=$(i[a]),r=Craft.getElementInfo(n).id;void 0===Craft.AssetSelectorModal.transformUrls[t][r]&&s.push(r)}s.length?(this.showFooterSpinner(),this.fetchMissingTransformUrls(s,t,(function(){e.hideFooterSpinner(),e.selectImagesWithTransform(t)}))):(this._selectedTransform=t,this.selectElements(),this._selectedTransform=null)},fetchMissingTransformUrls:function(t,e,i){var s=this,a=t.pop(),n={assetId:a,handle:e};Craft.postActionRequest("assets/generate-transform",n,(function(n,r){Craft.AssetSelectorModal.transformUrls[e][a]=!1,"success"===r&&n.url&&(Craft.AssetSelectorModal.transformUrls[e][a]=n.url),t.length?s.fetchMissingTransformUrls(t,e,i):i()}))},getElementInfo:function(t){var e=this.base(t);if(this._selectedTransform)for(var i=0;i<e.length;i++){var s=e[i].id;void 0!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&!1!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&(e[i].url=Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s])}return e},onSelect:function(t){this.settings.onSelect(t,this._selectedTransform)}},{defaults:{canSelectImageTransforms:!1,transforms:[]},transformUrls:{}}),Craft.registerElementSelectorModalClass("craft\\elements\\Asset",Craft.AssetSelectorModal)},9222:function(){Craft.AuthManager=Garnish.Base.extend({remainingSessionTime:null,checkRemainingSessionTimer:null,showLoginModalTimer:null,decrementLogoutWarningInterval:null,showingLogoutWarningModal:!1,showingLoginModal:!1,logoutWarningModal:null,loginModal:null,$logoutWarningPara:null,$passwordInput:null,$passwordSpinner:null,$loginBtn:null,$loginErrorPara:null,submitLoginIfLoggedOut:!1,init:function(){this.updateRemainingSessionTime(Craft.remainingSessionTime)},setCheckRemainingSessionTimer:function(t){this.checkRemainingSessionTimer&&clearTimeout(this.checkRemainingSessionTimer),this.checkRemainingSessionTimer=setTimeout(this.checkRemainingSessionTime.bind(this),1e3*t)},checkRemainingSessionTime:function(t){var e=this;$.ajax({url:Craft.getActionUrl("users/session-info",t?null:"dontExtendSession=1"),type:"GET",dataType:"json",complete:function(t,i){"success"===i?(void 0!==t.responseJSON.csrfTokenValue&&void 0!==Craft.csrfTokenValue&&(Craft.csrfTokenValue=t.responseJSON.csrfTokenValue),e.updateRemainingSessionTime(t.responseJSON.timeout),e.submitLoginIfLoggedOut=!1):e.updateRemainingSessionTime(-1)}})},updateRemainingSessionTime:function(t){this.remainingSessionTime=parseInt(t),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime?(this.remainingSessionTime?(this.showingLogoutWarningModal||this.showLogoutWarningModal(),this.remainingSessionTime<Craft.AuthManager.checkInterval&&(this.showLoginModalTimer&&clearTimeout(this.showLoginModalTimer),this.showLoginModalTimer=setTimeout(this.showLoginModal.bind(this),1e3*this.remainingSessionTime))):this.showingLoginModal?this.submitLoginIfLoggedOut&&this.submitLogin():this.showLoginModal(),this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval)):(this.hideLogoutWarningModal(),this.hideLoginModal(),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime+Craft.AuthManager.checkInterval?this.setCheckRemainingSessionTimer(this.remainingSessionTime-Craft.AuthManager.minSafeSessionTime+1):this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval))},showLogoutWarningModal:function(){var t;if(this.showingLoginModal?(this.hideLoginModal(!0),t=!0):t=!1,this.showingLogoutWarningModal=!0,!this.logoutWarningModal){var e=$('<form id="logoutwarningmodal" class="modal alert fitted"/>'),i=$('<div class="body"/>').appendTo(e),s=$('<div class="buttons right"/>').appendTo(i),a=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Log out now")}).appendTo(s),n=$("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Keep me logged in")}).appendTo(s);this.$logoutWarningPara=$("<p/>").prependTo(i),this.logoutWarningModal=new Garnish.Modal(e,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark logoutwarningmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){n.trigger("focus")}),100)}}),this.addListener(a,"activate","logout"),this.addListener(e,"submit","renewSession")}t?this.logoutWarningModal.quickShow():this.logoutWarningModal.show(),this.updateLogoutWarningMessage(),this.decrementLogoutWarningInterval=setInterval(this.decrementLogoutWarning.bind(this),1e3)},updateLogoutWarningMessage:function(){this.$logoutWarningPara.text(Craft.t("app","Your session will expire in {time}.",{time:Craft.secondsToHumanTimeDuration(this.remainingSessionTime)})),this.logoutWarningModal.updateSizeAndPosition()},decrementLogoutWarning:function(){this.remainingSessionTime>0&&(this.remainingSessionTime--,this.updateLogoutWarningMessage()),0===this.remainingSessionTime&&clearInterval(this.decrementLogoutWarningInterval)},hideLogoutWarningModal:function(t){this.showingLogoutWarningModal=!1,this.logoutWarningModal&&(t?this.logoutWarningModal.quickHide():this.logoutWarningModal.hide(),this.decrementLogoutWarningInterval&&clearInterval(this.decrementLogoutWarningInterval))},showLoginModal:function(){var t,e=this;if(this.showingLogoutWarningModal?(this.hideLogoutWarningModal(!0),t=!0):t=!1,this.showingLoginModal=!0,!this.loginModal){var i=$('<form id="loginmodal" class="modal alert fitted"/>'),s=$('<div class="body"><h2>'+Craft.t("app","Your session has ended.")+"</h2><p>"+Craft.t("app","Enter your password to log back in.")+"</p></div>").appendTo(i),a=$('<div class="inputcontainer">').appendTo(s),n=$('<div class="flex"/>').appendTo(a),r=$('<div class="flex-grow"/>').appendTo(n),o=$("<div/>").appendTo(n),l=$('<div class="passwordwrapper"/>').appendTo(r);this.$passwordInput=$('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'"/>').appendTo(l),this.$passwordSpinner=$('<div class="spinner hidden"/>').appendTo(a),this.$loginBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Login")}).appendTo(o),this.$loginErrorPara=$('<p class="error"/>').appendTo(s),this.loginModal=new Garnish.Modal(i,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark loginmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){e.$passwordInput.trigger("focus")}),100)},onFadeOut:function(){e.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(t){e.$passwordInput=t}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(i,"submit","login")}t?this.loginModal.quickShow():this.loginModal.show()},hideLoginModal:function(t){this.showingLoginModal=!1,this.loginModal&&(t?this.loginModal.quickHide():this.loginModal.hide())},logout:function(){$.get({url:Craft.getActionUrl("users/logout"),dataType:"json",success:function(){Craft.redirectTo("")}})},renewSession:function(t){t&&t.preventDefault(),this.hideLogoutWarningModal(),this.checkRemainingSessionTime(!0)},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$loginBtn.removeClass("disabled"),!0):(this.$loginBtn.addClass("disabled"),!1)},login:function(t){t&&t.preventDefault(),this.validatePassword()&&(this.$passwordSpinner.removeClass("hidden"),this.clearLoginError(),void 0!==Craft.csrfTokenValue?(this.submitLoginIfLoggedOut=!0,this.checkRemainingSessionTime()):this.submitLogin())},submitLogin:function(){var t=this,e={loginName:Craft.username,password:this.$passwordInput.val()};Craft.postActionRequest("users/login",e,(function(e,i){t.$passwordSpinner.addClass("hidden"),"success"===i?e.success?(t.hideLoginModal(),t.checkRemainingSessionTime()):(t.showLoginError(e.error),Garnish.shake(t.loginModal.$container),Garnish.isMobileBrowser(!0)||t.$passwordInput.trigger("focus")):t.showLoginError()}))},showLoginError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$loginErrorPara.text(t),this.loginModal.updateSizeAndPosition()},clearLoginError:function(){this.showLoginError("")}},{checkInterval:60,minSafeSessionTime:120})},1504:function(){function t(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Craft.BaseElementEditor=Garnish.Base.extend({$element:null,elementId:null,siteId:null,deltaNames:null,initialData:null,$header:null,$toolbar:null,$tabContainer:null,$editLink:null,$sidebarBtn:null,$loadSpinner:null,$body:null,$fieldsContainer:null,$sidebar:null,$footer:null,$siteSelectContainer:null,$siteSelect:null,$siteSpinner:null,$cancelBtn:null,$saveBtn:null,$saveSpinner:null,slideout:null,tabManager:null,showingSidebar:!1,cancelToken:null,ignoreFailedRequest:!1,initialDeltaValues:null,init:function(t,e){var i=this;void 0===e&&$.isPlainObject(t)&&(e=t,t=null),this.$element=$(t),this.setSettings(e,Craft.BaseElementEditor.defaults),this.$header=$("<header/>",{class:"pane-header"}),this.$toolbar=$("<div/>",{class:"ee-toolbar"}).appendTo(this.$header),this.$tabContainer=$("<div/>",{class:"pane-tabs"}).appendTo(this.$toolbar),this.$loadSpinner=$("<div/>",{class:"spinner",title:Craft.t("app","Loading"),"aria-label":Craft.t("app","Loading")}).appendTo(this.$toolbar),this.$editLink=$("<a/>",{target:"_blank",class:"btn hidden",title:Craft.t("app","Open the full edit page in a new tab"),"aria-label":Craft.t("app","Open the full edit page in a new tab"),"data-icon":"external"}).appendTo(this.$toolbar),this.$sidebarBtn=$("<button/>",{type:"button",class:"btn hidden sidebar-btn",title:Craft.t("app","Show sidebar"),"aria-label":Craft.t("app","Show sidebar"),"data-icon":"sidebar-".concat(Garnish.ltr?"right":"left")}).appendTo(this.$toolbar),this.addListener(this.$sidebarBtn,"click",(function(t){t.preventDefault(),i.showingSidebar?i.hideSidebar():i.showSidebar()})),this.$body=$("<div/>",{class:"ee-body"}),this.$fieldsContainer=$("<div/>",{class:"fields"}).appendTo(this.$body),this.$sidebar=$("<div/>",{class:"ee-sidebar hidden"}).appendTo(this.$body),Craft.trapFocusWithin(this.$sidebar),this.$footer=$("<div/>",{class:"ee-footer hidden"});var s=$("<div/>",{class:"ee-site-select"}).appendTo(this.$footer);this.$siteSelectContainer=$("<div/>",{class:"select hidden"}).appendTo(s),this.$siteSelect=$("<select/>").appendTo(this.$siteSelectContainer),this.$siteSpinner=$("<div/>",{class:"spinner hidden"}).appendTo(s),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footer),this.$saveBtn=$("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Save")}).appendTo(this.$footer),this.$saveSpinner=$("<div/>",{class:"spinner hidden"}).appendTo(this.$footer);var a=this.$header.add(this.$body).add(this.$footer);this.slideout=new Craft.Slideout(a,{containerElement:"form",containerAttributes:{action:"",method:"post",novalidate:"",class:"element-editor"},closeOnEsc:!1,closeOnShadeClick:!1}),this.slideout.$container.data("elementEditor",this),this.slideout.on("beforeClose",(function(){i.hideSidebar()})),this.slideout.on("close",(function(){i.trigger("closeSlideout"),i.destroy()})),Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0},(function(){i.saveElement()})),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){i.maybeCloseSlideout()})),this.addListener(this.$cancelBtn,"click",(function(){i.maybeCloseSlideout()})),this.addListener(this.slideout.$shade,"click",(function(){i.maybeCloseSlideout()})),this.addListener(this.slideout.$container,"click",(function(t){var e=$(event.target);!i.showingSidebar||e.closest(i.$sidebarBtn).length||e.closest(i.$sidebar).length||i.hideSidebar()})),this.addListener(this.slideout.$container,"submit",(function(t){t.preventDefault(),i.saveElement()})),this.addListener(this.$siteSelect,"change","switchSite"),this.load().then((function(){i.onShowHud(),i.onCreateForm(i.$body)}))},setElementAttribute:function(t,e){this.settings.attributes||(this.settings.attributes={}),null===e?delete this.settings.attributes[t]:this.settings.attributes[t]=e},getBaseData:function(){var t=$.extend({},this.settings.params);return this.settings.siteId?t.siteId=this.settings.siteId:this.$element&&this.$element.data("site-id")&&(t.siteId=this.$element.data("site-id")),this.settings.elementId?t.elementId=this.settings.elementId:this.$element&&this.$element.data("id")&&(t.elementId=this.$element.data("id")),this.settings.elementType&&(t.elementType=this.settings.elementType),this.settings.attributes&&(t.attributes=this.settings.attributes),this.settings.prevalidate&&(t.prevalidate=1),t},load:function(t,e){var i=this;return new Promise((function(s,a){i.trigger("beforeLoad"),i.trigger("beginLoading"),i.showLoadSpinner(),i.onBeginLoading(),i.cancelToken&&(i.ignoreFailedRequest=!0,i.cancelToken.cancel()),i.cancelToken=axios.CancelToken.source(),Craft.sendActionRequest("POST","elements/get-editor-html",{cancelToken:i.cancelToken.token,data:$.extend(i.getBaseData(),t||{},{includeSites:Craft.isMultiSite&&i.settings.showSiteSwitcher})}).then((function(t){i.hideLoadSpinner(),i.trigger("load"),i.trigger("endLoading"),i.onEndLoading(),i.cancelToken=null,null===i.initialDeltaValues&&(i.initialDeltaValues=t.data.initialDeltaValues),i.updateForm(t.data,e),i.cancelToken=null,s()})).catch((function(t){i.hideLoadSpinner(),i.onEndLoading(),i.cancelToken=null,i.ignoreFailedRequest||(Craft.cp.displayError(),a(t)),i.ignoreFailedRequest=!1}))}))},showHeader:function(){this.$header.removeClass("hidden")},hideHeader:function(){this.$header.addClass("hidden")},showLoadSpinner:function(){this.showHeader(),this.$loadSpinner.removeClass("hidden")},hideLoadSpinner:function(){this.$loadSpinner.addClass("hidden")},switchSite:function(){var t=this;if(!this.isDirty()||confirm(Craft.t("app","Switching sites will lose unsaved changes. Are you sure you want to switch sites?"))){var e=this.$siteSelect.val();e!=this.siteId&&(this.$siteSpinner.removeClass("hidden"),this.load({siteId:e}).then((function(){t.$siteSpinner.addClass("hidden")})).catch((function(){t.$siteSpinner.addClass("hidden"),t.$siteSelect.val(t.siteId)})))}else this.$siteSelect.val(this.siteId)},updateForm:function(t,e){var i=this;this.tabManager&&(this.$tabContainer.html(""),this.tabManager.destroy(),this.tabManager=null),e=!1!==e,this.siteId=t.siteId,this.$fieldsContainer.html(t.fieldHtml);var s=!1;if(t.sites&&t.sites.length>1){s=!0,this.$siteSelectContainer.removeClass("hidden"),this.$siteSelect.html("");for(var a=0;a<t.sites.length;a++){var n=t.sites[a],r=$("<option/>",{value:n.id,text:n.name}).appendTo(this.$siteSelect);n.id==t.siteId&&r.attr("selected","selected")}}else this.$siteSelectContainer.addClass("hidden");t.tabHtml&&(s=!0,this.$tabContainer.replaceWith(this.$tabContainer=$(t.tabHtml)),this.tabManager=new Craft.Tabs(this.$tabContainer),this.tabManager.on("deselectTab",(function(t){$(t.$tab.attr("href")).addClass("hidden")})),this.tabManager.on("selectTab",(function(t){$(t.$tab.attr("href")).removeClass("hidden"),Garnish.$win.trigger("resize"),i.$body.trigger("scroll")}))),t.editUrl?(s=!0,this.$editLink.removeClass("hidden").attr("href",t.editUrl)):this.$editLink&&this.$editLink.addClass("hidden"),t.sidebarHtml?(s=!0,this.$sidebarBtn.removeClass("hidden"),this.$sidebar.html(t.sidebarHtml),Craft.initUiElements(this.$sidebar),(new Craft.ElementThumbLoader).load($(this.$sidebar)),this.$sidebar.find("a").each((function(){this.hostname.length&&void 0===$(this).attr("target")&&$(this).attr("target","_blank")}))):this.$sidebarBtn&&(this.$sidebarBtn.addClass("hidden"),this.$sidebar.addClass("hidden")),s?this.showHeader():this.hideHeader(),this.$footer.removeClass("hidden"),e&&(this.deltaNames=t.deltaNames),Garnish.requestAnimationFrame((function(){Craft.appendHeadHtml(t.headHtml),Craft.appendFootHtml(t.footHtml),Craft.initUiElements(i.$fieldsContainer),e&&(i.initialData=i.slideout.$container.serialize()),Garnish.isMobileBrowser()||Craft.setFocusWithin(i.$fieldsContainer),i.trigger("updateForm")}))},showSidebar:function(){var t=this;this.showingSidebar||(this.$body.scrollTop(0).addClass("no-scroll"),this.$sidebar.off("transitionend.element-editor").css(this._closedSidebarStyles()).removeClass("hidden"),this.$sidebar[0].offsetWidth,this.$sidebar.css(this._openedSidebarStyles()),Garnish.isMobileBrowser()||this.$sidebar.one("transitionend.element-editor",(function(){Craft.setFocusWithin(t.$sidebar)})),this.$sidebarBtn.addClass("active").attr({title:Craft.t("app","Hide sidebar"),"aria-label":Craft.t("app","Hide sidebar")}),Garnish.$win.trigger("resize"),this.$sidebar.trigger("scroll"),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.hideSidebar()})),this.showingSidebar=!0)},hideSidebar:function(){var t=this;this.showingSidebar&&(this.$body.removeClass("no-scroll"),this.$sidebar.off("transitionend.element-editor").css(this._closedSidebarStyles()).one("transitionend.element-editor",(function(){t.$sidebar.addClass("hidden")})),this.$sidebarBtn.removeClass("active").attr({title:Craft.t("app","Show sidebar"),"aria-label":Craft.t("app","Show sidebar")}),Garnish.uiLayerManager.removeLayer(),this.showingSidebar=!1)},_openedSidebarStyles:function(){return t({},Garnish.ltr?"right":"left","0")},_closedSidebarStyles:function(){return t({},Garnish.ltr?"right":"left","-350px")},saveElement:function(){var t=this,e=this.settings.validators;if($.isArray(e))for(var i=0;i<e.length;i++)if($.isFunction(e[i])&&!e[i].call())return!1;this.$saveSpinner.removeClass("hidden");var s=$.param(this.getBaseData())+"&"+this.slideout.$container.serialize();s=Craft.findDeltaData(this.initialData,s,this.deltaNames,null,this.initialDeltaValues),Craft.postActionRequest("elements/save-element",s,(function(e,i){if(t.$saveSpinner.addClass("hidden"),"success"===i)if(e.success){if(t.$element&&t.siteId==t.$element.data("site-id")){var s=t.$element.find(".title"),a=s.find("a");a.length&&e.cpEditUrl?(a.attr("href",e.cpEditUrl),a.text(e.newTitle)):s.text(e.newTitle)}t.settings.elementType&&Craft.elementTypeNames[t.settings.elementType]&&Craft.cp.displayNotice(Craft.t("app","{type} saved.",{type:Craft.elementTypeNames[t.settings.elementType][0]})),t.closeSlideout(),t.trigger("saveElement",{response:e}),t.onSaveElement(e),t.settings.onSaveElement(e),Craft.cp.runQueue()}else t.updateForm(e,!1),Garnish.shake(t.slideout.$container)}))},isDirty:function(){return null!==this.initialData&&this.slideout.$container.serialize()!==this.initialData},maybeCloseSlideout:function(){this.slideout.isOpen&&(this.isDirty()&&!confirm(Craft.t("app","Are you sure you want to close the editor? Any changes will be lost."))||this.closeSlideout())},closeSlideout:function(){this.slideout.close(),this.onHideHud(),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel())},destroy:function(){this.slideout.destroy(),delete this.slideout,this.base()},loadHud:function(){this.load()},maybeCloseHud:function(){this.maybeCloseSlideout()},closeHud:function(){this.closeSlideout()},reloadForm:function(t,e){this.load(t).then((function(){e("success")})).catch((function(){e("error")}))},onBeginLoading:function(){this.settings.onBeginLoading()},onEndLoading:function(){this.settings.onEndLoading()},onSaveElement:function(t){},onCreateForm:function(t){this.settings.onCreateForm(t)},onShowHud:function(){this.trigger("showHud"),this.settings.onShowHud()},onHideHud:function(){this.trigger("hideHud"),this.settings.onHideHud()}},{defaults:{showSiteSwitcher:!0,elementId:null,elementType:null,siteId:null,attributes:null,params:null,prevalidate:!1,elementIndex:null,onSaveElement:$.noop,validators:[],onShowHud:$.noop,onHideHud:$.noop,onBeginLoading:$.noop,onEndLoading:$.noop,onCreateForm:$.noop}})},5774:function(){function t(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(t,i)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}Craft.BaseElementIndex=Garnish.Base.extend({initialized:!1,elementType:null,instanceState:null,sourceStates:null,sourceStatesStorageKey:null,searchTimeout:null,sourceSelect:null,$container:null,$main:null,isIndexBusy:!1,$sidebar:null,showingSidebar:null,sourceKey:null,sourceViewModes:null,$source:null,sourcesByKey:null,$visibleSources:null,$customizeSourcesBtn:null,customizeSourcesModal:null,$toolbar:null,toolbarOffset:null,$search:null,searching:!1,searchText:null,trashed:!1,drafts:!1,$clearSearchBtn:null,$statusMenuBtn:null,$statusMenuContainer:null,statusMenu:null,status:null,$siteMenuBtn:null,siteMenu:null,siteId:null,$sortMenuBtn:null,sortMenu:null,$sortAttributesList:null,$sortDirectionsList:null,$scoreSortAttribute:null,$structureSortAttribute:null,$elements:null,$viewModeBtnContainer:null,viewModeBtns:null,viewMode:null,view:null,_autoSelectElements:null,$countSpinner:null,$countContainer:null,page:1,resultSet:null,totalResults:null,$exportBtn:null,actions:null,actionsHeadHtml:null,actionsFootHtml:null,$selectAllContainer:null,$selectAllCheckbox:null,showingActionTriggers:!1,exporters:null,exportersByType:null,_$detachedToolbarItems:null,_$triggers:null,_ignoreFailedRequest:!1,_cancelToken:null,init:function(t,e,i){var s=this;if(this.elementType=t,this.$container=e,this.setSettings(i,Craft.BaseElementIndex.defaults),this.instanceState=this.getDefaultInstanceState(),this.sourceStates={},this.settings.storageKey&&$.extend(this.instanceState,Craft.getLocalStorage(this.settings.storageKey),{}),this.sourceStatesStorageKey="BaseElementIndex."+this.elementType+"."+this.settings.context,$.extend(this.sourceStates,Craft.getLocalStorage(this.sourceStatesStorageKey,{})),this.$main=this.$container.find(".main"),this.$toolbar=this.$container.find(this.settings.toolbarSelector),this.$statusMenuBtn=this.$toolbar.find(".statusmenubtn:first"),this.$statusMenuContainer=this.$statusMenuBtn.parent(),this.$siteMenuBtn=this.$container.find(".sitemenubtn:first"),this.$sortMenuBtn=this.$toolbar.find(".sortmenubtn:first"),this.$search=this.$toolbar.find(".search:first input:first"),this.$clearSearchBtn=this.$toolbar.find(".search:first > .clear"),this.$sidebar=this.$container.find(".sidebar:first"),this.$customizeSourcesBtn=this.$sidebar.find(".customize-sources"),this.$elements=this.$container.find(".elements:first"),this.$countSpinner=this.$container.find("#count-spinner"),this.$countContainer=this.$container.find("#count-container"),this.$exportBtn=this.$container.find("#export-btn"),this.settings.hideSidebar&&(this.$sidebar.hide(),$(".body, .content",this.$container).removeClass("has-sidebar")),this.initSources()){if(this.$customizeSourcesBtn.length&&this.addListener(this.$customizeSourcesBtn,"click","createCustomizeSourcesModal"),this.$statusMenuBtn.length&&(this.statusMenu=this.$statusMenuBtn.menubtn().data("menubtn").menu,this.statusMenu.on("optionselect",this._handleStatusChange.bind(this))),this.$siteMenuBtn.length){this.siteMenu=this.$siteMenuBtn.menubtn().data("menubtn").menu;var a=this.siteMenu.$options.filter(".sel:first");if(a.length||(a=this.siteMenu.$options.first()),a.length?this._setSite(a.data("site-id")):this.settings.criteria={id:"0"},this.siteMenu.on("optionselect",this._handleSiteChange.bind(this)),this.siteId){var n=this.settings.defaultSiteId||Craft.cp.getSiteId();if(n&&n!=this.siteId){var r=this.siteMenu.$options.filter('[data-site-id="'+n+'"]:first');r.length&&r.trigger("click")}}}else this.settings.criteria&&this.settings.criteria.siteId&&"*"!==this.settings.criteria.siteId?this._setSite(this.settings.criteria.siteId):this._setSite(Craft.siteId);this.settings.criteria&&this.settings.criteria.siteId&&delete this.settings.criteria.siteId,this.addListener(this.$search,"input",(function(){!s.searching&&s.$search.val()?s.startSearching():s.searching&&!s.$search.val()&&s.stopSearching(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.searchTimeout=setTimeout(s.updateElementsIfSearchTextChanged.bind(s),500)})),this.addListener(this.$search,"keypress",(function(t){t.keyCode===Garnish.RETURN_KEY&&(t.preventDefault(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.updateElementsIfSearchTextChanged())})),this.addListener(this.$clearSearchBtn,"click",(function(){s.clearSearch(!0),Garnish.isMobileBrowser(!0)||s.$search.trigger("focus")})),Garnish.isMobileBrowser(!0)||this.$search.trigger("focus"),this.$sortMenuBtn.length&&(this.sortMenu=this.$sortMenuBtn.menubtn().data("menubtn").menu,this.$sortAttributesList=this.sortMenu.$container.children(".sort-attributes"),this.$sortDirectionsList=this.sortMenu.$container.children(".sort-directions"),this.sortMenu.on("optionselect",this._handleSortChange.bind(this))),this.addListener(this.$exportBtn,"click","_showExportHud"),this.initialized=!0,this.afterInit(),this.selectDefaultSource(),this.setPage(Craft.pageNum),this.updateElements(!0)}},afterInit:function(){this.onAfterInit()},_createCancelToken:function(){return this._cancelToken=axios.CancelToken.source(),this._cancelToken.token},_cancelRequests:function(){var t=this;this._cancelToken&&(this._ignoreFailedRequest=!0,this._cancelToken.cancel(),Garnish.requestAnimationFrame((function(){t._ignoreFailedRequest=!1})))},getSourceContainer:function(){return this.$sidebar.find("nav > ul")},get $sources(){if(this.sourceSelect)return this.sourceSelect.$items},getSite:function(){var t=this;if(this.siteId)return Craft.sites.find((function(e){return e.id==t.siteId}))},initSources:function(){var t=this._getSourcesInList(this.getSourceContainer());if(0===t.length)return!1;this.sourceSelect||(this.sourceSelect=new Garnish.Select(this.$sidebar.find("nav"),{multi:!1,allowEmpty:!1,vertical:!0,onSelectionChange:this._handleSourceSelectionChange.bind(this)})),this.sourcesByKey={};for(var e=0;e<t.length;e++)this.initSource($(t[e]));return!0},selectDefaultSource:function(){var t,e=this.getDefaultSourceKey();return e&&(t=this.getSourceByKey(e),-1===this.$visibleSources.index(t)&&(t=null)),e&&t||(t=this.$visibleSources.first()),this.selectSource(t)},refreshSources:function(){var t=this;this.sourceSelect.removeAllItems(),this.setIndexBusy(),Craft.sendActionRequest("POST",this.settings.refreshSourcesAction,{data:{context:this.settings.context,elementType:this.elementType}}).then((function(e){t.setIndexAvailable(),t.getSourceContainer().replaceWith(e.data.html),t.initSources(),t.selectDefaultSource()})).catch((function(){t.setIndexAvailable(),t._ignoreFailedRequest||Craft.cp.displayError(Craft.t("app","A server error occurred."))}))},initSource:function(t){this.sourceSelect.addItems(t),this.initSourceToggle(t),this.sourcesByKey[t.data("key")]=t,t.data("hasNestedSources")&&-1!==this.instanceState.expandedSources.indexOf(t.data("key"))&&this._expandSource(t)},initSourceToggle:function(t){this.deinitSourceToggle(t);var e=this._getSourceToggle(t);e.length?(this.addListener(t,"dblclick","_handleSourceDblClick"),this.addListener(e,"click","_handleSourceToggleClick"),t.data("hasNestedSources",!0)):t.data("hasNestedSources",!1)},deinitSource:function(t){this.sourceSelect.removeItems(t),this.deinitSourceToggle(t),delete this.sourcesByKey[t.data("key")]},deinitSourceToggle:function(t){t.data("hasNestedSources")&&(this.removeListener(t,"dblclick"),this.removeListener(this._getSourceToggle(t),"click")),t.removeData("hasNestedSources")},getDefaultInstanceState:function(){return{selectedSource:null,expandedSources:[]}},getDefaultSourceKey:function(){if(this.settings.defaultSource){for(var t=this.settings.defaultSource.split("/"),e="",i=0;i<t.length;i++){e+=t[i];var s=this.getSourceByKey(e);if(!s)return this.instanceState.selectedSource;this._expandSource(s),e+="/"}return this._setSite(this.siteId),this.settings.defaultSource}return this.instanceState.selectedSource},getDefaultExpandedSources:function(){return this.instanceState.expandedSources},startSearching:function(){this.$clearSearchBtn.removeClass("hidden"),this.$scoreSortAttribute||(this.$scoreSortAttribute=$('<li><a data-attr="score">'+Craft.t("app","Score")+"</a></li>"),this.sortMenu.addOptions(this.$scoreSortAttribute.children())),this.$scoreSortAttribute.prependTo(this.$sortAttributesList),this.searching=!0,this._updateStructureSortOption(),this.setSortAttribute("score")},clearSearch:function(t){this.searching&&(this.$search.val(""),this.searchTimeout&&clearTimeout(this.searchTimeout),this.stopSearching(),t?this.updateElementsIfSearchTextChanged():this.searchText=null)},stopSearching:function(){this.$clearSearchBtn.addClass("hidden"),this.$scoreSortAttribute.detach(),this.searching=!1,this._updateStructureSortOption()},setInstanceState:function(t,e){"object"===i(t)?$.extend(this.instanceState,t):this.instanceState[t]=e,this.storeInstanceState()},storeInstanceState:function(){this.settings.storageKey&&Craft.setLocalStorage(this.settings.storageKey,this.instanceState)},getSourceState:function(t,e,i){return void 0===this.sourceStates[t]&&(this.sourceStates[t]={}),void 0===e?this.sourceStates[t]:void 0!==this.sourceStates[t][e]?this.sourceStates[t][e]:void 0!==i?i:null},getSelectedSourceState:function(t,e){return this.getSourceState(this.instanceState.selectedSource,t,e)},setSelecetedSourceState:function(t,e){var s=this.getSelectedSourceState();"object"===i(t)?$.extend(s,t):s[t]=e,this.sourceStates[this.instanceState.selectedSource]=s,Craft.setLocalStorage(this.sourceStatesStorageKey,this.sourceStates)},storeSortAttributeAndDirection:function(){var e=this.getSelectedSortAttribute();if("score"!==e){var i=[];if(e){var s=[e],a=this.getSelectedSourceState("order");a&&a!==e&&(i.push([a,this.getSelectedSourceState("sort")]),s.push(a));for(var n=this.getSelectedSourceState("orderHistory",[]),r=0;r<n.length;r++){var o=t(n[r],1)[0];if(!o||s.includes(o))break;i.push(n[r]),s.push(o)}}this.setSelecetedSourceState({order:e,sort:this.getSelectedSortDirection(),orderHistory:i})}},setPage:function(t){if("index"===this.settings.context){t=Math.max(t,1),this.page=t;var e=document.location.href.replace(/\?.*$/,"").replace(new RegExp("/"+Craft.pageTrigger.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\d+$"),"").replace(/\/+$/,"");1!==this.page&&("?"!==Craft.pageTrigger[0]&&(e+="/"),e+=Craft.pageTrigger+this.page),history.replaceState({},"",e)}},_resetCount:function(){this.resultSet=null,this.totalResults=null},getViewParams:function(){var t={siteId:this.siteId,search:this.searchText,offset:this.settings.batchSize*(this.page-1),limit:this.settings.batchSize};this.settings.canHaveDrafts&&(this.drafts||"index"===this.settings.context&&!this.status)&&(t.drafts=this.drafts||null,t.savedDraftsOnly=!0,this.drafts||(t.draftOf=!1)),this.trashed&&(t.trashed=!0),Garnish.hasAttr(this.$source,"data-override-status")||(t.status=this.status),$.extend(t,this.settings.criteria);var e={context:this.settings.context,elementType:this.elementType,source:this.instanceState.selectedSource,criteria:t,disabledElementIds:this.settings.disabledElementIds,viewState:$.extend({},this.getSelectedSourceState()),paginated:this._isViewPaginated()?1:0};return e.viewState.order=this.getSelectedSortAttribute(),e.viewState.sort=this.getSelectedSortDirection(),"structure"===this.getSelectedSortAttribute()&&(void 0===this.instanceState.collapsedElementIds&&(this.instanceState.collapsedElementIds=[]),e.collapsedElementIds=this.instanceState.collapsedElementIds),this.trigger("registerViewParams",{params:e}),e},updateElements:function(t){var e=this;if(this.initialized){this._cancelRequests(),this.setIndexBusy(),this.view&&(this.view.destroy(),delete this.view),!0!==t&&(this.setPage(1),this._resetCount());var i=this.getViewParams();Craft.sendActionRequest("POST",this.settings.updateElementsAction,{data:i,cancelToken:this._createCancelToken()}).then((function(t){e.setIndexAvailable(),("index"===e.settings.context?Garnish.$scrollContainer:e.$main).scrollTop(0),e._updateView(i,t.data)})).catch((function(t){e.setIndexAvailable(),e._ignoreFailedRequest||Craft.cp.displayError(Craft.t("app","A server error occurred."))}))}},updateElementsIfSearchTextChanged:function(){this.searchText!==(this.searchText=this.searching?this.$search.val():null)&&this.updateElements()},showActionTriggers:function(){this.showingActionTriggers||(this.$toolbar.css("min-height",this.$toolbar.height()),this._$detachedToolbarItems=this.$toolbar.children(),this._$detachedToolbarItems.detach(),this._$triggers?this._$triggers.appendTo(this.$toolbar):this._createTriggers(),this.showingActionTriggers=!0)},submitAction:function(t,e){var i=this,s=this.view.getSelectedElementIds();if(0!==s.length&&("string"==typeof t&&(t=this._findAction(t)),!t.confirm||confirm(t.confirm))){this._cancelRequests();var a=this.getViewParams();e=e?Craft.expandPostArray(e):{};var n=$.extend(a,t.settings||{},e,{elementAction:t.type,elementIds:s});this.setIndexBusy(),this._autoSelectElements=s,t.download?(Craft.csrfTokenName&&(n[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl(this.settings.submitActionsAction),n).then((function(t){i.setIndexAvailable()})).catch((function(t){i.setIndexAvailable()}))):Craft.sendActionRequest("POST",this.settings.submitActionsAction,{data:n,cancelToken:this._createCancelToken()}).then((function(e){i.setIndexAvailable(),e.data.success?(i._resetCount(),i._updateView(a,e.data),void 0!==e.data.badgeCounts&&i._updateBadgeCounts(e.data.badgeCounts),e.data.message&&Craft.cp.displayNotice(e.data.message),i.afterAction(t,n)):Craft.cp.displayError(e.data.message)})).catch((function(){i.setIndexAvailable()}))}},_findAction:function(t){for(var e=0;e<this.actions.length;e++)if(this.actions[e].type===t)return this.actions[e];throw"Invalid element action: ".concat(t)},afterAction:function(t,e){Craft.cp.runQueue(),this.onAfterAction(t,e)},hideActionTriggers:function(){this.showingActionTriggers&&(this._$detachedToolbarItems.appendTo(this.$toolbar),this._$triggers.detach(),this.$toolbar.css("min-height",""),this.showingActionTriggers=!1)},updateActionTriggers:function(){if(this.actions){var t=this.view.getSelectedElements().length;0!==t?(t===this.view.getEnabledElements().length?(this.$selectAllCheckbox.removeClass("indeterminate"),this.$selectAllCheckbox.addClass("checked"),this.$selectAllContainer.attr("aria-checked","true")):(this.$selectAllCheckbox.addClass("indeterminate"),this.$selectAllCheckbox.removeClass("checked"),this.$selectAllContainer.attr("aria-checked","mixed")),this.showActionTriggers()):(this.$selectAllCheckbox.removeClass("indeterminate checked"),this.$selectAllContainer.attr("aria-checked","false"),this.hideActionTriggers())}},getSelectedElements:function(){return this.view?this.view.getSelectedElements():$()},getSelectedElementIds:function(){return this.view?this.view.getSelectedElementIds():[]},setStatus:function(t){var e=this.statusMenu.$options.filter('a[data-status="'+t+'"]:first');e.length&&this.statusMenu.selectOption(e[0])},getSortAttributeOption:function(t){return this.$sortAttributesList.find('a[data-attr="'+t+'"]:first')},getSelectedSortAttribute:function(){return this.$sortAttributesList.find("a.sel:first").data("attr")},setSortAttribute:function(t){var e=this.getSortAttributeOption(t);if(e.length){this.$sortAttributesList.find("a.sel").removeClass("sel"),e.addClass("sel");var i=e.text();this.$sortMenuBtn.attr("title",Craft.t("app","Sort by {attribute}",{attribute:i})),this.$sortMenuBtn.text(i),"score"===t?this.setSortDirection("desc"):this.setSortDirection(e.data("default-dir")||"asc"),"structure"===t?this.$sortDirectionsList.find("a").addClass("disabled"):this.$sortDirectionsList.find("a").removeClass("disabled")}},getSortDirectionOption:function(t){return this.$sortDirectionsList.find("a[data-dir="+t+"]:first")},getSelectedSortDirection:function(){return this.$sortDirectionsList.find("a.sel:first").data("dir")},getSelectedViewMode:function(){return this.getSelectedSourceState("mode")||"table"},setSortDirection:function(t){"desc"!==t&&(t="asc"),this.$sortMenuBtn.attr("data-icon",t),this.$sortDirectionsList.find("a.sel").removeClass("sel"),this.getSortDirectionOption(t).addClass("sel")},getSourceByKey:function(t){return void 0===this.sourcesByKey[t]?null:this.sourcesByKey[t]},selectSource:function(t){if(!t||!t.length)return!1;if(this.$source&&this.$source[0]&&this.$source[0]===t[0]&&t.data("key")===this.sourceKey)return!1;this.hideActionTriggers(),this.$source=t,this.sourceKey=t.data("key"),this.setInstanceState("selectedSource",this.sourceKey),this.sourceSelect.selectItem(t),Craft.cp.updateSidebarMenuLabel(),this.searching&&(this.searchText=null,this.$search.val(""),this.stopSearching()),this.$sortAttributesList.children("li[data-extra]").remove();var e=this.$source.closest("nav > ul > li").children("a").data("sort-options");if(e)for(var i=0;i<e.length;i++){var s=$("<li/>",{"data-extra":!0}).append($("<a/>",{text:e[i][0],"data-attr":e[i][1]})).appendTo(this.$sortAttributesList);this.sortMenu.addOptions(s.children())}if(Garnish.hasAttr(this.$source,"data-has-structure")?(this.$structureSortAttribute||(this.$structureSortAttribute=$('<li><a data-attr="structure">'+Craft.t("app","Structure")+"</a></li>"),this.sortMenu.addOptions(this.$structureSortAttribute.children())),this.$structureSortAttribute.prependTo(this.$sortAttributesList)):this.$structureSortAttribute&&this.$structureSortAttribute.removeClass("sel").detach(),this.setStoredSortOptionsForSource(),this.$statusMenuBtn.length&&(Garnish.hasAttr(this.$source,"data-override-status")?this.$statusMenuContainer.addClass("hidden"):this.$statusMenuContainer.removeClass("hidden"),this.trashed)){var a=this.statusMenu.$options.first();this.setStatus(a.data("status"))}if(this.$viewModeBtnContainer&&this.$viewModeBtnContainer.remove(),this.viewModeBtns={},this.viewMode=null,this.sourceViewModes=this.getViewModesForSource(),this.sourceViewModes.length>1){this.$viewModeBtnContainer=$('<div class="btngroup"/>').appendTo(this.$toolbar);for(var n=0;n<this.sourceViewModes.length;n++){var r=this.sourceViewModes[n],o=$("<button/>",{type:"button",class:"btn"+(void 0!==r.className?" ".concat(r.className):""),"data-view":r.mode,"data-icon":r.icon,"aria-label":r.title,title:r.title}).appendTo(this.$viewModeBtnContainer);this.viewModeBtns[r.mode]=o,this.addListener(o,"click",{mode:r.mode},(function(t){this.selectViewMode(t.data.mode),this.updateElements()}))}}var l=this.getSelectedViewMode();return l&&this.doesSourceHaveViewMode(l)||(l=this.viewMode&&this.doesSourceHaveViewMode(this.viewMode)?this.viewMode:this.sourceViewModes[0].mode),this.selectViewMode(l),this.onSelectSource(),!0},selectSourceByKey:function(t){var e=this.getSourceByKey(t);return!!e&&this.selectSource(e)},setStoredSortOptionsForSource:function(){var t=this.getSelectedSourceState("order"),e=this.getSelectedSourceState("sort");t&&e||(t=this.getDefaultSort(),Garnish.isArray(t)&&(e=t[1],t=t[0])),"asc"!==e&&"desc"!==e&&(e="asc"),this.setSortAttribute(t),this.setSortDirection(e)},getDefaultSort:function(){return this.$source&&Garnish.hasAttr(this.$source,"data-default-sort")?this.$source.attr("data-default-sort").split(":"):[this.$sortAttributesList.find("a:first").data("attr"),"asc"]},getViewModesForSource:function(){var t=[{mode:"table",title:Craft.t("app","Display in a table"),icon:"list"}];return this.$source&&Garnish.hasAttr(this.$source,"data-has-thumbs")&&t.push({mode:"thumbs",title:Craft.t("app","Display as thumbnails"),icon:"grid"}),t},doesSourceHaveViewMode:function(t){for(var e=0;e<this.sourceViewModes.length;e++)if(this.sourceViewModes[e].mode===t)return!0;return!1},selectViewMode:function(t,e){e||this.doesSourceHaveViewMode(t)||(t=this.sourceViewModes[0].mode),t!==this.viewMode&&(this.viewMode&&void 0!==this.viewModeBtns[this.viewMode]&&this.viewModeBtns[this.viewMode].removeClass("active"),this.viewMode=t,this.setSelecetedSourceState("mode",this.viewMode),void 0!==this.viewModeBtns[this.viewMode]&&this.viewModeBtns[this.viewMode].addClass("active"))},createView:function(t,e){return new(this.getViewClass(t))(this,this.$elements,e)},getViewClass:function(t){switch(t){case"table":return Craft.TableElementIndexView;case"thumbs":return Craft.ThumbsElementIndexView;default:throw'View mode "'.concat(t,'" not supported.')}},rememberDisabledElementId:function(t){-1===$.inArray(t,this.settings.disabledElementIds)&&this.settings.disabledElementIds.push(t)},forgetDisabledElementId:function(t){var e=$.inArray(t,this.settings.disabledElementIds);-1!==e&&this.settings.disabledElementIds.splice(e,1)},enableElements:function(t){t.removeClass("disabled").parents(".disabled").removeClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.forgetDisabledElementId(i)}this.onEnableElements(t)},disableElements:function(t){t.removeClass("sel").addClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.rememberDisabledElementId(i)}this.onDisableElements(t)},getElementById:function(t){return this.view.getElementById(t)},enableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.enableElements(s):this.forgetDisabledElementId(i)}},disableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.disableElements(s):this.rememberDisabledElementId(i)}},selectElementAfterUpdate:function(t){null===this._autoSelectElements&&(this._autoSelectElements=[]),this._autoSelectElements.push(t)},addButton:function(t){this.getButtonContainer().append(t)},isShowingSidebar:function(){return null===this.showingSidebar&&(this.showingSidebar=this.$sidebar.length&&!this.$sidebar.hasClass("hidden")),this.showingSidebar},getButtonContainer:function(){if(this.settings.buttonContainer)return $(this.settings.buttonContainer);var t=$("#action-button");return t.length||(t=$('<div id="action-button"/>').appendTo($("#header"))),t},setIndexBusy:function(){this.$elements.addClass("busy"),this.isIndexBusy=!0},setIndexAvailable:function(){this.$elements.removeClass("busy"),this.isIndexBusy=!1},createCustomizeSourcesModal:function(){var t=new Craft.CustomizeSourcesModal(this,{onHide:function(){t.destroy()}});return t},disable:function(){this.sourceSelect&&this.sourceSelect.disable(),this.view&&this.view.disable(),this.base()},enable:function(){this.sourceSelect&&this.sourceSelect.enable(),this.view&&this.view.enable(),this.base()},onAfterInit:function(){this.settings.onAfterInit(),this.trigger("afterInit")},onSelectSource:function(){this.settings.onSelectSource(this.sourceKey),this.trigger("selectSource",{sourceKey:this.sourceKey})},onSelectSite:function(){this.settings.onSelectSite(this.siteId),this.trigger("selectSite",{siteId:this.siteId})},onUpdateElements:function(){this.settings.onUpdateElements(),this.trigger("updateElements")},onSelectionChange:function(){this.settings.onSelectionChange(),this.trigger("selectionChange")},onEnableElements:function(t){this.settings.onEnableElements(t),this.trigger("enableElements",{elements:t})},onDisableElements:function(t){this.settings.onDisableElements(t),this.trigger("disableElements",{elements:t})},onAfterAction:function(t,e){this.settings.onAfterAction(t,e),this.trigger("afterAction",{action:t,params:e})},_handleSourceSelectionChange:function(){this.sourceSelect.totalSelected?this.selectSource(this.sourceSelect.$selectedItems)&&this.updateElements():this.sourceSelect.selectItem(this.$visibleSources.first())},_handleActionTriggerSubmit:function(t){t.preventDefault();var e=$(t.currentTarget);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"),Garnish.getPostData(e))},_handleMenuActionTriggerSubmit:function(t){var e=$(t.option);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"))},_handleStatusChange:function(t){this.statusMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$statusMenuBtn.html(e.html()),this.trashed=!1,this.drafts=!1,this.status=null,Garnish.hasAttr(e,"data-trashed")?this.trashed=!0:Garnish.hasAttr(e,"data-drafts")?this.drafts=!0:this.status=e.data("status"),this._updateStructureSortOption(),this.updateElements()},_handleSiteChange:function(t){this.siteMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$siteMenuBtn.html(e.html()),this._setSite(e.data("site-id")),this.onSelectSite()},_setSite:function(t){var e,i,s=null===this.siteId;this.siteId=t,this.$visibleSources=$();for(var a=!(s||this.$source&&this.$source.length),n=0;n<this.$sources.length;n++)void 0===(i=this.$sources.eq(n)).data("sites")||-1!==i.data("sites").toString().split(",").indexOf(t.toString())?(i.parent().removeClass("hidden"),this.$visibleSources=this.$visibleSources.add(i),e||(e=i)):(i.parent().addClass("hidden"),this.$source&&this.$source.get(0)==i.get(0)&&(a=!0));this.initialized&&a&&this.selectSource(e);var r,o=this.getSourceContainer().children(".heading");for(n=0;n<o.length;n++)0!==(r=o.eq(n)).nextUntil(".heading",":not(.hidden)").length?r.removeClass("hidden"):r.addClass("hidden");this.initialized&&("index"===this.settings.context&&Craft.cp.setSiteId(t),this.updateElements())},_handleSortChange:function(t){var e=$(t.selectedOption);e.hasClass("disabled")||e.hasClass("sel")||(e.parent().parent().is(this.$sortAttributesList)?this.setSortAttribute(e.data("attr")):this.setSortDirection(e.data("dir")),this.storeSortAttributeAndDirection(),this.updateElements())},_handleSelectionChange:function(){this.updateActionTriggers(),this.onSelectionChange()},_handleSourceDblClick:function(t){this._toggleSource($(t.currentTarget)),t.stopPropagation()},_handleSourceToggleClick:function(t){this._toggleSource($(t.currentTarget).prev("a")),t.stopPropagation()},_updateStructureSortOption:function(){var t=this.getSortAttributeOption("structure");if(t.length)if(this.trashed||this.drafts||this.searching){if(t.addClass("disabled"),"structure"===this.getSelectedSortAttribute()){var e=this.$sortAttributesList.find("a:not(.disabled):first");this.setSortAttribute(e.data("attr")),this.setSortDirection("asc")}}else t.removeClass("disabled"),this.setStoredSortOptionsForSource()},_getSourcesInList:function(t){return t.children("li").children("a")},_getChildSources:function(t){var e=t.siblings("ul");return this._getSourcesInList(e)},_getSourceToggle:function(t){return t.siblings(".toggle")},_toggleSource:function(t){t.parent("li").hasClass("expanded")?this._collapseSource(t):this._expandSource(t)},_expandSource:function(t){t.next(".toggle").attr({"aria-expanded":"true","aria-label":Craft.t("app","Hide nested sources")}),t.parent("li").addClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.initSource($(e[i])),this.$visibleSources&&(this.$visibleSources=this.$visibleSources.add(e[i]));var s=t.data("key");-1===this.instanceState.expandedSources.indexOf(s)&&(this.instanceState.expandedSources.push(s),this.storeInstanceState())},_collapseSource:function(t){t.next(".toggle").attr({"aria-expanded":"false","aria-label":Craft.t("app","Show nested sources")}),t.parent("li").removeClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.deinitSource($(e[i])),this.$visibleSources=this.$visibleSources.not(e[i]);var s=this.instanceState.expandedSources.indexOf(t.data("key"));-1!==s&&(this.instanceState.expandedSources.splice(s,1),this.storeInstanceState())},_isViewPaginated:function(){return"index"===this.settings.context&&"structure"!==this.getSelectedSortAttribute()},_updateView:function(t,e){var i=this;this.actions&&(this.hideActionTriggers(),this.actions=this.actionsHeadHtml=this.actionsFootHtml=this._$triggers=null),this.$countContainer.length&&(this.$countSpinner.removeClass("hidden"),this.$countContainer.html(""),this._countResults().then((function(t){i.$countSpinner.addClass("hidden");var e=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][2]:"element",s=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][3]:"elements";if(i._isViewPaginated()){var a=Math.min(i.settings.batchSize*(i.page-1)+1,t),n=Math.min(a+(i.settings.batchSize-1),t),r=Craft.t("app","{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}",{first:a,last:n,total:t,item:e,items:s}),o=$('<div class="flex pagination"/>').appendTo(i.$countContainer),l=Math.max(Math.ceil(t/i.settings.batchSize),1),h=$("<div/>",{class:"page-link prev-page"+(i.page>1?"":" disabled"),title:Craft.t("app","Previous Page")}).appendTo(o),d=$("<div/>",{class:"page-link next-page"+(i.page<l?"":" disabled"),title:Craft.t("app","Next Page")}).appendTo(o);$("<div/>",{class:"page-info",text:r}).appendTo(o),i.page>1&&i.addListener(h,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page-1),this.updateElements(!0)})),i.page<l&&i.addListener(d,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page+1),this.updateElements(!0)}))}else{var c=Craft.t("app","{total, number} {total, plural, =1{{item}} other{{items}}}",{total:t,item:e,items:s});i.$countContainer.text(c)}})).catch((function(){i.$countSpinner.addClass("hidden")}))),this.$elements.html(e.html),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),this.$selectAllContainer=this.$elements.find(".selectallcontainer:first"),e.actions&&e.actions.length?this.$selectAllContainer.length&&(this.actions=e.actions,this.actionsHeadHtml=e.actionsHeadHtml,this.actionsFootHtml=e.actionsFootHtml,this.$selectAllCheckbox=$('<div class="checkbox"/>').prependTo(this.$selectAllContainer),this.$selectAllContainer.attr({role:"checkbox",tabindex:"0","aria-checked":"false","aria-label":Craft.t("app","Select all")}),this.addListener(this.$selectAllContainer,"click",(function(){0===this.view.getSelectedElements().length?this.view.selectAllElements():this.view.deselectAllElements()})),this.addListener(this.$selectAllContainer,"keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(t.preventDefault(),$(t.currentTarget).trigger("click"))}))):(this.$selectAllContainer.siblings().length||this.$selectAllContainer.parent(".header").remove(),this.$selectAllContainer.remove()),this.exporters=e.exporters,this.exportersByType=Craft.index(this.exporters||[],(function(t){return t.type})),this.exporters&&this.exporters.length?this.$exportBtn.removeClass("hidden"):this.$exportBtn.addClass("hidden");var s=this.actions||this.settings.selectable;if(this.view=this.createView(this.getSelectedViewMode(),{context:this.settings.context,batchSize:"index"!==this.settings.context||"structure"===this.getSelectedSortAttribute()?this.settings.batchSize:null,params:t,selectable:s,multiSelect:this.actions||this.settings.multiSelect,checkboxMode:!!this.actions,onSelectionChange:this._handleSelectionChange.bind(this)}),this._autoSelectElements){if(s)for(var a=0;a<this._autoSelectElements.length;a++)this.view.selectElementById(this._autoSelectElements[a]);this._autoSelectElements=null}this.onUpdateElements()},_updateBadgeCounts:function(t){for(var e in t)if(t.hasOwnProperty(e)){var i=this.getSourceByKey(e);if(i){var s=i.children(".badge");null!==t[e]?(s.length||(s=$('<span class="badge"/>').appendTo(i)),s.text(t[e])):s&&s.remove()}}},_countResults:function(){var t=this;return new Promise((function(e,i){if(null!==t.totalResults)e(t.totalResults);else{var s=t.getViewParams();delete s.criteria.offset,delete s.criteria.limit,null===t.resultSet&&(t.resultSet=Math.floor(1e8*Math.random())),s.resultSet=t.resultSet,Craft.sendActionRequest("POST",t.settings.countElementsAction,{data:s,cancelToken:t._createCancelToken()}).then((function(s){s.data.resultSet==t.resultSet?(t.totalResults=s.data.count,e(s.data.count)):i()})).catch(i)}}))},_createTriggers:function(){var t,e,i=[],s=[],a=[];for(t=0;t<this.actions.length;t++){var n=this.actions[t];if(n.trigger){var r=$('<form id="'+Craft.formatInputId(n.type)+'-actiontrigger"/>').data("action",n).append(n.trigger);this.addListener(r,"submit","_handleActionTriggerSubmit"),i.push(r)}else n.destructive?a.push(n):s.push(n)}if(s.length||a.length){var o=$("<form/>");e=$("<button/>",{type:"button",class:"btn menubtn","data-icon":"settings",title:Craft.t("app","Actions")}).appendTo(o);var l=$('<ul class="menu"/>').appendTo(o),h=this._createMenuTriggerList(s,!1),d=this._createMenuTriggerList(a,!0);h&&h.appendTo(l),h&&d&&$("<hr/>").appendTo(l),d&&d.appendTo(l),i.push(o)}for(this._$triggers=$(),t=0;t<i.length;t++){var c=$("<div/>").append(i[t]);this._$triggers=this._$triggers.add(c)}this._$triggers.appendTo(this.$toolbar),Craft.appendHeadHtml(this.actionsHeadHtml),Craft.appendFootHtml(this.actionsFootHtml),Craft.initUiElements(this._$triggers),e&&e.data("menubtn").on("optionSelect",this._handleMenuActionTriggerSubmit.bind(this))},_showExportHud:function(){var t=this;this.$exportBtn.addClass("active");for(var e=$("<form/>",{class:"export-form"}),i=[],s=0;s<this.exporters.length;s++)i.push({label:this.exporters[s].name,value:this.exporters[s].type});var a=Craft.ui.createSelectField({label:Craft.t("app","Export Type"),options:i,class:"fullwidth"}).appendTo(e),n=Craft.ui.createSelectField({label:Craft.t("app","Format"),options:[{label:"CSV",value:"csv"},{label:"JSON",value:"json"},{label:"XML",value:"xml"}],class:"fullwidth"}).appendTo(e),r=a.find("select");this.addListener(r,"change",(function(){var e=r.val();t.exportersByType[e].formattable?n.removeClass("hidden"):n.addClass("hidden")})),r.trigger("change");var o=this.view.getSelectedElementIds();if(!o.length)var l=Craft.ui.createTextField({label:Craft.t("app","Limit"),placeholder:Craft.t("app","No limit"),type:"number",min:1}).appendTo(e);$("<button/>",{type:"submit",class:"btn submit fullwidth",text:Craft.t("app","Export")}).appendTo(e);var h=$("<div/>",{class:"spinner hidden"}).appendTo(e);new Garnish.HUD(this.$exportBtn,e).on("hide",(function(){t.$exportBtn.removeClass("active")}));var d=!1;this.addListener(e,"submit",(function(t){if(t.preventDefault(),!d){d=!0,h.removeClass("hidden");var e=this.getViewParams();if(delete e.criteria.offset,delete e.criteria.limit,delete e.collapsedElementIds,e.type=a.find("select").val(),e.format=n.find("select").val(),o.length)e.criteria.id=o;else{var i=parseInt(l.find("input").val());i&&!isNaN(i)&&(e.criteria.limit=i)}Craft.csrfTokenValue&&(e[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl("element-indexes/export"),e).then((function(){d=!1,h.addClass("hidden")})).catch((function(){d=!1,h.addClass("hidden"),this._ignoreFailedRequest||Craft.cp.displayError(Craft.t("app","A server error occurred."))}))}}))},_createMenuTriggerList:function(t,e){if(t&&t.length){for(var i=$("<ul/>"),s=0;s<t.length;s++)$("<li/>").append($("<a/>",{id:Craft.formatInputId(t[s].type)+"-actiontrigger",class:e?"error":null,data:{action:t[s]},text:t[s].name})).appendTo(i);return i}}},{defaults:{context:"index",modal:null,storageKey:null,criteria:null,batchSize:100,disabledElementIds:[],selectable:!1,multiSelect:!1,buttonContainer:null,hideSidebar:!1,toolbarSelector:".toolbar:first",refreshSourcesAction:"element-indexes/get-source-tree-html",updateElementsAction:"element-indexes/get-elements",countElementsAction:"element-indexes/count-elements",submitActionsAction:"element-indexes/perform-action",defaultSiteId:null,defaultSource:null,canHaveDrafts:!1,onAfterInit:$.noop,onSelectSource:$.noop,onSelectSite:$.noop,onUpdateElements:$.noop,onSelectionChange:$.noop,onEnableElements:$.noop,onDisableElements:$.noop,onAfterAction:$.noop}})},8495:function(){Craft.BaseElementIndexView=Garnish.Base.extend({$container:null,$loadingMoreSpinner:null,$elementContainer:null,$scroller:null,elementIndex:null,thumbLoader:null,elementSelect:null,loadingMore:!1,_totalVisible:null,_morePending:null,_handleEnableElements:null,_handleDisableElements:null,init:function(t,e,i){var s=this;this.elementIndex=t,this.$container=$(e),this.setSettings(i,Craft.BaseElementIndexView.defaults),this.$loadingMoreSpinner=$('<div class="centeralign hidden"><div class="spinner loadingmore"></div></div>').insertAfter(this.$container),this.$elementContainer=this.getElementContainer();var a=this.$elementContainer.children();this.setTotalVisible(a.length),this.setMorePending(this.settings.batchSize&&a.length==this.settings.batchSize),this.thumbLoader=new Craft.ElementThumbLoader,this.thumbLoader.load(a),this.settings.selectable&&(this.elementSelect=new Garnish.Select(this.$elementContainer,a.filter(":not(.disabled)"),{multi:this.settings.multiSelect,vertical:this.isVerticalList(),handle:"index"===this.settings.context?".checkbox, .element:first":null,filter:":not(a):not(.toggle)",checkboxMode:this.settings.checkboxMode,onSelectionChange:this.onSelectionChange.bind(this)}),this._handleEnableElements=function(t){s.elementSelect.addItems(t.elements)},this._handleDisableElements=function(t){s.elementSelect.removeItems(t.elements)},this.elementIndex.on("enableElements",this._handleEnableElements),this.elementIndex.on("disableElements",this._handleDisableElements)),"index"===this.settings.context&&(this._handleElementEditing=function(t){var e=$(t.target);if("A"!==e.prop("nodeName")){var i;if(e.hasClass("element"))i=e;else if(!(i=e.closest(".element")).length)return;Garnish.hasAttr(i,"data-editable")&&s.createElementEditor(i)}},this.elementIndex.trashed||(this.addListener(this.$elementContainer,"dblclick",this._handleElementEditing),$.isTouchCapable()&&this.addListener(this.$elementContainer,"taphold",this._handleElementEditing))),this.afterInit(),this.settings.batchSize&&("index"===this.settings.context?this.$scroller=Garnish.$scrollContainer:this.$scroller=this.elementIndex.$main,this.$scroller.scrollTop(0),this.addListener(this.$scroller,"scroll","maybeLoadMore"),this.maybeLoadMore())},getElementContainer:function(){throw"Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method."},afterInit:function(){},getAllElements:function(){return this.$elementContainer.children()},getEnabledElements:function(){return this.$elementContainer.children(":not(.disabled)")},getElementById:function(t){var e=this.$elementContainer.children('[data-id="'+t+'"]:first');return e.length?e:null},getSelectedElements:function(){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.$selectedItems},getSelectedElementIds:function(){var t;try{t=this.getSelectedElements()}catch(t){}var e=[];if(t)for(var i=0;i<t.length;i++)e.push(t.eq(i).data("id"));return e},selectElement:function(t){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.selectItem(t,!0),!0},selectElementById:function(t){if(!this.elementSelect)throw"This view is not selectable.";var e=this.getElementById(t);return!!e&&(this.elementSelect.selectItem(e,!0),!0)},selectAllElements:function(){this.elementSelect.selectAll()},deselectAllElements:function(){this.elementSelect.deselectAll()},isVerticalList:function(){return!1},getTotalVisible:function(){return this._totalVisible},setTotalVisible:function(t){this._totalVisible=t},getMorePending:function(){return this._morePending},setMorePending:function(t){this._morePending=t},maybeLoadMore:function(){this.canLoadMore()&&this.loadMore()},canLoadMore:function(){return!(!this.getMorePending()||!this.settings.batchSize)&&(this.$scroller[0]===Garnish.$win[0]?Garnish.$win.innerHeight()+Garnish.$win.scrollTop()>=this.$container.offset().top+this.$container.height():this.$scroller.prop("scrollHeight")-this.$scroller.scrollTop()<=this.$scroller.outerHeight()+15)},loadMore:function(){var t=this;this.getMorePending()&&!this.loadingMore&&this.settings.batchSize&&(this.loadingMore=!0,this.$loadingMoreSpinner.removeClass("hidden"),this.removeListener(this.$scroller,"scroll"),Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:this.getLoadMoreParams()}).then((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden");var i=$(e.data.html);t.appendElements(i),Craft.appendHeadHtml(e.data.headHtml),Craft.appendFootHtml(e.data.footHtml),t.elementSelect&&(t.elementSelect.addItems(i.filter(":not(.disabled)")),t.elementIndex.updateActionTriggers()),t.setTotalVisible(t.getTotalVisible()+i.length),t.setMorePending(i.length==t.settings.batchSize),t.addListener(t.$scroller,"scroll","maybeLoadMore"),t.maybeLoadMore()})).catch((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden")})))},getLoadMoreParams:function(){var t=$.extend(!0,{},this.settings.params);return t.criteria.offset=this.getTotalVisible(),t},appendElements:function(t){t.appendTo(this.$elementContainer),this.thumbLoader.load(t),this.onAppendElements(t)},onAppendElements:function(t){this.settings.onAppendElements(t),this.trigger("appendElements",{newElements:t})},onSelectionChange:function(){this.settings.onSelectionChange(),this.trigger("selectionChange")},createElementEditor:function(t){Craft.createElementEditor(t.data("type"),t,{elementIndex:this.elementIndex})},disable:function(){this.elementSelect&&this.elementSelect.disable()},enable:function(){this.elementSelect&&this.elementSelect.enable()},destroy:function(){this.$loadingMoreSpinner.remove(),this.thumbLoader.destroy(),delete this.thumbLoader,this.elementSelect&&(this.elementIndex.off("enableElements",this._handleEnableElements),this.elementIndex.off("disableElements",this._handleDisableElements),this.elementSelect.destroy(),delete this.elementSelect),this.base()}},{defaults:{context:"index",batchSize:null,params:null,selectable:!1,multiSelect:!1,checkboxMode:!1,loadMoreElementsAction:"element-indexes/get-more-elements",onAppendElements:$.noop,onSelectionChange:$.noop}})},5970:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.BaseElementSelectInput=Garnish.Base.extend({thumbLoader:null,elementSelect:null,elementSort:null,modal:null,elementEditor:null,fieldLabel:null,$container:null,$elementsContainer:null,$elements:null,$addElementBtn:null,$addElementBtnContainer:null,_initialized:!1,init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","elementType","sources","criteria","sourceElementId","limit","modalStorageKey","fieldId"],a=0;a<s.length&&void 0!==arguments[a];a++)i[s[a]]=arguments[a];t=i}this.setSettings(t,Craft.BaseElementSelectInput.defaults),this.settings.modalStorageKey&&(this.modalStorageKey="BaseElementSelectInput."+this.settings.modalStorageKey),1==this.settings.limit&&(this.settings.sortable=!1),this.$container=this.getContainer(),this.fieldLabel=this.getFieldLabel(),this.$container.data("elementSelect",this),this.$elementsContainer=this.getElementsContainer(),this.$addElementBtn=this.getAddElementsBtn(),this.$addElementBtn&&(this.$addElementBtnContainer=this.$addElementBtn.parent(".flex"),this.$addElementBtnContainer.length||(this.$addElementBtnContainer=null)),this.thumbLoader=new Craft.ElementThumbLoader,this.initElementSelect(),this.initElementSort(),this.resetElements(),this.$addElementBtn&&this.addListener(this.$addElementBtn,"activate","showModal"),Garnish.requestAnimationFrame((function(){e._initialized=!0}))},get totalSelected(){return this.$elements.length},getContainer:function(){return $("#"+this.settings.id)},getFieldLabel:function(){if(this.$container)return this.$container.closest("fieldset").find("legend").first().data("label")},getElementsContainer:function(){return this.$container.children(".elements")},getElements:function(){return this.$elementsContainer.children()},getAddElementsBtn:function(){return this.$container.find(".btn.add:first")},initElementSelect:function(){this.settings.selectable&&(this.elementSelect=new Garnish.Select({multi:this.settings.sortable,filter:":not(.delete)"}))},initElementSort:function(){var t=this;this.settings.sortable&&(this.elementSort=new Garnish.DragSort({container:this.$elementsContainer,filter:this.settings.selectable?function(){return t.elementSort.$targetItem.hasClass("sel")?t.elementSelect.getSelectedItems():t.elementSort.$targetItem}:null,ignoreHandleSelector:".delete",axis:this.getElementSortAxis(),collapseDraggees:!0,magnetStrength:4,helperLagBase:1.5,onSortChange:this.settings.selectable?function(){t.elementSelect.resetItemOrder()}:null}))},getElementSortAxis:function(){return"list"===this.settings.viewMode?"y":null},canAddMoreElements:function(){return!this.settings.limit||this.$elements.length<this.settings.limit},updateAddElementsBtn:function(){this.canAddMoreElements()?this.enableAddElementsBtn():this.disableAddElementsBtn()},disableAddElementsBtn:function(){var t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.addClass("hidden")},enableAddElementsBtn:function(){var t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.removeClass("hidden")},focusNextLogicalElement:function(){if(this.canAddMoreElements()){var t=this.$addElementBtn;t&&t.get(0).focus()}else this.focusLastRemoveBtn()},focusLastRemoveBtn:function(){var t=this.$container.find(".delete");t.length&&t.last()[0].focus()},resetElements:function(){null!==this.$elements?this.removeElements(this.$elements):this.$elements=$(),this.addElements(this.getElements())},addElements:function(t){var e=this;this.thumbLoader.load(t),this.settings.selectable&&this.elementSelect.addItems(t),this.settings.sortable&&this.elementSort.addItems(t),this.settings.editable&&(this._handleShowElementEditor=function(t){var i=$(t.currentTarget);!Garnish.hasAttr(i,"data-editable")||i.hasClass("disabled")||i.hasClass("loading")||(e.elementEditor=e.createElementEditor(i))},this.addListener(t,"dblclick",this._handleShowElementEditor),$.isTouchCapable()&&this.addListener(t,"taphold",this._handleShowElementEditor)),t.find(".delete").on("click dblclick",(function(t){e.removeElement($(t.currentTarget).closest(".element")),t.stopPropagation()})),this.$elements=this.$elements.add(t),this.updateAddElementsBtn()},createElementEditor:function(t,e){return e||(e={}),e.prevalidate=this.settings.prevalidate,Craft.createElementEditor(this.settings.elementType,t,e)},removeElements:function(t){if(this.settings.selectable&&this.elementSelect.removeItems(t),this.modal){for(var e=[],i=0;i<t.length;i++){var s=t.eq(i).data("id");s&&e.push(s)}e.length&&this.modal.elementIndex.enableElementsById(e)}var a;if(t.children("input").prop("disabled",!0),this.settings.selectable){var n=this.$elements.index(t.last());a=this.$elements.eq(n+1).find(".delete")}a.length?a.focus():this.focusNextLogicalElement(),this.$elements=this.$elements.not(t),this.updateAddElementsBtn(),this.onRemoveElements()},removeElement:function(t){this.removeElements(t),this.animateElementAway(t,(function(){t.remove()}))},animateElementAway:function(t,e){t.css("z-index",0);var i={opacity:-1};i["margin-"+Craft.left]=-(t.outerWidth()+parseInt(t.css("margin-"+Craft.right))),"list"!==this.settings.viewMode&&0!==this.$elements.length||(i["margin-bottom"]=-(t.outerHeight()+parseInt(t.css("margin-bottom")))),window.draftEditor&&window.draftEditor.pause(),t.velocity(i,Craft.BaseElementSelectInput.REMOVE_FX_DURATION,(function(){e&&e(),window.draftEditor&&window.draftEditor.resume()}))},showModal:function(){this.canAddMoreElements()&&(this.modal?this.modal.show():this.modal=this.createModal())},createModal:function(){return Craft.createElementSelectorModal(this.settings.elementType,this.getModalSettings())},getModalSettings:function(){return $.extend({closeOtherModals:!1,storageKey:this.modalStorageKey,sources:this.settings.sources,criteria:this.settings.criteria,multiSelect:1!=this.settings.limit,showSiteMenu:this.settings.showSiteMenu,disabledElementIds:this.getDisabledElementIds(),onSelect:this.onModalSelect.bind(this),onHide:this.onModalHide.bind(this),triggerElement:this.$addElementBtn,modalTitle:Craft.t("app","Select {element}",{element:this.fieldLabel})},this.settings.modalSettings)},getSelectedElementIds:function(){for(var t=[],e=0;e<this.$elements.length;e++)t.push(this.$elements.eq(e).data("id"));return t},getDisabledElementIds:function(){var e,i=this.getSelectedElementIds();return!this.settings.allowSelfRelations&&this.settings.sourceElementId&&i.push(this.settings.sourceElementId),this.settings.disabledElementIds&&i.push.apply(i,function(e){if(Array.isArray(e))return t(e)}(e=this.settings.disabledElementIds)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i},onModalSelect:function(t){if(this.settings.limit){var e=this.settings.limit-this.$elements.length;t.length>e&&(t=t.slice(0,e))}this.selectElements(t),this.updateDisabledElementsInModal()},onModalHide:function(){var t=this;this.canAddMoreElements()||setTimeout((function(){t.focusNextLogicalElement()}),200)},selectElements:function(t){for(var e=0;e<t.length;e++){var i=t[e],s=this.createNewElement(i);this.appendElement(s),this.addElements(s),this.animateElementIntoPlace(i.$element,s),i.$element=s}this.onSelectElements(t)},createNewElement:function(t){var e=t.$element.clone(),i=Craft.t("app","Remove {label}",{label:t.label});return Craft.setElementSize(e,"large"===this.settings.viewMode?"large":"small"),e.addClass("removable"),e.prepend('<input type="hidden" name="'.concat(this.settings.name).concat(this.settings.single?"":"[]",'" value="').concat(t.id,'">')+'<button type="button" class="delete icon" title="'+Craft.t("app","Remove")+'" aria-label="'+i+'"></button>'),e},appendElement:function(t){t.appendTo(this.$elementsContainer)},animateElementIntoPlace:function(t,e){var i=t.offset(),s=e.offset(),a=e.clone().appendTo(Garnish.$bod);e.css("visibility","hidden"),a.css({position:"absolute",zIndex:1e4,top:i.top,left:i.left});var n={top:s.top,left:s.left};a.velocity(n,Craft.BaseElementSelectInput.ADD_FX_DURATION,(function(){a.remove(),e.css("visibility","visible")}))},updateDisabledElementsInModal:function(){this.modal.elementIndex&&this.modal.elementIndex.disableElementsById(this.getDisabledElementIds())},getElementById:function(t){for(var e=0;e<this.$elements.length;e++){var i=this.$elements.eq(e);if(i.data("id")==t)return i}},onSelectElements:function(t){this.trigger("selectElements",{elements:t}),this.settings.onSelectElements(t),window.draftEditor&&window.draftEditor.checkForm()},onRemoveElements:function(){this.trigger("removeElements"),this.settings.onRemoveElements()}},{ADD_FX_DURATION:200,REMOVE_FX_DURATION:200,defaults:{id:null,name:null,fieldId:null,elementType:null,sources:null,criteria:{},allowSelfRelations:!1,sourceElementId:null,disabledElementIds:null,viewMode:"list",single:!1,limit:null,showSiteMenu:!1,modalStorageKey:null,modalSettings:{},onSelectElements:$.noop,onRemoveElements:$.noop,sortable:!0,selectable:!0,editable:!0,prevalidate:!1,editorSettings:{}}})},4993:function(){Craft.BaseElementSelectorModal=Garnish.Modal.extend({elementType:null,elementIndex:null,$body:null,$selectBtn:null,$sidebar:null,$sources:null,$sourceToggles:null,$main:null,$search:null,$elements:null,$tbody:null,$primaryButtons:null,$secondaryButtons:null,$cancelBtn:null,$footerSpinner:null,init:function(t,e){this.elementType=t,this.setSettings(e,Craft.BaseElementSelectorModal.defaults);var i="elementSelectorModalHeading-"+Date.now(),s=$('<div class="modal elementselectormodal" aria-labelledby="'+i+'"></div>').appendTo(Garnish.$bod),a=($('<h2 id="'+i+'" class="visually-hidden">'+this.settings.modalTitle+"</h2>").appendTo(s),$('<div class="body"><div class="spinner big"></div></div>').appendTo(s)),n=$('<div class="footer"/>').appendTo(s);this.settings.fullscreen&&(s.addClass("fullscreen"),this.settings.minGutter=0),this.base(s,this.settings),this.$footerSpinner=$('<div class="spinner hidden"/>').appendTo(n),this.$secondaryButtons=$('<div class="buttons left secondary-buttons"/>').appendTo(n),this.$primaryButtons=$('<div class="buttons right"/>').appendTo(n),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$primaryButtons),this.$selectBtn=$("<button/>",{type:"button",class:"btn disabled submit",text:Craft.t("app","Select")}).appendTo(this.$primaryButtons),this.$body=a,this.addListener(this.$cancelBtn,"activate","cancel"),this.addListener(this.$selectBtn,"activate","selectElements")},onFadeIn:function(){this.elementIndex?Garnish.isMobileBrowser(!0)||this.elementIndex.$search.trigger("focus"):this._createElementIndex(),this.base()},onSelectionChange:function(){this.updateSelectBtnState()},updateSelectBtnState:function(){this.$selectBtn&&(this.elementIndex.getSelectedElements().length?this.enableSelectBtn():this.disableSelectBtn())},enableSelectBtn:function(){this.$selectBtn.removeClass("disabled")},disableSelectBtn:function(){this.$selectBtn.addClass("disabled")},enableCancelBtn:function(){this.$cancelBtn.removeClass("disabled")},disableCancelBtn:function(){this.$cancelBtn.addClass("disabled")},showFooterSpinner:function(){this.$footerSpinner.removeClass("hidden")},hideFooterSpinner:function(){this.$footerSpinner.addClass("hidden")},cancel:function(){this.$cancelBtn.hasClass("disabled")||this.hide()},selectElements:function(){if(this.elementIndex&&this.elementIndex.getSelectedElements().length){this.elementIndex.view.elementSelect.clearMouseUpTimeout();var t=this.elementIndex.getSelectedElements(),e=this.getElementInfo(t);this.onSelect(e),this.settings.disableElementsOnSelect&&this.elementIndex.disableElements(this.elementIndex.getSelectedElements()),this.settings.hideOnSelect&&this.hide()}},getElementInfo:function(t){for(var e=[],i=0;i<t.length;i++){var s=$(t[i]),a=Craft.getElementInfo(s);e.push(a)}return e},show:function(){this.updateSelectBtnState(),this.base()},onSelect:function(t){this.settings.onSelect(t)},disable:function(){this.elementIndex&&this.elementIndex.disable(),this.base()},enable:function(){this.elementIndex&&this.elementIndex.enable(),this.base()},_createElementIndex:function(){var t=this,e={context:"modal",elementType:this.elementType,sources:this.settings.sources};null!==this.settings.showSiteMenu&&"auto"!==this.settings.showSiteMenu&&(e.showSiteMenu=this.settings.showSiteMenu?"1":"0"),Craft.postActionRequest(this.settings.bodyAction,e,(function(e,i){"success"===i&&(t.$body.html(e.html),t.$body.has(".sidebar:not(.hidden)").length&&t.$body.addClass("has-sidebar"),t.elementIndex=Craft.createElementIndex(t.elementType,t.$body,Object.assign({context:"modal",modal:t,storageKey:t.settings.storageKey,criteria:t.settings.criteria,disabledElementIds:t.settings.disabledElementIds,selectable:!0,multiSelect:t.settings.multiSelect,buttonContainer:t.$secondaryButtons,onSelectionChange:t.onSelectionChange.bind(t),hideSidebar:t.settings.hideSidebar,defaultSiteId:t.settings.defaultSiteId,defaultSource:t.settings.defaultSource},t.settings.indexSettings)),t.addListener(t.elementIndex.$elements,"doubletap",(function(t,e){e.firstTap.target===e.secondTap.target&&this.selectElements()})))}))}},{defaults:{fullscreen:!1,resizable:!0,storageKey:null,sources:null,criteria:null,multiSelect:!1,showSiteMenu:null,disabledElementIds:[],disableElementsOnSelect:!1,hideOnSelect:!0,modalTitle:Craft.t("app","Select element"),onCancel:$.noop,onSelect:$.noop,hideSidebar:!1,defaultSiteId:null,defaultSource:null,bodyAction:"elements/get-modal-body",indexSettings:{}}})},8843:function(){Craft.BaseInputGenerator=Garnish.Base.extend({$source:null,$target:null,$form:null,settings:null,listening:null,timeout:null,init:function(t,e,i){this.$source=$(t),this.$target=$(e),this.$form=this.$source.closest("form"),this.setSettings(i),this.startListening()},setNewSource:function(t){var e=this.listening;this.stopListening(),this.$source=$(t),e&&this.startListening()},startListening:function(){this.listening||(this.listening=!0,this.addListener(this.$source,"input","onSourceTextChange"),this.addListener(this.$target,"input","onTargetTextChange"),this.addListener(this.$form,"submit","onFormSubmit"))},stopListening:function(){this.listening&&(this.listening=!1,this.timeout&&clearTimeout(this.timeout),this.removeAllListeners(this.$source),this.removeAllListeners(this.$target),this.removeAllListeners(this.$form))},onSourceTextChange:function(){this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(this.updateTarget.bind(this),250)},onTargetTextChange:function(){this.$target.get(0)===document.activeElement&&this.stopListening()},onFormSubmit:function(){this.timeout&&clearTimeout(this.timeout),this.updateTarget()},updateTarget:function(){if(this.$target.is(":visible")){var t=this.$source.val();if(void 0!==t){var e=this.generateTargetValue(t);this.$target.val(e);for(var i=0;i<this.$target.length;i++)this.$target[i].dispatchEvent(new InputEvent("input",{inputType:"insertText"})),this.$target[i].dispatchEvent(new Event("input"));this.$target.is(":focus")&&Craft.selectFullValue(this.$target)}}},generateTargetValue:function(t){return t}})},525:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CP=Garnish.Base.extend({authManager:null,$nav:null,$navToggle:null,$globalSidebar:null,$globalContainer:null,$mainContainer:null,$alerts:null,$crumbs:null,$breadcrumbList:null,$breadcrumbItems:null,$notificationContainer:null,$main:null,$primaryForm:null,$headerContainer:null,$header:null,$mainContent:null,$details:null,$sidebarContainer:null,$sidebar:null,$contentContainer:null,$edition:null,$confirmUnloadForms:null,$deltaForms:null,$collapsibleTables:null,isMobile:null,fixedHeader:!1,breadcrumbListWidth:0,breadcrumbDisclosureItem:'<li class="breadcrumb-toggle-wrapper" data-disclosure-item><button data-disclosure-trigger aria-controls="breadcrumb-disclosure" aria-haspopup="true">'.concat(Craft.t("app","More…"),'</button><div id="breadcrumb-disclosure" class="menu menu--disclosure" data-disclosure-menu><ul></ul></div></li>'),tabManager:null,enableQueue:!0,totalJobs:0,jobInfo:null,displayedJobInfo:null,displayedJobInfoUnchanged:1,trackJobProgressTimeout:null,jobProgressIcon:null,checkingForUpdates:!1,forcingRefreshOnUpdatesCheck:!1,includingDetailsOnUpdatesCheck:!1,checkForUpdatesCallbacks:null,resizeTimeout:null,init:function(){var t=this;0!==Craft.remainingSessionTime&&(this.authManager=new Craft.AuthManager),this.$nav=$("#nav"),this.$navToggle=$("#nav-toggle"),this.$globalSidebar=$("#global-sidebar"),this.$globalContainer=$("#global-container"),this.$mainContainer=$("#main-container"),this.$alerts=$("#alerts"),this.$crumbs=$("#crumbs"),this.$breadcrumbList=$(".breadcrumb-list"),this.$breadcrumbItems=$(".breadcrumb-list li"),this.$notificationContainer=$("#notifications"),this.$main=$("#main"),this.$primaryForm=$("#main-form"),this.$headerContainer=$("#header-container"),this.$header=$("#header"),this.$mainContent=$("#main-content"),this.$details=$("#details"),this.$sidebarContainer=$("#sidebar-container"),this.$sidebar=$("#sidebar"),this.$contentContainer=$("#content-container"),this.$collapsibleTables=$("table.collapsible"),this.isMobile=Garnish.isMobileBrowser(),this.updateSidebarMenuLabel();for(var i=this.$details.find(".meta > .field > .instructions"),s=0;s<i.length;s++){var a=i.eq(s),n=a.siblings(".heading").children("label");$("<span/>",{class:"info",html:a.children().html()}).appendTo(n),a.remove()}!this.isMobile&&this.$header.length&&(this.addListener(Garnish.$win,"scroll","updateFixedHeader"),this.updateFixedHeader()),Garnish.$doc.ready((function(){t.addListener(Garnish.$win,"resize",(function(e){if(e.target===window){t.handleWindowResize(),clearTimeout(t.resizeTimeout);var i=t;t.resizeTimeout=setTimeout((function(){i.setSidebarNavAttributes()}),100)}})),t.handleWindowResize(),t.setSidebarNavAttributes();var e=t.$notificationContainer.children(".error"),i=t.$notificationContainer.children(":not(.error)");e.delay(2*Craft.CP.notificationDuration).velocity("fadeOut"),i.delay(Craft.CP.notificationDuration).velocity("fadeOut"),Garnish.requestAnimationFrame(t.initSpecialForms.bind(t))})),this.$alerts.length&&this.initAlerts(),this.addListener(this.$navToggle,"click","toggleNav"),this.addListener($("#sidebar-toggle"),"click","toggleSidebar"),this.$primaryForm.length||(this.$primaryForm=$("form[data-saveshortcut]:first")),this.$primaryForm.length&&Garnish.hasAttr(this.$primaryForm,"data-saveshortcut")&&function(){var e=[],i=t.$primaryForm.data("actions");if(void 0===i)e.push([{keyCode:Garnish.S_KEY,ctrl:!0},{redirect:t.$primaryForm.data("saveshortcut-redirect"),retainScroll:Garnish.hasAttr(t.$primaryForm,"saveshortcut-scroll")}]);else for(var s=0;s<i.length;s++){var a=i[s];a.shortcut&&e.push([{keyCode:Garnish.S_KEY,ctrl:!0,shift:!!a.shift},{action:a.action,redirect:a.redirect,confirm:a.confirm,params:a.params,data:a.data,retainScroll:a.retainScroll}])}for(var n=function(i){Garnish.uiLayerManager.registerShortcut(e[i][0],(function(){t.submitPrimaryForm(e[i][1])}))},r=0;r<e.length;r++)n(r)}(),this.initTabs();var r=Craft.getLocalStorage("scrollY");if(void 0!==r&&(Craft.removeLocalStorage("scrollY"),Garnish.$doc.ready((function(){Garnish.requestAnimationFrame((function(){window.scrollTo(0,r)}))}))),$.isTouchCapable()&&(this.$mainContainer.on("focus","input, textarea, .focusable-input",this._handleInputFocus.bind(this)),this.$mainContainer.on("blur","input, textarea, .focusable-input",this._handleInputBlur.bind(this))),Craft.announcements.length){var o,l=$("#announcements-btn").removeClass("hidden"),h=Craft.announcements.some((function(t){return t.unread}));h&&l.addClass("unread"),this.addListener(l,"click",(function(){if(o)o.show();else{var t="";Craft.group(Craft.announcements,"timestamp").forEach((function(i){var s=function(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(t,i)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(i,2),a=s[0];s[1],a.forEach((function(e,i){t+='<div class="announcement '.concat(e.unread?"unread":"",'">')+(0===i?'<div class="timestamp">'.concat(e.timestamp,"</div>"):"")+"<h2>".concat(e.heading,"</h2>")+"<p>".concat(e.body,"</p>")+"</div>"}))})),o=new Garnish.HUD(l,'<div id="announcements">'.concat(t,"</div>"),{onShow:function(){l.addClass("active")},onHide:function(){l.removeClass("active")}}),$("a",o.$main).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===$(this).attr("target")&&$(this).attr("rel","noopener").attr("target","_blank")})),h&&(l.removeClass("unread"),Craft.sendActionRequest("POST","users/mark-announcements-as-read",{data:{ids:Craft.announcements.map((function(t){return t.id}))}}))}}))}},initSpecialForms:function(){if(this.$confirmUnloadForms=$("form[data-confirm-unload]"),this.$deltaForms=$("form[data-delta]"),this.$confirmUnloadForms.length){for(var t,e,i=this.$confirmUnloadForms.add(this.$deltaForms),s=0;s<i.length;s++)(t=i.eq(s)).data("initialSerializedValue")||(e="function"==typeof t.data("serializer")?t.data("serializer")():t.serialize(),t.data("initialSerializedValue",e)),this.addListener(t,"submit",(function(e){if(Garnish.hasAttr(t,"data-confirm-unload")&&this.removeListener(Garnish.$win,"beforeunload"),Garnish.hasAttr(t,"data-delta")){var i;e.preventDefault(),i="function"==typeof t.data("serializer")?t.data("serializer")():t.serialize();var s=Craft.findDeltaData(t.data("initialSerializedValue"),i,Craft.deltaNames);Craft.createForm(s).appendTo(Garnish.$bod).submit()}}));this.addListener(Garnish.$win,"beforeunload",(function(t){var e,i,s=!1;if(void 0!==Craft.livePreview&&Craft.livePreview.inPreviewMode)s=!0;else for(var a=0;a<this.$confirmUnloadForms.length;a++)if(i="function"==typeof(e=this.$confirmUnloadForms.eq(a)).data("serializer")?e.data("serializer")():e.serialize(),e.data("initialSerializedValue")!==i){s=!0;break}if(s){var n=Craft.t("app","Any changes will be lost if you leave this page.");return t?t.originalEvent.returnValue=n:window.event.returnValue=n,n}}))}},_handleInputFocus:function(){this.updateFixedHeader()},_handleInputBlur:function(){this.updateFixedHeader()},submitPrimaryForm:function(e){this.trigger("beforeSaveShortcut"),"object"===t(e)&&$.isPlainObject(e)||(e={}),e.redirect||(e.redirect=this.$primaryForm.data("saveshortcut-redirect")),e.data||(e.data={}),e.data.saveShortcut=!0,Craft.submitForm(this.$primaryForm,e)},updateSidebarMenuLabel:function(){var t=this.$sidebar.find("a.sel:first"),e=t.children(".label");$("#selected-sidebar-item-label").text(e.length?e.text():t.text()),Garnish.$bod.removeClass("showing-sidebar")},toggleNav:function(){var t=this.navIsExpanded();null!==t&&(t?(this.disableGlobalSidebarLinks(),this.$navToggle.focus(),this.$navToggle.attr("aria-expanded","false"),Garnish.$bod.removeClass("showing-nav")):(this.enableGlobalSidebarLinks(),this.$globalSidebar.find(":focusable")[0].focus(),this.$navToggle.attr("aria-expanded","true"),Garnish.$bod.addClass("showing-nav")))},enableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");$(t).each((function(){$(this).attr("tabindex","0")}))},disableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");$(t).each((function(){$(this).attr("tabindex","-1")}))},setSidebarNavAttributes:function(){var t=this.navIsExpanded();null!==t&&(t?this.enableGlobalSidebarLinks():this.disableGlobalSidebarLinks())},navIsExpanded:function(){if(!this.$globalSidebar[0])return null;var t=getComputedStyle(this.$globalSidebar[0]).getPropertyValue("--is-always-visible").trim();return"true"===this.$navToggle.attr("aria-expanded")||"true"===t},toggleSidebar:function(){Garnish.$bod.toggleClass("showing-sidebar")},initTabs:function(){this.tabManager&&(this.tabManager.destroy(),this.tabManager=null);var t=$("#tabs");if(t.length&&(this.tabManager=new Craft.Tabs(t),this.tabManager.on("selectTab",(function(t){var e=t.$tab.attr("href");if("#"===e.charAt(0)&&$(e).removeClass("hidden"),Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll"),e&&"#"===e.charAt(0)){var i=$("#context-btn").menubtn().data("menubtn");if(i)for(var s=0;s<i.menu.$options.length;s++){var a=i.menu.$options[s];a.href&&(a.href=a.href.match(/^[^#]*/)[0]+e)}}"undefined"!=typeof history&&Garnish.requestAnimationFrame((function(){history.replaceState(void 0,void 0,e)}))})),this.tabManager.on("deselectTab",(function(t){"#"===t.$tab.attr("href").charAt(0)&&$(t.$tab.attr("href")).addClass("hidden")})),window.LOCATION_HASH)){var e=this.tabManager.$tabs.filter('[href="#'.concat(window.LOCATION_HASH,'"]'));e.length&&this.tabManager.selectTab(e)}},get $tabsContainer(){return this.tabManager?this.tabManager.$container:void 0},get $tabsList(){return this.tabManager?this.tabManager.$ul:void 0},get $tabs(){return this.tabManager?this.tabManager.$ul.find("> li"):void 0},get $selectedTab(){return this.tabManager?this.tabManager.$selectedTab:void 0},get selectedTabIndex(){return this.tabManager?this.tabManager.$tabs.index(this.tabManager.$selectedTab):void 0},get $focusableTab(){return this.tabManager?this.tabManager.$focusableTab:void 0},selectTab:function(t){this.tabManager&&this.tabManager.selectTab(t)},deselectTab:function(){this.tabManager&&this.tabManager.deselectTab()},handleWindowResize:function(){this.updateResponsiveTables(),this.handleBreadcrumbVisibility()},breadcrumbItemsWrap:function(){if(this.$breadcrumbItems[0]){this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","");for(var t=this.$breadcrumbList[0].getBoundingClientRect().width,e=0,i=this.$breadcrumbList.find("li"),s=0;s<i.length;s++)e+=i.get(s).getBoundingClientRect().width;return this.breadcrumbListWidth=t,!(e<=t||e<t+1&&(this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","-1px"),1))}},handleBreadcrumbVisibility:function(){if(this.breadcrumbItemsWrap()){0===this.$breadcrumbList.find("[data-disclosure-item]").length&&this.$breadcrumbList.append(this.breadcrumbDisclosureItem);var t,e=this.$breadcrumbList.find("[data-disclosure-item]")[0].offsetWidth,i=this.breadcrumbListWidth;this.$breadcrumbItems.each((function(s){if(!(e+this.offsetWidth<i))return!1;t=s,e+=this.offsetWidth}));var s=this.$breadcrumbItems.slice(0,t+1),a=this.$breadcrumbItems.slice(t+1);this.$breadcrumbList.html(""),this.$breadcrumbList.append(s),this.$breadcrumbList.append(this.breadcrumbDisclosureItem),this.$breadcrumbList.find("[data-disclosure-menu] ul").append(a),this.$breadcrumbList.find("[data-disclosure-trigger]").disclosureMenu()}},updateResponsiveTables:function(){for(this.updateResponsiveTables._i=0;this.updateResponsiveTables._i<this.$collapsibleTables.length;this.updateResponsiveTables._i++)this.updateResponsiveTables._$table=this.$collapsibleTables.eq(this.updateResponsiveTables._i),this.updateResponsiveTables._containerWidth=this.updateResponsiveTables._$table.parent().width(),this.updateResponsiveTables._check=!1,this.updateResponsiveTables._containerWidth>0&&(void 0===this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._check=!0:(this.updateResponsiveTables._isCollapsed=this.updateResponsiveTables._$table.hasClass("collapsed"),this.updateResponsiveTables._containerWidth>this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._isCollapsed&&(this.updateResponsiveTables._$table.removeClass("collapsed"),this.updateResponsiveTables._check=!0):this.updateResponsiveTables._isCollapsed||(this.updateResponsiveTables._check=!0)),this.updateResponsiveTables._check&&this.updateResponsiveTables._$table.width()-30>this.updateResponsiveTables._containerWidth&&this.updateResponsiveTables._$table.addClass("collapsed"),this.updateResponsiveTables._$table.data("lastContainerWidth",this.updateResponsiveTables._containerWidth))},updateFixedHeader:function(){if(!this.isMobile)if(this.$main.length&&this.$headerContainer[0].getBoundingClientRect().top<0){if(!this.fixedHeader){var t=this.$headerContainer.height();this.$contentContainer.css("min-height","calc(100vh - "+(t+14+48-1)+"px)"),this.$headerContainer.height(t),Garnish.$bod.addClass("fixed-header"),this.$contentContainer.outerHeight(),this.$details.outerHeight();var e={top:t+"px","max-height":"calc(100vh - "+t+"px)"};this.$sidebar.addClass("fixed").css(e),this.$details.addClass("fixed").css(e),this.fixedHeader=!0}}else this.fixedHeader&&(this.$headerContainer.height("auto"),Garnish.$bod.removeClass("fixed-header"),this.$contentContainer.css("min-height",""),this.$sidebar.removeClass("fixed").css({top:"","max-height":""}),this.$details.removeClass("fixed").css({top:"","max-height":""}),this.fixedHeader=!1)},displayNotification:function(t,e){var i=Craft.CP.notificationDuration;["cp-error","error"].includes(t)?(i*=2,icon="alert",label=Craft.t("app","Error")):(icon="info",label=Craft.t("app","Notice"));var s=$('\n            <div class="notification '.concat(t.replace("cp-",""),'">\n                <span data-icon="').concat(icon,'" aria-label="').concat(label,'"></span>\n                ').concat(e,"\n            </div>\n            ")).appendTo(this.$notificationContainer),a=-s.outerWidth()/2+"px";s.hide().css({opacity:0,"margin-left":a,"margin-right":a}).velocity({opacity:1,"margin-left":"2px","margin-right":"2px"},{display:"inline-block",duration:"fast"}).delay(i).velocity({opacity:0,"margin-left":a,"margin-right":a},{complete:function(){s.remove()}}),this.trigger("displayNotification",{notificationType:t,message:e})},displayNotice:function(t){this.displayNotification("notice",t)},displayError:function(t){t||(t=Craft.t("app","A server error occurred.")),this.displayNotification("error",t)},fetchAlerts:function(){var t={path:Craft.path};Craft.queueActionRequest("app/get-cp-alerts",t,this.displayAlerts.bind(this))},displayAlerts:function(t){if(this.$alerts.remove(),Garnish.isArray(t)&&t.length){this.$alerts=$('<ul id="alerts"/>').prependTo($("#page-container"));for(var e=0;e<t.length;e++)$('<li><span data-icon="alert" aria-label="'.concat(Craft.t("app","Error"),'"></span> ').concat(t[e],"</li>")).appendTo(this.$alerts);var i=this.$alerts.outerHeight();this.$alerts.css("margin-top",-i).velocity({"margin-top":0},"fast"),this.initAlerts()}},initAlerts:function(){for(var t=this,e=this.$alerts.find('a[class^="shun:"]'),i=0;i<e.length;i++)this.addListener(e[i],"click",(function(e){e.preventDefault();var i=$(e.currentTarget),s={message:i.prop("className").substr(5)};Craft.queueActionRequest("app/shun-cp-alert",s,(function(e,s){"success"===s&&(e.success?i.parent().remove():t.displayError(e.error))}))}))},checkForUpdates:function(t,e,i){var s=this;if("function"==typeof e&&(i=e,e=!1),this.checkingForUpdates&&(!0===t&&!this.forcingRefreshOnUpdatesCheck||!0===e&&!this.includingDetailsOnUpdatesCheck)){var a=i;i=function(){s.checkForUpdates(t,e,a)}}"function"==typeof i&&(Garnish.isArray(this.checkForUpdatesCallbacks)||(this.checkForUpdatesCallbacks=[]),this.checkForUpdatesCallbacks.push(i)),this.checkingForUpdates||(this.checkingForUpdates=!0,this.forcingRefreshOnUpdatesCheck=!0===t,this.includingDetailsOnUpdatesCheck=!0===e,this._checkForUpdates(t,e).then((function(t){if(s.updateUtilitiesBadge(),s.checkingForUpdates=!1,Garnish.isArray(s.checkForUpdatesCallbacks)){var e=s.checkForUpdatesCallbacks;s.checkForUpdatesCallbacks=null;for(var i=0;i<e.length;i++)e[i](t)}s.trigger("checkForUpdates",{updateInfo:t})})))},_checkForUpdates:function(t,e){var i=this;return new Promise((function(s,a){t?i._getUpdates(e).then((function(t){s(t)})):i._checkForCachedUpdates(e).then((function(t){!1!==t.cached&&s(t),i._getUpdates(e).then((function(t){s(t)}))}))}))},_checkForCachedUpdates:function(t){return new Promise((function(e,i){var s={onlyIfCached:!0,includeDetails:t};Craft.postActionRequest("app/check-for-updates",s,(function(t,i){e("success"===i?t:{cached:!1})}))}))},_getUpdates:function(t){var e=this;return new Promise((function(i,s){Craft.sendApiRequest("GET","updates").then((function(s){e._cacheUpdates(s,t).then(i)})).catch((function(t){e._cacheUpdates({}).then(i)}))}))},_cacheUpdates:function(t,e){return new Promise((function(i,s){Craft.postActionRequest("app/cache-updates",{updates:t,includeDetails:e},(function(t,e){"success"===e?i(t):s()}),{contentType:"json"})}))},updateUtilitiesBadge:function(){var t=$("#nav-utilities").find("> a:not(.sel)");t.length&&Craft.queueActionRequest("app/get-utilities-badge-count",(function(e){var i=t.children(".badge");e.badgeCount?(i.length||(i=$('<span class="badge"/>').appendTo(t)),i.text(e.badgeCount)):i.length&&i.remove()}))},runQueue:function(){var t=this;this.enableQueue&&(Craft.runQueueAutomatically?Craft.queueActionRequest("queue/run",(function(e,i){"success"===i&&t.trackJobProgress(!1,!0)})):this.trackJobProgress(!1,!0))},trackJobProgress:function(t,e){if(e&&this.trackJobProgressTimeout&&(clearTimeout(this.trackJobProgressTimeout),this.trackJobProgressTimeout=null),!this.trackJobProgressTimeout&&this.enableQueue)if(!0===t){var i=Math.min(6e4,500*this.displayedJobInfoUnchanged);this.trackJobProgressTimeout=setTimeout(this._trackJobProgressInternal.bind(this),i)}else this._trackJobProgressInternal()},_trackJobProgressInternal:function(){var t=this;Craft.queueActionRequest("queue/get-job-info?limit=50&dontExtendSession=1",(function(e,i){"success"===i&&(t.trackJobProgressTimeout=null,t.totalJobs=e.total,t.setJobInfo(e.jobs),t.jobInfo.length&&t.trackJobProgress(!0))}))},setJobInfo:function(t){if(this.enableQueue){this.jobInfo=t;var e=this.displayedJobInfo;this.displayedJobInfo=this.getDisplayedJobInfo(),e&&this.displayedJobInfo&&e.id===this.displayedJobInfo.id&&e.progress===this.displayedJobInfo.progress&&e.progressLabel===this.displayedJobInfo.progressLabel&&e.status===this.displayedJobInfo.status?this.displayedJobInfoUnchanged++:this.displayedJobInfoUnchanged=1,this.updateJobIcon(),this.trigger("setJobInfo")}},getDisplayedJobInfo:function(){if(!this.enableQueue)return null;for(var t=[Craft.CP.JOB_STATUS_RESERVED,Craft.CP.JOB_STATUS_FAILED,Craft.CP.JOB_STATUS_WAITING],e=0;e<t.length;e++)for(var i=0;i<this.jobInfo.length;i++)if(this.jobInfo[i].status===t[e]&&(t[e]!==Craft.CP.JOB_STATUS_WAITING||!this.jobInfo[i].delay))return this.jobInfo[i];return null},updateJobIcon:function(){this.enableQueue&&this.$nav.length&&(this.displayedJobInfo?(this.jobProgressIcon||(this.jobProgressIcon=new i),this.displayedJobInfo.status===Craft.CP.JOB_STATUS_RESERVED||this.displayedJobInfo.status===Craft.CP.JOB_STATUS_WAITING?(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.setDescription(this.displayedJobInfo.description,this.displayedJobInfo.progressLabel),this.jobProgressIcon.setProgress(this.displayedJobInfo.progress)):this.displayedJobInfo.status===Craft.CP.JOB_STATUS_FAILED&&this.jobProgressIcon.showFailMode(Craft.t("app","Failed"))):this.jobProgressIcon&&(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.complete(),delete this.jobProgressIcon))},getSiteId:function(){var t=Craft.getLocalStorage("BaseElementIndex.siteId");return void 0!==t?(Craft.removeLocalStorage("BaseElementIndex.siteId"),this.setSiteId(t),t):Craft.getCookie("siteId")},setSiteId:function(t){Craft.setCookie("siteId",t,{maxAge:31536e3})}},{notificationDuration:2e3,JOB_STATUS_WAITING:1,JOB_STATUS_RESERVED:2,JOB_STATUS_DONE:3,JOB_STATUS_FAILED:4}),Garnish.$scrollContainer=Garnish.$win,Craft.cp=new Craft.CP;var i=Garnish.Base.extend({$li:null,$a:null,$label:null,$progressLabel:null,progress:null,failMode:!1,_$bgCanvas:null,_$staticCanvas:null,_$hoverCanvas:null,_$failCanvas:null,_staticCtx:null,_hoverCtx:null,_canvasSize:null,_arcPos:null,_arcRadius:null,_lineWidth:null,_arcStartPos:0,_arcEndPos:0,_arcStartStepSize:null,_arcEndStepSize:null,_arcStep:null,_arcStepTimeout:null,_arcAnimateCallback:null,_progressBar:null,init:function(){this.$li=$("<li/>").appendTo(Craft.cp.$nav.children("ul")),this.$a=$("<a/>",{id:"job-icon",href:Craft.canAccessQueueManager?Craft.getUrl("utilities/queue-manager"):null}).appendTo(this.$li),this.$canvasContainer=$('<span class="icon"/>').appendTo(this.$a);var t=$('<span class="label"/>').appendTo(this.$a);this.$label=$("<span/>").appendTo(t),this.$progressLabel=$('<span class="progress-label"/>').appendTo(t).hide();var e=window.devicePixelRatio>1?2:1;this._canvasSize=18*e,this._arcPos=this._canvasSize/2,this._arcRadius=7*e,this._lineWidth=3*e,this._$bgCanvas=this._createCanvas("bg","#61666b"),this._$staticCanvas=this._createCanvas("static","#d7d9db"),this._$hoverCanvas=this._createCanvas("hover","#fff"),this._$failCanvas=this._createCanvas("fail","#da5a47").hide(),this._staticCtx=this._$staticCanvas[0].getContext("2d"),this._hoverCtx=this._$hoverCanvas[0].getContext("2d"),this._drawArc(this._$bgCanvas[0].getContext("2d"),0,1),this._drawArc(this._$failCanvas[0].getContext("2d"),0,1)},setDescription:function(t,e){this.$a.attr("title",t),this.$label.text(t),e?this.$progressLabel.text(e).show():this.$progressLabel.hide()},setProgress:function(t){0==t?(this._$staticCanvas.hide(),this._$hoverCanvas.hide()):(this._$staticCanvas.show(),this._$hoverCanvas.show(),this.progress&&t>this.progress?this._animateArc(0,t/100):this._setArc(0,t/100)),this.progress=t},complete:function(){var t=this;this._animateArc(0,1,(function(){t._$bgCanvas.velocity("fadeOut"),t._animateArc(1,1,(function(){t.$a.remove(),t.destroy()}))}))},showFailMode:function(t){this.failMode||(this.failMode=!0,this.progress=null,this._$bgCanvas.hide(),this._$staticCanvas.hide(),this._$hoverCanvas.hide(),this._$failCanvas.show(),this.setDescription(t))},hideFailMode:function(){this.failMode&&(this.failMode=!1,this._$bgCanvas.show(),this._$staticCanvas.show(),this._$hoverCanvas.show(),this._$failCanvas.hide())},_createCanvas:function(t,e){var i=$('<canvas id="job-icon-'+t+'" width="'+this._canvasSize+'" height="'+this._canvasSize+'"/>').appendTo(this.$canvasContainer),s=i[0].getContext("2d");return s.strokeStyle=e,s.lineWidth=this._lineWidth,s.lineCap="round",i},_setArc:function(t,e){this._arcStartPos=t,this._arcEndPos=e,this._drawArc(this._staticCtx,t,e),this._drawArc(this._hoverCtx,t,e)},_drawArc:function(t,e,i){t.clearRect(0,0,this._canvasSize,this._canvasSize),t.beginPath(),t.arc(this._arcPos,this._arcPos,this._arcRadius,(1.5+2*e)*Math.PI,(1.5+2*i)*Math.PI),t.stroke(),t.closePath()},_animateArc:function(t,e,i){this._arcStepTimeout&&clearTimeout(this._arcStepTimeout),this._arcStep=0,this._arcStartStepSize=(t-this._arcStartPos)/10,this._arcEndStepSize=(e-this._arcEndPos)/10,this._arcAnimateCallback=i,this._takeNextArcStep()},_takeNextArcStep:function(){this._setArc(this._arcStartPos+this._arcStartStepSize,this._arcEndPos+this._arcEndStepSize),this._arcStep++,this._arcStep<10?this._arcStepTimeout=setTimeout(this._takeNextArcStep.bind(this),50):this._arcAnimateCallback&&this._arcAnimateCallback()}})},3778:function(){Craft.CategoryIndex=Craft.BaseElementIndex.extend({editableGroups:null,$newCategoryBtnGroup:null,$newCategoryBtn:null,init:function(t,e,i){this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){this.editableGroups=[];for(var t=0;t<Craft.editableCategoryGroups.length;t++){var e=Craft.editableCategoryGroups[t];this.getSourceByKey("group:"+e.uid)&&this.editableGroups.push(e)}this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultGroupHandle)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultGroupHandle)return e.data("key")}return this.base()},updateButton:function(){var t=this;if(this.$source){var e,i,s,a=this.$source.data("handle");if(this.editableGroups.length){var n,r;if(this.$newCategoryBtnGroup&&this.$newCategoryBtnGroup.remove(),a)for(e=0;e<this.editableGroups.length;e++)if(this.editableGroups[e].handle===a){n=this.editableGroups[e];break}if(this.$newCategoryBtnGroup=$('<div class="btngroup submit"/>'),n?(i=this._getGroupTriggerHref(n),s="index"===this.settings.context?Craft.t("app","New category"):Craft.t("app","New {group} category",{group:n.name}),this.$newCategoryBtn=$('<a class="btn submit add icon" '+i+' role="button">'+Craft.escapeHtml(s)+"</a>").appendTo(this.$newCategoryBtnGroup),"index"!==this.settings.context&&this.addListener(this.$newCategoryBtn,"click",(function(t){this._openCreateCategoryModal(t.currentTarget.getAttribute("data-id"))})),this.editableGroups.length>1&&(r=$("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newCategoryBtnGroup))):this.$newCategoryBtn=r=$("<button/>",{type:"button",class:"btn submit add icon menubtn",text:Craft.t("app","New category")}).appendTo(this.$newCategoryBtnGroup),r){var o='<div class="menu"><ul>';for(e=0;e<this.editableGroups.length;e++){var l=this.editableGroups[e];"index"!==this.settings.context&&l===n||(i=this._getGroupTriggerHref(l),s="index"===this.settings.context?l.name:Craft.t("app","New {group} category",{group:l.name}),o+="<li><a "+i+">"+Craft.escapeHtml(s)+"</a></li>")}o+="</ul></div>",$(o).appendTo(this.$newCategoryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",(function(e){t._openCreateCategoryModal(e.option.getAttribute("data-id"))}))}this.addButton(this.$newCategoryBtnGroup)}if("index"===this.settings.context&&"undefined"!=typeof history){var d="categories";a&&(d+="/"+a),history.replaceState({},"",Craft.getUrl(d))}}},_getGroupTriggerHref:function(t){if("index"===this.settings.context){var e="categories/".concat(t.handle,"/new"),i=this.getSite(),s=i?{site:i.handle}:void 0;return'href="'.concat(Craft.getUrl(e,s),'"')}return'data-id="'.concat(t.id,'"')},_openCreateCategoryModal:function(t){var e=this;if(!this.$newCategoryBtn.hasClass("loading")){for(var i,s=0;s<this.editableGroups.length;s++)if(this.editableGroups[s].id==t){i=this.editableGroups[s];break}if(i){this.$newCategoryBtn.addClass("inactive");var a=this.$newCategoryBtn.text();this.$newCategoryBtn.text(Craft.t("app","New {group} category",{group:i.name})),Craft.createElementEditor(this.elementType,{hudTrigger:this.$newCategoryBtnGroup,siteId:this.siteId,attributes:{groupId:t},onHideHud:function(){e.$newCategoryBtn.removeClass("inactive").text(a)},onSaveElement:function(t){var s="group:"+i.uid;e.sourceKey!==s&&e.selectSourceByKey(s),e.clearSearch(),e.selectElementAfterUpdate(t.id),e.updateElements()}})}}}}),Craft.registerElementIndexClass("craft\\elements\\Category",Craft.CategoryIndex)},6617:function(){Craft.CategorySelectInput=Craft.BaseElementSelectInput.extend({setSettings:function(){this.base.apply(this,arguments),this.settings.sortable=!1},getModalSettings:function(){var t=this.base();return t.hideOnSelect=!1,t},getElements:function(){return this.$elementsContainer.find(".element")},onModalSelect:function(t){var e=this;this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<t.length;s++)i.push(t[s].id);var a={categoryIds:i,siteId:t[0].siteId,id:this.settings.id,name:this.settings.name,branchLimit:this.settings.branchLimit,selectionLabel:this.settings.selectionLabel};Craft.postActionRequest("elements/get-categories-input-html",a,(function(i,s){if(e.modal.enable(),e.modal.enableCancelBtn(),e.modal.enableSelectBtn(),e.modal.hideFooterSpinner(),"success"===s){var a=$(i.html).children(".elements");e.$elementsContainer.replaceWith(a),e.$elementsContainer=a,e.resetElements();for(var n=[],r=0;r<t.length;r++){var o=t[r],l=e.getElementById(o.id);l&&(e.animateElementIntoPlace(o.$element,l),n.push(o))}e.updateDisabledElementsInModal(),e.modal.hide(),e.onSelectElements(n)}}))},removeElement:function(t){var e=t.add(t.parent().siblings("ul").find(".element"));this.removeElements(e);for(var i=0;i<e.length;i++)this._animateCategoryAway(e,i)},_animateCategoryAway:function(t,e){var i,s=this;e===t.length-1&&(i=function(){var e=t.first().parent().parent(),i=e.parent();i[0]===s.$elementsContainer[0]||e.siblings().length?e.remove():i.remove()});var a=function(){s.animateElementAway(t.eq(e),i)};0===e?a():setTimeout(a,100*e)}})},9482:function(){Craft.charts={},Craft.charts.DataTable=Garnish.Base.extend({columns:null,rows:null,init:function(t){var e=t.columns,i=t.rows;i.forEach((function(t){$.each(t,(function(i){var s;switch(e[i].type){case"date":s=d3.timeParse("%Y-%m-%d"),t[i]=s(t[i]);break;case"datetime":s=d3.timeParse("%Y-%m-%d %H:00:00"),t[i]=s(t[i]);break;case"percent":t[i]=t[i]/100;break;case"number":t[i]=+t[i]}}))})),this.columns=e,this.rows=i}}),Craft.charts.Tip=Garnish.Base.extend({$container:null,$tip:null,init:function(t){this.$container=t,this.$tip=$('<div class="tooltip"></div>').appendTo(this.$container),this.hide()},setContent:function(t){this.$tip.html(t)},setPosition:function(t){this.$tip.css("left","".concat(t.left,"px")),this.$tip.css("top","".concat(t.top,"px"))},show:function(){this.$tip.css("display","block")},hide:function(){this.$tip.css("display","none")}}),Craft.charts.BaseChart=Garnish.Base.extend({$container:null,$chart:null,chartBaseClass:"cp-chart",dataTable:null,formatLocale:null,timeFormatLocale:null,orientation:null,svg:null,width:null,height:null,init:function(t,e){var i=this;this.$container=t,this.setSettings(Craft.charts.BaseChart.defaults),this.setSettings(e);var s={formats:window.d3Formats,formatLocaleDefinition:window.d3FormatLocaleDefinition,timeFormatLocaleDefinition:window.d3TimeFormatLocaleDefinition};this.setSettings(s),d3.select(window).on("resize",(function(){i.resize()}))},setSettings:function(t,e){var i=void 0===this.settings?{}:this.settings;this.settings=$.extend(!0,{},i,e,t)},draw:function(t,e){this.setSettings(e),this.dataTable=t,this.formatLocale=d3.formatLocale(this.settings.formatLocaleDefinition),this.timeFormatLocale=d3.timeFormatLocale(this.settings.timeFormatLocaleDefinition),this.orientation=this.settings.orientation,this.$chart&&this.$chart.remove();var i=this.chartBaseClass;this.settings.chartClass&&(i+=" "+this.settings.chartClass),this.$chart=$('<div class="'.concat(i,'" />')).appendTo(this.$container)},resize:function(){this.draw(this.dataTable,this.settings)},onAfterDrawTicks:function(){$(".tick",this.$chart).each((function(t,e){var i=$("text",e);i.clone().appendTo(e),i.attr("stroke","#ffffff"),i.attr("stroke-width",3)}))}},{defaults:{formatLocaleDefinition:null,timeFormatLocaleDefinition:null,formats:{numberFormat:",.2f",percentFormat:",.2%",currencyFormat:"$,.2f",shortDateFormats:{day:"%-m/%-d",month:"%-m/%y",year:"%Y"}},margin:{top:0,right:0,bottom:0,left:0},chartClass:null,colors:["#0594D1","#DE3800","#FF9A00","#009802","#9B009B"]}}),Craft.charts.Area=Craft.charts.BaseChart.extend({tip:null,drawingArea:null,init:function(t,e){this.base(t,Craft.charts.Area.defaults),this.setSettings(e)},draw:function(t,e){this.base(t,e),this.tip&&(this.tip=null);var i=this.getChartMargin();this.width=this.$chart.width()-i.left-i.right,this.height=this.$chart.height()-i.top-i.bottom;var s={width:this.width+(i.left+i.right),height:this.height+(i.top+i.bottom),translateX:"rtl"!==this.orientation?i.left:i.right,translateY:i.top};this.svg=d3.select(this.$chart.get(0)).append("svg").attr("width",s.width).attr("height",s.height),this.drawingArea=this.svg.append("g").attr("transform","translate(".concat(s.translateX,",").concat(s.translateY,")")),this.drawTicks(),this.drawAxes(),this.drawChart(),this.drawTipTriggers()},drawTicks:function(){var t=this.getX(!0),e=d3.axisBottom(t).tickFormat(this.getXFormatter()).ticks(3);this.drawingArea.append("g").attr("class","x ticks-axis").attr("transform","translate(0, ".concat(this.height,")")).call(e);var i,s=this.getY();"rtl"!==this.orientation?(i=d3.axisLeft(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").call(i)):(i=d3.axisRight(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").attr("transform","translate(".concat(this.width,",0)")).call(i)),this.onAfterDrawTicks()},drawAxes:function(){if(this.settings.xAxis.showAxis){var t=this.getX(),e=d3.axisBottom(t).ticks(0).tickSizeOuter(0);this.drawingArea.append("g").attr("class","x axis").attr("transform","translate(0, ".concat(this.height,")")).call(e)}if(this.settings.yAxis.showAxis){var i,s=this.getY();"rtl"===this.orientation?(i=d3.axisLeft(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(this.width-0,", 0)")).call(i)):(i=d3.axisRight(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(0,", 0)")).call(i))}},drawChart:function(){var t=this.getX(!0),e=this.getY();if(this.settings.xAxis.gridlines){var i=d3.axisBottom(t);this.drawingArea.append("g").attr("class","x grid-line").attr("transform","translate(0,".concat(this.height,")")).call(i.tickSize(-this.height,0,0).tickFormat(""))}if(this.settings.yAxis.gridlines){var s=d3.axisLeft(e);this.drawingArea.append("g").attr("class","y grid-line").attr("transform","translate(0 , 0)").call(s.tickSize(-this.width,0).tickFormat("").tickValues(this.getYTickValues()).ticks(2))}var a=d3.line().x((function(e){return t(e[0])})).y((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-line").append("path").datum(this.dataTable.rows).style("fill","none").style("stroke",this.settings.colors[0]).style("stroke-width","3px").attr("d",a);var n=d3.area().x((function(e){return t(e[0])})).y0(this.height).y1((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-area").append("path").datum(this.dataTable.rows).style("fill",this.settings.colors[0]).style("fill-opacity","0.3").attr("d",n),this.settings.plots&&this.drawingArea.append("g").attr("class","plots").selectAll("circle").data(this.dataTable.rows).enter().append("circle").style("fill",this.settings.colors[0]).attr("class",(function(t,e){return"plot plot-".concat(e)})).attr("r",4).attr("cx",(function(e){return t(e[0])})).attr("cy",(function(t){return e(t[1])}))},drawTipTriggers:function(){var t=this;if(this.settings.tips){this.tip||(this.tip=new Craft.charts.Tip(this.$chart));var e=this.getChartMargin(),i=(this.drawingArea.select(".x path.domain").node().getTotalLength()-e.left-e.right-12)/(this.dataTable.rows.length-1),s=Math.max(0,i),a=this.getX(!0),n=this.getY();this.drawingArea.append("g").attr("class","tip-triggers").selectAll("rect").data(this.dataTable.rows).enter().append("rect").attr("class","tip-trigger").style("fill","transparent").style("fill-opacity","1").attr("width",s).attr("height",this.height).attr("x",(function(t){return a(t[0])-s/2})).on("mouseover",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",5);var s=$("<div />"),r=$('<div class="x-value" />').appendTo(s),o=$('<div class="y-value" />').appendTo(s);r.html(t.getXFormatter()(e[0])),o.html(t.getYFormatter()(e[1]));var l=s.get(0);t.tip.setContent(l);var h,d=t.getChartMargin(),c=24,u=n(e[1])+c;"rtl"!==t.orientation?(h=a(e[0])+d.left+c,t.$chart.offset().left+h+t.tip.$tip.width()>t.$chart.offset().left+t.$chart.width()-c&&(h=a(e[0])-(t.tip.$tip.width()+c))):h=a(e[0])-(t.tip.$tip.width()+d.left+c),h<0&&(h=a(e[0])+d.left+c);var p={top:u,left:h};t.tip.setPosition(p),t.tip.show()})).on("mouseout",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",4),t.tip.hide()}))}},getChartMargin:function(){var t=this,e=this.settings.margin,i=this.getYTickValues(),s=0;return $.each(i,(function(e,i){var a=8*t.getYFormatter()(i).length;a>s&&(s=a)})),s+=10,e.left=s,e},getX:function(t){var e=d3.min(this.dataTable.rows,(function(t){return t[0]})),i=d3.max(this.dataTable.rows,(function(t){return t[0]})),s=[e,i];"rtl"===this.orientation&&(s=[i,e]);var a=0,n=0;t&&(a=0,n=0);var r=d3.scaleTime().range([a,this.width-n]);return r.domain(s),r},getY:function(){var t=[0,this.getYMaxValue()],e=d3.scaleLinear().range([this.height,0]);return e.domain(t),e},getXFormatter:function(){return this.settings.xAxis.formatter!==$.noop?this.settings.xAxis.formatter(this):Craft.charts.utils.getTimeFormatter(this.timeFormatLocale,this.settings)},getYFormatter:function(){return this.settings.yAxis.formatter!==$.noop?this.settings.yAxis.formatter(this):Craft.charts.utils.getNumberFormatter(this.formatLocale,this.dataTable.columns[1].type,this.settings)},getYMaxValue:function(){return d3.max(this.dataTable.rows,(function(t){return t[1]}))},getYTickValues:function(){var t=this.getYMaxValue();return t>1?[t/2,t]:[0,t]}},{defaults:{chartClass:"area",margin:{top:25,right:5,bottom:25,left:0},plots:!0,tips:!0,xAxis:{gridlines:!1,showAxis:!0,formatter:$.noop},yAxis:{gridlines:!0,showAxis:!1,formatter:$.noop}}}),Craft.charts.utils={getDuration:function(t){var e=parseInt(t,10),i={hours:Math.floor(e/3600),minutes:Math.floor((e-3600*i.hours)/60),seconds:e-3600*i.hours-60*i.minutes};return i.hours<10&&(i.hours="0".concat(i.hours)),i.minutes<10&&(i.minutes="0".concat(i.minutes)),i.seconds<10&&(i.seconds="0".concat(i.seconds)),"".concat(i.hours,":").concat(i.minutes,":").concat(i.seconds)},getTimeFormatter:function(t,e){switch(e.dataScale){case"year":return t.format("%Y");case"month":return t.format(e.formats.shortDateFormats.month);case"hour":return t.format("".concat(e.formats.shortDateFormats.day," %H:00:00"));default:return t.format(e.formats.shortDateFormats.day)}},getNumberFormatter:function(t,e,i){switch(e){case"currency":return t.format(i.formats.currencyFormat);case"percent":return t.format(i.formats.percentFormat);case"time":return Craft.charts.utils.getDuration;case"number":return t.format(i.formats.numberFormat)}}}},3352:function(){Craft.ColorInput=Garnish.Base.extend({$container:null,$input:null,$colorContainer:null,$colorPreview:null,$colorInput:null,init:function(t){this.$container=$(t),this.$input=this.$container.find(".color-input"),this.$colorContainer=this.$container.children(".color"),this.$colorPreview=this.$colorContainer.children(".color-preview"),this.createColorInput(),this.handleTextChange(),this.addListener(this.$input,"input","handleTextChange")},createColorInput:function(){var t=document.createElement("input");t.setAttribute("type","color"),"color"===t.type&&(this.$colorContainer.removeClass("static"),this.$colorInput=$(t).addClass("color-preview-input").attr({"aria-controls":this.$input.attr("id"),"aria-label":Craft.t("app","Color picker")}).appendTo(this.$colorPreview),this.addListener(this.$colorInput,"click",(function(t){t.stopPropagation()})),this.addListener(this.$colorContainer,"click",(function(){this.$colorInput.trigger("click")})),this.addListener(this.$colorInput,"input","updateColor"))},updateColor:function(){this.$input.val(this.$colorInput.val()),this.handleTextChange()},handleTextChange:function(){var t=this.$input.val();t!==(t=Craft.trim(t))&&this.$input.val(t),t.length&&"#"===t[0]&&(t=t.substr(1),this.$input.val(t)),t.length?(3===t.length&&(t=t[0].repeat(2)+t[1].repeat(2)+t[2].repeat(2)),t.match(/^[0-9a-f]{6}$/i)?(this.$colorPreview.css("background-color","#".concat(t)),this.$colorInput&&this.$colorInput.val("#".concat(t))):this.$colorPreview.css("background-color","")):this.$colorPreview.css("background-color","")}},{_browserSupportsColorInputs:null,doesBrowserSupportColorInputs:function(){return Craft.ColorInput._browserSupportsColorInputs,Craft.ColorInput._browserSupportsColorInputs}})},587:function(){function t(t){return function(t){if(Array.isArray(t))return i(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function s(t){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},s(t)}var a=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi;jQuery.htmlPrefilter=function(t){return t.replace(a,"<$1></$2>")},$.extend(Craft,{navHeight:48,index:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.index() must be an array.";return t.reduce((function(t,i,s){return t["string"==typeof e?i[e]:e(i,s)]=i,t}),{})},group:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.group() must be an array.";var i={};return t.reduce((function(t,s,a){var n="string"==typeof e?s[e]:e(s,a);return i.hasOwnProperty(n)||(i[n]=[[],n],t.push(i[n])),i[n][0].push(s),t}),[])},t:function(t,e,i){return void 0!==Craft.translations[t]&&void 0!==Craft.translations[t][e]&&(e=Craft.translations[t][e]),i?this.formatMessage(e,i):e},formatMessage:function(t,e){var i;if(!1===(i=this._tokenizePattern(t)))throw"Message pattern is invalid.";for(var a=0;a<i.length;a++){var n=i[a];if("object"===s(n)&&!1===(i[a]=this._parseToken(n,e)))throw"Message pattern is invalid."}return i.join("")},_tokenizePattern:function(e){var i,s,a=1,n=t(e);if(-1===(i=s=n.indexOf("{")))return[e];for(var r=[n.slice(0,s).join("")];;){var o=n.indexOf("{",s+1),l=n.indexOf("}",s+1);if(-1===o&&(o=!1),-1===l&&(l=!1),!1===o&&!1===l)break;if(!1===o&&(o=n.length),l>o?(a++,s=o):(a--,s=l),0===a&&(r.push(n.slice(i+1,s).join("").split(",",3)),i=s+1,r.push(n.slice(i,o).join("")),i=o),0!==a&&(!1===o||!1===l))break}return 0===a&&r},_parseToken:function(e,i){var a=this,n=Craft.trim(e[0]);if(void 0===i[n])return"{".concat(e.join(","),"}");var r=i[n],o=void 0!==e[1]?Craft.trim(e[1]):"none";switch(o){case"number":return function(){var t=void 0!==e[2]?Craft.trim(e[2]):null;if(null!==t&&"integer"!==t)throw"Message format 'number' is only supported for integer values.";var i,s=Craft.formatNumber(r);return null===t&&-1!==(i="".concat(r).indexOf("."))&&(s+=".".concat(r.substr(i+1))),s}();case"none":return r;case"select":return function(){if(void 0===e[2])return!1;for(var t=a._tokenizePattern(e[2]),s=t.length,n=!1,o=0;o+1<s;o++){if(Garnish.isArray(t[o])||!Garnish.isArray(t[o+1]))return!1;var l=Craft.trim(t[o++]);(!1===n&&"other"===l||l==r)&&(n=t[o].join(","))}return!1!==n&&a.formatMessage(n,i)}();case"plural":return function(){if(void 0===e[2])return!1;for(var n=a._tokenizePattern(e[2]),o=n.length,l=!1,h=0,d=0;d+1<o;d++){if("object"===s(n[d])||"object"!==s(n[d+1]))return!1;var c=Craft.trim(n[d++]),u=t(c);if(1===d&&"offset:"===c.substring(0,7)){var p=t(c.replace(/[\n\r\t]/g," ")).indexOf(" ",7);if(-1===p)throw"Message pattern is invalid.";h=parseInt(Craft.trim(u.slice(7,p).join(""))),c=Craft.trim(u.slice(p+1,p+1+u.length).join(""))}(!1===l&&"other"===c||"="===c[0]&&parseInt(u.slice(1,1+u.length).join(""))===r||"one"===c&&r-h==1)&&(l=("string"==typeof n[d]?[n[d]]:n[d]).map((function(t){return t.replace("#",r-h)})).join(","))}return!1!==l&&a.formatMessage(l,i)}();default:throw"Message format '".concat(o,"' is not supported.")}},formatDate:function(t){return"object"!==s(t)&&(t=new Date(t)),$.datepicker.formatDate(Craft.datepickerOptions.dateFormat,t)},formatNumber:function(t,e){return void 0===e&&(e=",.0f"),d3.formatLocale(d3FormatLocaleDefinition).format(e)(t)},shortcutText:function(t,e,i){return"Mac"===Craft.clientOs?(i?"⌥":"")+(e?"⇧":"")+"⌘"+t:"Ctrl+"+(i?"Alt+":"")+(e?"Shift+":"")+t},escapeHtml:function(t){return $("<div/>").text(t).html()},escapeRegex:function(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},getText:function(t){return $("<div/>").html(t).text()},encodeUriComponent:function(t){t=encodeURIComponent(t);var e={"!":"%21","*":"%2A","'":"%27","(":"%28",")":"%29"};for(var i in e){var s=new RegExp("\\"+i,"g");t=t.replace(s,e[i])}return t},selectFullValue:function(t){var e=$(t),i=e.val();if(void 0!==e[0].setSelectionRange){var s=2*i.length;e[0].setSelectionRange(0,s)}else e.val(i)},formatInputId:function(t){return this.rtrim(t.replace(/[^\w]+/g,"-"),"-")},getUrl:function(t,e,i){"string"!=typeof t&&(t="");var s="";if($.isPlainObject(e)){var a=[];for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];"#"===n?s=r:null!==r&&""!==r&&a.push(n+"="+r)}e=a}e=Garnish.isArray(e)?e.join("&"):Craft.trim(e,"&?");var o=t.indexOf("#");-1!==o&&(s||(s=t.substr(o+1)),t=t.substr(0,o));var l,h=t.indexOf("?");if(-1!==h&&(e=t.substr(h+1)+(e?"&"+e:""),t=t.substr(0,h)),-1!==t.search("://")||"/"===t[0])return t+(e?"?"+e:"")+(s?"#"+s:"");if(t=Craft.trim(t,"/"),i){if(l=i,t&&Craft.pathParam){var d=l.match(new RegExp("[&?]"+Craft.escapeRegex(Craft.pathParam)+"=[^&]+"));d&&(l=l.replace(d[0],Craft.rtrim(d[0],"/")+"/"+t),t="")}}else l=Craft.baseUrl;if(-1!==(h=l.indexOf("?"))&&(e=l.substr(h+1)+(e?"&"+e:""),l=l.substr(0,h)),!Craft.omitScriptNameInUrls&&t)if(Craft.usePathInfo||!Craft.pathParam)-1===l.search(Craft.scriptName)&&(l=Craft.rtrim(l,"/")+"/"+Craft.scriptName);else{if(e&&e.substr(0,Craft.pathParam.length+1)===Craft.pathParam+"="){var c,u=e.indexOf("&");-1!==u?(c=e.substring(2,u),e=e.substr(u+1)):(c=e.substr(2),e=null),t=(c=Craft.rtrim(c))+(t?"/"+t:"")}e=Craft.pathParam+"="+t+(e?"&"+e:""),t=null}return t&&(l=Craft.rtrim(l,"/")+"/"+t),e&&(l+="?"+e),s&&(l+="#"+s),l},getCpUrl:function(t,e){return this.getUrl(t,e,Craft.baseCpUrl)},getSiteUrl:function(t,e){return this.getUrl(t,e,Craft.baseSiteUrl)},getActionUrl:function(t,e){return Craft.getUrl(t,e,Craft.actionUrl)},redirectTo:function(t){document.location.href=this.getUrl(t)},getCsrfInput:function(){return Craft.csrfTokenName?'<input type="hidden" name="'+Craft.csrfTokenName+'" value="'+Craft.csrfTokenValue+'"/>':""},postActionRequest:function(t,e,i,a){"function"==typeof e&&(a=i,i=e,e={}),(a=a||{}).contentType&&a.contentType.match(/\bjson\b/)&&("object"===s(e)&&(e=JSON.stringify(e)),a.contentType="application/json; charset=utf-8");var n=$.ajax($.extend({url:Craft.getActionUrl(t),type:"POST",dataType:"json",headers:this._actionHeaders(),data:e,success:i,error:function(t,e,s){4===t.readyState&&(void 0!==Craft.cp?Craft.cp.displayError():alert(Craft.t("app","A server error occurred.")),i&&i(null,e,t))}},a));return"function"==typeof a.send&&a.send(n),n},_waitingOnAjax:!1,_ajaxQueue:[],queueActionRequest:function(t,e,i,s){"function"==typeof e&&(s=i,i=e,e=void 0),Craft._ajaxQueue.push([t,e,i,s]),Craft._waitingOnAjax||Craft._postNextActionRequestInQueue()},_postNextActionRequestInQueue:function(){Craft._waitingOnAjax=!0;var t=Craft._ajaxQueue.shift();Craft.postActionRequest(t[0],t[1],(function(e,i,s){t[2]&&"function"==typeof t[2]&&t[2](e,i,s),Craft._ajaxQueue.length?Craft._postNextActionRequestInQueue():Craft._waitingOnAjax=!1}),t[3])},_actionHeaders:function(){var t={"X-Registered-Asset-Bundles":Object.keys(Craft.registeredAssetBundles).join(","),"X-Registered-Js-Files":Object.keys(Craft.registeredJsFiles).join(",")};return Craft.csrfTokenValue&&(t["X-CSRF-Token"]=Craft.csrfTokenValue),t},sendActionRequest:function(t,e,i){var s=this;return new Promise((function(a,n){(i=i?$.extend({},i):{}).method=t,i.url=Craft.getActionUrl(e),i.headers=$.extend({"X-Requested-With":"XMLHttpRequest"},i.headers||{},s._actionHeaders()),i.params=$.extend({},i.params||{},{v:(new Date).getTime()}),axios.request(i).then(a).catch(n)}))},sendApiRequest:function(t,e,i){var s=this;return new Promise((function(a,n){var r=(i=i?$.extend({},i):{}).cancelToken||null;s._getApiHeaders(r).then((function(o){i.method=t,i.baseURL=Craft.baseApiUrl,i.url=e,i.headers=$.extend(o,i.headers||{}),i.params=$.extend(Craft.apiParams||{},i.params||{},{v:(new Date).getTime()}),s._apiHeaders||(i.params.processCraftHeaders=1),Craft.httpProxy&&(i.proxy=Craft.httpProxy),axios.request(i).then((function(t){s._processApiHeaders(t.headers,r).then((function(){a(t.data)})).catch(n)})).catch(n)})).catch(n)}))},_loadingApiHeaders:!1,_apiHeaders:null,_apiHeaderWaitlist:[],_getApiHeaders:function(t){var i=this;return new Promise((function(s,a){i._loadingApiHeaders?i._apiHeaderWaitlist.push([s,a]):i._apiHeaders?s(i._apiHeaders):(i._loadingApiHeaders=!0,i.sendActionRequest("POST","app/api-headers",{cancelToken:t}).then((function(t){i._loadingApiHeaders?s(t.data):a(e)})).catch((function(t){i._rejectApiRequests(a,t)})))}))},_processApiHeaders:function(t,i){var s=this;return new Promise((function(a,n){s._apiHeaders?a():s.sendActionRequest("POST","app/process-api-response-headers",{data:{headers:t},cancelToken:i}).then((function(t){if(s._loadingApiHeaders)for(s._apiHeaders=t.data,s._loadingApiHeaders=!1,a();s._apiHeaderWaitlist.length;)s._apiHeaderWaitlist.shift()[0](s._apiHeaders);else n(e)})).catch((function(t){s._rejectApiRequests(n,t)}))}))},_rejectApiRequests:function(t,e){for(this._loadingApiHeaders=!1,t(e);this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1](e)},clearCachedApiHeaders:function(){for(this._apiHeaders=null,this._loadingApiHeaders=!1;this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1]()},downloadFromUrl:function(t,e,i){return new Promise((function(a,n){var r=new XMLHttpRequest;r.open(t,e,!0),"object"===s(i)?(r.setRequestHeader("Content-Type","application/json; charset=UTF-8"),i=JSON.stringify(i)):r.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),r.responseType="blob",r.onload=function(){if(200===r.status){var t=r.getResponseHeader("content-disposition"),e=/"([^"]*)"/.exec(t),i=null!=e&&e[1]?e[1]:"Download",s=r.getResponseHeader("content-type"),o=new Blob([r.response],{type:s}),l=document.createElement("a");l.href=window.URL.createObjectURL(o),l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),a()}else n()},r.send(i)}))},stringToArray:function(t){if("string"!=typeof t)return t;for(var e=t.split(","),i=0;i<e.length;i++)e[i]=$.trim(e[i]);return e},findDeltaData:function(t,e,i,a,n){t="string"==typeof t?t:"",e="string"==typeof e?e:"",i.sort((function(t,e){return t.length===e.length?0:t.length>e.length?1:-1})),void 0===n&&(n=Craft.initialDeltaValues);for(var r=this._groupParamsByDeltaNames(t.split("&"),i,!1,n),o=this._groupParamsByDeltaNames(e.split("&"),i,!0,!1),l=o.__root__,h=0;h<i.length;h++)(Craft.inArray(i[h],Craft.modifiedDeltaNames)||"object"===s(o[i[h]])&&("object"!==s(r[i[h]])||JSON.stringify(r[i[h]])!==JSON.stringify(o[i[h]])))&&((l=l.concat(o[i[h]])).push("modifiedDeltaNames[]="+i[h]),a&&a(i[h],o[i[h]]));return l.join("&")},_groupParamsByDeltaNames:function(t,e,i,s){var a={};i&&(a.__root__=[]);var n=function(t){return encodeURIComponent(t).replace("%3D","=")};t=t.map((function(t){return decodeURIComponent(t)}));t:for(var r=0;r<t.length;r++){for(var o=e.length-1;o>=0;o--){var l=t[r].substr(0,e[o].length+1);if(l===e[o]+"="||l===e[o]+"["){void 0===a[e[o]]&&(a[e[o]]=[]),a[e[o]].push(n(t[r]));continue t}}i&&a.__root__.push(n(t[r]))}if(s){var h=function(t,e){return $.isArray(e)||$.isPlainObject(e)?e=$.param(e):"string"==typeof e?e=encodeURIComponent(e):null===e&&(e=""),"".concat(encodeURIComponent(t),"=").concat(e)};for(var d in s)if(s.hasOwnProperty(d))if($.isPlainObject(s[d]))for(var c in a[d]=[],s[d])s[d].hasOwnProperty(c)&&a[d].push(h("".concat(d,"[").concat(c,"]"),s[d][c]));else a[d]=[h(d,s[d])]}return a},expandPostArray:function(t){var e,i={};for(var a in t)if(t.hasOwnProperty(a)){var n,r=t[a],o=a.match(/^(\w+)(\[.*)?/);if(o[2])for(n=o[2].match(/\[[^\[\]]*\]/g),e=0;e<n.length;e++)n[e]=n[e].substring(1,n[e].length-1);else n=[];n.unshift(o[1]);var l=i;for(e=0;e<n.length;e++)e<n.length-1?("object"!==s(l[n[e]])&&(n[e+1]&&parseInt(n[e+1])!=n[e+1]?l[n[e]]={}:l[n[e]]=[]),l=l[n[e]]):(n[e]||(n[e]=l.length),l[n[e]]=r)}return i},createForm:function(t){var e=$("<form/>",{attr:{method:"post",action:"","accept-charset":"UTF-8"}});if("string"==typeof t)for(var i,s=t.split("&"),a=0;a<s.length;a++)i=s[a].split("=",2),$("<input/>",{type:"hidden",name:decodeURIComponent(i[0]),value:decodeURIComponent(i[1]||"")}).appendTo(e);return e},compare:function(t,e,i){if(s(t)!==s(e))return!1;if("object"===s(t)){if(t.length!==e.length)return!1;if(t instanceof Array!=e instanceof Array)return!1;if(!(t instanceof Array))if(void 0===i||!0===i){if(!Craft.compare(Craft.getObjectKeys(t).sort(),Craft.getObjectKeys(e).sort()))return!1}else if(!Craft.compare(Craft.getObjectKeys(t),Craft.getObjectKeys(e)))return!1;for(var a in t)if(t.hasOwnProperty(a)&&!Craft.compare(t[a],e[a]))return!1;return!0}return t===e},getObjectKeys:function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&e.push(i);return e},escapeChars:function(t){Garnish.isArray(t)||(t=t.split());for(var e="",i=0;i<t.length;i++)e+="\\"+t[i];return e},ltrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("^["+Craft.escapeChars(e)+"]+");return t.replace(i,"")},rtrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("["+Craft.escapeChars(e)+"]+$");return t.replace(i,"")},trim:function(t,e){return t=Craft.ltrim(t,e),Craft.rtrim(t,e)},startsWith:function(t,e){return t.substr(0,e.length)===e},filterArray:function(t,e){for(var i=[],s=0;s<t.length;s++)("function"==typeof e?e(t[s],s):t[s])&&i.push(t[s]);return i},inArray:function(t,e){return $.isPlainObject(e)&&(e=Object.values(e)),e.includes(t)},removeFromArray:function(t,e){var i=$.inArray(t,e);return-1!==i&&(e.splice(i,1),!0)},getLast:function(t){return t.length?t[t.length-1]:null},uppercaseFirst:function(t){return t.charAt(0).toUpperCase()+t.slice(1)},lowercaseFirst:function(t){return t.charAt(0).toLowerCase()+t.slice(1)},parseUrl:function(t){var e=t.match(/^(?:(https?):\/\/|\/\/)([^\/\:]*)(?:\:(\d+))?(\/[^\?]*)?(?:\?([^#]*))?(#.*)?/);return e?{scheme:e[1],host:e[2]+(e[3]?":"+e[3]:""),hostname:e[2],port:e[3]||null,path:e[4]||"/",query:e[5]||null,hash:e[6]||null}:{}},isSameHost:function(t){var e=this.parseUrl(document.location.href);if(!e)return!1;var i=this.parseUrl(t);return!!i&&e.host===i.host},secondsToHumanTimeDuration:function(t,e){void 0===e&&(e=!0);var i=604800,s=Math.floor(t/i);t%=i;var a=Math.floor(t/86400);t%=86400;var n,r=Math.floor(t/3600);t%=3600,e?(n=Math.floor(t/60),t%=60):(n=Math.round(t/60),t=0);var o=[];return s&&o.push(s+" "+(1===s?Craft.t("app","week"):Craft.t("app","weeks"))),a&&o.push(a+" "+(1===a?Craft.t("app","day"):Craft.t("app","days"))),r&&o.push(r+" "+(1===r?Craft.t("app","hour"):Craft.t("app","hours"))),!n&&(e||s||a||r)||o.push(n+" "+(1===n?Craft.t("app","minute"):Craft.t("app","minutes"))),!t&&(!e||s||a||r||n)||o.push(t+" "+(1===t?Craft.t("app","second"):Craft.t("app","seconds"))),o.join(", ")},asciiString:function(t,e){t=t.normalize("NFC");for(var i,s="",a=0;a<t.length;a++)i=t.charAt(a),s+="string"==typeof(e||Craft.asciiCharMap)[i]?(e||Craft.asciiCharMap)[i]:i;return s},randomString:function(t){for(var e="",i=0;i<t;i++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e},createErrorList:function(t){for(var e=$(document.createElement("ul")).addClass("errors"),i=0;i<t.length;i++){var s=$(document.createElement("li"));s.appendTo(e),s.html(t[i])}return e},appendHeadHtml:function(t){if(t){var e=$("link[href]");if(e.length){for(var i,s=[],a=0;a<e.length;a++)i=e.eq(a).attr("href").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var n=new RegExp('<link\\s[^>]*href="(?:'+s.join("|")+')".*?></link>',"g");t=t.replace(n,"")}$("head").append(t)}},appendFootHtml:function(t){if(t){var e=$("script[src]");if(e.length){for(var i,s=[],a=0;a<e.length;a++)i=e.eq(a).attr("src").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var n=new RegExp('<script\\s[^>]*src="(?:'+s.join("|")+')".*?><\/script>',"g");t=t.replace(n,"")}Garnish.$bod.append(t)}},initUiElements:function(t){$(".grid",t).grid(),$(".info",t).infoicon(),$(".checkbox-select",t).checkboxselect(),$(".fieldtoggle",t).fieldtoggle(),$(".lightswitch",t).lightswitch(),$(".nicetext",t).nicetext(),$(".formsubmit",t).formsubmit(),$(".menubtn:not([data-disclosure-trigger])",t).menubtn(),$("[data-disclosure-trigger]",t).disclosureMenu(),$(".datetimewrapper",t).datetime(),$('.datewrapper > input[type="date"], .timewrapper > input[type="time"]',t).datetimeinput(),$("a",t).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===$(this).attr("target")&&$(this).attr("rel","noopener").attr("target","_blank")}))},_elementIndexClasses:{},_elementSelectorModalClasses:{},_elementEditorClasses:{},registerElementIndexClass:function(t,e){if(void 0!==this._elementIndexClasses[t])throw"An element index class has already been registered for the element type “"+t+"”.";this._elementIndexClasses[t]=e},registerElementSelectorModalClass:function(t,e){if(void 0!==this._elementSelectorModalClasses[t])throw"An element selector modal class has already been registered for the element type “"+t+"”.";this._elementSelectorModalClasses[t]=e},registerElementEditorClass:function(t,e){if(void 0!==this._elementEditorClasses[t])throw"An element editor class has already been registered for the element type “"+t+"”.";this._elementEditorClasses[t]=e},createElementIndex:function(t,e,i){return new(void 0!==this._elementIndexClasses[t]?this._elementIndexClasses[t]:Craft.BaseElementIndex)(t,e,i)},createElementSelectorModal:function(t,e){return new(void 0!==this._elementSelectorModalClasses[t]?this._elementSelectorModalClasses[t]:Craft.BaseElementSelectorModal)(t,e)},createElementEditor:function(t,e,i){return void 0===i&&$.isPlainObject(e)?(i=e,e=null):"object"!==s(i)&&(i={}),i.elementType||(i.elementType=t),new(void 0!==this._elementEditorClasses[t]?this._elementEditorClasses[t]:Craft.BaseElementEditor)(e,i)},getLocalStorage:function(t,e){return t="Craft-"+Craft.systemUid+"."+t,"undefined"!=typeof localStorage&&void 0!==localStorage[t]?JSON.parse(localStorage[t]):e},setLocalStorage:function(t,e){if("undefined"!=typeof localStorage){t="Craft-"+Craft.systemUid+"."+t;try{localStorage[t]=JSON.stringify(e)}catch(t){}}},removeLocalStorage:function(t){"undefined"!=typeof localStorage&&localStorage.removeItem("Craft-".concat(Craft.systemUid,".").concat(t))},getCookie:function(t){return document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)Craft-".concat(Craft.systemUid,":").concat(t,"\\s*\\=\\s*([^;]*).*$)|^.*$")),"$1")},setCookie:function(t,e,i){i=$.extend({},this.defaultCookieOptions,i);var s="Craft-".concat(Craft.systemUid,":").concat(t,"=").concat(encodeURIComponent(e));i.path&&(s+=";path=".concat(i.path)),i.domain&&(s+=";domain=".concat(i.domain)),i.maxAge?s+=";max-age-in-seconds=".concat(i.maxAge):i.expires&&(s+=";expires=".concat(i.expires.toUTCString())),i.secure&&(s+=";secure"),document.cookie=s},removeCookie:function(t){this.setCookie(t,"",new Date("1970-01-01T00:00:00"))},getElementInfo:function(t){var e=$(t);return e.hasClass("element")||(e=e.find(".element:first")),{id:e.data("id"),siteId:e.data("site-id"),label:e.data("label"),status:e.data("status"),url:e.data("url"),hasThumb:e.hasClass("hasthumb"),$element:e}},setElementSize:function(t,e){var i=$(t);if("small"!==e&&"large"!==e&&(e="small"),!i.hasClass(e)){var s="small"===e?"large":"small";if(i.addClass(e).removeClass(s),i.hasClass("hasthumb")){var a=i.find("> .elementthumb > img"),n=$("<img/>",{sizes:("small"===e?"30":"100")+"px",srcset:a.attr("srcset")||a.attr("data-pfsrcset")});a.replaceWith(n),picturefill({elements:[n[0]]})}}},submitForm:function(t,e){if(void 0===e&&(e={}),!e.confirm||confirm(e.confirm)){if(e.action&&$("<input/>",{type:"hidden",name:"action",val:e.action}).appendTo(t),e.redirect&&$("<input/>",{type:"hidden",name:"redirect",val:e.redirect}).appendTo(t),e.params)for(var i in e.params){var s=e.params[i];$("<input/>",{type:"hidden",name:i,val:s}).appendTo(t)}e.retainScroll&&this.setLocalStorage("scrollY",window.scrollY),t.trigger($.extend({type:"submit"},e.data))}},trapFocusWithin:function(t){Garnish.trapFocusWithin(t)},setFocusWithin:function(t){Garnish.setFocusWithin(t)}}),$.extend($.fn,{animateLeft:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({left:t},e,i,s):this.velocity({right:t},e,i,s)},animateRight:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({right:t},e,i,s):this.velocity({left:t},e,i,s)},disable:function(){return this.each((function(){var t=$(this);t.addClass("disabled"),t.data("activatable")&&t.removeAttr("tabindex")}))},enable:function(){return this.each((function(){var t=$(this);t.removeClass("disabled"),t.data("activatable")&&t.attr("tabindex","0")}))},grid:function(){return this.each((function(){var t=$(this),e={};t.data("item-selector")&&(e.itemSelector=t.data("item-selector")),t.data("cols")&&(e.cols=parseInt(t.data("cols"))),t.data("max-cols")&&(e.maxCols=parseInt(t.data("max-cols"))),t.data("min-col-width")&&(e.minColWidth=parseInt(t.data("min-col-width"))),t.data("mode")&&(e.mode=t.data("mode")),t.data("fill-mode")&&(e.fillMode=t.data("fill-mode")),t.data("col-class")&&(e.colClass=t.data("col-class")),t.data("snap-to-grid")&&(e.snapToGrid=!!t.data("snap-to-grid")),new Craft.Grid(this,e)}))},infoicon:function(){return this.each((function(){new Craft.InfoIcon(this)}))},checkboxselect:function(){return this.each((function(){$.data(this,"checkboxselect")||new Garnish.CheckboxSelect(this)}))},fieldtoggle:function(){return this.each((function(){$.data(this,"fieldtoggle")||new Craft.FieldToggle(this)}))},lightswitch:function(t,e,i){return"settings"===t?("string"==typeof e?(t={})[e]=i:t=e,this.each((function(){var e=$.data(this,"lightswitch");e&&e.setSettings(t)}))):($.isPlainObject(t)||(t={}),this.each((function(){var e=$.extend({},t);Garnish.hasAttr(this,"data-value")&&(e.value=$(this).attr("data-value")),Garnish.hasAttr(this,"data-indeterminate-value")&&(e.indeterminateValue=$(this).attr("data-indeterminate-value")),$.data(this,"lightswitch")||new Craft.LightSwitch(this,e)})))},nicetext:function(){return this.each((function(){$.data(this,"nicetext")||new Garnish.NiceText(this)}))},formsubmit:function(){return this.on("click",(function(t){var e=$(t.currentTarget),i=e.data("params")||{};e.data("param")&&(i[e.data("param")]=e.data("value"));var s=e.data("menu")?e.data("menu").$anchor:e,a=s.attr("data-form")?$("#"+s.attr("data-form")):s.closest("form");Craft.submitForm(a,{confirm:e.data("confirm"),action:e.data("action"),redirect:e.data("redirect"),params:i,data:$.extend({customTrigger:e},e.data("event-data"))})}))},menubtn:function(){return this.each((function(){var t=$(this);if(!t.data("menubtn")&&t.next().hasClass("menu")){var e={};t.data("menu-anchor")&&(e.menuAnchor=t.data("menu-anchor")),new Garnish.MenuBtn(t,e)}}))},disclosureMenu:function(){return this.each((function(){var t=$(this);!t.data("trigger")&&t.attr("aria-controls")&&new Garnish.DisclosureMenu(t)}))},datetime:function(){return this.each((function(){var t=$(this),e=t.find('input:not([name$="[timezone]"])'),i=function(){for(var i=!1,s=0;s<e.length;s++)if(e.eq(s).val()){i=!0;break}if(i){if(!t.children(".clear-btn").length)var a=$("<button/>",{type:"button",class:"clear-btn",title:Craft.t("app","Clear"),"aria-label":Craft.t("app","Clear")}).appendTo(t).on("click",(function(){for(var t=0;t<e.length;t++)e.eq(t).val("").trigger("input").trigger("change");a.remove(),e.first().filter('[type="text"]').focus()}))}else t.children(".clear-btn").remove()};e.on("change",i),i()}))},datetimeinput:function(){return this.each((function(){var t=$(this),e=function(){""===t.val()?t.addClass("empty-value"):t.removeClass("empty-value")};t.on("input",e),e()}))}}),Garnish.NiceText.charsLeftHtml=function(t){return Craft.t("app",'<span class="visually-hidden">Characters left:</span> {chars, number}',{chars:t})},Garnish.$doc.ready((function(){Craft.initUiElements()}))},691:function(){function t(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(t,i)||e(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CustomizeSourcesModal=Garnish.Modal.extend({elementIndex:null,$elementIndexSourcesContainer:null,$sidebar:null,$sourcesContainer:null,$sourceSettingsContainer:null,$newHeadingBtn:null,$footer:null,$footerBtnContainer:null,$saveBtn:null,$cancelBtn:null,$saveSpinner:null,$loadingSpinner:null,sourceSort:null,sources:null,selectedSource:null,updateSourcesOnSave:!1,availableTableAttributes:null,init:function(t,e){var i=this;this.base(),this.setSettings(e,{resizable:!0}),this.elementIndex=t,this.$elementIndexSourcesContainer=this.elementIndex.$sidebar.children("nav").children("ul");var s=$('<form class="modal customize-sources-modal"/>').appendTo(Garnish.$bod);this.$sidebar=$('<div class="cs-sidebar block-types"/>').appendTo(s),this.$sourcesContainer=$('<div class="sources">').appendTo(this.$sidebar),this.$sourceSettingsContainer=$('<div class="source-settings">').appendTo(s),this.$footer=$('<div class="footer"/>').appendTo(s),this.$footerBtnContainer=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footerBtnContainer),this.$saveBtn=$("<button/>",{type:"button",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(this.$footerBtnContainer),this.$saveSpinner=$('<div class="spinner hidden"/>').appendTo(this.$footerBtnContainer),this.$newHeadingBtn=$("<button/>",{type:"button",class:"btn submit add icon",text:Craft.t("app","New heading")}).appendTo($('<div class="buttons left secondary-buttons"/>').appendTo(this.$footer)),this.$loadingSpinner=$('<div class="spinner"/>').appendTo(s),this.setContainer(s),this.show();var a={elementType:this.elementIndex.elementType};Craft.postActionRequest("element-index-settings/get-customize-sources-modal-data",a,(function(t,e){i.$loadingSpinner.remove(),"success"===e&&(i.$saveBtn.removeClass("disabled"),i.buildModal(t))})),this.addListener(this.$newHeadingBtn,"click","handleNewHeadingBtnClick"),this.addListener(this.$cancelBtn,"click","hide"),this.addListener(this.$saveBtn,"click","save"),this.addListener(this.$container,"submit","save")},buildModal:function(t){var e=this;this.availableTableAttributes=t.availableTableAttributes,this.sourceSort=new Garnish.DragSort({handle:".move",axis:"y",onSortChange:function(){e.updateSourcesOnSave=!0}}),this.sources=[];for(var i=0;i<t.sources.length;i++){var s=this.addSource(t.sources[i]);this.sources.push(s)}this.selectedSource||void 0===this.sources[0]||this.sources[0].select()},addSource:function(t){var e,i=$('<div class="customize-sources-item"/>').appendTo(this.$sourcesContainer),s=$('<div class="label"/>').appendTo(i),a=$('<input type="hidden"/>').appendTo(i);return $('<a class="move icon" title="'+Craft.t("app","Reorder")+'" role="button"></a>').appendTo(i),void 0!==t.heading?(i.addClass("heading"),a.attr("name","sourceOrder[][heading]"),(e=new Craft.CustomizeSourcesModal.Heading(this,i,s,a,t)).updateItemLabel(t.heading)):(a.attr("name","sourceOrder[][key]").val(t.key),(e=new Craft.CustomizeSourcesModal.Source(this,i,s,a,t)).updateItemLabel(t.label),(this.elementIndex.sourceKey+"/").substr(0,t.key.length+1)===t.key+"/"&&e.select()),this.sourceSort.addItems(i),e},handleNewHeadingBtnClick:function(){var t=this.addSource({heading:""});Garnish.scrollContainerToElement(this.$sidebar,t.$item),t.select(),this.updateSourcesOnSave=!0},save:function(t){var e=this;if(t&&t.preventDefault(),!this.$saveBtn.hasClass("disabled")&&this.$saveSpinner.hasClass("hidden")){this.$saveSpinner.removeClass("hidden");var i=this.$container.serialize()+"&elementType="+this.elementIndex.elementType;Craft.postActionRequest("element-index-settings/save-customize-sources-modal-settings",i,(function(t,i){if(e.$saveSpinner.addClass("hidden"),"success"===i&&t.success){if(e.updateSourcesOnSave&&e.$elementIndexSourcesContainer.length){for(var s,a=null,n=0;n<e.sourceSort.$items.length;n++){var r=e.sourceSort.$items.eq(n).data("source"),o=r.getIndexSource();o&&(r.isHeading()?s=o:(s&&(e.appendSource(s,a),a=s,s=null),e.appendSource(o,a),a=o))}if(a){var l=a.nextAll();e.elementIndex.sourceSelect.removeItems(l),l.remove()}}e.selectedSource&&e.selectedSource.sourceData.key&&(e.elementIndex.selectSourceByKey(e.selectedSource.sourceData.key),e.elementIndex.updateElements()),Craft.cp.displayNotice(Craft.t("app","Source settings saved")),e.hide()}else{var h="success"===i&&t.error?t.error:Craft.t("app","A server error occurred.");Craft.cp.displayError(h)}}))}},appendSource:function(t,e){e?t.insertAfter(e):t.prependTo(this.$elementIndexSourcesContainer)},destroy:function(){for(var t=0;t<this.sources.length;t++)this.sources[t].destroy();delete this.sources,this.base()}}),Craft.CustomizeSourcesModal.BaseSource=Garnish.Base.extend({modal:null,$item:null,$itemLabel:null,$itemInput:null,$settingsContainer:null,sourceData:null,init:function(t,e,i,s,a){this.modal=t,this.$item=e,this.$itemLabel=i,this.$itemInput=s,this.sourceData=a,this.$item.data("source",this),this.addListener(this.$item,"click","select")},isHeading:function(){return!1},isSelected:function(){return this.modal.selectedSource===this},select:function(){this.isSelected()||(this.modal.selectedSource&&this.modal.selectedSource.deselect(),this.$item.addClass("sel"),this.modal.selectedSource=this,this.$settingsContainer?this.$settingsContainer.removeClass("hidden"):this.$settingsContainer=this.createSettings().appendTo(this.modal.$sourceSettingsContainer),this.modal.$sourceSettingsContainer.scrollTop(0))},createSettings:function(){return $("<div/>")},getIndexSource:function(){},deselect:function(){this.$item.removeClass("sel"),this.modal.selectedSource=null,this.$settingsContainer.addClass("hidden")},updateItemLabel:function(t){this.$itemLabel.text(t)},destroy:function(){this.$item.data("source",null),this.base()}}),Craft.CustomizeSourcesModal.Source=Craft.CustomizeSourcesModal.BaseSource.extend({createSettings:function(){var t=$("<div/>").append(Craft.ui.createTextField({label:Craft.t("app","Header Column Heading"),id:"defaultHeaderColHeading"+Math.floor(1e5*Math.random()),name:"sources[".concat(this.sourceData.key,"][headerColHeading]"),value:this.sourceData.headerColHeading,placeholder:this.sourceData.defaultHeaderColHeading}));return this.sourceData.tableAttributes.length&&t.append(this.createTableColumnsField()),t},createTableColumnsField:function(){var s=t(this.sourceData.tableAttributes[0],2),a=s[0],n=s[1],r=this.createTableColumnOption(a,n,!0,!0),o=$("<div/>"),l=[a];$('<input type="hidden" name="sources['+this.sourceData.key+'][tableAttributes][]" value=""/>').appendTo(o);for(var h=1;h<this.sourceData.tableAttributes.length;h++){var d=t(this.sourceData.tableAttributes[h],2),c=d[0],u=d[1];o.append(this.createTableColumnOption(c,u,!1,!0)),l.push(c)}var p,g=this.modal.availableTableAttributes.slice(0);g.push.apply(g,function(t){if(Array.isArray(t))return i(t)}(p=this.sourceData.availableTableAttributes)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(p)||e(p)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}());for(var f=0;f<g.length;f++){var m=t(g[f],2),v=m[0],C=m[1];Craft.inArray(v,l)||o.append(this.createTableColumnOption(v,C,!1,!1))}return new Garnish.DragSort(o.children(),{handle:".move",axis:"y"}),Craft.ui.createField($([r[0],o[0]]),{label:Craft.t("app","Table Columns"),instructions:Craft.t("app","Choose which table columns should be visible for this source, and in which order.")})},createTableColumnOption:function(t,e,i,s){var a=$('<div class="customize-sources-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(e),name:"sources["+this.sourceData.key+"][tableAttributes][]",value:t,checked:s,disabled:i}));return i&&a.children(".move").addClass("disabled"),a},getIndexSource:function(){var t=this.modal.elementIndex.getSourceByKey(this.sourceData.key);if(t)return t.closest("li")}}),Craft.CustomizeSourcesModal.Heading=Craft.CustomizeSourcesModal.BaseSource.extend({$labelField:null,$labelInput:null,$deleteBtn:null,isHeading:function(){return!0},select:function(){this.base(),this.$labelInput.trigger("focus")},createSettings:function(){var t=$("<div/>");return this.$labelField=Craft.ui.createTextField({label:Craft.t("app","Heading"),instructions:Craft.t("app","This can be left blank if you just want an unlabeled separator."),value:this.sourceData.heading}).appendTo(t),this.$labelInput=this.$labelField.find(".text"),t.append("<hr/>"),this.$deleteBtn=$('<a class="error delete"/>').text(Craft.t("app","Delete heading")).appendTo(t),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","deleteHeading"),t},handleLabelInputChange:function(){this.updateItemLabel(this.$labelInput.val()),this.modal.updateSourcesOnSave=!0},updateItemLabel:function(t){this.$itemLabel.html((t?Craft.escapeHtml(t):'<em class="light">'+Craft.t("app","(blank)")+"</em>")+"&nbsp;"),this.$itemInput.val(t)},deleteHeading:function(){this.modal.sourceSort.removeItems(this.$item),this.modal.sources.splice($.inArray(this,this.modal.sources),1),this.modal.updateSourcesOnSave=!0,this.isSelected()&&(this.deselect(),this.modal.sources.length&&this.modal.sources[0].select()),this.$item.remove(),this.$settingsContainer.remove(),this.destroy()},getIndexSource:function(){var t=this.$labelInput?this.$labelInput.val():this.sourceData.heading;return $('<li class="heading"/>').append($("<span/>").text(t))}})},1519:function(){Craft.DataTableSorter=Garnish.DragSort.extend({$table:null,init:function(t,e){this.$table=$(t);var i=this.$table.children("tbody").children(":not(.filler)");(e=$.extend({},Craft.DataTableSorter.defaults,e)).container=this.$table.children("tbody"),e.helper=this.getHelper.bind(this),e.caboose="<tr/>",e.axis=Garnish.Y_AXIS,e.magnetStrength=4,e.helperLagBase=1.5,this.base(i,e)},getHelper:function(t){var e=$('<div class="'+this.settings.helperClass+'"/>').appendTo(Garnish.$bod),i=$("<table/>").appendTo(e),s=$("<tbody/>").appendTo(i);t.appendTo(s),i.width(this.$table.width()),i.prop("className",this.$table.prop("className"));for(var a=this.$table.find("tr:first").children(),n=t.children(),r=0;r<n.length;r++)$(n[r]).width($(a[r]).width());return e}},{defaults:{handle:".move",helperClass:"datatablesorthelper"}})},501:function(){Craft.DeleteUserModal=Garnish.Modal.extend({id:null,userId:null,$deleteActionRadios:null,$deleteSpinner:null,userSelect:null,_deleting:!1,init:function(t,e){var i=this;this.id=Math.floor(1e9*Math.random()),this.userId=t,e=$.extend(Craft.DeleteUserModal.defaults,e);var s,a=$('<form class="modal fitted deleteusermodal" method="post" accept-charset="UTF-8">'+Craft.getCsrfInput()+'<input type="hidden" name="action" value="users/delete-user"/>'+(Garnish.isArray(this.userId)?"":'<input type="hidden" name="userId" value="'+this.userId+'"/>')+(e.redirect?'<input type="hidden" name="redirect" value="'+e.redirect+'"/>':"")+"</form>").appendTo(Garnish.$bod),n=$('<div class="body"><div class="content-summary"><p>'+Craft.t("app","What do you want to do with their content?")+'</p><ul class="bullets"></ul></div><div class="options"><label><input type="radio" name="contentAction" value="transfer"/> '+Craft.t("app","Transfer it to:")+'</label><div id="transferselect'+this.id+'" class="elementselect"><div class="elements"></div><button type="button" class="btn add icon dashed">'+Craft.t("app","Choose a user")+'</button></div></div><div><label class="error"><input type="radio" name="contentAction" value="delete"/> '+Craft.t("app","Delete their content")+"</label></div></div>").appendTo(a),r=$('<div class="buttons right"/>').appendTo(n),o=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(r);if(e.contentSummary.length)for(var l=0;l<e.contentSummary.length;l++)n.find("ul").append($("<li/>",{text:e.contentSummary[l]}));else n.find("ul").remove();if(this.$deleteActionRadios=n.find("input[type=radio]"),this.$deleteSubmitBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:this._submitBtnLabel(!1)}).appendTo(r),this.$deleteSpinner=$('<div class="spinner hidden"/>').appendTo(r),Garnish.isArray(this.userId)){s=["and"];for(var h=0;h<this.userId.length;h++)s.push("not "+this.userId[h])}else s="not "+this.userId;this.userSelect=new Craft.BaseElementSelectInput({id:"transferselect"+this.id,name:"transferContentTo",elementType:"craft\\elements\\User",criteria:{id:s},limit:1,modalSettings:{closeOtherModals:!1},onSelectElements:function(){i.updateSizeAndPosition(),i.$deleteActionRadios.first().prop("checked")?i.validateDeleteInputs():i.$deleteActionRadios.first().trigger("click")},onRemoveElements:this.validateDeleteInputs.bind(this),selectable:!1,editable:!1}),this.addListener(o,"click","hide"),this.addListener(this.$deleteActionRadios,"change","validateDeleteInputs"),this.addListener(a,"submit","handleSubmit"),this.base(a,e)},_submitBtnLabel:function(t){var e=t?"Delete {num, plural, =1{user} other{users}} and content":"Delete {num, plural, =1{user} other{users}}";return Craft.t("app",e,{num:Garnish.isArray(this.userId)?this.userId.length:1})},validateDeleteInputs:function(){var t=!1;return this.$deleteActionRadios.eq(1).prop("checked")?(t=!0,this.$deleteSubmitBtn.text(this._submitBtnLabel(!0))):(this.$deleteSubmitBtn.text(this._submitBtnLabel(!1)),this.$deleteActionRadios.eq(0).prop("checked")&&(t=!!this.userSelect.totalSelected)),this.updateSizeAndPosition(),t?this.$deleteSubmitBtn.removeClass("disabled"):this.$deleteSubmitBtn.addClass("disabled"),t},handleSubmit:function(t){if(!this._deleting&&this.validateDeleteInputs()){this.$deleteSubmitBtn.addClass("active"),this.$deleteSpinner.removeClass("hidden"),this.disable(),this.userSelect.disable(),this._deleting=!0;try{!1===this.settings.onSubmit()&&t.preventDefault()}catch(e){throw t.preventDefault(),this.$deleteSpinner.addClass("hidden"),e}}else t.preventDefault()},onFadeIn:function(){Garnish.isMobileBrowser(!0)||this.$deleteActionRadios.first().trigger("focus"),this.base()}},{defaults:{contentSummary:[],onSubmit:$.noop,redirect:null}})},1923:function(){function t(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.DraftEditor=Garnish.Base.extend({$revisionBtn:null,$revisionLabel:null,$spinner:null,$expandSiteStatusesBtn:null,$statusIcon:null,$editMetaBtn:null,metaHud:null,$nameTextInput:null,$saveMetaBtn:null,$siteStatusPane:null,$globalLightswitch:null,$siteLightswitches:null,$addlSiteField:null,siteIds:null,newSiteIds:null,enableAutosave:null,lastSerializedValue:null,listeningForChanges:!1,pauseLevel:0,timeout:null,saving:!1,cancelToken:null,ignoreFailedRequest:!1,queue:null,submittingForm:!1,duplicatedElements:null,errors:null,httpStatus:null,httpError:null,openingPreview:!1,preview:null,activatingPreviewToken:!1,activatedPreviewToken:!1,previewTokenQueue:null,previewLinks:null,scrollY:null,createdProvisionalDraft:!1,bc:null,init:function(e){var i,s,a=this;if(this.setSettings(e,Craft.DraftEditor.defaults),this.queue=[],this.previewTokenQueue=[],this.duplicatedElements={},this.enableAutosave=Craft.autosaveDrafts,this.previewLinks=[],this.siteIds=Object.keys(this.settings.siteStatuses).map((function(t){return parseInt(t)})),this.$revisionBtn=$("#context-btn"),this.$revisionLabel=$("#revision-label"),this.$spinner=$("#revision-spinner"),this.$expandSiteStatusesBtn=$("#expand-status-btn"),this.$statusIcon=$("#revision-status"),this.$statusMessage=$("#revision-status-message"),this.settings.canEditMultipleSites&&this.addListener(this.$expandSiteStatusesBtn,"click","expandSiteStatuses"),this.settings.previewTargets.length){this.settings.enablePreview&&this.addListener($("#preview-btn"),"click","openPreview");var n=$("#preview-btn-container");if(1===this.settings.previewTargets.length){var r=(i=this.settings.previewTargets,s=1,function(t){if(Array.isArray(t))return t}(i)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(i,s)||t(i,s)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];this.createPreviewLink(r).attr("id","share-btn").addClass("btn").appendTo(n)}else this.createShareMenu(n)}this.settings.revisionId||(Craft.cp.$primaryForm.data("serializer",(function(){return a.serializeForm(!0)})),this.addListener(Craft.cp.$primaryForm,"submit","handleFormSubmit"),this.settings.isProvisionalDraft?this.initForProvisionalDraft():this.settings.draftId&&!this.settings.isUnpublishedDraft?this.initForDraft():this.settings.canUpdateSource||this.addListener(Craft.cp.$primaryForm,"submit.saveShortcut",(function(t){t.saveShortcut&&(t.preventDefault(),a.createDraft(),a.removeListener(Craft.cp.$primaryForm,"submit.saveShortcut"))})),this.listenForChanges(),this.addListener(this.$statusIcon,"click",(function(){a.showStatusHud(a.$statusIcon)})),"undefined"==typeof BroadcastChannel||this.settings.revisionId||(this.bc=new BroadcastChannel("DraftEditor"),this.bc.onmessage=function(t){"saveDraft"===t.data.event&&t.data.canonicalId===a.settings.sourceId&&(t.data.draftId===a.settings.draftId||t.data.isProvisionalDraft&&!a.settings.draftId)&&window.location.reload()}))},listenForChanges:function(){this.listeningForChanges||this.pauseLevel>0||!this.enableAutosave||!this.settings.saveDraftAction||(this.listeningForChanges=!0,this.addListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(t){$(t.target).is(this.statusIcons())||(clearTimeout(this.timeout),["keypress","keyup","change"].includes(t.type)?this.timeout=setTimeout(this.checkForm.bind(this),500):this.checkForm())})))},stopListeningForChanges:function(){this.listeningForChanges&&(this.removeListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup"),clearTimeout(this.timeout),this.listeningForChanges=!1)},pause:function(){this.pauseLevel++,this.stopListeningForChanges()},resume:function(){if(0===this.pauseLevel)throw"Craft.DraftEditor::resume() should only be called after pause().";this.pauseLevel--,0===this.pauseLevel&&this.enableAutosave&&(this.checkForm(),this.listenForChanges())},initForProvisionalDraft:function(){var t=this,e=$("#discard-changes");e.length||(e=this.$revisionBtn.data("menubtn")?this.$revisionBtn.data("menubtn").menu.$container.find("#discard-changes"):null),e&&e.length&&this.addListener(e,"click",(function(){confirm(Craft.t("app","Are you sure you want to discard your changes?"))&&Craft.submitForm(Craft.cp.$primaryForm,{action:t.settings.deleteDraftAction,redirect:t.settings.hashedCpEditUrl,params:{draftId:t.settings.draftId,provisional:t.settings.isProvisionalDraft}})}))},initForDraft:function(){var t=this;this.createEditMetaBtn(),this.settings.canUpdateSource&&Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0,alt:!0},(function(){Craft.submitForm(Craft.cp.$primaryForm,{action:t.settings.publishDraftAction,redirect:t.settings.hashedCpEditUrl})}),0)},expandSiteStatuses:function(){var t=this;this.removeListener(this.$expandSiteStatusesBtn,"click"),this.$expandSiteStatusesBtn.velocity({opacity:0},"fast",(function(){t.$expandSiteStatusesBtn.remove()}));var e=$("#enabledForSite-".concat(this.settings.siteId,"-field"));if(this.$siteStatusPane=e.parent(),this.settings.revisionId)this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));else{e.addClass("nested");var i=Craft.ui.createLightswitchField({id:"enabled",label:Craft.t("app","Enabled"),name:"enabled"}).insertBefore(e);i.find("label").css("font-weight","bold"),this.$globalLightswitch=i.find(".lightswitch"),this.settings.revisionId||this._showField(i);var s=Object.values(this.settings.siteStatuses),a=s.includes(!0),n=s.includes(!1),r=a&&n?"-":a?"1":"",o=encodeURIComponent("enabledForSite[".concat(this.settings.siteId,"]"))+"="+(this.settings.enabledForSite?"1":"");this.$siteLightswitches=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this)),this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));for(var l="enabled=".concat(r),h=0;h<this.$siteLightswitches.length;h++){var d=this.$siteLightswitches.eq(h).data("lightswitch").$input;l+="&"+encodeURIComponent(d.attr("name"))+"="+d.val()}Craft.cp.$primaryForm.data("initialSerializedValue",Craft.cp.$primaryForm.data("initialSerializedValue").replace(o,l)),this.lastSerializedValue&&(this.lastSerializedValue=this.lastSerializedValue.replace(o,l)),this.settings.addlSites&&this.settings.addlSites.length&&this._createAddlSiteField(),this.$globalLightswitch.on("change",this._updateSiteStatuses.bind(this)),this._updateGlobalStatus()}},_getOtherSupportedSites:function(){var t=this;return Craft.sites.filter((function(e){return e.id!=t.settings.siteId&&t.siteIds.includes(e.id)}))},_showField:function(t){var e=t.height();t.css("overflow","hidden").height(0).velocity({height:e},"fast",(function(){t.css({overflow:"",height:""})}))},_removeField:function(t){t.height(),t.css("overflow","hidden").velocity({height:0},"fast",(function(){t.remove()}))},_updateGlobalStatus:function(){var t=!0,e=!0;this.$siteLightswitches.each((function(){if($(this).data("lightswitch").on?e=!1:t=!1,!t&&!e)return!1})),t?this.$globalLightswitch.data("lightswitch").turnOn(!0):e?this.$globalLightswitch.data("lightswitch").turnOff(!0):this.$globalLightswitch.data("lightswitch").turnIndeterminate(!0)},_updateSiteStatuses:function(){var t=this.$globalLightswitch.data("lightswitch").on;this.$siteLightswitches.each((function(){t?$(this).data("lightswitch").turnOn(!0):$(this).data("lightswitch").turnOff(!0)}))},_createSiteStatusField:function(t,e){var i=Craft.ui.createLightswitchField({id:"enabledForSite-".concat(t.id),label:Craft.t("app","Enabled for {site}",{site:t.name}),name:"enabledForSite[".concat(t.id,"]"),on:void 0!==e?e:!this.settings.siteStatuses.hasOwnProperty(t.id)||this.settings.siteStatuses[t.id],disabled:!!this.settings.revisionId});if(this.$addlSiteField?i.insertBefore(this.$addlSiteField):i.appendTo(this.$siteStatusPane),!this.settings.revisionId){i.addClass("nested");var s=i.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this));this.$siteLightswitches=this.$siteLightswitches.add(s)}return this._showField(i),i},_createAddlSiteField:function(){var i,s=this,a=Craft.sites.filter((function(t){return!s.siteIds.includes(t.id)&&s.settings.addlSites.some((function(e){return e.siteId==t.id}))}));if(a.length){var n=Craft.ui.createSelect({options:[{label:Craft.t("app","Add a site…")}].concat((i=a.map((function(t){return{label:t.name,value:t.id}})),function(t){if(Array.isArray(t))return e(t)}(i)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(i)||t(i)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()))}).addClass("fullwidth");this.$addlSiteField=Craft.ui.createField(n,{}).addClass("nested add").appendTo(this.$siteStatusPane);var r=n.find("select");r.on("change",(function(){var t=parseInt(r.val()),e=Craft.sites.find((function(e){return e.id===t}));if(e){var i=s.settings.addlSites.find((function(t){return t.siteId==e.id}));s._createSiteStatusField(e,i.enabledByDefault),s._updateGlobalStatus(),r.val("").find('option[value="'.concat(t,'"]')).remove(),null===s.newSiteIds&&(s.newSiteIds=[]),s.siteIds.push(t),s.newSiteIds.push(t),1===r.find("option").length&&s._removeField(s.$addlSiteField)}})),this._showField(this.$addlSiteField)}},showStatusHud:function(t){var e;null===this.errors?e="<p>".concat(this._saveSuccessMessage(),"</p>"):(e='<p class="error"><strong>'.concat(this._saveFailMessage(),"</strong></p>"),this.errors.length&&(e+='<ul class="errors">'+this.errors.map((function(t){return"<li>".concat(Craft.escapeHtml(t),"</li>")})).join("")+"</ul>"),this.httpError&&(e+='<p class="http-error code">'.concat(Craft.escapeHtml(this.httpError),"</p>")),400===this.httpStatus&&(e+='<button class="btn refresh-btn">'.concat(Craft.t("app","Refresh"),"</button>")));var i=new Garnish.HUD(t,e,{hudClass:"hud revision-status-hud",onHide:function(){i.destroy()}});i.$mainContainer.find(".refresh-btn").on("click",(function(){window.location.reload()}))},_saveSuccessMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes have been stored."):Craft.t("app","The draft has been saved.")},_saveFailMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes could not be stored."):Craft.t("app","The draft could not be saved.")},spinners:function(){return this.preview?this.$spinner.add(this.preview.$spinner):this.$spinner},statusIcons:function(){return this.preview?this.$statusIcon.add(this.preview.$statusIcon):this.$statusIcon},statusMessage:function(){return this.preview?this.$statusMessage.add(this.preview.$statusMessage):this.$statusMessage},createEditMetaBtn:function(){var t=$("#context-btngroup");this.$editMetaBtn=$("<button/>",{type:"button",class:"btn edit icon",title:Craft.t("app","Edit draft settings")}).appendTo(t),t.find(".btngroup-btn-last").removeClass("btngroup-btn-last"),this.addListener(this.$editMetaBtn,"click","showMetaHud")},createPreviewLink:function(t,e){var i=this,s=$("<a/>",{href:this.getTokenizedPreviewUrl(t.url,null,!1),text:e||Craft.t("app","View"),target:"_blank",data:{targetUrl:t.url,targetLabel:t.label}});return this.addListener(s,"click",(function(){setTimeout((function(){i.activatePreviewToken()}),1)})),this.previewLinks.push(s),s},updatePreviewLinks:function(){var t=this;this.previewLinks.forEach((function(e){t.updatePreviewLinkHref(e),t.activatedPreviewToken&&t.removeListener(e,"click")}))},updatePreviewLinkHref:function(t){t.attr("href",this.getTokenizedPreviewUrl(t.data("targetUrl"),null,!1))},activatePreviewToken:function(){this.settings.isLive||(this.activatedPreviewToken=!0,this.updatePreviewLinks())},createShareMenu:function(t){var e=this;$("<button/>",{id:"share-btn",type:"button",class:"btn menubtn",text:Craft.t("app","View")}).appendTo(t);var i=$("<div/>",{class:"menu"}).appendTo(t),s=$("<ul/>").appendTo(i);this.settings.previewTargets.forEach((function(t){$("<li/>").append(e.createPreviewLink(t,t.label)).appendTo(s)}))},getPreviewTokenParams:function(){var t={elementType:this.settings.elementType,sourceId:this.settings.sourceId,siteId:this.settings.siteId,revisionId:this.settings.revisionId,previewToken:this.settings.previewToken};return this.settings.draftId&&!this.settings.isProvisionalDraft&&(t.draftId=this.settings.draftId),t},getPreviewToken:function(){var t=this;return new Promise((function(e,i){t.activatedPreviewToken?e(t.settings.previewToken):t.activatingPreviewToken?t.previewTokenQueue.push(e):(t.activatingPreviewToken=!0,Craft.sendActionRequest("POST","preview/create-token",{data:t.getPreviewTokenParams()}).then((function(){for(t.activatingPreviewToken=!1,t.activatePreviewToken(),e(t.settings.previewToken);t.previewTokenQueue.length;)t.previewTokenQueue.shift()(t.settings.previewToken)})).catch(i))}))},getTokenizedPreviewUrl:function(t,e,i){var s=this;void 0===i&&(i=!0);var a={};if(!e&&this.settings.isLive||(a[e||"x-craft-preview"]=Craft.randomString(10)),this.settings.siteToken&&(a[Craft.siteToken]=this.settings.siteToken),this.settings.isLive){var n=Craft.getUrl(t,a);return i?new Promise((function(t){t(n)})):n}if(!this.settings.previewToken)throw"Missing preview token";a[Craft.tokenParam]=this.settings.previewToken;var r=Craft.getUrl(t,a);if(this.activatedPreviewToken)return i?new Promise((function(t){t(r)})):r;if(i)return new Promise((function(t,e){s.getPreviewToken().then((function(){t(r)})).catch(e)}));var o=this.getPreviewTokenParams();return o.redirect=encodeURIComponent(r),Craft.getActionUrl("preview/create-token",o)},getPreview:function(){var t=this;return this.preview||(this.preview=new Craft.Preview(this),this.enableAutosave||(this.preview.on("open",(function(){t.enableAutosave=!0,t.listenForChanges()})),this.preview.on("close",(function(){t.enableAutosave=!1,t.stopListeningForChanges();var e=t.statusIcons();e.hasClass("checkmark-icon")&&e.addClass("hidden")}))),this.preview.on("close",(function(){t.scrollY&&(window.scrollTo(0,t.scrollY),t.scrollY=null)}))),this.preview},openPreview:function(){var t=this;return new Promise((function(e,i){t.openingPreview=!0,t.ensureIsDraftOrRevision(!0).then((function(){t.scrollY=window.scrollY,t.getPreview().open(),t.openingPreview=!1,e()})).catch(i)}))},ensureIsDraftOrRevision:function(t){var e=this;return new Promise((function(i,s){if(e.settings.draftId||e.settings.revisionId)i();else{if(t&&e.serializeForm(!0)===Craft.cp.$primaryForm.data("initialSerializedValue"))return void i();e.createDraft().then(i).catch(s)}}))},serializeForm:function(t){var e=Craft.cp.$primaryForm.serialize();return this.isPreviewActive()&&(e=e.replace("__PREVIEW_FIELDS__=1",this.preview.$editor.serialize())),t&&!this.settings.isUnpublishedDraft&&(e=(e=e.replace(/&action=[^&]*/,"")).replace(/&redirect=[^&]*/,"")),e},checkForm:function(t){if(!(this.settings.revisionId||this.pauseLevel>0)&&this.enableAutosave&&this.settings.saveDraftAction)if(clearTimeout(this.timeout),this.timeout=null,void 0!==Craft.cp.$primaryForm.data("initialSerializedValue")){var e=this.serializeForm(!0);if(t||e!==(this.lastSerializedValue||Craft.cp.$primaryForm.data("initialSerializedValue"))){var i=(!this.settings.draftId||this.settings.isProvisionalDraft)&&!this.settings.revisionId;this.saveDraft(e,i).catch((function(t){console.warn("Couldn’t save draft:",t)}))}}else this.timeout=setTimeout(this.checkForm.bind(this),500)},isPreviewActive:function(){return this.preview&&this.preview.isActive},createDraft:function(){var t=this;return new Promise((function(e,i){t.saveDraft(t.serializeForm(!0)).then(e).catch(i)}))},saveDraft:function(t){var e=this;return new Promise((function(i,s){if(e.submittingForm)s("Form already being submitted.");else if(e.saving)e.queue.push((function(){e.checkForm()}));else{e.lastSerializedValue=t,e.saving=!0,e.errors=null,e.httpStatus=null,e.httpError=null,e.cancelToken=axios.CancelToken.source(),e.spinners().removeClass("hidden"),e.statusIcons().velocity("stop").css("opacity","").removeClass("invisible checkmark-icon alert-icon fade-out").addClass("hidden"),e.statusMessage().empty(),e.$saveMetaBtn&&e.$saveMetaBtn.addClass("active");var a=[],n=e.prepareData(t,e.settings.isUnpublishedDraft?void 0:function(t,e){e.length&&a.push(decodeURIComponent(e[0].split("=")[0]))});!e.settings.isProvisionalDraft&&e.settings.draftId||(n+="&provisional=1"),Craft.sendActionRequest("POST",e.settings.saveDraftAction,{cancelToken:e.cancelToken.token,headers:{"content-type":"application/x-www-form-urlencoded"},data:n}).then((function(n){e._afterSaveRequest(),n.data.errors&&(e.errors=n.data.errors,e._showFailStatus(),s(n.data.errors));var r=!e.settings.draftId;r&&(e.settings.isProvisionalDraft=!0,e.createdProvisionalDraft=!0),n.data.title&&$("#header h1").text(n.data.title),n.data.docTitle&&(document.title=n.data.docTitle),e.settings.isProvisionalDraft?r&&e.$revisionLabel.append($("<span/>",{text:" — ".concat(Craft.t("app","Edited"))})):(e.$revisionLabel.text(n.data.draftName),e.settings.draftName=n.data.draftName);var o=e.$revisionBtn.data("menubtn")?e.$revisionBtn.data("menubtn").menu:null;for(var l in e.newSiteIds&&(o||(e.$revisionBtn.removeClass("disabled").addClass("menubtn"),new Garnish.MenuBtn(e.$revisionBtn),(o=e.$revisionBtn.data("menubtn").menu).$container.removeClass("hidden")),e.newSiteIds.forEach((function(t){var i=o.$options.filter("[data-site-id=".concat(t,"]")),s=e.settings.addlSites.find((function(e){return e.siteId==t}));s&&void 0!==s.enabledByDefault&&!s.enabledByDefault||i.find(".status").removeClass("disabled").addClass("enabled"),i.parent().removeClass("hidden").closest(".site-group").removeClass("hidden")})),o.$container.find(".revision-hr").removeClass("hidden"),e.newSiteIds=null),e.settings.isProvisionalDraft?r&&($("#action").attr("value",e.settings.publishDraftAction),e.settings.draftId=n.data.draftId,e.settings.isLive=!1,e.previewToken=null,o&&o.$container.find("#current-revision").append($("<div/>",{class:"edited-desc"}).append($("<p/>",{text:Craft.t("app","Showing your unsaved changes.")})).append($("<button/>",{id:"discard-changes",class:"btn",text:Craft.t("app","Discard changes")}))),e.initForProvisionalDraft()):o&&(o.$options.filter(".sel").find(".draft-name").text(n.data.draftName),o.$options.filter(".sel").find(".draft-meta").text(n.data.creator?Craft.t("app","Saved {timestamp} by {creator}",{timestamp:n.data.timestamp,creator:n.data.creator}):Craft.t("app","Saved {timestamp}",{timestamp:n.data.timestamp}))),n.data.previewTargets&&JSON.stringify(n.data.previewTargets)!==JSON.stringify(e.settings.previewTargets)&&e.updatePreviewTargets(n.data.previewTargets),r&&(e.updatePreviewLinks(),e.trigger("createProvisionalDraft")),e.$nameTextInput&&e.checkMetaValues(),n.data.duplicatedElements)l!=e.settings.sourceId&&n.data.duplicatedElements.hasOwnProperty(l)&&(e.duplicatedElements[l]=n.data.duplicatedElements[l]);for(var h=n.data.modifiedAttributes.map((function(t){return'[name="'.concat(t,'"],[name^="').concat(t,'["]')})).concat(a.map((function(t){return'[name="'.concat(t,'"]')}))),d=$(h.join(",")).parents().filter(".field:not(:has(> .status-badge))"),c=0;c<d.length;c++)d.eq(c).prepend($("<div/>",{class:"status-badge modified",title:Craft.t("app","This field has been modified.")}).append($("<span/>",{class:"visually-hidden",html:Craft.t("app","This field has been modified.")})));e.afterUpdate(t),e.bc&&e.bc.postMessage({event:"saveDraft",canonicalId:e.settings.sourceId,draftId:e.settings.draftId,isProvisionalDraft:e.settings.isProvisionalDraft}),i()})).catch((function(t){e._afterSaveRequest(),e.ignoreFailedRequest||(e.errors=[],t&&t.response&&(e.httpStatus=t.response.status,e.httpError=t.response.data?t.response.data.error:null),e._showFailStatus(),s(t)),e.ignoreFailedRequest=!1}))}}))},_afterSaveRequest:function(){this.spinners().addClass("hidden"),this.$saveMetaBtn&&this.$saveMetaBtn.removeClass("active"),this.saving=!1},_showFailStatus:function(){this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden checkmark-icon").addClass("alert-icon"),this.setStatusMessage(this._saveFailMessage())},prepareData:function(t,e){return t=Craft.findDeltaData(Craft.cp.$primaryForm.data("initialSerializedValue"),t,Craft.deltaNames,e),t=this.swapDuplicatedElementIds(t),this.settings.draftId&&(t+="&draftId=".concat(this.settings.draftId),this.settings.isProvisionalDraft&&(t+="&provisional=1")),null!==this.settings.draftName&&(t+="&draftName=".concat(this.settings.draftName)),t},swapDuplicatedElementIds:function(t){var e=this,i=Object.keys(this.duplicatedElements).join("|");if(""===i)return t;for(var s=encodeURIComponent("["),a=encodeURIComponent("]");t!==(t=t.replace(new RegExp("(&fields".concat(s,"[^=]+").concat(a).concat(s,")(").concat(i,")(").concat(a,")"),"g"),(function(t,i,s,a){return i+e.duplicatedElements[s]+a})).replace(new RegExp("&(fields".concat(s,"[^=]+)=(").concat(i,")\\b"),"g"),(function(t,i,n){return i.match(new RegExp("".concat(s,"(enabled|sortOrder|type|typeId)").concat(a,"$")))?t:"&".concat(i,"=").concat(e.duplicatedElements[n])}))););return t},updatePreviewTargets:function(t){var e=this;t.forEach((function(t){var i=e.settings.previewTargets.find((function(e){return e.label===t.label}));i&&(i.url=t.url);var s=e.previewLinks.find((function(e){return e.data("targetLabel")===t.label}));s&&(s.data("targetUrl",t.url),e.updatePreviewLinkHref(s))}))},afterUpdate:function(t){Craft.cp.$primaryForm.data("initialSerializedValue",t),Craft.initialDeltaValues={};var e=this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden").addClass("checkmark-icon");this.setStatusMessage(this._saveSuccessMessage()),Craft.autosaveDrafts||e.velocity("stop").velocity({opacity:0},{delay:2e3,complete:function(){e.addClass("hidden")}}),this.trigger("update"),this.nextInQueue()},setStatusMessage:function(t){this.statusIcons().attr("title",t),this.statusMessage().empty().append($("<span/>",{class:"visually-hidden",text:t}))},nextInQueue:function(){this.queue.length&&this.queue.shift()()},showMetaHud:function(){this.metaHud?this.metaHud.show():(this.createMetaHud(),this.onMetaHudShow()),Garnish.isMobileBrowser(!0)||this.$nameTextInput.trigger("focus")},createMetaHud:function(){var t=$("<div/>"),e=$('<div class="field"><div class="heading"><label for="draft-name">'+Craft.t("app","Draft Name")+"</label></div></div>").appendTo(t),i=$('<div class="input"/>').appendTo(e);this.$nameTextInput=$('<input type="text" class="text fullwidth" id="draft-name"/>').appendTo(i).val(this.settings.draftName);var s=$('<div class="hud-footer flex flex-center"/>').appendTo(t);$('<div class="flex-grow"></div>').appendTo(s),this.$saveMetaBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(s),this.metaHud=new Garnish.HUD(this.$editMetaBtn,t,{onSubmit:this.saveMeta.bind(this)}),this.addListener(this.$nameTextInput,"input","checkMetaValues"),this.metaHud.on("show",this.onMetaHudShow.bind(this)),this.metaHud.on("hide",this.onMetaHudHide.bind(this)),this.metaHud.on("escape",this.onMetaHudEscape.bind(this))},onMetaHudShow:function(){this.$editMetaBtn.addClass("active")},onMetaHudHide:function(){this.$editMetaBtn.removeClass("active")},onMetaHudEscape:function(){this.$nameTextInput.val(this.settings.draftName)},checkMetaValues:function(){return this.$nameTextInput.val()&&this.$nameTextInput.val()!==this.settings.draftName?(this.$saveMetaBtn.removeClass("disabled"),!0):(this.$saveMetaBtn.addClass("disabled"),!1)},shakeMetaHud:function(){Garnish.shake(this.metaHud.$hud)},saveMeta:function(){this.checkMetaValues()?(this.settings.draftName=this.$nameTextInput.val(),this.metaHud.hide(),this.checkForm(!0)):this.shakeMetaHud()},handleFormSubmit:function(t){if(t.preventDefault(),!this.submittingForm)if(!this.settings.draftId||this.settings.isUnpublishedDraft||this.settings.isProvisionalDraft||void 0!==t.autosave&&!t.autosave||!(t.saveShortcut||t.customTrigger&&t.customTrigger.data("action")===this.settings.saveDraftAction)||!this.enableAutosave){Craft.cp.$confirmUnloadForms=Craft.cp.$confirmUnloadForms.not(Craft.cp.$primaryForm),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel());var e=this.prepareData(this.serializeForm(!1)),i=Craft.createForm(e);i.appendTo(Garnish.$bod),i.submit(),this.submittingForm=!0}else this.checkForm(!0)}},{defaults:{elementType:null,sourceId:null,siteId:null,isUnpublishedDraft:!1,enabled:!1,enabledForSite:!1,isLive:!1,isProvisionalDraft:!1,siteStatuses:null,addlSites:[],cpEditUrl:null,draftId:null,revisionId:null,draftName:null,canEditMultipleSites:!1,canUpdateSource:!1,saveDraftAction:null,deleteDraftAction:null,publishDraftAction:null,hashedCpEditUrl:null,hashedAddAnotherRedirectUrl:null,enablePreview:!1,previewTargets:[],previewToken:null,siteToken:null}})},2318:function(){Craft.DynamicGenerator=Craft.BaseInputGenerator.extend({callback:$.noop,init:function(t,e,i){this.callback=i,this.base(t,e)},generateTargetValue:function(t){return this.callback(t)}})},4755:function(){Craft.EditableTable=Garnish.Base.extend({initialized:!1,id:null,baseName:null,columns:null,sorter:null,biggestId:-1,$table:null,$tbody:null,$addRowBtn:null,$tableParent:null,$statusMessage:null,rowCount:0,hasMaxRows:!1,hasMinRows:!1,radioCheckboxes:null,init:function(t,e,i,s){var a=this;if(this.id=t,this.baseName=e,this.columns=i,this.setSettings(s,Craft.EditableTable.defaults),this.radioCheckboxes={},this.$table=$("#"+t),this.$tbody=this.$table.children("tbody"),this.$tableParent=this.$table.parent(),this.$statusMessage=this.$tableParent.find("[data-status-message]"),this.rowCount=this.$tbody.find("tr").length,this.$table.data("editable-table")&&(console.warn("Double-instantiating an editable table on an element"),this.$table.data("editable-table").destroy()),this.$table.data("editable-table",this),this.sorter=new Craft.DataTableSorter(this.$table,{helperClass:"editabletablesorthelper",copyDraggeeInputValuesToHelper:!0,onSortChange:function(){a.updateAllRows()}}),this.isVisible()?this.initialize():setTimeout(this.initializeIfVisible.bind(this),500),this.settings.minRows&&this.rowCount<this.settings.minRows)for(var n=this.rowCount;n<this.settings.minRows;n++)this.addRow()},isVisible:function(){return this.$table.parent().height()>0},initialize:function(){if(this.initialized)return!1;this.initialized=!0,this.removeListener(Garnish.$win,"resize");for(var t=this.$tbody.children(),e=0;e<t.length;e++)this.createRowObj(t[e]);var i=this.$table.parent(".input");return i.length&&this.$table.width()>i.width()&&i.css("overflow-x","auto"),this.$addRowBtn=this.$table.next(".add"),this.updateAddRowButton(),this.addListener(this.$addRowBtn,"activate","addRow"),!0},initializeIfVisible:function(){this.removeListener(Garnish.$win,"resize"),this.isVisible()?this.initialize():this.addListener(Garnish.$win,"resize","initializeIfVisible")},updateAddRowButton:function(){this.canAddRow()?(this.$addRowBtn.css("opacity","1"),this.$addRowBtn.css("pointer-events","auto"),this.$addRowBtn.attr("aria-disabled","false")):(this.$addRowBtn.css("opacity","0.2"),this.$addRowBtn.css("pointer-events","none"),this.$addRowBtn.attr("aria-disabled","true"))},updateAllRows:function(){if(!this.settings.staticRows)for(var t=this.$table.find("> tbody > tr"),e=0;e<t.length;e++)this.updateRow(t.eq(e))},updateRow:function(t){if(!this.settings.staticRows){var e=t.find("button.delete");e.length&&(e.attr("aria-label",Craft.t("app","Delete row {index}",{index:t.index()+1})),this.canDeleteRow()?e.removeAttr("disabled").removeClass("disabled"):e.attr("disabled","disabled").addClass("disabled"))}},updateDeleteRowButton:function(t){this.updateRow(this.$table.find('tr[data-id="'.concat(t,'"]')))},updateStatusMessage:function(){var t,e=this;this.$statusMessage.empty(),t=this.canAddRow()?Craft.t("app","Row could not be deleted. Minimum number of rows reached."):Craft.t("app","Row could not be added. Maximum number of rows reached."),setTimeout((function(){e.$statusMessage.text(t)}),250)},canDeleteRow:function(){return this.rowCount>this.settings.minRows},deleteRow:function(t){this.canDeleteRow()?(this.sorter.removeItems(t.$tr),t.$tr.remove(),this.rowCount--,this.updateAllRows(),this.updateAddRowButton(),0===this.rowCount&&this.$table.addClass("hidden"),this.settings.onDeleteRow(t.$tr),t.destroy()):this.updateStatusMessage()},canAddRow:function(){return!this.settings.staticRows&&(!this.settings.maxRows||this.rowCount<this.settings.maxRows)},addRow:function(t,e){if(this.canAddRow()){var i=this.settings.rowIdPrefix+(this.biggestId+1),s=this.createRow(i,this.columns,this.baseName,$.extend({},this.settings.defaultValues));e?s.prependTo(this.$tbody):s.appendTo(this.$tbody);var a=this.createRowObj(s);return this.sorter.addItems(s),!1!==t&&s.find("input:visible,textarea:visible,select:visible").first().trigger("focus"),this.rowCount++,this.updateAllRows(),this.updateAddRowButton(),this.$table.removeClass("hidden"),this.settings.onAddRow(s),a}this.updateStatusMessage()},createRow:function(t,e,i,s){return Craft.EditableTable.createRow(t,e,i,s)},createRowObj:function(t){return new Craft.EditableTable.Row(this,t)},focusOnPrevRow:function(t,e,i){var s,a=t.prev("tr");if((s=a.length?a.data("editable-table-row"):this.addRow(!1,!0))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))a&&this.focusOnPrevRow(a,e,i);else{var n=$("textarea,input.text",s.$tds[e]);n.length&&($(i).trigger("blur"),n.trigger("focus"))}},focusOnNextRow:function(t,e,i){var s,a=t.next("tr");if((s=a.length?a.data("editable-table-row"):this.addRow(!1))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))a&&this.focusOnNextRow(a,e,i);else{var n=$("textarea,input.text",s.$tds[e]);n.length&&($(i).trigger("blur"),n.trigger("focus"))}},importData:function(t,e,i){for(var s=t.split(/\r?\n|\r/),a=0;a<s.length;a++){for(var n=s[a].split("\t"),r=0;r<n.length;r++){var o=n[r];e.$tds.eq(i+r).find("textarea,input[type!=hidden]").val(o).trigger("input")}var l=e.$tr.next("tr");e=l.length?l.data("editable-table-row"):this.addRow(!1)}},destroy:function(){this.$table.removeData("editable-table"),this.base()}},{textualColTypes:["autosuggest","color","date","email","multiline","number","singleline","template","time","url"],defaults:{rowIdPrefix:"",defaultValues:{},staticRows:!1,minRows:null,maxRows:null,onAddRow:$.noop,onDeleteRow:$.noop},createRow:function(t,e,i,s){var a=$("<tr/>",{"data-id":t});for(var n in e)if(e.hasOwnProperty(n)){var r,o=e[n],l=void 0!==s[n]?s[n]:"";if("heading"===o.type)r=$("<th/>",{scope:"row",class:o.class,html:l});else{var h=i+"["+t+"]["+n+"]";switch(r=$("<td/>",{class:"".concat(o.class," ").concat(o.type,"-cell"),width:o.width}),Craft.inArray(o.type,Craft.EditableTable.textualColTypes)&&r.addClass("textual"),o.code&&r.addClass("code"),o.type){case"checkbox":$('<div class="checkbox-wrapper"/>').append(Craft.ui.createCheckbox({name:h,value:o.value||"1",checked:!!l})).appendTo(r);break;case"color":Craft.ui.createColorInput({name:h,value:l,small:!0}).appendTo(r);break;case"date":Craft.ui.createDateInput({name:h,value:l}).appendTo(r);break;case"lightswitch":Craft.ui.createLightswitch({name:h,value:o.value||"1",on:!!l,small:!0}).appendTo(r);break;case"select":Craft.ui.createSelect({name:h,options:o.options,value:l||function(){for(var t in o.options)if(o.options.hasOwnProperty(t)&&o.options[t].default)return void 0!==o.options[t].value?o.options[t].value:t;return null}(),class:"small"}).appendTo(r);break;case"time":Craft.ui.createTimeInput({name:h,value:l}).appendTo(r);break;case"email":case"url":Craft.ui.createTextInput({name:h,value:l,type:o.type,placeholder:o.placeholder||null}).appendTo(r);break;default:$("<textarea/>",{name:h,rows:o.rows||1,val:l,placeholder:o.placeholder}).appendTo(r)}}r.appendTo(a)}return $("<td/>",{class:"thin action"}).append($("<a/>",{class:"move icon",title:Craft.t("app","Reorder")})).appendTo(a),$("<td/>",{class:"thin action"}).append($("<button/>",{class:"delete icon",title:Craft.t("app","Delete"),type:"button"})).appendTo(a),a}}),Craft.EditableTable.Row=Garnish.Base.extend({table:null,id:null,niceTexts:null,$tr:null,$tds:null,tds:null,$textareas:null,$deleteBtn:null,init:function(t,e){this.table=t,this.$tr=$(e),this.$tds=this.$tr.children(),this.tds=[],this.id=this.$tr.attr("data-id"),this.$tr.data("editable-table-row",this);var i=parseInt(this.id.substr(this.table.settings.rowIdPrefix.length));i>this.table.biggestId&&(this.table.biggestId=i),this.$textareas=$(),this.niceTexts=[];var s,a,n,r,o,l={},h=0;for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(a=this.table.columns[s],n=this.tds[s]=this.$tds[h],Craft.inArray(a.type,Craft.EditableTable.textualColTypes)?(r=$("textarea",n),this.$textareas=this.$textareas.add(r),this.addListener(r,"focus","onTextareaFocus"),this.addListener(r,"mousedown","ignoreNextTextareaFocus"),this.niceTexts.push(new Garnish.NiceText(r,{onHeightChange:this.onTextareaHeightChange.bind(this)})),this.addListener(r,"keypress",{tdIndex:h,type:a.type},"handleKeypress"),this.addListener(r,"input",{type:a.type},"validateValue"),r.trigger("input"),"multiline"!==a.type&&this.addListener(r,"paste",{tdIndex:h,type:a.type},"handlePaste"),l[s]=r):"checkbox"===a.type&&(o=$('input[type="checkbox"]',n),a.radioMode&&(void 0===this.table.radioCheckboxes[s]&&(this.table.radioCheckboxes[s]=[]),this.table.radioCheckboxes[s].push(o[0]),this.addListener(o,"change",{colId:s},"onRadioCheckboxChange")),a.toggle&&this.addListener(o,"change",{colId:s},(function(t){this.applyToggleCheckbox(t.data.colId)}))),$(n).hasClass("disabled")||this.addListener(n,"click",{td:n},(function(t){t.target===t.data.td&&$(t.data.td).find("textarea,input,select,.lightswitch").focus()})),h++);for(s in this.onTextareaHeightChange(),this.table.columns)this.table.columns.hasOwnProperty(s)&&"checkbox"===(a=this.table.columns[s]).type&&a.toggle&&this.applyToggleCheckbox(s);for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(a=this.table.columns[s]).autopopulate&&void 0!==l[a.autopopulate]&&!l[s].val()&&new Craft.HandleGenerator(l[s],l[a.autopopulate],{allowNonAlphaStart:!0});var d=this.$tr.children().last().find(".delete");this.addListener(d,"click","deleteRow");var c=this.$tr.find("input,textarea,select,.lightswitch");this.addListener(c,"focus",(function(t){$(t.currentTarget).closest("td:not(.disabled)").addClass("focus")})),this.addListener(c,"blur",(function(t){$(t.currentTarget).closest("td").removeClass("focus")}))},onTextareaFocus:function(t){this.onTextareaHeightChange();var e=$(t.currentTarget);e.data("ignoreNextFocus")?e.data("ignoreNextFocus",!1):setTimeout((function(){Craft.selectFullValue(e)}),0)},onRadioCheckboxChange:function(t){if(t.currentTarget.checked)for(var e=0;e<this.table.radioCheckboxes[t.data.colId].length;e++){var i=this.table.radioCheckboxes[t.data.colId][e];i.checked=i===t.currentTarget}},applyToggleCheckbox:function(t){for(var e,i,s=this.table.columns[t],a=$('input[type="checkbox"]',this.tds[t]).prop("checked"),n=0;n<s.toggle.length;n++)e=s.toggle[n],this.table.colum,(i="!"===e[0])&&(e=e.substr(1)),a&&!i||!a&&i?$(this.tds[e]).removeClass("disabled").find("textarea, input").prop("disabled",!1):$(this.tds[e]).addClass("disabled").find("textarea, input").prop("disabled",!0)},ignoreNextTextareaFocus:function(t){$.data(t.currentTarget,"ignoreNextFocus",!0)},handleKeypress:function(t){var e=t.keyCode?t.keyCode:t.charCode,i=Garnish.isCtrlKeyPressed(t);if(e===Garnish.RETURN_KEY&&("multiline"!==t.data.type||i))return t.preventDefault(),void(t.shiftKey?this.table.focusOnPrevRow(this.$tr,t.data.tdIndex,t.currentTarget):this.table.focusOnNextRow(this.$tr,t.data.tdIndex,t.currentTarget));"number"!==t.data.type||i||Craft.inArray(e,Craft.EditableTable.Row.numericKeyCodes)||t.preventDefault()},handlePaste:function(t){var e=Craft.trim(t.originalEvent.clipboardData.getData("Text")," \n\r");e.match(/[\t\r\n]/)&&(t.preventDefault(),this.table.importData(e,this,t.data.tdIndex))},validateValue:function(t){if("multiline"!==t.data.type){var e;if("number"===t.data.type){var i=t.currentTarget.value.match(/^\s*(-?[\d\\.]*)/);e=null!==i?i[1]:""}else e=t.currentTarget.value.replace(/[\r\n]/g,"");e!==t.currentTarget.value&&(t.currentTarget.value=e)}},onTextareaHeightChange:function(){for(var t=-1,e=0;e<this.niceTexts.length;e++)this.niceTexts[e].height>t&&(t=this.niceTexts[e].height);this.$textareas.css("min-height",t);var i=this.$textareas.filter(":visible").first().parent().height();i>t&&this.$textareas.css("min-height",i)},deleteRow:function(){this.table.deleteRow(this)}},{numericKeyCodes:[9,8,37,38,39,40,45,91,46,190,48,49,50,51,52,53,54,55,56,57]})},8468:function(){Craft.ElementActionTrigger=Garnish.Base.extend({maxLevels:null,newChildUrl:null,$trigger:null,$selectedItems:null,triggerEnabled:!0,init:function(t){this.setSettings(t,Craft.ElementActionTrigger.defaults),this.$trigger=$("#"+t.type.replace(/[\[\]\\]+/g,"-")+"-actiontrigger"),this.settings.activate&&(this.$trigger.data("custom-handler",!0),"FORM"===this.$trigger.prop("nodeName")?this.addListener(this.$trigger,"submit","handleTriggerActivation"):this.addListener(this.$trigger,"click","handleTriggerActivation")),this.updateTrigger(),Craft.elementIndex.on("selectionChange",this.updateTrigger.bind(this))},updateTrigger:function(){0!==Craft.elementIndex.getSelectedElements().length&&(this.validateSelection()?this.enableTrigger():this.disableTrigger())},validateSelection:function(){var t=!0;return this.$selectedItems=Craft.elementIndex.getSelectedElements(),!this.settings.batch&&this.$selectedItems.length>1?t=!1:"function"==typeof this.settings.validateSelection&&(t=this.settings.validateSelection(this.$selectedItems)),t},enableTrigger:function(){this.triggerEnabled||(this.$trigger.removeClass("disabled"),this.triggerEnabled=!0)},disableTrigger:function(){this.triggerEnabled&&(this.$trigger.addClass("disabled"),this.triggerEnabled=!1)},handleTriggerActivation:function(t){t.preventDefault(),t.stopPropagation(),this.triggerEnabled&&this.settings.activate(this.$selectedItems)}},{defaults:{type:null,batch:!0,validateSelection:null,activate:null}})},8895:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.ElementThumbLoader=Garnish.Base.extend({queue:null,workers:[],init:function(){this.queue=[];for(var t=0;t<3;t++)this.workers.push(new Craft.ElementThumbLoader.Worker(this))},load:function(t){for(var e=this,i=t.find(".elementthumb"),s=function(t){var s=i.eq(t),a=s.scrollParent();if("FIELDSET"===a.prop("nodeName")&&(a=a.scrollParent()),a[0]===document.body&&(a=Garnish.$doc),e.isVisible(s,a))e.addToQueue(s[0]);else{var n="thumb"+Math.floor(1e6*Math.random());Craft.ElementThumbLoader.invisibleThumbs[n]=[e,s,a],a.on("scroll.".concat(n),{$thumb:s,$scrollParent:a,key:n},(function(t){e.isVisible(t.data.$thumb,t.data.$scrollParent)&&(delete Craft.ElementThumbLoader.invisibleThumbs[t.data.key],a.off("scroll.".concat(t.data.key)),e.addToQueue(t.data.$thumb[0]))}))}},a=0;a<i.length;a++)s(a)},addToQueue:function(t){this.queue.push(t);for(var e=0;e<this.workers.length;e++)this.workers[e].active||this.workers[e].loadNext()},isVisible:function(t,e){var i,s,a=t.offset().top;return e[0]===document?(i=e.scrollTop(),s=Garnish.$win.height()):(i=e.offset().top,s=e.height()),a>i&&a<i+s+1e3},destroy:function(){for(var t=0;t<this.workers.length;t++)this.workers[t].destroy();this.base()}},{invisibleThumbs:{},retryAll:function(){for(var e in Craft.ElementThumbLoader.invisibleThumbs){var i=(r=Craft.ElementThumbLoader.invisibleThumbs[e],o=3,function(t){if(Array.isArray(t))return t}(r)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(r,o)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(r,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),s=i[0],a=i[1],n=i[2];delete Craft.ElementThumbLoader.invisibleThumbs[e],n.off("scroll.".concat(e)),s.load(a.parent())}var r,o}}),Craft.ElementThumbLoader.Worker=Garnish.Base.extend({loader:null,active:!1,init:function(t){this.loader=t},loadNext:function(){var t=this.loader.queue.shift();if(void 0!==t){this.active=!0;var e=$(t);if(e.find("img").length)this.loadNext();else{var i=$("<img/>",{sizes:e.attr("data-sizes"),srcset:e.attr("data-srcset"),alt:""});this.addListener(i,"load,error","loadNext"),i.appendTo(e),picturefill({elements:[i[0]]})}}else this.active=!1}})},4233:function(){Craft.ElevatedSessionForm=Garnish.Base.extend({$form:null,inputs:null,init:function(t,e){if(this.$form=$(t),void 0!==e){this.inputs=[],e=$.makeArray(e);for(var i=0;i<e.length;i++)for(var s=$(e[i]),a=0;a<s.length;a++){var n=s.eq(a);this.inputs.push({input:n,val:Garnish.getInputPostVal(n)})}}this.addListener(this.$form,"submit","handleFormSubmit")},handleFormSubmit:function(t){if(Craft.elevatedSessionManager.fetchingTimeout)return t.preventDefault(),void t.stopImmediatePropagation();if(this.inputs){for(var e,i=!1,s=0;s<this.inputs.length;s++)if((e=this.inputs[s].input).data("passwordInput")&&(e=e.data("passwordInput").$currentInput),Garnish.getInputPostVal(e)!==this.inputs[s].val){i=!0;break}if(!i)return}t.preventDefault(),t.stopImmediatePropagation(),Craft.elevatedSessionManager.requireElevatedSession(this.submitForm.bind(this))},submitForm:function(){this.disable(),this.$form.trigger("submit"),this.enable()}})},9699:function(){Craft.ElevatedSessionManager=Garnish.Base.extend({fetchingTimeout:!1,passwordModal:null,$passwordInput:null,$passwordSpinner:null,$submitBtn:null,$errorPara:null,callback:null,requireElevatedSession:function(t){var e=this;this.callback=t,this.fetchingTimeout=!0,Craft.postActionRequest("users/get-elevated-session-timeout",(function(t,i){e.fetchingTimeout=!1,"success"===i&&(!1===t.timeout||t.timeout>=Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout?e.callback():e.showPasswordModal())}))},showPasswordModal:function(){var t=this;if(this.passwordModal)this.passwordModal.show();else{var e=$('<form id="elevatedsessionmodal" class="modal secure fitted"/>'),i=$('<div class="body"><p>'+Craft.t("app","Enter your password to continue.")+"</p></div>").appendTo(e),s=$('<div class="inputcontainer">').appendTo(i),a=$('<div class="flex"/>').appendTo(s),n=$('<div class="flex-grow"/>').appendTo(a),r=$("<td/>").appendTo(a),o=$('<div class="passwordwrapper"/>').appendTo(n);this.$passwordInput=$('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'" autocomplete="current-password"/>').appendTo(o),this.$passwordSpinner=$('<div class="spinner hidden"/>').appendTo(s),this.$submitBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Submit")}).appendTo(r),this.$errorPara=$('<p class="error"/>').appendTo(i),this.passwordModal=new Garnish.Modal(e,{closeOtherModals:!1,onFadeIn:function(){setTimeout(t.focusPasswordInput.bind(t),100)},onFadeOut:function(){t.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(e){t.$passwordInput=e}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(e,"submit","submitPassword")}},focusPasswordInput:function(){Garnish.isMobileBrowser(!0)||this.$passwordInput.trigger("focus")},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$submitBtn.removeClass("disabled"),!0):(this.$submitBtn.addClass("disabled"),!1)},submitPassword:function(t){var e=this;if(t&&t.preventDefault(),this.validatePassword()){this.$passwordSpinner.removeClass("hidden"),this.clearLoginError();var i={currentPassword:this.$passwordInput.val()};Craft.postActionRequest("users/start-elevated-session",i,(function(t,i){e.$passwordSpinner.addClass("hidden"),"success"===i?t.success?(e.passwordModal.hide(),e.callback()):(e.showPasswordError(t.message||Craft.t("app","Incorrect password.")),Garnish.shake(e.passwordModal.$container),e.focusPasswordInput()):e.showPasswordError()}))}},showPasswordError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$errorPara.text(t),this.passwordModal.updateSizeAndPosition()},clearLoginError:function(){this.showPasswordError("")}},{minSafeElevatedSessionTimeout:5}),Craft.elevatedSessionManager=new Craft.ElevatedSessionManager},1402:function(){Craft.EntryIndex=Craft.BaseElementIndex.extend({publishableSections:null,$newEntryBtnGroup:null,$newEntryBtn:null,init:function(t,e,i){this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){this.publishableSections=[];for(var t=0;t<Craft.publishableSections.length;t++){var e=Craft.publishableSections[t];this.getSourceByKey("section:"+e.uid)&&this.publishableSections.push(e)}this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSectionHandle){if("singles"===defaultSectionHandle)return"singles";for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultSectionHandle)return e.data("key")}}return this.base()},updateButton:function(){var t=this;if(this.$source){var e,i,s,a;if(e="singles"===this.$source.data("key")?"singles":this.$source.data("handle"),this.publishableSections.length){var n,r;if(this.$newEntryBtnGroup&&this.$newEntryBtnGroup.remove(),e)for(i=0;i<this.publishableSections.length;i++)if(this.publishableSections[i].handle===e){n=this.publishableSections[i];break}if(this.$newEntryBtnGroup=$('<div class="btngroup submit"/>'),n?(s=this._getSectionTriggerHref(n),a="index"===this.settings.context?Craft.t("app","New entry"):Craft.t("app","New {section} entry",{section:n.name}),this.$newEntryBtn=$('<a class="btn submit add icon" '+s+' role="button" tabindex="0">'+Craft.escapeHtml(a)+"</a>").appendTo(this.$newEntryBtnGroup),"index"!==this.settings.context&&this.addListener(this.$newEntryBtn,"click",(function(t){this._openCreateEntryModal(t.currentTarget.getAttribute("data-id"))})),this.publishableSections.length>1&&(r=$("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newEntryBtnGroup))):this.$newEntryBtn=r=$("<button/>",{type:"button",class:"btn submit add icon menubtn",text:Craft.t("app","New entry")}).appendTo(this.$newEntryBtnGroup),r){var o='<div class="menu"><ul>';for(i=0;i<this.publishableSections.length;i++){var l=this.publishableSections[i];("index"===this.settings.context&&-1!==$.inArray(this.siteId,l.sites)||"index"!==this.settings.context&&l!==n)&&(s=this._getSectionTriggerHref(l),a="index"===this.settings.context?l.name:Craft.t("app","New {section} entry",{section:l.name}),o+="<li><a "+s+">"+Craft.escapeHtml(a)+"</a></li>")}o+="</ul></div>",$(o).appendTo(this.$newEntryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",(function(e){t._openCreateEntryModal(e.option.getAttribute("data-id"))}))}this.addButton(this.$newEntryBtnGroup)}if("index"===this.settings.context&&"undefined"!=typeof history){var d="entries";e&&(d+="/"+e),history.replaceState({},"",Craft.getUrl(d))}}},_getSectionTriggerHref:function(t){if("index"===this.settings.context){var e="entries/".concat(t.handle,"/new"),i=this.getSite(),s=i?{site:i.handle}:void 0;return'href="'.concat(Craft.getUrl(e,s),'"')}return'data-id="'.concat(t.id,'"')},_openCreateEntryModal:function(t){var e=this;if(!this.$newEntryBtn.hasClass("loading")){for(var i,s=0;s<this.publishableSections.length;s++)if(this.publishableSections[s].id==t){i=this.publishableSections[s];break}if(i){this.$newEntryBtn.addClass("inactive");var a=this.$newEntryBtn.text();this.$newEntryBtn.text(Craft.t("app","New {section} entry",{section:i.name})),Craft.createElementEditor(this.elementType,{hudTrigger:this.$newEntryBtnGroup,siteId:this.siteId,attributes:{sectionId:t,typeId:i.entryTypes[0].id,enabled:i.canPublish?1:0},onHideHud:function(){e.$newEntryBtn.removeClass("inactive").text(a)},onSaveElement:function(t){var s="section:"+i.uid;e.sourceKey!==s&&e.selectSourceByKey(s),e.clearSearch(),e.setSortAttribute("dateCreated"),e.setSortDirection("desc"),e.selectElementAfterUpdate(t.id),e.updateElements()}})}}}}),Craft.registerElementIndexClass("craft\\elements\\Entry",Craft.EntryIndex)},8201:function(){Craft.FieldLayoutDesigner=Garnish.Base.extend({$container:null,$tabContainer:null,$newTabBtn:null,$sidebar:null,$libraryToggle:null,$selectedLibrary:null,$fieldLibrary:null,$uiLibrary:null,$uiLibraryElements:null,$fieldSearch:null,$clearFieldSearchBtn:null,$fieldGroups:null,$fields:null,tabGrid:null,elementDrag:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.FieldLayoutDesigner.defaults);var s=this.$container.children(".fld-workspace");this.$tabContainer=s.children(".fld-tabs"),this.$newTabBtn=s.children(".fld-new-tab-btn"),this.$sidebar=this.$container.children(".fld-sidebar"),this.$fieldLibrary=this.$selectedLibrary=this.$sidebar.children(".fld-field-library");var a=this.$fieldLibrary.children(".search");this.$fieldSearch=a.children("input"),this.$clearFieldSearchBtn=a.children(".clear"),this.$fieldGroups=this.$sidebar.find(".fld-field-group"),this.$fields=this.$fieldGroups.children(".fld-element"),this.$uiLibrary=this.$sidebar.children(".fld-ui-library"),this.$uiLibraryElements=this.$uiLibrary.children(),this.tabGrid=new Craft.Grid(this.$tabContainer,{itemSelector:".fld-tab",minColWidth:264,fillMode:"grid",snapToGrid:24});for(var n=this.$tabContainer.children(),r=0;r<n.length;r++)this.initTab($(n[r]));if($("<input/>",{type:"hidden",name:this.settings.elementPlacementInputName.replace("[__TAB_NAME__][]",""),value:""}).insertBefore(this.$container),this.elementDrag=new Craft.FieldLayoutDesigner.ElementDrag(this),this.settings.customizableTabs&&(this.tabDrag=new Craft.FieldLayoutDesigner.TabDrag(this),this.addListener(this.$newTabBtn,"activate","addTab")),this.settings.customizableUi){var o=this.$sidebar.children(".btngroup");new Craft.Listbox(o,{onChange:function(t){i.$selectedLibrary.addClass("hidden"),i.$selectedLibrary=i["$".concat(t.data("library"),"Library")].removeClass("hidden")}})}this.addListener(this.$fieldSearch,"input",(function(){var t=i.$fieldSearch.val().toLowerCase().replace(/['"]/g,"");if(!t)return i.$fieldLibrary.find(".filtered").removeClass("filtered"),void i.$clearFieldSearchBtn.addClass("hidden");i.$clearFieldSearchBtn.removeClass("hidden");var e=i.$fields.filter('[data-keywords*="'.concat(t,'"]')).add(i.$fieldGroups.filter('[data-name*="'.concat(t,'"]')).children(".fld-element")).removeClass("filtered");i.$fields.not(e).addClass("filtered");for(var s=0;s<i.$fieldGroups.length;s++){var a=i.$fieldGroups.eq(s);a.find(".fld-element:not(.hidden):not(.filtered)").length?a.removeClass("filtered"):a.addClass("filtered")}})),this.addListener(this.$fieldSearch,"keydown",(function(t){switch(t.keyCode){case Garnish.ESC_KEY:i.$fieldSearch.val("").trigger("input");break;case Garnish.RETURN_KEY:t.preventDefault()}})),this.addListener(this.$clearFieldSearchBtn,"click",(function(){i.$fieldSearch.val("").trigger("input")}))},initTab:function(t){if(this.settings.customizableTabs){var e=t.find(".tabs .settings");$('<div class="menu" data-align="center"/>').insertAfter(e).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"rename",text:Craft.t("app","Rename")}))).append($("<li/>").append($("<a/>",{"data-action":"remove",text:Craft.t("app","Remove")})))).append($("<hr/>")).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"moveLeft",text:Craft.t("app","Move to the left")}))).append($("<li/>").append($("<a/>",{"data-action":"moveRight",text:Craft.t("app","Move to the right")}))));var i=new Garnish.MenuBtn(e,{onOptionSelect:this.onTabOptionSelect.bind(this)});i.menu.on("show",(function(){t.prev(".fld-tab").length?i.menu.$container.find("[data-action=moveLeft]").removeClass("disabled"):i.menu.$container.find("[data-action=moveLeft]").addClass("disabled"),t.next(".fld-tab").length?i.menu.$container.find("[data-action=moveRight]").removeClass("disabled"):i.menu.$container.find("[data-action=moveRight]").addClass("disabled")}))}for(var s=t.children(".fld-tabcontent").children(),a=0;a<s.length;a++)this.initElement($(s[a]))},initElement:function(t){new Craft.FieldLayoutDesigner.Element(this,t)},onTabOptionSelect:function(t){if(this.settings.customizableTabs){var e=$(t),i=e.data("menu").$anchor.parent().parent().parent();switch(e.data("action")){case"rename":this.renameTab(i);break;case"remove":this.removeTab(i);break;case"moveLeft":var s=i.prev(".fld-tab");s.length&&i.insertBefore(s);break;case"moveRight":var a=i.next(".fld-tab");a.length&&i.insertAfter(a)}}},renameTab:function(t){if(this.settings.customizableTabs){var e=t.find(".tabs .tab span"),i=e.text(),s=this.promptForTabName(i);s&&s!==i&&(e.text(s),t.find(".placement-input").attr("name",this.getElementPlacementInputName(s)))}},promptForTabName:function(t){return Craft.escapeHtml(prompt(Craft.t("app","Give your tab a name."),t))},removeTab:function(t){if(this.settings.customizableTabs){for(var e=t.find(".fld-element"),i=0;i<e.length;i++){var s=$(e[i]).attr("data-attribute");this.removeFieldByHandle(s)}this.tabGrid.removeItems(t),this.tabDrag.removeItems(t),t.remove()}},removeField:function(t){var e=t.attr("data-attribute");t.remove(),this.removeFieldByHandle(e),this.tabGrid.refreshCols(!0)},removeFieldByHandle:function(t){this.$fields.filter('[data-attribute="'.concat(t,'"]:first')).removeClass("hidden").closest(".fld-field-group").removeClass("hidden")},addTab:function(){if(this.settings.customizableTabs){var t=this.promptForTabName();if(t){var e=$('\n<div class="fld-tab">\n  <div class="tabs">\n    <div class="tab sel draggable">\n      <span>'.concat(t,'</span>\n      <a class="settings icon" title="').concat(Craft.t("app","Rename"),'"></a>\n    </div>\n  </div>\n  <div class="fld-tabcontent"></div>\n</div>\n')).appendTo(this.$tabContainer);this.tabGrid.addItems(e),this.tabDrag.addItems(e),this.initTab(e)}}},getElementPlacementInputName:function(t){return this.settings.elementPlacementInputName.replace(/__TAB_NAME__/g,Craft.encodeUriComponent(t))}},{defaults:{customizableTabs:!0,customizableUi:!0,elementPlacementInputName:"elementPlacements[__TAB_NAME__][]",elementConfigInputName:"elementConfigs[__ELEMENT_KEY__]"}}),Craft.FieldLayoutDesigner.Element=Garnish.Base.extend({designer:null,$container:null,$placementInput:null,$configInput:null,$settingsContainer:null,$editBtn:null,config:null,isField:!1,attribute:null,requirable:!1,key:null,hasCustomWidth:!1,hasSettings:!1,hud:null,init:function(t,e){var i=this;this.designer=t,this.$container=e,this.$container.data("fld-element",this),this.config=this.$container.data("config"),$.isPlainObject(this.config)||(this.config={}),this.config.type=this.$container.data("type"),this.isField=this.$container.hasClass("fld-field"),this.requirable=this.isField&&Garnish.hasAttr(this.$container,"data-requirable"),this.key=Craft.randomString(10),this.isField&&(this.attribute=this.$container.data("attribute"));var s=this.$container.data("settings-html"),a=this.requirable&&this.$container.hasClass("fld-required");this.hasCustomWidth=this.designer.settings.customizableUi&&Garnish.hasAttr(this.$container,"data-has-custom-width"),this.hasSettings=s||this.requirable,this.hasSettings&&(s=s?s.replace(/\b__ELEMENT_KEY__\b/g,this.key):"",this.$settingsContainer=$("<div/>",{class:"hidden"}),this.$editBtn=$("<a/>",{role:"button",tabindex:0,class:"settings icon",title:Craft.t("app","Edit")}),this.$editBtn.on("click",(function(){i.hud?(i.hud.show(),i.hud.updateSizeAndPosition(!0)):i.createSettingsHud(s,a)}))),this.initUi(),this.$container.attr("data-config",null),this.$container.attr("data-keywords",null),this.$container.attr("data-settings-html",null)},initUi:function(){var t=this;this.$placementInput=$("<input/>",{class:"placement-input",type:"hidden",name:"",value:this.key}).appendTo(this.$container),this.updatePlacementInput(),this.$configInput=$("<input/>",{type:"hidden",name:this.designer.settings.elementConfigInputName.replace(/\b__ELEMENT_KEY__\b/g,this.key)}).appendTo(this.$container),this.updateConfigInput(),this.hasCustomWidth&&new Craft.SlidePicker(this.config.width||100,{min:25,max:100,step:25,valueLabel:function(t){return Craft.t("app","{pct} width",{pct:"".concat(t,"%")})},onChange:function(e){t.config.width=e,t.updateConfigInput()}}).$container.appendTo(this.$container),this.hasSettings&&this.$editBtn.appendTo(this.$container)},createSettingsHud:function(t,e){var i=this,s='\n<div class="fld-element-settings">\n  '.concat(t,'\n  <div class="hud-footer">\n    <div class="buttons right">\n      <button class="btn submit" type="submit">').concat(Craft.t("app","Apply"),'</button>\n      <div class="spinner hidden"></div>\n    </div>\n  </div>\n</div>\n');this.hud=new Garnish.HUD(this.$container,s,{onShow:function(t){Garnish.requestAnimationFrame((function(){i.hud.$main.find(".text:first").trigger("focus")}))},onSubmit:function(){i.applyHudSettings()}}),Craft.initUiElements(this.hud.$main),this.requirable&&Craft.ui.createLightswitchField({label:Craft.t("app","Required"),id:"".concat(this.key,"-required"),name:"required",on:e}).prependTo(this.hud.$main),this.trigger("createSettingsHud")},applyHudSettings:function(){var t=this;this.hud.$body.serializeArray().forEach((function(e){var i=e.name,s=e.value;t.config[i]=s})),this.updateConfigInput();var e=this.hud.$body.find(".spinner").removeClass("hidden");Craft.sendActionRequest("POST","fields/render-layout-element-selector",{data:{config:this.config}}).then((function(i){e.addClass("hidden"),t.$editBtn.detach(),t.$container.html($(i.data.html).html()),t.initUi(),t.updateRequiredClass(),t.hud.hide()})).catch((function(i){console.error(i),e.addClass("hidden"),t.updateRequiredClass(),t.hud.hide()}))},updatePlacementInput:function(){var t=this.$container.closest(".fld-tab").find(".tab span");if(t.length){var e=this.designer.getElementPlacementInputName(t.text());this.$placementInput.attr("name",e)}},updateConfigInput:function(){this.$configInput.val(JSON.stringify(this.config))},updateRequiredClass:function(){this.requirable&&(this.config.required?this.$container.addClass("fld-required"):this.$container.removeClass("fld-required"))}}),Craft.FieldLayoutDesigner.BaseDrag=Garnish.Drag.extend({designer:null,$insertion:null,showingInsertion:!1,$caboose:null,init:function(t,e){this.designer=t,this.base(this.findItems(),e)},onDragStart:function(){this.base(),this.$insertion=this.createInsertion(),this.$caboose=this.createCaboose(),this.$items=$().add(this.$items.add(this.$caboose)),Garnish.$bod.addClass("dragging")},removeCaboose:function(){this.$items=this.$items.not(this.$caboose),this.$caboose.remove()},swapDraggeeWithInsertion:function(){this.$insertion.insertBefore(this.$draggee),this.$draggee.detach(),this.$items=$().add(this.$items.not(this.$draggee).add(this.$insertion)),this.showingInsertion=!0},swapInsertionWithDraggee:function(){this.$insertion.replaceWith(this.$draggee),this.$items=$().add(this.$items.not(this.$insertion).add(this.$draggee)),this.showingInsertion=!1},setMidpoints:function(){for(var t=0;t<this.$items.length;t++){var e=$(this.$items[t]),i=e.offset();e.hasClass("unused")||e.data("midpoint",{left:i.left+e.outerWidth()/2,top:i.top+e.outerHeight()/2})}},getClosestItem:function(){for(this.getClosestItem._closestItem=null,this.getClosestItem._closestItemMouseDiff=null,this.getClosestItem._i=0;this.getClosestItem._i<this.$items.length;this.getClosestItem._i++)this.getClosestItem._$item=$(this.$items[this.getClosestItem._i]),this.getClosestItem._midpoint=this.getClosestItem._$item.data("midpoint"),this.getClosestItem._midpoint&&(this.getClosestItem._mouseDiff=Garnish.getDist(this.getClosestItem._midpoint.left,this.getClosestItem._midpoint.top,this.mouseX,this.mouseY),(null===this.getClosestItem._closestItem||this.getClosestItem._mouseDiff<this.getClosestItem._closestItemMouseDiff)&&(this.getClosestItem._closestItem=this.getClosestItem._$item[0],this.getClosestItem._closestItemMouseDiff=this.getClosestItem._mouseDiff));return this.getClosestItem._closestItem},checkForNewClosestItem:function(){this.checkForNewClosestItem._closestItem=this.getClosestItem(),this.checkForNewClosestItem._closestItem!==this.$insertion[0]&&(this.showingInsertion&&$.inArray(this.$insertion[0],this.$items)<$.inArray(this.checkForNewClosestItem._closestItem,this.$items)&&-1===$.inArray(this.checkForNewClosestItem._closestItem,this.$caboose)?this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem):this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem),this.$items=$().add(this.$items.add(this.$insertion)),this.showingInsertion=!0,this.designer.tabGrid.refreshCols(!0),this.setMidpoints())},onDragStop:function(){var t=this;this.showingInsertion&&this.swapInsertionWithDraggee(),this.removeCaboose(),this.designer.tabGrid.refreshCols(!0);var e=this.$draggee.offset();!e||0===e.top&&0===e.left?(this.$draggee.css({display:this.draggeeDisplay,visibility:"visible",opacity:0}).velocity({opacity:1},Garnish.FX_DURATION),this.helpers[0].velocity({opacity:0},Garnish.FX_DURATION,(function(){t._showDraggee()}))):this.returnHelpersToDraggees(),this.base(),Garnish.$bod.removeClass("dragging")}}),Craft.FieldLayoutDesigner.TabDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({init:function(t){this.base(t,{handle:".tab"})},findItems:function(){return this.designer.$tabContainer.find("> div.fld-tab")},onDragStart:function(){this.base(),this.swapDraggeeWithInsertion(),this.setMidpoints()},swapDraggeeWithInsertion:function(){this.base(),this.designer.tabGrid.removeItems(this.$draggee),this.designer.tabGrid.addItems(this.$insertion)},swapInsertionWithDraggee:function(){this.base(),this.designer.tabGrid.removeItems(this.$insertion),this.designer.tabGrid.addItems(this.$draggee)},onDrag:function(){this.checkForNewClosestItem(),this.base()},onDragStop:function(){this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:"hidden"})},createCaboose:function(){var t=$('<div class="fld-tab fld-tab-caboose"/>').appendTo(this.designer.$tabContainer);return this.designer.tabGrid.addItems(t),t},removeCaboose:function(){this.base(),this.designer.tabGrid.removeItems(this.$caboose)},createInsertion:function(){var t=this.$draggee.find(".tab");return $('\n<div class="fld-tab fld-insertion" style="height: '.concat(this.$draggee.height(),'px;">\n  <div class="tabs"><div class="tab sel draggable" style="width: ').concat(t.width(),"px; height: ").concat(t.height(),'px;"></div></div>\n  <div class="fld-tabcontent" style="height: ').concat(this.$draggee.find(".fld-tabcontent").height(),'px;"></div>\n</div>\n'))}}),Craft.FieldLayoutDesigner.ElementDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({draggingLibraryElement:!1,draggingField:!1,onDragStart:function(){this.base(),this.draggingLibraryElement=this.$draggee.hasClass("unused"),this.draggingField=this.$draggee.hasClass("fld-field"),this.draggingLibraryElement&&!this.draggingField&&this.$draggee.css({display:this.draggeeDisplay,visibility:"visible"}),this.draggingLibraryElement||this.swapDraggeeWithInsertion(),this.setMidpoints()},onDrag:function(){this.isDraggeeMandatory()||this.isHoveringOverTab()?this.checkForNewClosestItem():this.showingInsertion&&(this.$insertion.remove(),this.$items=$().add(this.$items.not(this.$insertion)),this.showingInsertion=!1,this.designer.tabGrid.refreshCols(!0),this.setMidpoints()),this.base()},isDraggeeMandatory:function(){return Garnish.hasAttr(this.$draggee,"data-mandatory")},isHoveringOverTab:function(){for(var t=0;t<this.designer.tabGrid.$items.length;t++)if(Garnish.hitTest(this.mouseX,this.mouseY,this.designer.tabGrid.$items.eq(t)))return!0;return!1},findItems:function(){return this.designer.$tabContainer.find(".fld-element").add(this.designer.$sidebar.find(".fld-element"))},createCaboose:function(){for(var t=$(),e=this.designer.$tabContainer.find("> .fld-tab > .fld-tabcontent"),i=0;i<e.length;i++)t=t.add($("<div/>").appendTo(e[i]));return t},createInsertion:function(){return $('<div class="fld-element fld-insertion" style="height: '.concat(this.$draggee.outerHeight(),'px;"/>'))},onDragStop:function(){var t=this.showingInsertion;if(t){if(this.draggingLibraryElement){var e=this.$draggee.clone().removeClass("unused");this.designer.initElement(e),this.draggingField&&(this.$draggee.css({visibility:"inherit",display:"field"}).addClass("hidden"),0===this.$draggee.siblings(".fld-field:not(.hidden)").length&&this.$draggee.closest(".fld-field-group").addClass("hidden")),this.$draggee=e,this.addItems(e)}}else if(!this.draggingLibraryElement){var i=this.draggingField?this.designer.$fields.filter('[data-attribute="'.concat(this.$draggee.data("attribute"),'"]:first')):this.designer.$uiLibraryElements.filter('[data-type="'.concat(this.$draggee.data("type").replace(/\\/g,"\\\\"),'"]:first'));this.draggingField&&(i.removeClass("hidden"),i.closest(".fld-field-group").removeClass("hidden")),this.removeItems(this.$draggee),this.$draggee=i}this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:this.draggingField||t?"hidden":"visible"}),t&&this.$draggee.data("fld-element").updatePlacementInput()}})},3347:function(){Craft.FieldToggle=Garnish.Base.extend({$toggle:null,targetPrefix:null,targetSelector:null,reverseTargetSelector:null,_$target:null,_$reverseTarget:null,type:null,init:function(t){switch(this.$toggle=$(t),this.$toggle.data("fieldtoggle")&&(console.warn("Double-instantiating a field toggle on an element"),this.$toggle.data("fieldtoggle").destroy()),this.$toggle.data("fieldtoggle",this),this.type=this.getType(),"select"===this.type||"fieldset"===this.type?this.targetPrefix=this.$toggle.attr("data-target-prefix")||"":(this.targetSelector=this.normalizeTargetSelector(this.$toggle.data("target")),this.reverseTargetSelector=this.normalizeTargetSelector(this.$toggle.data("reverse-target"))),this.findTargets(),this.type){case"link":this.addListener(this.$toggle,"click","onToggleChange");break;case"fieldset":this.addListener(this.$toggle.find("input"),"change","onToggleChange");break;default:this.addListener(this.$toggle,"change","onToggleChange"),this.onToggleChange()}},normalizeTargetSelector:function(t){return t&&!t.match(/^[#\.]/)&&(t="#"+t),t},getType:function(){var t=this.$toggle.prop("nodeName");if("INPUT"===t&&"checkbox"===this.$toggle.attr("type")||"checkbox"===this.$toggle.attr("role")||"switch"===this.$toggle.attr("role"))return"checkbox";switch(t){case"SELECT":return Garnish.hasAttr(this.$toggle,"data-boolean-menu")?"booleanMenu":"select";case"A":return"link";case"FIELDSET":return"fieldset"}console.warn("Unexpected field toggle:",this.$toggle[0])},findTargets:function(){"select"===this.type||"fieldset"===this.type?(this.getToggleVal(),this._$target=$(this.normalizeTargetSelector(this.targetPrefix+this.getToggleVal()))):(this.targetSelector&&(this._$target=$(this.targetSelector)),this.reverseTargetSelector&&(this._$reverseTarget=$(this.reverseTargetSelector)))},getToggleVal:function(){switch(this.type){case"checkbox":return void 0!==this.$toggle.prop("checked")?this.$toggle.prop("checked"):"true"===this.$toggle.attr("aria-checked");case"booleanMenu":var t=this.$toggle.data("boolean");if(void 0!==t)return t;var e=this.$toggle.val();return e&&"0"!==e;default:var i;return null==(i="fieldset"===this.type?this.$toggle.find("input:checked:first").val():Garnish.getInputPostVal(this.$toggle))?null:i.replace(/[^\w]+/g,"-")}},onToggleChange:function(){"select"===this.type||"fieldset"===this.type?(this.hideTarget(this._$target),this.findTargets(),this.showTarget(this._$target)):(this.findTargets(),"link"===this.type?this.onToggleChange._show=this.$toggle.hasClass("collapsed")||!this.$toggle.hasClass("expanded"):this.onToggleChange._show=!!this.getToggleVal(),this.onToggleChange._show?(this.showTarget(this._$target),this.hideTarget(this._$reverseTarget)):(this.hideTarget(this._$target),this.showTarget(this._$reverseTarget)),delete this.onToggleChange._show)},showTarget:function(t){var e=this;if(t&&t.length){if(this.showTarget._currentHeight=t.height(),t.removeClass("hidden"),"select"!==this.type&&"fieldset"!==this.type){"link"===this.type&&(this.$toggle.removeClass("collapsed"),this.$toggle.addClass("expanded"));for(var i=0;i<t.length;i++)!function(t){"SPAN"!==t.prop("nodeName")&&(t.height("auto"),e.showTarget._targetHeight=t.height(),t.css({height:e.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:e.showTarget._targetHeight},"fast",(function(){t.css({height:"",overflow:""})})))}(t.eq(i));delete this.showTarget._targetHeight}delete this.showTarget._currentHeight,Garnish.$win.trigger("resize")}},hideTarget:function(t){if(t&&t.length)if("select"===this.type||"fieldset"===this.type)t.addClass("hidden");else{"link"===this.type&&(this.$toggle.removeClass("expanded"),this.$toggle.addClass("collapsed"));for(var e=0;e<t.length;e++)!function(t){t.hasClass("hidden")||("SPAN"===t.prop("nodeName")?t.addClass("hidden"):(t.css("overflow","hidden"),t.velocity("stop"),t.velocity({height:0},"fast",(function(){t.addClass("hidden")}))))}(t.eq(e))}},destroy:function(){this.$toggle.removeData("fieldtoggle"),this.base()}})},9478:function(){Craft.Grid=Garnish.Base.extend({$container:null,$items:null,items:null,totalCols:null,colGutterDrop:null,colPctWidth:null,possibleItemColspans:null,possibleItemPositionsByColspan:null,itemPositions:null,itemColspansByPosition:null,layouts:null,layout:null,itemHeights:null,leftPadding:null,_refreshingCols:!1,_refreshColsAfterRefresh:!1,_forceRefreshColsAfterRefresh:!1,init:function(t,e){var i=this;this.$container=$(t),this.$container.data("grid")&&(console.warn("Double-instantiating a grid on an element"),this.$container.data("grid").destroy()),this.$container.data("grid",this),this.setSettings(e,Craft.Grid.defaults),this.handleContainerHeightProxy=function(){i.refreshCols(!1,!0)},this.$items=this.$container.children(this.settings.itemSelector),this.setItems(),this.refreshCols(!0,!1),Garnish.$doc.ready((function(){i.refreshCols(!1,!1)}))},addItems:function(t){this.$items=$().add(this.$items.add(t)),this.setItems(),this.refreshCols(!0,!0)},removeItems:function(t){this.$items=$().add(this.$items.not(t)),this.setItems(),this.refreshCols(!0,!0)},resetItemOrder:function(){this.$items=$().add(this.$items),this.setItems(),this.refreshCols(!0,!0)},setItems:function(){for(this.setItems._={},this.items=[],this.setItems._.i=0;this.setItems._.i<this.$items.length;this.setItems._.i++)this.items.push($(this.$items[this.setItems._.i]));delete this.setItems._},refreshCols:function(t){if(this._refreshingCols)return this._refreshColsAfterRefresh=!0,void(t&&(this._forceRefreshColsAfterRefresh=!0));if(this._refreshingCols=!0,this.items.length)if(this.refreshCols._={},this.refreshCols._.oldHeight=this.$container[0].style.height,this.$container[0].style.height=1,this.refreshCols._.scrollHeight=this.$container[0].scrollHeight,this.$container[0].style.height=this.refreshCols._.oldHeight,0!==this.refreshCols._.scrollHeight)if(this.settings.cols?this.refreshCols._.totalCols=this.settings.cols:(this.refreshCols._.totalCols=Math.floor(this.$container.width()/this.settings.minColWidth),null!==this.totalCols&&this.refreshCols._.totalCols>this.totalCols&&(this.refreshCols._.totalCols=Math.floor((this.$container.width()-20)/this.settings.minColWidth)),this.settings.maxCols&&this.refreshCols._.totalCols>this.settings.maxCols&&(this.refreshCols._.totalCols=this.settings.maxCols)),0===this.refreshCols._.totalCols&&(this.refreshCols._.totalCols=1),!0===t||this.totalCols!==this.refreshCols._.totalCols){if(this.totalCols=this.refreshCols._.totalCols,this.colGutterDrop=this.settings.gutter*(this.totalCols-1)/this.totalCols,this.removeListener(this.$container,"resize"),"grid"===this.settings.fillMode)for(this.refreshCols._.itemIndex=0;this.refreshCols._.itemIndex<this.items.length;){for(this.refreshCols._.tallestItemHeight=-1,this.refreshCols._.colIndex=0,this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.itemHeight=this.items[this.refreshCols._.i].height("auto").height(),this.refreshCols._.itemHeight>this.refreshCols._.tallestItemHeight&&(this.refreshCols._.tallestItemHeight=this.refreshCols._.itemHeight),this.refreshCols._.colIndex++;for(this.settings.snapToGrid&&(this.refreshCols._.remainder=this.refreshCols._.tallestItemHeight%this.settings.snapToGrid,this.refreshCols._.remainder&&(this.refreshCols._.tallestItemHeight+=this.settings.snapToGrid-this.refreshCols._.remainder)),this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.items[this.refreshCols._.i].height(this.refreshCols._.tallestItemHeight);this.refreshCols._.itemIndex+=this.totalCols}else if(this.removeListener(this.$items,"resize"),1===this.totalCols)this.$container.height("auto"),this.$items.show().css({position:"relative",width:"auto",top:0}).css(Craft.left,0);else{for(this.$items.css("position","absolute"),this.colPctWidth=100/this.totalCols,this.layouts=[],this.itemPositions=[],this.itemColspansByPosition=[],this.possibleItemColspans=[],this.possibleItemPositionsByColspan=[],this.itemHeightsByColspan=[],this.refreshCols._.item=0;this.refreshCols._.item<this.items.length;this.refreshCols._.item++)for(this.possibleItemColspans[this.refreshCols._.item]=[],this.possibleItemPositionsByColspan[this.refreshCols._.item]={},this.itemHeightsByColspan[this.refreshCols._.item]={},this.refreshCols._.$item=this.items[this.refreshCols._.item].show(),this.refreshCols._.positionRight="right"===this.refreshCols._.$item.data("position"),this.refreshCols._.positionLeft="left"===this.refreshCols._.$item.data("position"),this.refreshCols._.minColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("min-colspan")?this.refreshCols._.$item.data("min-colspan"):1,this.refreshCols._.maxColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("max-colspan")?this.refreshCols._.$item.data("max-colspan"):this.totalCols,this.refreshCols._.minColspan>this.totalCols&&(this.refreshCols._.minColspan=this.totalCols),this.refreshCols._.maxColspan>this.totalCols&&(this.refreshCols._.maxColspan=this.totalCols),this.refreshCols._.colspan=this.refreshCols._.minColspan;this.refreshCols._.colspan<=this.refreshCols._.maxColspan;this.refreshCols._.colspan++)for(this.refreshCols._.$item.css("width",this.getItemWidthCss(this.refreshCols._.colspan)),this.itemHeightsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=this.refreshCols._.$item.outerHeight(),this.possibleItemColspans[this.refreshCols._.item].push(this.refreshCols._.colspan),this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=[],this.refreshCols._.positionLeft?(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=0):this.refreshCols._.positionRight?(this.refreshCols._.minPosition=this.totalCols-this.refreshCols._.colspan,this.refreshCols._.maxPosition=this.refreshCols._.minPosition):(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=this.totalCols-this.refreshCols._.colspan),this.refreshCols._.position=this.refreshCols._.minPosition;this.refreshCols._.position<=this.refreshCols._.maxPosition;this.refreshCols._.position++)this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan].push(this.refreshCols._.position);for(this.refreshCols._.colHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.totalCols;this.refreshCols._.i++)this.refreshCols._.colHeights.push(0);for(this.createLayouts(0,[],[],this.refreshCols._.colHeights,0),this.refreshCols._.layoutTotalCols=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)for(this.refreshCols._.layoutTotalCols[this.refreshCols._.i]=0,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j]&&this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;for(this.refreshCols._.highestTotalCols=Math.max.apply(null,this.refreshCols._.layoutTotalCols),this.refreshCols._.i=this.layouts.length-1;this.refreshCols._.i>=0;this.refreshCols._.i--)this.refreshCols._.layoutTotalCols[this.refreshCols._.i]!==this.refreshCols._.highestTotalCols&&this.layouts.splice(this.refreshCols._.i,1);for(this.refreshCols._.layoutHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)this.refreshCols._.layoutHeights.push(Math.max.apply(null,this.layouts[this.refreshCols._.i].colHeights));for(this.refreshCols._.shortestHeight=Math.min.apply(null,this.refreshCols._.layoutHeights),this.refreshCols._.shortestLayouts=[],this.refreshCols._.emptySpaces=[],this.refreshCols._.i=0;this.refreshCols._.i<this.refreshCols._.layoutHeights.length;this.refreshCols._.i++)if(this.refreshCols._.layoutHeights[this.refreshCols._.i]===this.refreshCols._.shortestHeight){for(this.refreshCols._.shortestLayouts.push(this.layouts[this.refreshCols._.i]),this.refreshCols._.emptySpace=this.layouts[this.refreshCols._.i].emptySpace,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.refreshCols._.emptySpace+=this.refreshCols._.shortestHeight-this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j];this.refreshCols._.emptySpaces.push(this.refreshCols._.emptySpace)}for(this.layout=this.refreshCols._.shortestLayouts[$.inArray(Math.min.apply(null,this.refreshCols._.emptySpaces),this.refreshCols._.emptySpaces)],this.refreshCols._.i=0;this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.css={width:this.getItemWidthCss(this.layout.colspans[this.refreshCols._.i])},this.refreshCols._.css[Craft.left]=this.getItemLeftPosCss(this.layout.positions[this.refreshCols._.i]),this.items[this.refreshCols._.i].css(this.refreshCols._.css);this.isSimpleLayout()?(this.$container.height("auto"),this.$items.css({position:"relative",top:0,"margin-bottom":this.settings.gutter+"px"})):(this.$items.css("position","absolute"),this.positionItems(),this.addListener(this.$items,"resize","onItemResize"))}this.completeRefreshCols(),this.addListener(this.$container,"resize",this.handleContainerHeightProxy),this.onRefreshCols()}else this.completeRefreshCols();else this.completeRefreshCols();else this.completeRefreshCols()},completeRefreshCols:function(){var t=this;if(void 0!==this.refreshCols._&&delete this.refreshCols._,this._refreshingCols=!1,this._refreshColsAfterRefresh){var e=this._forceRefreshColsAfterRefresh;this._refreshColsAfterRefresh=!1,this._forceRefreshColsAfterRefresh=!1,Garnish.requestAnimationFrame((function(){t.refreshCols(e)}))}},getItemWidth:function(t){return this.colPctWidth*t},getItemWidthCss:function(t){return"calc("+this.getItemWidth(t)+"% - "+this.colGutterDrop+"px)"},getItemWidthInPx:function(t){return this.getItemWidth(t)/100*this.$container.width()-this.colGutterDrop},getItemLeftPosCss:function(t){return"calc(("+this.getItemWidth(1)+"% + "+(this.settings.gutter-this.colGutterDrop)+"px) * "+t+")"},getItemLeftPosInPx:function(t){return(this.getItemWidth(1)/100*this.$container.width()+(this.settings.gutter-this.colGutterDrop))*t},createLayouts:function(t,e,i,s,a){new Craft.Grid.LayoutGenerator(this).createLayouts(t,e,i,s,a)},isSimpleLayout:function(){for(this.isSimpleLayout._={},this.isSimpleLayout._.i=0;this.isSimpleLayout._.i<this.layout.positions.length;this.isSimpleLayout._.i++)if(0!==this.layout.positions[this.isSimpleLayout._.i])return delete this.isSimpleLayout._,!1;return delete this.isSimpleLayout._,!0},positionItems:function(){for(this.positionItems._={},this.positionItems._.colHeights=[],this.positionItems._.i=0;this.positionItems._.i<this.totalCols;this.positionItems._.i++)this.positionItems._.colHeights.push(0);for(this.positionItems._.i=0;this.positionItems._.i<this.items.length;this.positionItems._.i++){for(this.positionItems._.endingCol=this.layout.positions[this.positionItems._.i]+this.layout.colspans[this.positionItems._.i]-1,this.positionItems._.affectedColHeights=[],this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.affectedColHeights.push(this.positionItems._.colHeights[this.positionItems._.col]);for(this.positionItems._.top=Math.max.apply(null,this.positionItems._.affectedColHeights),this.positionItems._.top>0&&(this.positionItems._.top+=this.settings.gutter),this.items[this.positionItems._.i].css("top",this.positionItems._.top),this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.colHeights[this.positionItems._.col]=this.positionItems._.top+this.itemHeightsByColspan[this.positionItems._.i][this.layout.colspans[this.positionItems._.i]]}this.$container.height(Math.max.apply(null,this.positionItems._.colHeights)),delete this.positionItems._},onItemResize:function(t){this.onItemResize._={},t.stopPropagation(),this.onItemResize._.item=$.inArray(t.currentTarget,this.$items),-1!==this.onItemResize._.item&&(this.onItemResize._.newHeight=this.items[this.onItemResize._.item].outerHeight(),this.onItemResize._.newHeight!==this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]&&(this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]=this.onItemResize._.newHeight,this.positionItems(!1))),delete this.onItemResize._},onRefreshCols:function(){this.trigger("refreshCols"),this.settings.onRefreshCols()},destroy:function(){this.$container.removeData("grid"),this.base()}},{defaults:{itemSelector:".item",cols:null,maxCols:null,minColWidth:320,gutter:14,fillMode:"top",colClass:"col",snapToGrid:null,onRefreshCols:$.noop}}),Craft.Grid.LayoutGenerator=Garnish.Base.extend({grid:null,_:null,init:function(t){this.grid=t},createLayouts:function(t,e,i,s,a){for(this._={},this._.c=0;this._.c<this.grid.possibleItemColspans[t].length;this._.c++){for(this._.colspan=this.grid.possibleItemColspans[t][this._.c],this._.tallestColHeightsByPosition=[],this._.p=0;this._.p<this.grid.possibleItemPositionsByColspan[t][this._.colspan].length;this._.p++){for(this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.colHeightsForPosition=[],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.colHeightsForPosition.push(s[this._.col]);this._.tallestColHeightsByPosition[this._.p]=Math.max.apply(null,this._.colHeightsForPosition)}for(this._.p=$.inArray(Math.min.apply(null,this._.tallestColHeightsByPosition),this._.tallestColHeightsByPosition),this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.positions=e.slice(0),this._.colspans=i.slice(0),this._.colHeights=s.slice(0),this._.emptySpace=a,this._.positions.push(this._.position),this._.colspans.push(this._.colspan),this._.tallestColHeight=this._.tallestColHeightsByPosition[this._.p],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.emptySpace+=this._.tallestColHeight-this._.colHeights[this._.col],this._.colHeights[this._.col]=this._.tallestColHeight+this.grid.itemHeightsByColspan[t][this._.colspan];t===this.grid.items.length-1?this.grid.layouts.push({positions:this._.positions,colspans:this._.colspans,colHeights:this._.colHeights,emptySpace:this._.emptySpace}):this.grid.createLayouts(t+1,this._.positions,this._.colspans,this._.colHeights,this._.emptySpace)}delete this._}})},2387:function(){Craft.HandleGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){var e=t.replace("/<(.*?)>/g","");e=(e=e.replace(/['"‘’“”\[\]\(\)\{\}:]/g,"")).toLowerCase(),e=Craft.asciiString(e),this.settings.allowNonAlphaStart||(e=e.replace(/^[^a-z]+/,""));var i=Craft.filterArray(e.split(/[^a-z0-9]+/));if(e="","snake"===Craft.handleCasing)return i.join("_");for(var s=0;s<i.length;s++)"pascal"!==Craft.handleCasing&&0===s?e+=i[s]:e+=i[s].charAt(0).toUpperCase()+i[s].substr(1);return e}})},7966:function(){Craft.ImageUpload=Garnish.Base.extend({$container:null,progressBar:null,uploader:null,init:function(t){this.setSettings(t,Craft.ImageUpload.defaults),this.initImageUpload()},initImageUpload:function(){this.$container=$(this.settings.containerSelector),this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var t={url:Craft.getActionUrl(this.settings.uploadAction),formData:this.settings.postParameters,fileInput:this.$container.find(this.settings.fileInputSelector),paramName:this.settings.uploadParamName};void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),t.events={},t.events.fileuploadstart=this._onUploadStart.bind(this),t.events.fileuploadprogressall=this._onUploadProgress.bind(this),t.events.fileuploaddone=this._onUploadComplete.bind(this),t.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,t),this.initButtons()},initButtons:function(){var t=this;this.$container.find(this.settings.uploadButtonSelector).on("click",(function(e){t.$container.find(t.settings.fileInputSelector).trigger("click")})),this.$container.find(this.settings.deleteButtonSelector).on("click",(function(e){confirm(Craft.t("app","Are you sure you want to delete this image?"))&&($(e.currentTarget).parent().append('<div class="blocking-modal"></div>'),Craft.postActionRequest(t.settings.deleteAction,t.settings.postParameters,(function(e,i){"success"===i&&t.refreshImage(e)})))}))},refreshImage:function(t){$(this.settings.containerSelector).replaceWith(t.html),this.settings.onAfterRefreshImage(t),this.initImageUpload()},_onUploadStart:function(t){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){e.result.error?alert(e.result.error):($(e.result.html),this.refreshImage(e.result)),this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},_onUploadFailure:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))}},{defaults:{postParameters:{},uploadAction:"",deleteAction:"",fileInputSelector:"",onAfterRefreshImage:$.noop,containerSelector:null,uploadButtonSelector:null,deleteButtonSelector:null,uploadParamName:"files"}})},657:function(){Craft.InfoIcon=Garnish.Base.extend({$icon:null,content:null,hud:null,init:function(t){var e=this;if(this.$icon=$(t),this.$icon.data("infoicon")?(console.warn("Double-instantiating an info icon on an element"),this.content=this.$icon.data("infoicon").content,this.$icon.data("infoicon").destroy()):(this.content=this.$icon.html(),this.$icon.html("").attr({tabindex:0,role:"button","aria-label":Craft.t("app","Information")})),this.$icon.data("infoicon",this),this.$icon[0].previousSibling&&this.$icon[0].previousSibling.nodeType===Node.TEXT_NODE&&!this.$icon.parent().hasClass("nowrap")){var i=this.$icon[0].previousSibling.nodeValue.match(/[^\s\-]+\s*$/);i&&(this.$icon[0].previousSibling.nodeValue=this.$icon[0].previousSibling.nodeValue.substr(0,i.index),$("<span/>",{class:"nowrap",html:i[0].replace(/\s+$/,"")+" "}).insertAfter(this.$icon[0].previousSibling).append(this.$icon))}this.addListener(this.$icon,"click",(function(t){t.preventDefault(),t.stopPropagation(),e.showHud()})),this.addListener(this.$icon,"keydown",(function(t){e.hud&&e.hud.showing||![Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)||(t.preventDefault(),t.stopPropagation(),e.showHud())}))},showHud:function(t){var e=this;this.hud?this.hud.show():(this.hud=new Garnish.HUD(this.$icon,this.content,{hudClass:"hud info-hud",closeOtherHUDs:!1,onShow:function(){Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY,(function(){e.hud.hide()}))}}),Craft.initUiElements(this.hud.$body))},destroy:function(){this.$icon.removeData("infoicon"),this.base()}})},4487:function(){Craft.LightSwitch=Garnish.Base.extend({settings:null,$outerContainer:null,$innerContainer:null,$input:null,small:!1,on:!1,indeterminate:!1,dragger:null,dragStartMargin:null,init:function(t,e){if(this.$outerContainer=$(t),this.$outerContainer.data("lightswitch")&&(console.warn("Double-instantiating a lightswitch on an element"),this.$outerContainer.data("lightswitch").destroy()),this.$outerContainer.data("lightswitch",this),this.small=this.$outerContainer.hasClass("small"),this.setSettings(e,Craft.LightSwitch.defaults),this.$innerContainer=this.$outerContainer.find(".lightswitch-container:first"),this.$input=this.$outerContainer.find("input:first"),!this.$input.prop("disabled")){this.on=this.$outerContainer.hasClass("on"),this.indeterminate=this.$outerContainer.hasClass("indeterminate"),this.addListener(this.$outerContainer,"mousedown","_onMouseDown"),this.addListener(this.$outerContainer,"keydown","_onKeyDown"),this.dragger=new Garnish.BaseDrag(this.$outerContainer,{axis:Garnish.X_AXIS,ignoreHandleSelector:null,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)});var i=this.$outerContainer.parent(".lightswitch-inner-container");i.length&&(this.addListener(i.children('span[data-toggle="off"]'),"click",this.turnOff),this.addListener(i.children('span[data-toggle="on"]'),"click",this.turnOn))}},turnOn:function(t){var e=!this.on;if(this.on=!0,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,0);else{var i={};i["margin-"+Craft.left]=0,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(this.settings.value),this.$outerContainer.addClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","true"),e&&!0!==t&&this.onChange()},turnOff:function(t){var e=this.on||this.indeterminate;if(this.on=!1,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,this._getOffMargin());else{var i={};i["margin-"+Craft.left]=this._getOffMargin(),this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(""),this.$outerContainer.removeClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","false"),e&&!0!==t&&this.onChange()},turnIndeterminate:function(t){var e=!this.indeterminate;this.on=!1,this.indeterminate=!0,this.$outerContainer.addClass("dragging");var i={};i["margin-"+Craft.left]=this._getOffMargin()/2,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this)),this.$input.val(this.settings.indeterminateValue),this.$outerContainer.removeClass("on"),this.$outerContainer.addClass("indeterminate"),this.$outerContainer.attr("aria-checked","mixed"),e&&!0!==t&&this.onChange()},toggle:function(){this.indeterminate||!this.on?this.turnOn():this.turnOff()},onChange:function(){this.trigger("change"),this.settings.onChange(this.on),this.$outerContainer.trigger("change")},_onMouseDown:function(){this.addListener(Garnish.$doc,"mouseup","_onMouseUp")},_onMouseUp:function(){this.removeListener(Garnish.$doc,"mouseup"),this.dragger.dragging||this.toggle()},_onKeyDown:function(t){switch(t.keyCode){case Garnish.SPACE_KEY:this.toggle(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.turnOn():this.turnOff(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.turnOff():this.turnOn(),t.preventDefault()}},_getMargin:function(){return parseInt(this.$innerContainer.css("margin-"+Craft.left))},_onDragStart:function(){this.$outerContainer.addClass("dragging"),this.dragStartMargin=this._getMargin()},_onDrag:function(){var t;(t="ltr"===Craft.orientation?this.dragStartMargin+this.dragger.mouseDistX:this.dragStartMargin-this.dragger.mouseDistX)<this._getOffMargin()?t=this._getOffMargin():t>0&&(t=0),this.$innerContainer.css("margin-"+Craft.left,t)},_onDragStop:function(){var t=this._getMargin();console.log(t),t>this._getOffMargin()/2?this.turnOn():this.turnOff()},_onSettle:function(){this.$outerContainer.removeClass("dragging")},destroy:function(){this.$outerContainer.removeData("lightswitch"),this.base(),this.dragger.destroy()},_getOffMargin:function(){return this.small?-10:-12}},{animationDuration:100,defaults:{value:"1",indeterminateValue:"-",onChange:$.noop}})},6966:function(){Craft.Listbox=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,selectedOptionIndex:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.Listbox.defaults),this.$container.data("listbox")&&(console.warn("Double-instantiating a listbox on an element"),this.$container.data("listbox").destroy()),this.$container.data("listbox",this),this.$options=this.$container.find("[role=option]"),this.$selectedOption=this.$options.filter("[aria-selected=true]"),this.$selectedOption.length?this.selectedOptionIndex=this.$options.index(this.$selectedOption):this.$selectedOption=null,this.addListener(this.$container,"keydown",(function(t){switch(t.keyCode){case Garnish.UP_KEY:i.selectPrev(),t.preventDefault();break;case Garnish.DOWN_KEY:i.selectNext(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?i.selectPrev():i.selectNext(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?i.selectNext():i.selectPrev(),t.preventDefault()}})),this.addListener(this.$options,"click",(function(t){i.select(i.$options.index($(t.currentTarget))),t.preventDefault()}))},select:function(t){t<0||t>=this.$options.length||t===this.selectedOptionIndex||(this.$selectedOption.removeClass(this.settings.selectedClass).attr("aria-selected","false"),this.$selectedOption=this.$options.eq(t).addClass(this.settings.selectedClass).attr("aria-selected","true"),this.selectedOptionIndex=t,this.settings.onChange(this.$selectedOption,t),this.trigger("change",{$selectedOption:this.$selectedOption,selectedOptionIndex:t}))},selectPrev:function(){null===this.selectedOptionIndex?this.select(0):this.select(this.selectedOptionIndex-1)},selectNext:function(){null===this.selectedOptionIndex?this.select(0):this.select(this.selectedOptionIndex+1)},destroy:function(){this.$container.removeData("listbox"),this.base()}},{defaults:{selectedClass:"active",focusClass:"focus",onChange:$.noop}})},5080:function(){Craft.LivePreview=Garnish.Base.extend({$extraFields:null,$trigger:null,$shade:null,$editorContainer:null,$editor:null,$dragHandle:null,$previewContainer:null,$iframeContainer:null,$iframe:null,$fieldPlaceholder:null,previewUrl:null,token:null,basePostData:null,inPreviewMode:!1,fields:null,lastPostData:null,updateIframeInterval:null,loading:!1,checkAgain:!1,dragger:null,dragStartEditorWidth:null,_slideInOnIframeLoad:!1,_forceUpdateIframeProxy:null,_scrollX:null,_scrollY:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){var e=this;this.setSettings(t,Craft.LivePreview.defaults),this.settings.previewUrl?this.previewUrl=this.settings.previewUrl:this.previewUrl=Craft.baseSiteUrl.replace(/\/+$/,"")+"/","https:"===document.location.protocol&&(this.previewUrl=this.previewUrl.replace(/^http:/,"https:")),this.basePostData=$.extend({},this.settings.previewParams),this._forceUpdateIframeProxy=this.forceUpdateIframe.bind(this),this.$extraFields=$(this.settings.extraFields),this.$trigger=$(this.settings.trigger),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.LivePreview.defaultEditorWidth),this.addListener(this.$trigger,"activate","toggle"),Craft.cp.on("beforeSaveShortcut",(function(){e.inPreviewMode&&e.moveFieldsBack()}))},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.LivePreview.minEditorWidthInPx&&(t=(e=Craft.LivePreview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},toggle:function(){this.inPreviewMode?this.exit():this.enter()},enter:function(){var t=this;if(!this.inPreviewMode)if(this.token){if(this.trigger("beforeEnter"),$(document.activeElement).trigger("blur"),!this.$editor){this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=$("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);$("<div/>",{class:"flex-grow"}).appendTo(e);var s=$("<button/>",{type:"button",class:"btn submit",text:Craft.t("app","Save")}).appendTo(e);this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(i,"click","exit"),this.addListener(s,"click","save")}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];for(var a=$(this.settings.fields),n=0;n<a.length;n++){var r=$(a[n]),o=this._getClone(r);this.$fieldPlaceholder.insertAfter(r),r.detach(),this.$fieldPlaceholder.replaceWith(o),r.appendTo(this.$editor),this.fields.push({$field:r,$clone:o})}this.updateIframe()?this._slideInOnIframeLoad=!0:this.slideIn(),Garnish.on(Craft.BaseElementEditor,"saveElement",this._forceUpdateIframeProxy),Garnish.on(Craft.AssetImageEditor,"save",this._forceUpdateIframeProxy),Craft.ElementThumbLoader.retryAll(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.exit()})),this.inPreviewMode=!0,this.trigger("enter")}else this.createToken()},createToken:function(){var t=this;Craft.postActionRequest("live-preview/create-token",{previewAction:this.settings.previewAction},(function(e,i){"success"===i&&(t.token=e.token,t.enter())}))},save:function(){Craft.cp.submitPrimaryForm()},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;$("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",(function(){t.updateIframeInterval=setInterval(t.updateIframe.bind(t),1e3)}))},exit:function(){var t=this;this.inPreviewMode&&(this.trigger("beforeExit"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),this.updateIframeInterval&&clearInterval(this.updateIframeInterval),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",(function(){t.$previewContainer.hide()})),Garnish.off(Craft.BaseElementEditor,"saveElement",this._forceUpdateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.inPreviewMode=!1,this.trigger("exit"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth())},updateIframe:function(t){if(t&&(this.lastPostData=null),!this.inPreviewMode)return!1;if(this.loading)return this.checkAgain=!0,!1;var e=$.extend(Garnish.getPostData(this.$editor),Garnish.getPostData(this.$extraFields));if(this.lastPostData&&Craft.compare(e,this.lastPostData,!1))return!1;this.lastPostData=e,this.loading=!0;var i=this.$iframe?$(this.$iframe[0].contentWindow.document):null;return this._scrollX=i?i.scrollLeft():0,this._scrollY=i?i.scrollTop():0,$.ajax({url:this.previewUrl+(-1!==this.previewUrl.indexOf("?")?"&":"?")+Craft.tokenParam+"="+this.token,method:"POST",data:$.extend({},e,this.basePostData),headers:{"X-Craft-Token":this.token},xhrFields:{withCredentials:!0},crossDomain:!0,success:this.handleSuccess.bind(this),error:this.handleError.bind(this)}),!0},forceUpdateIframe:function(){return this.updateIframe(!0)},handleSuccess:function(t){var e=this,i=t+'<script type="text/javascript">window.scrollTo('+this._scrollX+", "+this._scrollY+");<\/script>",s=$('<iframe class="lp-preview" frameborder="0"/>');this.$iframe?s.insertBefore(this.$iframe):s.appendTo(this.$iframeContainer),this.addListener(s,"load",(function(){this.$iframe&&this.$iframe.remove(),this.$iframe=s,this._slideInOnIframeLoad&&(this.slideIn(),this._slideInOnIframeLoad=!1),this.removeListener(s,"load")})),Garnish.requestAnimationFrame((function(){s[0].contentWindow.document.open(),s[0].contentWindow.document.write(i),s[0].contentWindow.document.close(),e.onResponse()}))},handleError:function(){this.onResponse()},onResponse:function(){this.loading=!1,this.checkAgain&&(this.checkAgain=!1,this.updateIframe())},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)}},{defaultEditorWidth:.33,minEditorWidthInPx:320,defaults:{trigger:".livepreviewbtn",fields:null,extraFields:null,previewUrl:null,previewAction:null,previewParams:{}}}),Craft.LivePreview.init=function(t){Craft.livePreview=new Craft.LivePreview(t)}},7439:function(){Craft.PasswordInput=Garnish.Base.extend({$passwordWrapper:null,$passwordInput:null,$textInput:null,$currentInput:null,$showPasswordToggle:null,showingPassword:null,init:function(t,e){this.$passwordInput=$(t),this.$passwordWrapper=this.$passwordInput.parent(".passwordwrapper"),this.settings=$.extend({},Craft.PasswordInput.defaults,e),this.$passwordInput.data("passwordInput")&&(console.warn("Double-instantiating a password input on an element"),this.$passwordInput.data("passwordInput").destroy()),this.$passwordInput.data("passwordInput",this),this.$showPasswordToggle=$('<button type="button" class="invisible" />'),this.$showPasswordToggle.addClass("password-toggle"),this.$showPasswordToggle.insertAfter(this.$passwordInput),this.initInputFocusEvents(this.$passwordInput),this.addListener(this.$showPasswordToggle,"click","onClick"),this.hidePassword(),this.addListener(this.$passwordWrapper.closest("form"),"submit","hidePassword")},setCurrentInput:function(t){this.$currentInput&&(t.insertAfter(this.$currentInput),this.$currentInput.detach(),t.trigger("focus"),t.val(this.$currentInput.val())),this.$currentInput=t,this.addListener(this.$currentInput,"keypress,keyup,change,blur","onInputChange")},updateToggleLabel:function(t){this.$showPasswordToggle.text(t)},initInputFocusEvents:function(t){this.addListener(t,"focus",(function(){this.$passwordWrapper.addClass("focus")})),this.addListener(t,"blur",(function(){this.$passwordWrapper.removeClass("focus")}))},showPassword:function(){this.showingPassword||(this.$textInput||(this.$textInput=this.$passwordInput.clone(!0),this.$textInput.attr({type:"text",autocapitalize:"off"}),this.initInputFocusEvents(this.$textInput)),this.setCurrentInput(this.$textInput),this.updateToggleLabel(Craft.t("app","Hide")),this.showingPassword=!0)},hidePassword:function(){!1!==this.showingPassword&&(this.setCurrentInput(this.$passwordInput),this.updateToggleLabel(Craft.t("app","Show")),this.showingPassword=!1,this.addListener(this.$passwordInput,"keydown","onKeyDown"))},togglePassword:function(){this.showingPassword?this.hidePassword():this.showPassword(),this.settings.onToggleInput(this.$currentInput)},onKeyDown:function(t){t.keyCode===Garnish.ALT_KEY&&this.$currentInput.val()&&(this.showPassword(),this.$showPasswordToggle.addClass("invisible"),this.addListener(this.$textInput,"keyup","onKeyUp"))},onKeyUp:function(t){t.preventDefault(),t.keyCode===Garnish.ALT_KEY&&(this.hidePassword(),this.$showPasswordToggle.removeClass("invisible"))},onInputChange:function(){this.$currentInput.val()?this.$showPasswordToggle.removeClass("invisible"):this.$showPasswordToggle.addClass("invisible")},onClick:function(t){if(this.$currentInput[0].setSelectionRange){var e=this.$currentInput[0].selectionStart,i=this.$currentInput[0].selectionEnd;this.togglePassword(),this.$currentInput[0].setSelectionRange(e,i)}else this.togglePassword()},destroy:function(){this.$passwordInput.removeData("passwordInput"),this.base()}},{defaults:{onToggleInput:$.noop}})},5328:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}Craft.Preview=Garnish.Base.extend({draftEditor:null,$shade:null,$editorContainer:null,$editor:null,$spinner:null,$statusIcon:null,$dragHandle:null,$previewContainer:null,$iframeContainer:null,$previewHeader:null,$targetBtn:null,$targetMenu:null,$deviceTypeContainer:null,$orientationBtn:null,$refreshBtn:null,$deviceMask:null,$devicePreviewContainer:null,$iframe:null,iframeLoaded:!1,$tempInput:null,$fieldPlaceholder:null,isActive:!1,isVisible:!1,activeTarget:0,currentDeviceType:"desktop",deviceOrientation:null,deviceWidth:"",deviceHeight:"",deviceMaskDimensions:{phone:{width:375,height:753},tablet:{width:768,height:1110}},draftId:null,url:null,fields:null,iframeHeight:null,scrollTop:null,dragger:null,dragStartEditorWidth:null,_updateIframeProxy:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){this.draftEditor=t,this._updateIframeProxy=this.updateIframe.bind(this),this.$tempInput=$("<input/>",{type:"hidden",name:"__PREVIEW_FIELDS__",value:"1"}),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.Preview.defaultEditorWidth)},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.Preview.minEditorWidthInPx&&(t=(e=Craft.Preview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},open:function(){var t=this;if(!this.isActive){if(this.isActive=!0,this.trigger("beforeOpen"),$(document.activeElement).trigger("blur"),!this.$editor){this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=$("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);if($("<div/>",{class:"flex-grow"}).appendTo(e),this.$spinner=$("<div/>",{class:"spinner hidden",title:Craft.t("app","Saving")}).appendTo(e),this.$statusIcon=$("<div/>",{class:"invisible"}).appendTo(e),this.$statusMessage=$("<span/>",{class:"visually-hidden","aria-live":"polite"}).appendTo(e),Craft.Pro){if(this.$previewHeader=$("<header/>",{class:"lp-preview-header"}).appendTo(this.$previewContainer),this.draftEditor.settings.previewTargets.length>1){this.$targetBtn=$("<button/>",{type:"button",class:"btn menubtn",text:this.draftEditor.settings.previewTargets[0].label}).appendTo(this.$previewHeader),this.$targetMenu=$("<div/>",{class:"menu lp-target-menu"}).insertAfter(this.$targetBtn);for(var s,a=$("<ul/>",{class:"padded"}).appendTo(this.$targetMenu),n=0;n<this.draftEditor.settings.previewTargets.length;n++)s=$("<li/>").appendTo(a),$("<a/>",{data:{target:n},text:this.draftEditor.settings.previewTargets[n].label,class:0===n?"sel":null}).appendTo(s);new Garnish.MenuBtn(this.$targetBtn,{onOptionSelect:function(e){t.switchTarget($(e).data("target"))}}),$('<div class="flex-grow"/>').appendTo(this.$previewHeader)}this._buildDeviceTypeFieldset(),$('<div class="flex-grow"/>').appendTo(this.$previewHeader);var r=$('<div class="buttons"/>').appendTo(this.$previewHeader);this.$orientationBtn=$("<button/>",{type:"button",class:"btn disabled","data-icon":"rotate",disabled:"",text:Craft.t("app","Rotate"),"aria-label":Craft.t("app","Rotate")}).appendTo(r),this.addListener(this.$orientationBtn,"click","switchOrientation"),this.$refreshBtn=$("<button/>",{type:"button",class:"btn hidden",text:Craft.t("app","Refresh"),"data-icon":"refresh"}).appendTo(r),this._updateRefreshBtn(),this.addListener(this.$refreshBtn,"click",(function(){t.updateIframe(!1,!0)})),this.deviceOrientation=Craft.getLocalStorage("LivePreview.orientation"),this.addListener($("input",this.$deviceTypeContainer),"change","switchDeviceType")}this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$devicePreviewContainer=$("<div/>",{class:"lp-device-preview-container"}).appendTo(this.$iframeContainer),this.$deviceMask=$("<div/>",{class:"lp-device-mask"}).appendTo(this.$iframeContainer),this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(i,"click","close"),this.addListener(this.$statusIcon,"click",(function(){t.draftEditor.showStatusHud(t.$statusIcon)}))}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];var o=$("#content .field").not($("#content .field .field"));if(o.length){this.$tempInput.insertBefore(o.get(0));for(var l=0;l<o.length;l++){var h=$(o[l]),d=this._getClone(h);this.$fieldPlaceholder.insertAfter(h),h.detach(),this.$fieldPlaceholder.replaceWith(d),h.appendTo(this.$editor),this.fields.push({$field:h,$clone:d})}}this.updateIframe(),this.draftEditor.on("update",this._updateIframeProxy),Garnish.on(Craft.BaseElementEditor,"saveElement",this._updateIframeProxy),Garnish.on(Craft.AssetImageEditor,"save",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.trigger("open")}},_buildDeviceTypeFieldset:function(){this.$deviceTypeContainer=$("<fieldset/>",{class:"lp-device-type"}).appendTo(this.$previewHeader),$("<legend/>",{text:Craft.t("app","Device type"),class:"visually-hidden"}).appendTo(this.$deviceTypeContainer);var t=$("<div/>",{class:"lp-device-type__radio-group"}).appendTo(this.$deviceTypeContainer),e=$("<div/>",{class:"lp-device-type__item"}).appendTo(t);$("<input/>",{class:"lp-device-type__input visually-hidden",type:"radio",name:"device",value:"desktop",id:"device-desktop",checked:!0,data:{width:"",height:""}}).appendTo(e);var i=$("<label/>",{for:"device-desktop",class:"btn lp-device-type__label lp-device-type__label--desktop active",title:Craft.t("app","Desktop")}).appendTo(e);$("<span/>",{class:"visually-hidden",text:Craft.t("app","Desktop")}).appendTo(i);var s=$("<div/>",{class:"lp-device-type__item"}).appendTo(t);$("<input/>",{class:"lp-device-type__input visually-hidden",type:"radio",name:"device",value:"tablet",id:"device-tablet",data:{width:768,height:1024}}).appendTo(s);var a=$("<label/>",{for:"device-tablet",class:"btn lp-device-type__label lp-device-type__label--tablet",title:Craft.t("app","Tablet")}).appendTo(s);$("<span/>",{class:"visually-hidden",text:Craft.t("app","Tablet")}).appendTo(a);var n=$("<div/>",{class:"lp-device-type__item"}).appendTo(t);$("<input/>",{class:"lp-device-type__input visually-hidden",type:"radio",name:"device",value:"phone",id:"device-phone",data:{width:375,height:667}}).appendTo(n);var r=$("<label/>",{for:"device-phone",class:"btn lp-device-type__label lp-device-type__label--phone",title:Craft.t("app","Mobile")}).appendTo(n);$("<span/>",{class:"visually-hidden",text:Craft.t("app","Mobile")}).appendTo(r)},_activeTarget:function(){return this.draftEditor.settings.previewTargets[this.activeTarget]},_autoRefresh:function(){var e=this._activeTarget();return void 0===t(e.refresh)||!!e.refresh},_updateRefreshBtn:function(){this._autoRefresh()?this.$refreshBtn.addClass("hidden"):this.$refreshBtn.removeClass("hidden")},switchTarget:function(t){this.activeTarget=t,this.$targetBtn.text(this.draftEditor.settings.previewTargets[t].label),this.$targetMenu.find("a.sel").removeClass("sel"),this.$targetMenu.find("a").eq(t).addClass("sel"),this.updateIframe(!0),this._updateRefreshBtn(),this.trigger("switchTarget",{previewTarget:this.draftEditor.settings.previewTargets[t]})},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;this.isActive&&!this.isVisible&&($("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,"slow"),this.isVisible=!0,Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})))},close:function(){var t=this;this.isActive&&this.isVisible&&(this.trigger("beforeClose"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),this.$tempInput.detach(),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",(function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating"),t.$previewContainer.hide()})),this.draftEditor.off("update",this._updateIframeProxy),Garnish.off(Craft.BaseElementEditor,"saveElement",this._updateIframeProxy),Garnish.off(Craft.AssetImageEditor,"save",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.isActive=!1,this.isVisible=!1,this.trigger("close"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth()),this._devicePreviewIsActive()&&this.updateDevicePreview()},_useIframeResizer:function(){return!1!==Craft.previewIframeResizerOptions},updateIframe:function(t,e){var i=this;if(!this.isActive)return!1;t=!0===t,this.draftId===(this.draftId=this.draftEditor.settings.draftId)&&this.$iframe||(e=!0);var s=this._activeTarget();void 0===e&&(e=t||this._autoRefresh()),this.trigger("beforeUpdateIframe",{previewTarget:s,resetScroll:t,refresh:e}),e?this.draftEditor.getTokenizedPreviewUrl(s.url,"x-craft-live-preview").then((function(e){var s;t?i.scrollTop=null:i.iframeLoaded&&i.$iframe&&(i._useIframeResizer()?(i.iframeHeight=i.$iframe.height(),i.scrollTop=i.$iframeContainer.scrollTop()):(s=Craft.isSameHost(e))&&i.$iframe[0].contentWindow&&(i.scrollTop=$(i.$iframe[0].contentWindow.document).scrollTop())),i.iframeLoaded=!1;var a=$("<iframe/>",{class:"lp-preview",frameborder:0,src:e,title:Craft.t("app","Preview")});i.$iframe?i.$iframe.replaceWith(a):a.appendTo(i.$devicePreviewContainer),i._useIframeResizer()?(t||null===i.iframeHeight||(a.height(i.iframeHeight),i.$iframeContainer.scrollTop(i.scrollTop)),iFrameResize($.extend({checkOrigin:!1,scrolling:!0,onInit:function(t){i.iframeLoaded=!0,i.iframeHeight=null,i.scrollTop=null,t.scrolling="no"}},Craft.previewIframeResizerOptions||{}),a[0])):a.on("load",(function(){i.iframeLoaded=!0,!t&&s&&null!==i.scrollTop&&$(a[0].contentWindow.document).scrollTop(i.scrollTop)})),i.url=e,i.$iframe=a,i._devicePreviewIsActive()&&i.updateDevicePreview(),i.trigger("afterUpdateIframe",{previewTarget:i.draftEditor.settings.previewTargets[i.activeTarget],$iframe:i.$iframe}),i.slideIn()})):this.slideIn()},_devicePreviewIsActive:function(){return"desktop"!==this.currentDeviceType},switchDeviceType:function(t){this.$iframeContainer.removeClass("lp-iframe-container--rotating");var e=$(t.target),i=e.closest(".lp-device-type__item"),s=e.val();if(s===this.currentDeviceType)return!1;this.currentDeviceType=s,this.deviceWidth=e.data("width"),this.deviceHeight=e.data("height"),this.$deviceTypeContainer.find(".btn").removeClass("active"),i.find(".btn").addClass("active"),"desktop"===this.currentDeviceType?(this.$orientationBtn.addClass("disabled").attr("disabled",""),this.$iframeContainer.removeClass("lp-iframe-container--has-device-preview")):(this.$orientationBtn.removeClass("disabled").removeAttr("disabled"),this.$iframeContainer.addClass("lp-iframe-container--has-device-preview")),"tablet"===this.currentDeviceType?this.$iframeContainer.addClass("lp-iframe-container--tablet"):this.$iframeContainer.removeClass("lp-iframe-container--tablet"),"desktop"!==this.currentDeviceType&&this.updateDevicePreview()},switchOrientation:function(){var t=this;if(!this._devicePreviewIsActive())return!1;this.deviceOrientation&&"portrait"!==this.deviceOrientation?this.deviceOrientation="portrait":this.deviceOrientation="landscape",Craft.setLocalStorage("LivePreview.orientation",this.deviceOrientation),this.$iframeContainer.addClass("lp-iframe-container--rotating"),this.updateDevicePreview(),setTimeout((function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating")}),300)},updateDevicePreview:function(){var t=1,e=1,i=1,s=this.$previewContainer.height()-50-48,a=this.$previewContainer.width()-48,n=this.deviceMaskDimensions[this.currentDeviceType].height,r=this.deviceMaskDimensions[this.currentDeviceType].width;"landscape"===this.deviceOrientation?(a<n&&(t=a/n),s<r&&(e=s/r)):(s<n&&(t=s/n),a<r&&(e=a/r)),i=t,e<t&&(i=e);var o=-100/i/2,l="landscape"===this.deviceOrientation?"-90deg":"0deg";this.$deviceMask.css({width:this.deviceMaskDimensions[this.currentDeviceType].width+"px",height:this.deviceMaskDimensions[this.currentDeviceType].height+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%) rotate("+l+")"}),"landscape"===this.deviceOrientation?this.$devicePreviewContainer.css({width:this.deviceHeight+"px",height:this.deviceWidth+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:0,marginLeft:"-"+12*i+"px"}):this.$devicePreviewContainer.css({width:this.deviceWidth+"px",height:this.deviceHeight+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:"-"+12*i+"px",marginLeft:0})},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e.find("[name]").prop("disabled",!0),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)}},{defaultEditorWidth:.33,minEditorWidthInPx:320})},6419:function(){Craft.PreviewFileModal=Garnish.Modal.extend({assetId:null,$spinner:null,elementSelect:null,type:null,loaded:null,requestId:0,init:function(t,e,i){if((i=$.extend(this.defaultSettings,i)).onHide=this._onHide.bind(this),Craft.PreviewFileModal.openInstance){var s=Craft.PreviewFileModal.openInstance;return s.assetId!==t&&(s.loadAsset(t,i.startingWidth,i.startingHeight),s.elementSelect=e),this.destroy()}Craft.PreviewFileModal.openInstance=this,this.elementSelect=e,this.$container=$('<div class="modal previewmodal loading"/>').appendTo(Garnish.$bod),this.base(this.$container,$.extend({resizable:!0},i)),this.$container&&(this.$container.velocity("stop"),this.$container.show().css("opacity",1),this.$shade.velocity("stop"),this.$shade.show().css("opacity",1)),this.loadAsset(t,i.startingWidth,i.startingHeight)},_onHide:function(){return Craft.PreviewFileModal.openInstance=null,this.elementSelect&&this.elementSelect.focusItem(this.elementSelect.$focusedItem),this.$shade.remove(),this.destroy()},selfDestruct:function(){var t=Craft.PreviewFileModal.openInstance;return t.hide(),t.$shade.remove(),t.destroy(),Craft.PreviewFileModal.openInstance=null,!0},loadAsset:function(t,e,i){var s=this;this.assetId=t,this.$container.empty(),this.loaded=!1,this.desiredHeight=null,this.desiredWidth=null;var a=.66*Garnish.$win.height(),n=Math.min(a/3*4,Garnish.$win.width()-2*this.settings.minGutter);if(a=n/4*3,e&&i){var r=e/i;n=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter),(n=(a=Math.min(n/r,Garnish.$win.height()-2*this.settings.minGutter))*r)>Math.min(e,Garnish.$win.width()-2*this.settings.minGutter)&&(a=(n=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter))/r)}this._resizeContainer(n,a),this.$spinner=$('<div class="spinner centeralign"></div>').appendTo(this.$container);var o=this.$container.height()/2-this.$spinner.height()/2+"px",l=this.$container.width()/2-this.$spinner.width()/2+"px";this.$spinner.css({left:l,top:o,position:"absolute"}),this.requestId++,Craft.postActionRequest("assets/preview-file",{assetId:t,requestId:this.requestId},(function(t,e){if(s.$container.removeClass("loading"),s.$spinner.remove(),s.loaded=!0,"success"===e)if(t.success){if(t.requestId!=s.requestId)return;if(!t.previewHtml)return s.$container.addClass("zilch"),void s.$container.append($("<p/>",{text:Craft.t("app","No preview available.")}));s.$container.removeClass("zilch"),s.$container.append(t.previewHtml),Craft.appendHeadHtml(t.headHtml),Craft.appendFootHtml(t.footHtml)}else alert(t.error),s.hide()}))},_resizeContainer:function(t,e){this.$container.css({width:t,"min-width":t,"max-width":t,height:e,"min-height":e,"max-height":e,top:(Garnish.$win.height()-e)/2,left:(Garnish.$win.width()-t)/2})}},{defaultSettings:{startingWidth:null,startingHeight:null}})},872:function(){Craft.ProgressBar=Garnish.Base.extend({$progressBar:null,$innerProgressBar:null,$progressBarStatus:null,_itemCount:0,_processedItemCount:0,_displaySteps:!1,init:function(t,e){e&&(this._displaySteps=!0),this.$progressBar=$('<div class="progressbar pending hidden"/>').appendTo(t),this.$innerProgressBar=$('<div class="progressbar-inner"/>').appendTo(this.$progressBar),this.$progressBarStatus=$('<div class="progressbar-status hidden" />').insertAfter(this.$progressBar),this.resetProgressBar()},resetProgressBar:function(){this.setProgressPercentage(100),this.$progressBar.addClass("pending"),this.setItemCount(1),this.setProcessedItemCount(0),this.$progressBarStatus.html(""),this._displaySteps&&this.$progressBar.addClass("has-status")},hideProgressBar:function(){var t=this;this.$progressBar.fadeTo("fast",.01,(function(){t.$progressBar.addClass("hidden").fadeTo(1,1,$.noop)})),this.$progressBarStatus.fadeTo("fast",.01,(function(){t.$progressBarStatus.addClass("hidden").fadeTo(1,1,$.noop)}))},showProgressBar:function(){this.$progressBar.removeClass("hidden"),this.$progressBarStatus.removeClass("hidden")},setItemCount:function(t){this._itemCount=t},incrementItemCount:function(t){this._itemCount+=t},setProcessedItemCount:function(t){this._processedItemCount=t},incrementProcessedItemCount:function(t){this._processedItemCount+=t},updateProgressBar:function(){this._itemCount=Math.max(this._itemCount,1);var t=Math.min(100,Math.round(100*this._processedItemCount/this._itemCount));this.setProgressPercentage(t),this._displaySteps&&this.$progressBarStatus.html(this._processedItemCount+" / "+this._itemCount)},setProgressPercentage:function(t,e){0===t?this.$progressBar.addClass("pending"):(this.$progressBar.removeClass("pending"),e?this.$innerProgressBar.velocity("stop").velocity({width:t+"%"},"fast"):this.$innerProgressBar.velocity("stop").width(t+"%"))}})},1396:function(){Craft.PromptHandler=Garnish.Base.extend({modal:null,$modalContainerDiv:null,$prompt:null,$promptApplyToRemainingContainer:null,$promptApplyToRemainingCheckbox:null,$promptApplyToRemainingLabel:null,$pomptChoices:null,_prompts:[],_promptBatchCallback:$.noop,_promptBatchReturnData:[],_promptBatchNum:0,resetPrompts:function(){this._prompts=[],this._promptBatchCallback=$.noop,this._promptBatchReturnData=[],this._promptBatchNum=0},addPrompt:function(t){this._prompts.push(t)},getPromptCount:function(){return this._prompts.length},showBatchPrompts:function(t){this._promptBatchCallback=t,this._promptBatchReturnData=[],this._promptBatchNum=0,this._showNextPromptInBatch()},_showNextPromptInBatch:function(){var t=this._prompts[this._promptBatchNum].prompt,e=this._prompts.length-(this._promptBatchNum+1);this._showPrompt(t.message,t.choices,this._handleBatchPromptSelection.bind(this),e)},_handleBatchPromptSelection:function(t,e){var i=this._prompts[this._promptBatchNum],s=this._prompts.length-(this._promptBatchNum+1),a=$.extend(i,{choice:t});this._promptBatchReturnData.push(a),s?(this._promptBatchNum++,e?this._handleBatchPromptSelection(t,!0):this._showNextPromptInBatch()):"function"==typeof this._promptBatchCallback&&this._promptBatchCallback(this._promptBatchReturnData)},_showPrompt:function(t,e,i,s){this._promptCallback=i,null===this.modal&&(this.modal=new Garnish.Modal({closeOtherModals:!1})),null===this.$modalContainerDiv&&(this.$modalContainerDiv=$('<div class="modal fitted prompt-modal"></div>').addClass().appendTo(Garnish.$bod)),this.$prompt=$('<div class="body"></div>').appendTo(this.$modalContainerDiv.empty()),this.$promptMessage=$('<p class="prompt-msg"/>').appendTo(this.$prompt),this.$promptChoices=$('<div class="options"></div>').appendTo(this.$prompt),this.$promptApplyToRemainingContainer=$('<label class="assets-applytoremaining"/>').appendTo(this.$prompt).hide(),this.$promptApplyToRemainingCheckbox=$('<input type="checkbox"/>').appendTo(this.$promptApplyToRemainingContainer),this.$promptApplyToRemainingLabel=$("<span/>").appendTo(this.$promptApplyToRemainingContainer),this.$promptButtons=$('<div class="buttons right"/>').appendTo(this.$prompt),this.modal.setContainer(this.$modalContainerDiv),this.$promptMessage.html(t);for(var a=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$promptButtons),n=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","OK")}).appendTo(this.$promptButtons),r=0;r<e.length;r++){var o=$('<div><label><input type="radio" name="promptAction" value="'+e[r].value+'"/> '+e[r].title+"</label></div>").appendTo(this.$promptChoices).find("input");this.addListener(o,"click",(function(){n.removeClass("disabled")}))}this.addListener(n,"activate",(function(t){var e=$(t.currentTarget).parents(".modal").find("input[name=promptAction]:checked").val(),i=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice(e,i)})),this.addListener(a,"activate",(function(){var t=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice("cancel",t)})),s&&(this.$promptApplyToRemainingContainer.show(),this.$promptApplyToRemainingLabel.html(" "+Craft.t("app","Apply this to the {number} remaining conflicts?",{number:s}))),this.modal.show(),this.modal.removeListener(Garnish.Modal.$shade,"click"),this.addListener(Garnish.Modal.$shade,"click","_cancelPrompt")},_selectPromptChoice:function(t,e){var i=this;this.$prompt.fadeOut("fast",(function(){i.modal.hide(),i._promptCallback(t,e)}))},_cancelPrompt:function(){this._selectPromptChoice("cancel",!0)}})},4070:function(){!function(t){Craft.SlidePicker=Garnish.Base.extend({min:null,max:null,totalSteps:null,value:null,$container:null,$buttons:null,init:function(e,i){var s=this;this.setSettings(i,Craft.SlidePicker.defaults),this.$container=t("<div/>",{class:"slide-picker",role:"slider",tabindex:0}),this.refresh(),this.setValue(e,!1),this.addListener(this.$container,"keydown",(function(t){switch(t.keyCode){case Garnish.UP_KEY:s.setValue(s.value+s.settings.step),t.preventDefault();break;case Garnish.DOWN_KEY:s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?s.setValue(s.value+s.settings.step):s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?s.setValue(s.value-s.settings.step):s.setValue(s.value+s.settings.step),t.preventDefault()}}))},refresh:function(){var e=this;if(this.min=this._min(),this.max=this._max(),this.totalSteps=(this.max-this.min)/this.settings.step,!Number.isInteger(this.totalSteps))throw"Invalid SlidePicker config";this.$buttons&&this.$buttons.remove(),this.$container.attr("aria-valuemin",this.min),this.$container.attr("aria-valuemax",this.max),this.$buttons=t();for(var i=this.min;i<=this.max;i+=this.settings.step)this.$buttons=this.$buttons.add(t("<a/>",{title:this.settings.valueLabel(i),data:{value:i}}));if(this.$buttons.appendTo(this.$container),null!==this.value){var s=this.value;this.value=null,this.setValue(s,!1)}this.addListener(this.$buttons,"mouseover",(function(i){e.$buttons.removeClass("active-hover last-active-hover"),t(i.currentTarget).addClass("active-hover last-active-hover").prevAll().addClass("active-hover")})),this.addListener(this.$buttons,"mouseout",(function(){e.$buttons.removeClass("active-hover")})),this.addListener(this.$buttons,"click",(function(i){e.setValue(t.data(i.currentTarget,"value")),i.stopPropagation(),e.$container.focus()}))},setValue:function(t,e){if(t=Math.max(Math.min(t,this.max),this.min),this.value!==(this.value=t)){this.$container.attr({"aria-valuenow":this.value,"aria-valuetext":this.settings.valueLabel(this.value)}),this.$buttons.removeClass("last-active active");var i=this.$buttons.eq((this.value-this.min)/this.settings.step);i.add(i.prevAll()).addClass("active"),i.addClass("last-active"),!1!==e&&this.settings.onChange(t)}},_min:function(){return"function"==typeof this.settings.min?this.settings.min():this.settings.min},_max:function(){return"function"==typeof this.settings.max?this.settings.max():this.settings.max}},{defaults:{min:0,max:100,step:10,valueLabel:null,onChange:t.noop}})}(jQuery)},5763:function(){Craft.SlideRuleInput=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,$input:null,value:null,startPositionX:null,init:function(t,e){var i=this;this.setSettings(e,Craft.SlideRuleInput.defaultSettings),this.value=0,this.graduationsMin=-70,this.graduationsMax=70,this.slideMin=-45,this.slideMax=45,this.$container=$("#"+t),this.$overlay=$('<div class="overlay"></div>').appendTo(this.$container),this.$cursor=$('<div class="cursor"></div>').appendTo(this.$container),this.$graduations=$('<div class="graduations"></div>').appendTo(this.$container),this.$graduationsUl=$("<ul></ul>").appendTo(this.$graduations);for(var s=this.graduationsMin;s<=this.graduationsMax;s++){var a=$('<li class="graduation" data-graduation="'+s+'"><div class="label">'+s+"</div></li>").appendTo(this.$graduationsUl);s%5==0&&a.addClass("main-graduation"),0===s&&a.addClass("selected")}this.$options=this.$container.find(".graduation"),this.addListener(this.$container,"resize",this._handleResize.bind(this)),this.addListener(this.$container,"tapstart",this._handleTapStart.bind(this)),this.addListener(Garnish.$bod,"tapmove",this._handleTapMove.bind(this)),this.addListener(Garnish.$bod,"tapend",this._handleTapEnd.bind(this)),setTimeout((function(){i.graduationsCalculatedWidth=10*(i.$options.length-1),i.$graduationsUl.css("left",-i.graduationsCalculatedWidth/2+i.$container.width()/2)}),50)},_handleResize:function(){var t=this.valueToPosition(this.value);this.$graduationsUl.css("left",t)},_handleTapStart:function(t,e){t.preventDefault(),this.startPositionX=e.position.x,this.startLeft=this.$graduationsUl.position().left,this.dragging=!0,this.onStart()},_handleTapMove:function(t,e){if(this.dragging){t.preventDefault();var i=this.startPositionX-e.position.x,s=this.startLeft-i,a=this.positionToValue(s);this.setValue(a),this.onChange()}},setValue:function(t){var e=this.valueToPosition(t);t<this.slideMin?(t=this.slideMin,e=this.valueToPosition(t)):t>this.slideMax&&(t=this.slideMax,e=this.valueToPosition(t)),this.$graduationsUl.css("left",e),t>=this.slideMin&&t<=this.slideMax&&(this.$options.removeClass("selected"),$.each(this.$options,(function(e,i){$(i).data("graduation")>0&&$(i).data("graduation")<=t&&$(i).addClass("selected"),$(i).data("graduation")<0&&$(i).data("graduation")>=t&&$(i).addClass("selected"),0==$(i).data("graduation")&&$(i).addClass("selected")}))),this.value=t},_handleTapEnd:function(t){this.dragging&&(t.preventDefault(),this.dragging=!1,this.onEnd())},positionToValue:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return(this.$graduations.width()/2+-1*t)/this.graduationsCalculatedWidth*i-e},valueToPosition:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return-((t+e)*this.graduationsCalculatedWidth/i-this.$graduations.width()/2)},onStart:function(){"function"==typeof this.settings.onChange&&this.settings.onStart(this)},onChange:function(){"function"==typeof this.settings.onChange&&this.settings.onChange(this)},onEnd:function(){"function"==typeof this.settings.onChange&&this.settings.onEnd(this)},defaultSettings:{onStart:$.noop,onChange:$.noop,onEnd:$.noop}})},5759:function(){!function(t){Craft.Slideout=Garnish.Base.extend({$outerContainer:null,$container:null,$shade:null,isOpen:!1,init:function(e,i){var s=this;this.setSettings(i,Craft.Slideout.defaults),Garnish.isMobileBrowser()||(this.$shade=t('<div class="slideout-shade"/>').appendTo(Garnish.$bod),this.settings.closeOnShadeClick&&this.addListener(this.$shade,"click",(function(t){t.stopPropagation(),s.close()}))),this.$outerContainer=t("<div/>",{class:"slideout-container hidden"}),this.$container=t("<".concat(this.settings.containerElement,"/>"),this.settings.containerAttributes).addClass("slideout").append(e).data("slideout",this).appendTo(this.$outerContainer),Garnish.addModalAttributes(this.$outerContainer),Garnish.isMobileBrowser()&&this.$container.addClass("so-mobile"),Craft.trapFocusWithin(this.$container),this.settings.autoOpen&&this.open()},open:function(){var t=this;this.isOpen||(this.setTriggerElement(document.activeElement),this._cancelTransitionListeners(),this.$shade&&this.$shade.appendTo(Garnish.$bod).show(),this.$outerContainer.appendTo(Garnish.$bod).removeClass("hidden"),Garnish.isMobileBrowser()?this.$container.css("top","100vh"):this.$container.css(Garnish.ltr?"left":"right","100vw"),this.$container.one("transitionend.slideout",(function(){Craft.setFocusWithin(t.$container)})),this.$shade&&(this.$shade[0].offsetWidth,this.$shade.addClass("so-visible")),this.$container[0].offsetWidth,Craft.Slideout.addPanel(this),this.enable(),Garnish.uiLayerManager.addLayer(this.$outerContainer),Garnish.hideModalBackgroundLayers(this.$outerContainer),this.settings.closeOnEsc&&Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})),this.isOpen=!0,this.trigger("open"))},setTriggerElement:function(t){this.settings.triggerElement=t},close:function(){var t=this;this.isOpen&&(this.trigger("beforeClose"),this.disable(),this.isOpen=!1,this._cancelTransitionListeners(),this.$shade&&this.$shade.removeClass("so-visible").one("transitionend.slideout",(function(){t.$shade.hide()})),Craft.Slideout.removePanel(this),Garnish.uiLayerManager.removeLayer(),Garnish.resetModalBackgroundLayerVisibility(this.$outerContainer),this.$container.one("transitionend.slideout",(function(){t.$outerContainer.addClass("hidden"),t.trigger("close")})),this.settings.triggerElement&&this.settings.triggerElement.focus())},_cancelTransitionListeners:function(){this.$shade&&this.$shade.off("transitionend.slideout"),this.$container.off("transitionend.slideout")},destroy:function(){this.$shade&&(this.$shade.remove(),this.$shade=null),this.$outerContainer.remove(),this.$outerContainer=null,this.$container=null,this.base()}},{defaults:{containerElement:"div",containerAttributes:{},autoOpen:!0,closeOnEsc:!0,closeOnShadeClick:!0,triggerElement:null},openPanels:[],addPanel:function(t){Craft.Slideout.openPanels.unshift(t),Garnish.isMobileBrowser()?t.$container.css("top",0):Craft.Slideout.updateStyles()},removePanel:function(t){Craft.Slideout.openPanels=Craft.Slideout.openPanels.filter((function(e){return e!==t})),Garnish.isMobileBrowser()?t.$container.css("top","100vh"):(t.$container.css(Garnish.ltr?"left":"right","100vw"),Craft.Slideout.updateStyles())},updateStyles:function(){var t=Craft.Slideout.openPanels.length;Craft.Slideout.openPanels.forEach((function(e,i){e.$container.css(Garnish.ltr?"left":"right","".concat((t-i)/t*50,"vw"))})),0!==t?Garnish.$bod.addClass("no-scroll"):Garnish.$bod.removeClass("no-scroll")}})}(jQuery)},5185:function(){Craft.SlugGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace(/<(.*?)>/g,"")).replace(/['"‘’“”\[\]\(\)\{\}:]/g,""),Craft.allowUppercaseInSlug||(t=t.toLowerCase()),Craft.limitAutoSlugsToAscii&&(t=Craft.asciiString(t,this.settings.charMap));var e=Craft.filterArray(XRegExp.matchChain(t,[XRegExp("[\\p{L}\\p{N}\\p{M}]+")]));return e.length?e.join(Craft.slugWordSeparator):""}})},8030:function(){Craft.Structure=Garnish.Base.extend({id:null,$container:null,state:null,structureDrag:null,init:function(t,e,i){this.id=t,this.$container=$(e),this.setSettings(i,Craft.Structure.defaults),this.$container.data("structure")&&(console.warn("Double-instantiating a structure on an element"),this.$container.data("structure").destroy()),this.$container.data("structure",this),this.state={},this.settings.storageKey&&$.extend(this.state,Craft.getLocalStorage(this.settings.storageKey,{})),void 0===this.state.collapsedElementIds&&(this.state.collapsedElementIds=[]);for(var s=this.$container.find("ul").prev(".row"),a=0;a<s.length;a++){var n=$(s[a]),r=n.parent(),o=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(n);-1!==$.inArray(n.children(".element").data("id"),this.state.collapsedElementIds)&&r.addClass("collapsed"),this.initToggle(o)}this.settings.sortable&&(this.structureDrag=new Craft.StructureDrag(this,this.settings.maxLevels)),this.settings.newChildUrl&&this.initNewChildMenus(this.$container.find(".add"))},initToggle:function(t){var e=this;t.on("click",(function(t){var i=$(t.currentTarget).closest("li"),s=i.children(".row").find(".element:first").data("id"),a=$.inArray(s,e.state.collapsedElementIds);i.hasClass("collapsed")?(i.removeClass("collapsed"),-1!==a&&e.state.collapsedElementIds.splice(a,1)):(i.addClass("collapsed"),-1===a&&e.state.collapsedElementIds.push(s)),e.settings.storageKey&&Craft.setLocalStorage(e.settings.storageKey,e.state)}))},initNewChildMenus:function(t){this.addListener(t,"click","onNewChildMenuClick")},onNewChildMenuClick:function(t){var e=$(t.currentTarget);if(!e.data("menubtn")){var i=e.parent().children(".element").data("id"),s=Craft.getUrl(this.settings.newChildUrl,"parentId="+i);$('<div class="menu"><ul><li><a href="'+s+'">'+Craft.t("app","New child")+"</a></li></ul></div>").insertAfter(e),new Garnish.MenuBtn(e).showMenu()}},getIndent:function(t){return Craft.Structure.baseIndent+(t-1)*Craft.Structure.nestedIndent},addElement:function(t){var e=$('<li data-level="1"/>').appendTo(this.$container),i=$('<div class="row" style="margin-'+Craft.left+": -"+Craft.Structure.baseIndent+"px; padding-"+Craft.left+": "+Craft.Structure.baseIndent+'px;">').appendTo(e);if(i.append(t),this.settings.sortable&&(i.append('<a class="move icon" title="'+Craft.t("app","Move")+'"></a>'),this.structureDrag.addItems(e)),this.settings.newChildUrl){var s=$('<a class="add icon" title="'+Craft.t("app","New child")+'"></a>').appendTo(i);this.initNewChildMenus(s)}i.css("margin-bottom",-30),i.velocity({"margin-bottom":0},"fast")},removeElement:function(t){var e,i=this,s=t.parent().parent();this.settings.sortable&&this.structureDrag.removeItems(s),s.siblings().length||(e=s.parent()),s.css("visibility","hidden").velocity({marginBottom:-s.height()},"fast",(function(){s.remove(),void 0!==e&&i._removeUl(e)}))},_removeUl:function(t){t.siblings(".row").children(".toggle").remove(),t.remove()},destroy:function(){this.$container.removeData("structure"),this.base()}},{baseIndent:8,nestedIndent:35,defaults:{storageKey:null,sortable:!1,newChildUrl:null,maxLevels:null}})},3096:function(){Craft.StructureDrag=Garnish.Drag.extend({structure:null,maxLevels:null,draggeeLevel:null,$helperLi:null,$targets:null,draggeeHeight:null,init:function(t,e){this.structure=t,this.maxLevels=e,this.$insertion=$('<li class="draginsertion"/>');var i=this.structure.$container.find("li");this.base(i,{handle:".element:first, .move:first",helper:this.getHelper.bind(this)})},getHelper:function(t){this.$helperLi=t;var e=$('<ul class="structure draghelper"/>').append(t);return t.css("padding-"+Craft.left,this.$draggee.css("padding-"+Craft.left)),t.find(".move").removeAttr("title"),e},onDragStart:function(){var t=this;this.$targets=$(),this.findTargets(this.structure.$container),this.draggeeLevel=0;var e=this.$draggee;do{this.draggeeLevel++,e=e.find("> ul > li")}while(e.length);this.draggeeHeight=this.$draggee.height(),this.$draggee.velocity({height:0},"fast",(function(){t.$draggee.addClass("hidden")})),this.base(),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&this.cancelDrag()}))},findTargets:function(t){for(var e=t.children().not(this.$draggee),i=0;i<e.length;i++){var s=$(e[i]);this.$targets=this.$targets.add(s.children(".row")),s.hasClass("collapsed")||this.findTargets(s.children("ul"))}},onDrag:function(){for(this._.$closestTarget&&(this._.$closestTarget.removeClass("draghover"),this.$insertion.remove()),this._.$closestTarget=null,this._.closestTargetPos=null,this._.closestTargetYDiff=null,this._.closestTargetOffset=null,this._.closestTargetHeight=null,this._.i=0;this._.i<this.$targets.length&&(this._.$target=$(this.$targets[this._.i]),this._.targetOffset=this._.$target.offset(),this._.targetHeight=this._.$target.outerHeight(),this._.targetYMidpoint=this._.targetOffset.top+this._.targetHeight/2,this._.targetYDiff=Math.abs(this.mouseY-this._.targetYMidpoint),0===this._.i||this.mouseY>=this._.targetOffset.top+5&&this._.targetYDiff<this._.closestTargetYDiff);this._.i++)this._.$closestTarget=this._.$target,this._.closestTargetPos=this._.i,this._.closestTargetYDiff=this._.targetYDiff,this._.closestTargetOffset=this._.targetOffset,this._.closestTargetHeight=this._.targetHeight;if(this._.$closestTarget)if(0===this._.closestTargetPos&&this.mouseY<this._.closestTargetOffset.top+5)this.$insertion.prependTo(this.structure.$container);else if(this._.$closestTargetLi=this._.$closestTarget.parent(),this._.closestTargetLevel=this._.$closestTargetLi.data("level"),this._.closestTargetPos<this.$targets.length-1?(this._.$nextTargetLi=$(this.$targets[this._.closestTargetPos+1]).parent(),this._.nextTargetLevel=this._.$nextTargetLi.data("level")):(this._.$nextTargetLi=null,this._.nextTargetLevel=null),this._.hoveringBetweenRows=this.mouseY>=this._.closestTargetOffset.top+this._.closestTargetHeight-5,this._.$nextTargetLi&&this._.nextTargetLevel==this._.closestTargetLevel)this._.hoveringBetweenRows?(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel-1)&&this.$insertion.insertAfter(this._.$closestTargetLi):(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover");else if(this._.$nextTargetLi&&this._.nextTargetLevel>this._.closestTargetLevel)(!this.maxLevels||this.maxLevels>=this._.nextTargetLevel+this.draggeeLevel-1)&&(this._.hoveringBetweenRows?this.$insertion.insertBefore(this._.$nextTargetLi):(this._.$closestTarget.addClass("draghover"),this.$insertion.appendTo(this._.$closestTargetLi.children("ul"))));else if(this._.hoveringBetweenRows){for(this._.draggeeX=this.mouseX-this.targetItemMouseDiffX,"rtl"===Craft.orientation&&(this._.draggeeX+=this.$helperLi.width()),this._.$parentLis=this._.$closestTarget.parentsUntil(this.structure.$container,"li"),this._.$closestParentLi=null,this._.closestParentLiXDiff=null,this._.closestParentLevel=null,this._.i=0;this._.i<this._.$parentLis.length;this._.i++)this._.$parentLi=$(this._.$parentLis[this._.i]),this._.parentLiX=this._.$parentLi.offset().left,"rtl"===Craft.orientation&&(this._.parentLiX+=this._.$parentLi.width()),this._.parentLiXDiff=Math.abs(this._.parentLiX-this._.draggeeX),this._.parentLevel=this._.$parentLi.data("level"),(!this.maxLevels||this.maxLevels>=this._.parentLevel+this.draggeeLevel-1)&&(!this._.$closestParentLi||this._.parentLiXDiff<this._.closestParentLiXDiff&&(!this._.$nextTargetLi||this._.parentLevel>=this._.nextTargetLevel))&&(this._.$closestParentLi=this._.$parentLi,this._.closestParentLiXDiff=this._.parentLiXDiff,this._.closestParentLevel=this._.parentLevel);this._.$closestParentLi&&this.$insertion.insertAfter(this._.$closestParentLi)}else(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover")},cancelDrag:function(){this.$insertion.remove(),this._.$closestTarget&&this._.$closestTarget.removeClass("draghover"),this.onMouseUp()},onDragStop:function(){var t=this;if(this._.$closestTarget&&(this.$insertion.parent().length||this._.$closestTarget.hasClass("draghover"))){var e,i;if(this.$draggee.siblings().length||(e=this.$draggee.parent()),this.$insertion.parent().length){var s=this.$insertion.next().add(this.$insertion.prev());-1===$.inArray(this.$draggee[0],s)?(this.$insertion.replaceWith(this.$draggee),i=!0):(this.$insertion.remove(),i=!1)}else{var a=this._.$closestTargetLi.children("ul");if(e&&a.length&&a[0]===e[0])i=!1;else{if(a.length)this._.$closestTargetLi.hasClass("collapsed")&&this._.$closestTarget.children(".toggle").trigger("click");else{var n=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(this._.$closestTarget);this.structure.initToggle(n),a=$("<ul>").appendTo(this._.$closestTargetLi)}this.$draggee.appendTo(a),i=!0}}if(this._.$closestTarget.removeClass("draghover"),i){e&&this.structure._removeUl(e);var r,o=this.$draggee.parentsUntil(this.structure.$container,"li").length+1;o!=this.$draggee.data("level")&&(1==this.$draggee.data("level")?((r={})["padding-"+Craft.left]=38,this.$helperLi.velocity(r,"fast")):1==o&&((r={})["padding-"+Craft.left]=Craft.Structure.baseIndent,this.$helperLi.velocity(r,"fast")),this.setLevel(this.$draggee,o));var l=this.$draggee.children(".row").children(".element"),h={structureId:this.structure.id,elementId:l.data("id"),siteId:l.data("site-id"),prevId:this.$draggee.prev().children(".row").children(".element").data("id"),parentId:this.$draggee.parent("ul").parent("li").children(".row").children(".element").data("id")};Craft.postActionRequest("structures/move-element",h,(function(t,e){"success"===e&&Craft.cp.displayNotice(Craft.t("app","New order saved."))}))}}this.$draggee.velocity("stop").removeClass("hidden").velocity({height:this.draggeeHeight},"fast",(function(){t.$draggee.css("height","auto")})),this.returnHelpersToDraggees(),this.base()},setLevel:function(t,e){t.data("level",e);var i=this.structure.getIndent(e),s={};s["margin-"+Craft.left]="-"+i+"px",s["padding-"+Craft.left]=i+"px",this.$draggee.children(".row").css(s);for(var a=t.children("ul").children(),n=0;n<a.length;n++)this.setLevel($(a[n]),e+1)}})},3331:function(){Craft.StructureTableSorter=Garnish.DragSort.extend({tableView:null,structureId:null,maxLevels:null,_basePadding:null,_helperMargin:null,_$firstRowCells:null,_$titleHelperCell:null,_titleHelperCellOuterWidth:null,_ancestors:null,_updateAncestorsFrame:null,_draggeeLevel:null,_draggeeLevelDelta:null,draggingLastElements:null,_loadingDraggeeLevelDelta:!1,_targetLevel:null,_targetLevelBounds:null,_positionChanged:null,init:function(t,e,i){this.tableView=t,this.structureId=this.tableView.$table.data("structure-id"),this.maxLevels=parseInt(this.tableView.$table.attr("data-max-levels")),this._basePadding=14+(this.tableView.elementIndex.actions?14:24),this._helperMargin=this.tableView.elementIndex.actions?54:0,i=$.extend({},Craft.StructureTableSorter.defaults,i,{handle:".move",collapseDraggees:!0,singleHelper:!0,helperSpacingY:2,magnetStrength:4,helper:this.getHelper.bind(this),helperLagBase:1.5,axis:Garnish.Y_AXIS}),this.base(e,i)},findDraggee:function(){var t=this;this._draggeeLevel=this._targetLevel=this.$targetItem.data("level"),this._draggeeLevelDelta=0;for(var e=$(this.$targetItem),i=this.$targetItem.next();i.length;){var s=i.data("level");if(s<=this._draggeeLevel)break;var a=s-this._draggeeLevel;a>this._draggeeLevelDelta&&(this._draggeeLevelDelta=a),e=e.add(i),i=i.next()}if(this.draggingLastElements=!i.length,this.maxLevels&&this.draggingLastElements&&this.tableView.getMorePending()){this._loadingDraggeeLevelDelta=!0;var n=this._getAjaxBaseData(this.$targetItem);Craft.postActionRequest("structures/get-element-level-delta",n,(function(e,i){"success"===i&&(t._loadingDraggeeLevelDelta=!1,t.dragging&&(t._draggeeLevelDelta=e.delta,t.drag(!1)))}))}return e},getHelper:function(t){var e=$('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),i=$('<div class="tableview"/>').appendTo(e),s=$('<table class="data"/>').appendTo(i),a=$("<tbody/>").appendTo(s);t.appendTo(a),this._$firstRowCells=this.tableView.$elementContainer.children("tr:first").children();for(var n=t.children(),r=0;r<n.length;r++){var o=$(n[r]);if(o.hasClass("checkbox-cell"))o.remove();else{var l=$(this._$firstRowCells[r]),h=l[0].getBoundingClientRect().width;l.css("width",h+"px"),o.css("width",h+"px"),Garnish.hasAttr(l,"data-titlecell")&&(this._$titleHelperCell=o,parseInt(l.css("padding-"+Craft.left)),this._titleHelperCellOuterWidth=h,o.css("padding-"+Craft.left,this._basePadding))}}return e},canInsertBefore:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t.prev(),t)},canInsertAfter:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t,t.next())},onDragStart:function(){this._ancestors=this._getAncestors(this.$targetItem,this.$targetItem.data("level")),this._setTargetLevelBounds(),this.tableView.maybeLoadMore(),this.base()},onDrag:function(){this.base(),this._updateIndent()},onInsertionPointChange:function(){this._setTargetLevelBounds(),this._updateAncestorsBeforeRepaint(),this.base()},onDragStop:function(){var t=this;if(this._positionChanged=!1,this.base(),this._targetLevel!=this._draggeeLevel){for(var e=this._targetLevel-this._draggeeLevel,i=0;i<this.$draggee.length;i++){var s=$(this.$draggee[i]),a=s.data("level")+e,n=this._basePadding+this._getLevelIndent(a);s.data("level",a),s.find(".element").data("level",a),s.children("[data-titlecell]:first").css("padding-"+Craft.left,n)}this._positionChanged=!0}if(this._positionChanged){for(var r=this._getAjaxBaseData(this.$draggee),o=this.$draggee.first().prev();o.length;){var l=o.data("level");if(l==this._targetLevel){r.prevId=o.data("id");break}if(l<this._targetLevel){r.parentId=o.data("id");var h=o.find("> th > .toggle");if(!h.hasClass("expanded")){h.addClass("expanded");var d=this.tableView._createSpinnerRowAfter(o);this.tableView.elementSelect&&this.tableView.elementSelect.removeItems(this.$targetItem),this.removeItems(this.$targetItem),this.$targetItem.remove(),this.tableView._totalVisible--}break}o=o.prev()}Craft.postActionRequest("structures/move-element",r,(function(e,i){if("success"===i){if(!e.success)return Craft.cp.displayError(Craft.t("app","A server error occurred.")),void t.tableView.elementIndex.updateElements();Craft.cp.displayNotice(Craft.t("app","New position saved.")),t.onPositionChange(),d&&d.parent().length&&(d.remove(),t.tableView._expandElement(h,!0)),Craft.cp.runQueue()}}))}},onSortChange:function(){this.tableView.elementSelect&&this.tableView.elementSelect.resetItemOrder(),this._positionChanged=!0,this.base()},onPositionChange:function(){var t=this;Garnish.requestAnimationFrame((function(){t.trigger("positionChange"),t.settings.onPositionChange()}))},onReturnHelpersToDraggees:function(){if(this._$firstRowCells.css("width",""),this.draggingLastElements&&this.tableView.getMorePending()){this.tableView._totalVisible+=this.newDraggeeIndexes[0]-this.oldDraggeeIndexes[0];var t=this.$draggee.last().nextAll();t.length&&(this.removeItems(t),t.remove(),this.tableView.maybeLoadMore())}this.base()},_getLevelBounds:function(t,e){if(e&&e.length?this._getLevelBounds._minLevel=e.data("level"):this._getLevelBounds._minLevel=1,t&&t.length?this._getLevelBounds._maxLevel=t.data("level")+1:this._getLevelBounds._maxLevel=1,this.maxLevels){if(1!=this._getLevelBounds._minLevel&&this._getLevelBounds._minLevel+this._draggeeLevelDelta>this.maxLevels)return!1;this._getLevelBounds._maxLevel+this._draggeeLevelDelta>this.maxLevels&&(this._getLevelBounds._maxLevel=this.maxLevels-this._draggeeLevelDelta,this._getLevelBounds._maxLevel<this._getLevelBounds._minLevel&&(this._getLevelBounds._maxLevel=this._getLevelBounds._minLevel))}return{min:this._getLevelBounds._minLevel,max:this._getLevelBounds._maxLevel}},_setTargetLevelBounds:function(){this._targetLevelBounds=this._getLevelBounds(this.$draggee.first().prev(),this.$draggee.last().next())},_updateIndent:function(t){this._updateIndent._mouseDist=this.realMouseX-this.mousedownX,"rtl"===Craft.orientation&&(this._updateIndent._mouseDist*=-1),this._updateIndent._indentationDist=Math.round(this._updateIndent._mouseDist/Craft.StructureTableSorter.LEVEL_INDENT),this._updateIndent._targetLevel=this._draggeeLevel+this._updateIndent._indentationDist,this._updateIndent._targetLevel<this._targetLevelBounds.min?(this._updateIndent._indentationDist+=this._targetLevelBounds.min-this._updateIndent._targetLevel,this._updateIndent._targetLevel=this._targetLevelBounds.min):this._updateIndent._targetLevel>this._targetLevelBounds.max&&(this._updateIndent._indentationDist-=this._updateIndent._targetLevel-this._targetLevelBounds.max,this._updateIndent._targetLevel=this._targetLevelBounds.max),this._targetLevel!==(this._targetLevel=this._updateIndent._targetLevel)&&this._updateAncestorsBeforeRepaint(),this._updateIndent._targetLevelMouseDiff=this._updateIndent._mouseDist-this._updateIndent._indentationDist*Craft.StructureTableSorter.LEVEL_INDENT,this._updateIndent._magnetImpact=Math.round(this._updateIndent._targetLevelMouseDiff/15),Math.abs(this._updateIndent._magnetImpact)>Craft.StructureTableSorter.MAX_GIVE&&(this._updateIndent._magnetImpact=(this._updateIndent._magnetImpact>0?1:-1)*Craft.StructureTableSorter.MAX_GIVE),this._updateIndent._closestLevelMagnetIndent=this._getLevelIndent(this._targetLevel)+this._updateIndent._magnetImpact,this.helpers[0].css("margin-"+Craft.left,this._updateIndent._closestLevelMagnetIndent+this._helperMargin),this._$titleHelperCell.css("width",this._titleHelperCellOuterWidth-this._updateIndent._closestLevelMagnetIndent)},_getLevelIndent:function(t){return(t-1)*Craft.StructureTableSorter.LEVEL_INDENT},_getAjaxBaseData:function(t){return{structureId:this.structureId,elementId:t.data("id"),siteId:t.find(".element:first").data("site-id")}},_getAncestors:function(t,e){if(this._getAncestors._ancestors=[],0!=e)for(this._getAncestors._level=e,this._getAncestors._$prevRow=t.prev();this._getAncestors._$prevRow.length&&!(this._getAncestors._$prevRow.data("level")<this._getAncestors._level&&(this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow),this._getAncestors._level=this._getAncestors._$prevRow.data("level"),0==this._getAncestors._level));)this._getAncestors._$prevRow=this._getAncestors._$prevRow.prev();return this._getAncestors._ancestors},_updateAncestorsBeforeRepaint:function(){this._updateAncestorsFrame&&Garnish.cancelAnimationFrame(this._updateAncestorsFrame),this._updateAncestorsFrame=Garnish.requestAnimationFrame(this._updateAncestors.bind(this))},_updateAncestors:function(){for(this._updateAncestorsFrame=null,this._updateAncestors._i=0;this._updateAncestors._i<this._ancestors.length;this._updateAncestors._i++)this._updateAncestors._$ancestor=this._ancestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")-1),0==this._updateAncestors._$ancestor.data("descendants")&&this._updateAncestors._$ancestor.find("> th > .toggle:first").remove();for(this._updateAncestors._newAncestors=this._getAncestors(this.$targetItem,this._targetLevel),this._updateAncestors._i=0;this._updateAncestors._i<this._updateAncestors._newAncestors.length;this._updateAncestors._i++)this._updateAncestors._$ancestor=this._updateAncestors._newAncestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")+1),1==this._updateAncestors._$ancestor.data("descendants")&&$('<span class="toggle expanded" title="'+Craft.t("app","Show/hide children")+'"></span>').insertAfter(this._updateAncestors._$ancestor.find("> th .move:first"));this._ancestors=this._updateAncestors._newAncestors,delete this._updateAncestors._i,delete this._updateAncestors._$ancestor,delete this._updateAncestors._newAncestors}},{HELPER_MARGIN:0,LEVEL_INDENT:44,MAX_GIVE:22,defaults:{onPositionChange:$.noop}})},53:function(){Craft.TableElementIndexView=Craft.BaseElementIndexView.extend({$table:null,$selectedSortHeader:null,structureTableSort:null,_totalVisiblePostStructureTableDraggee:null,_morePendingPostStructureTableDraggee:!1,getElementContainer:function(){return this.$table=this.$container.find("table:first"),this.$table.children("tbody:first")},afterInit:function(){this.initTableHeaders(),"index"===this.elementIndex.settings.context&&"structure"===this.elementIndex.getSelectedSortAttribute()&&Garnish.hasAttr(this.$table,"data-structure-id")?this.structureTableSort=new Craft.StructureTableSorter(this,this.getAllElements()):this.structureTableSort=null,"structure"===this.elementIndex.getSelectedSortAttribute()&&this.addListener(this.$elementContainer,"click",(function(t){var e=$(t.target);e.hasClass("toggle")&&!1===this._collapseElement(e)&&this._expandElement(e)}))},initTableHeaders:function(){for(var t=this.elementIndex.getSelectedSortAttribute(),e=this.$table.children("thead").children().children("[data-attribute]"),i=0;i<e.length;i++){var s=e.eq(i),a=s.attr("data-attribute");if(a===t){this.$selectedSortHeader=s;var n=this.elementIndex.getSelectedSortDirection();s.addClass("ordered "+n).on("click",this._handleSelectedSortHeaderClick.bind(this))}else this.elementIndex.getSortAttributeOption(a).length&&s.addClass("orderable").on("click",this._handleUnselectedSortHeaderClick.bind(this))}},isVerticalList:function(){return!0},getTotalVisible:function(){return this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee:this._totalVisible},setTotalVisible:function(t){this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee=t:this._totalVisible=t},getMorePending:function(){return this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee:this._morePending},setMorePending:function(t){this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee=t:this._morePending=this._morePendingPostStructureTableDraggee=t},getLoadMoreParams:function(){var t=this.base();return this._isStructureTableDraggingLastElements()&&(t.criteria.positionedAfter=this.structureTableSort.$targetItem.data("id")),t},appendElements:function(t){this.base(t),this.structureTableSort&&this.structureTableSort.addItems(t),Craft.cp.updateResponsiveTables()},createElementEditor:function(t){var e=this;Craft.createElementEditor(t.data("type"),t,{params:{includeTableAttributesForSource:this.elementIndex.sourceKey},onSaveElement:function(i){i.tableAttributes&&e._updateTableAttributes(t,i.tableAttributes)},elementIndex:this.elementIndex})},_collapseElement:function(t,e){if(!e&&!t.hasClass("expanded"))return!1;t.removeClass("expanded");for(var i=t.parent().parent(),s=i.data("id"),a=i.data("level"),n=i.next();n.length;){if(!Garnish.hasAttr(n,"data-spinnerrow")){if(n.data("level")<=a)break;this.elementSelect&&this.elementSelect.removeItems(n),this.structureTableSort&&this.structureTableSort.removeItems(n),this._totalVisible--}var r=n.next();n.remove(),n=r}this.elementIndex.instanceState.collapsedElementIds||(this.elementIndex.instanceState.collapsedElementIds=[]),this.elementIndex.instanceState.collapsedElementIds.push(s),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds),this.maybeLoadMore()},_expandElement:function(t,e){var i=this;if(!e&&t.hasClass("expanded"))return!1;if(t.addClass("expanded"),this.elementIndex.instanceState.collapsedElementIds){var s=t.parent().parent(),a=s.data("id"),n=$.inArray(a,this.elementIndex.instanceState.collapsedElementIds);if(-1!==n){this.elementIndex.instanceState.collapsedElementIds.splice(n,1),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds);var r=this._createSpinnerRowAfter(s),o=$.extend(!0,{},this.settings.params);o.criteria.descendantOf=a,Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:o}).then((function(t){if(r.parent().length){var e=$(t.data.html),s=i._totalVisible+e.length,a=i.settings.batchSize&&e.length===i.settings.batchSize;if(a){var n=r.nextAll();i.elementSelect&&i.elementSelect.removeItems(n),i.structureTableSort&&i.structureTableSort.removeItems(n),n.remove(),s-=n.length}else a=i._morePending;r.replaceWith(e),i.thumbLoader.load(e),(i.elementIndex.actions||i.settings.selectable)&&(i.elementSelect.addItems(e.filter(":not(.disabled)")),i.elementIndex.updateActionTriggers()),i.structureTableSort&&i.structureTableSort.addItems(e),Craft.appendHeadHtml(t.data.headHtml),Craft.appendFootHtml(t.data.footHtml),Craft.cp.updateResponsiveTables(),i.setTotalVisible(s),i.setMorePending(a),i.maybeLoadMore()}})).catch((function(t){Craft.cp.displayError(),r.parent().length}))}}},_createSpinnerRowAfter:function(t){return $('<tr data-spinnerrow><td class="centeralign" colspan="'+t.children().length+'"><div class="spinner"/></td></tr>').insertAfter(t)},_isStructureTableDraggingLastElements:function(){return this.structureTableSort&&this.structureTableSort.dragging&&this.structureTableSort.draggingLastElements},_handleSelectedSortHeaderClick:function(t){var e=$(t.currentTarget);if(!e.hasClass("loading")){var i="asc"===this.elementIndex.getSelectedSortDirection()?"desc":"asc";this.elementIndex.setSortDirection(i),this._handleSortHeaderClick(t,e)}},_handleUnselectedSortHeaderClick:function(t){var e=$(t.currentTarget);if(!e.hasClass("loading")){var i=e.attr("data-attribute");this.elementIndex.setSortAttribute(i),this._handleSortHeaderClick(t,e)}},_handleSortHeaderClick:function(t,e){this.$selectedSortHeader&&this.$selectedSortHeader.removeClass("ordered asc desc"),e.removeClass("orderable").addClass("ordered loading"),this.elementIndex.storeSortAttributeAndDirection(),this.elementIndex.updateElements(),this.elementIndex.setIndexAvailable()},_updateTableAttributes:function(t,e){var i=t.closest("tr");for(var s in e)e.hasOwnProperty(s)&&i.children('[data-attr="'+s+'"]:first').html(e[s])}})},7745:function(){Craft.Tabs=Garnish.Base.extend({$container:null,$ul:null,$menuBtn:null,$tabs:null,$selectedTab:null,$focusableTab:null,menu:null,init:function(t){var e=this;this.$container=$(t),this.$ul=this.$container.find("> ul:first"),this.$tabs=this.$ul.find("> li > a"),this.$selectedTab=this.$tabs.filter(".sel:first"),this.$focusableTab=this.$tabs.filter("[tabindex=0]:first"),this.$menuBtn=this.$container.find("> .menubtn:first").menubtn(),this.menu=this.$menuBtn.data("menubtn").menu,this.$container.data("tabs")&&(console.warn("Double-instantiating a tab manager on an element"),this.$container.data("tabs").destroy()),this.$container.data("tabs",this);for(var i=0;i<this.$tabs.length;i++){var s=this.$tabs.eq(i),a=s.attr("href");a&&"#"===a.charAt(0)&&(this.addListener(s,"keydown",(function(t){[Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)&&(t.preventDefault(),e.selectTab(t.currentTarget))})),this.addListener(s,"click",(function(t){t.preventDefault(),$(t.currentTarget),e.selectTab(t.currentTarget),e.makeTabFocusable(t.currentTarget)})),a.substr(1)===window.LOCATION_HASH&&($initialTab=s)),this.addListener(s,"keydown",(function(t){var i;[Garnish.LEFT_KEY,Garnish.RIGHT_KEY].includes(t.keyCode)&&$.contains(e.$ul[0],t.currentTarget)&&(i=t.keyCode===("ltr"===Craft.orientation?Garnish.LEFT_KEY:Garnish.RIGHT_KEY)?$(t.currentTarget).parent().prev("li").children("a"):$(t.currentTarget).parent().next("li").children("a")).length&&(t.preventDefault(),e.makeTabFocusable(i),i.focus(),e.scrollToTab(i))}))}this.updateMenuBtn(),Garnish.$win.on("resize",(function(){e.updateMenuBtn()})),this.menu.$options.on("click",(function(t){var e=$(t.currentTarget).attr("href");e&&"#"===e.charAt(0)&&t.preventDefault()})),this.menu.on("optionselect",(function(t){e.selectTab($(t.selectedOption).data("id"))}))},selectTab:function(t){var e=this._getTab(t);e[0]!==this.$selectedTab[0]&&(this.deselectTab(),this.$selectedTab=e.addClass("sel"),this.makeTabFocusable(e),this.scrollToTab(e),this.menu.$options.removeClass("sel"),this.menu.$options.filter('[data-id="'.concat(e.data("id"),'"]')).addClass("sel"),this.trigger("selectTab",{$tab:e}),$("#content").trigger("scroll"))},deselectTab:function(){var t=this.$selectedTab.removeClass("sel");this.$selectedTab=null,this.trigger("deselectTab",{$tab:t})},makeTabFocusable:function(t){var e=this._getTab(t);e[0]!==this.$focusableTab[0]&&(this.$focusableTab.attr("tabindex","-1"),this.$focusableTab=e.attr("tabindex","0"))},scrollToTab:function(t){var e=this._getTab(t),i=this.$ul.scrollLeft(),s=e.offset().left-this.$ul.offset().left,a=!1;if(s<0)a=i+s-24;else{var n=e.outerWidth(),r=this.$ul.prop("clientWidth");s+n>r&&(a=i+(s-(r-n))+24)}!1!==a&&this.$ul.scrollLeft(a)},updateMenuBtn:function(){Math.floor(this.$ul.prop("scrollWidth")-48)>this.$container.prop("clientWidth")?(this.$ul.addClass("scrollable"),this.$menuBtn.removeClass("hidden")):(this.$ul.removeClass("scrollable"),this.$menuBtn.addClass("hidden"))},_getTab:function(t){if(t instanceof jQuery)return t;if(t instanceof HTMLElement)return $(t);if("string"!=typeof t)throw"Invalid tab ID";var e=this.$tabs.filter('[data-id="'.concat(t,'"]'));if(!e.length)throw"Invalid tab ID: ".concat(t);return e},destroy:function(){this.$container.removeData("tabs"),this.base()}})},5074:function(){Craft.TagSelectInput=Craft.BaseElementSelectInput.extend({searchTimeout:null,searchMenu:null,$container:null,$elementsContainer:null,$elements:null,$addTagInput:null,$spinner:null,_ignoreBlur:!1,init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","tagGroupId","sourceElementId"],a=0;a<s.length&&void 0!==arguments[a];a++)i[s[a]]=arguments[a];t=i}this.base($.extend({},Craft.TagSelectInput.defaults,t)),this.$addTagInput=this.$container.children(".add").children(".text"),this.$spinner=this.$addTagInput.next(),this.addListener(this.$addTagInput,"input",(function(){e.searchTimeout&&clearTimeout(e.searchTimeout),e.searchTimeout=setTimeout(e.searchForTags.bind(e),500)})),this.addListener(this.$addTagInput,"keydown",(function(t){switch(t.keyCode===Garnish.RETURN_KEY&&t.preventDefault(),t.keyCode){case Garnish.RETURN_KEY:return t.preventDefault(),void(this.searchMenu&&this.selectTag(this.searchMenu.$options.filter(".hover")));case Garnish.DOWN_KEY:if(t.preventDefault(),this.searchMenu){var e=this.searchMenu.$options.filter(".hover");if(e.length){var i=e.parent().nextAll().find("a:not(.disabled)").first();i.length&&this.focusOption(i)}else this.focusOption(this.searchMenu.$options.eq(0))}return;case Garnish.UP_KEY:if(t.preventDefault(),this.searchMenu){var s=this.searchMenu.$options.filter(".hover");if(s.length){var a=s.parent().prevAll().find("a:not(.disabled)").last();a.length&&this.focusOption(a)}else this.focusOption(this.searchMenu.$options.eq(this.searchMenu.$options.length-1))}return}})),this.addListener(this.$addTagInput,"focus",(function(){this.searchMenu&&this.searchMenu.show()})),this.addListener(this.$addTagInput,"blur",(function(){var t=this;this._ignoreBlur?this._ignoreBlur=!1:setTimeout((function(){t.searchMenu&&t.searchMenu.hide()}),1)}))},focusOption:function(t){this.searchMenu.$options.removeClass("hover"),t.addClass("hover"),this.searchMenu.$menuList.attr("aria-activedescendant",t.attr("id"))},getAddElementsBtn:$.noop,getElementSortAxis:function(){return null},searchForTags:function(){var t=this;if(this.searchMenu&&this.killSearchMenu(),this.$addTagInput.val()){this.$spinner.removeClass("hidden");for(var e=[],i=0;i<this.$elements.length;i++){var s=$(this.$elements[i]).data("id");s&&e.push(s)}this.settings.sourceElementId&&e.push(this.settings.sourceElementId);var a={search:this.$addTagInput.val(),tagGroupId:this.settings.tagGroupId,excludeIds:e};Craft.postActionRequest("tags/search-for-tags",a,(function(e,i){if(t.searchMenu&&t.killSearchMenu(),t.$spinner.addClass("hidden"),"success"===i){for(var s,n=$('<div class="menu tagmenu"/>').appendTo(Garnish.$bod),r=$("<ul/>").appendTo(n),o=0;o<e.tags.length;o++)s=$("<li/>").appendTo(r),$('<a data-icon="tag"/>').appendTo(s).text(e.tags[o].title).data("id",e.tags[o].id).addClass(e.tags[o].exclude?"disabled":"");e.exactMatch||(s=$("<li/>").appendTo(r),$('<a data-icon="plus"/>').appendTo(s).text(a.search)),r.find("a:not(.disabled):first").addClass("hover"),t.searchMenu=new Garnish.Menu(n,{attachToElement:t.$addTagInput,onOptionSelect:t.selectTag.bind(t)}),t.addListener(n,"mousedown",(function(){t._ignoreBlur=!0})),t.searchMenu.show()}}))}else this.$spinner.addClass("hidden")},selectTag:function(t){var e=this,i=$(t);if(!i.hasClass("disabled")){var s=i.data("id"),a=i.text(),n=$("<div/>",{class:"element small removable","data-id":s,"data-site-id":this.settings.targetSiteId,"data-label":a,"data-editable":"1"}).appendTo(this.$elementsContainer),r=$("<input/>",{type:"hidden",name:this.settings.name+"[]",value:s}).appendTo(n);$("<a/>",{class:"delete icon",title:Craft.t("app","Remove")}).appendTo(n);var o=$("<div/>",{class:"label"}).appendTo(n);$("<span/>",{class:"title",text:a}).appendTo(o);var l=-(n.outerWidth()+10);this.$addTagInput.css("margin-"+Craft.left,l+"px");var h={};if(h["margin-"+Craft.left]=0,this.$addTagInput.velocity(h,"fast"),this.$elements=this.$elements.add(n),this.addElements(n),this.killSearchMenu(),this.$addTagInput.val(""),this.$addTagInput.trigger("focus"),!s){n.addClass("loading disabled");var d={groupId:this.settings.tagGroupId,title:a};Craft.postActionRequest("tags/create-tag",d,(function(t,i){"success"===i&&t.success?(n.attr("data-id",t.id),r.val(t.id),n.removeClass("loading disabled")):(e.removeElement(n),"success"===i&&Craft.cp.displayError(Craft.t("app","A server error occurred.")))}))}}},killSearchMenu:function(){this.searchMenu.hide(),this.searchMenu.destroy(),this.searchMenu=null}},{defaults:{tagGroupId:null}})},3958:function(){Craft.ThumbsElementIndexView=Craft.BaseElementIndexView.extend({getElementContainer:function(){return this.$container.children("ul")}})},1592:function(){Craft.ui={createTextInput:function(t){t=$.extend({autocomplete:!1},t);var e=$("<input/>",{attr:{class:"text",type:t.type||"text",inputmode:t.inputmode,id:t.id,size:t.size,name:t.name,value:t.value,maxlength:t.maxlength,autofocus:this.getAutofocusValue(t.autofocus),autocomplete:"boolean"==typeof t.autocomplete?t.autocomplete?"on":"off":t.autocomplete,disabled:this.getDisabledValue(t.disabled),readonly:t.readonly,title:t.title,placeholder:t.placeholder,step:t.step,min:t.min,max:t.max}});return t.class&&e.addClass(t.class),t.placeholder&&e.addClass("nicetext"),"password"===t.type&&e.addClass("password"),t.disabled&&e.addClass("disabled"),t.size||e.addClass("fullwidth"),t.showCharsLeft&&t.maxlength&&e.attr("data-show-chars-left").css("padding-"+("ltr"===Craft.orientation?"right":"left"),7.2*t.maxlength.toString().length+14+"px"),(t.placeholder||t.showCharsLeft)&&new Garnish.NiceText(e),"password"===t.type?$('<div class="passwordwrapper"/>').append(e):e},createTextField:function(t){return t.id||(t.id="text"+Math.floor(1e9*Math.random())),this.createField(this.createTextInput(t),t)},createCopyTextInput:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.buttonId||"".concat(e,"-btn"),s=$("<div/>",{class:"copytext"}),a=this.createTextInput($.extend({},t,{readonly:!0})).appendTo(s);return $("<button/>",{type:"button",id:i,class:"btn","data-icon":"clipboard",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard")}).appendTo(s).on("click",(function(){a[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),a[0].setSelectionRange(0,0)})),s},createCopyTextBtn:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.value,s=$("<div/>",{id:e,class:"copytextbtn",role:"button",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard"),tabindex:"0"});t.class&&s.addClass(t.class);var a=$("<input/>",{value:i,readonly:!0,size:i.length,tabindex:"-1"}).appendTo(s),n=($("<span/>",{"data-icon":"clipboard","aria-hidden":"true"}).appendTo(s),function(){a[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),a[0].setSelectionRange(0,0),s.focus()});return s.on("click",(function(){n()})),s.on("keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(n(),t.preventDefault())})),s},createCopyTextField:function(t){return t.id||(t.id="copytext"+Math.floor(1e9*Math.random())),this.createField(this.createCopyTextInput(t),t)},createCopyTextPrompt:function(t){var e=$("<div/>",{class:"modal fitted"}),i=$("<div/>",{class:"body"}).appendTo(e);this.createCopyTextField($.extend({size:Math.max(Math.min(t.value.length,50),25)},t)).appendTo(i);var s=new Garnish.Modal(e,{closeOtherModals:!1});return e.on("copy",(function(){s.hide()})),e},createTextarea:function(t){var e=$("<textarea/>",{class:"text",rows:t.rows||2,cols:t.cols||50,id:t.id,name:t.name,maxlength:t.maxlength,autofocus:t.autofocus&&!Garnish.isMobileBrowser(!0),disabled:!!t.disabled,placeholder:t.placeholder,html:t.value});return t.showCharsLeft&&e.attr("data-show-chars-left",""),t.class&&e.addClass(t.class),t.size||e.addClass("fullwidth"),e},createTextareaField:function(t){return t.id||(t.id="textarea"+Math.floor(1e9*Math.random())),this.createField(this.createTextarea(t),t)},createSelect:function(t){var e=$("<div/>",{class:"select"});t.class&&e.addClass(t.class);var i=$("<select/>",{id:t.id,name:t.name,autofocus:t.autofocus&&Garnish.isMobileBrowser(!0),disabled:t.disabled,"data-target-prefix":t.targetPrefix}).appendTo(e);if($.isPlainObject(t.options)){var s=[];for(var a in t.options)if(t.options.hasOwnProperty(a)){var n=t.options[a];$.isPlainObject(n)?void 0!==n.optgroup?s.push(n):s.push({label:n.label,value:void 0!==n.value?n.value:a,disabled:void 0!==n.disabled&&n.disabled}):s.push({label:n,value:a})}t.options=s}for(var r=null,o=0;o<t.options.length;o++){var l=t.options[o];void 0!==l.optgroup?r=$("<optgroup/>",{label:l.label}).appendTo(i):$("<option/>",{value:l.value,selected:l.value==t.value,disabled:void 0!==l.disabled&&l.disabled,html:l.label}).appendTo(r||i)}return t.toggle&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i)),e},createSelectField:function(t){return t.id||(t.id="select"+Math.floor(1e9*Math.random())),this.createField(this.createSelect(t),t)},createCheckbox:function(t){var e=t.id||"checkbox"+Math.floor(1e9*Math.random()),i=$("<input/>",{type:"checkbox",value:void 0!==t.value?t.value:"1",id:e,class:"checkbox",name:t.name,checked:t.checked?"checked":null,autofocus:this.getAutofocusValue(t.autofocus),disabled:this.getDisabledValue(t.disabled),"data-target":t.toggle,"data-reverse-target":t.reverseToggle});t.class&&i.addClass(t.class),(t.toggle||t.reverseToggle)&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i));var s=$("<label/>",{for:e,html:t.label});return t.name&&(t.name.length<3||"[]"!==t.name.substr(-2))?$([$("<input/>",{type:"hidden",name:t.name,value:""})[0],i[0],s[0]]):$([i[0],s[0]])},createCheckboxField:function(t){t.id||(t.id="checkbox"+Math.floor(1e9*Math.random()));var e=$('<div class="field checkboxfield"/>',{id:"".concat(t.id,"-field")});return t.first&&e.addClass("first"),t.instructions&&e.addClass("has-instructions"),this.createCheckbox(t).appendTo(e),t.instructions&&$('<div class="instructions"/>').text(t.instructions).appendTo(e),e},createCheckboxSelect:function(t){var e,i,s=$('<fieldset class="checkbox-select"/>');t.class&&s.addClass(t.class),t.showAllOption?(e=t.allValue||"*",i=t.values==e,$("<div/>").appendTo(s).append(this.createCheckbox({id:t.id,class:"all",label:"<b>"+(t.allLabel||Craft.t("app","All"))+"</b>",name:t.name,value:e,checked:i,autofocus:t.autofocus}))):i=!1;for(var a=0;a<t.options.length;a++){var n=t.options[a];n.value!=e&&$("<div/>").appendTo(s).append(this.createCheckbox({label:n.label,name:t.name?t.name+"[]":null,value:n.value,checked:i||(t.values||[]).includes(n.value),disabled:i}))}return new Garnish.CheckboxSelect(s),s},createCheckboxSelectField:function(t){return t.fieldset=!0,t.id||(t.id="checkboxselect"+Math.floor(1e9*Math.random())),this.createField(this.createCheckboxSelect(t),t)},createLightswitch:function(t){var e=t.value||"1",i=t.indeterminateValue||"-",s=$("<button/>",{type:"button",class:"lightswitch","data-value":e,"data-indeterminate-value":i,id:t.id,role:"checkbox","aria-checked":t.on?"true":t.indeterminate?"mixed":"false","aria-labelledby":t.labelId,"data-target":t.toggle,"data-reverse-target":t.reverseToggle});return t.on?s.addClass("on"):t.indeterminate&&s.addClass("indeterminate"),t.small&&s.addClass("small"),t.disabled&&s.addClass("disabled"),$('<div class="lightswitch-container"><div class="handle"></div></div>').appendTo(s),t.name&&$("<input/>",{type:"hidden",name:t.name,value:t.on?e:t.indeterminate?i:"",disabled:t.disabled}).appendTo(s),(t.toggle||t.reverseToggle)&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s)),new Craft.LightSwitch(s,{onChange:t.onChange||$.noop}),s},createLightswitchField:function(t){return t.id||(t.id="lightswitch"+Math.floor(1e9*Math.random())),this.createField(this.createLightswitch(t),t).addClass("lightswitch-field")},createColorInput:function(t){var e=t.id||"color"+Math.floor(1e9*Math.random()),i=t.containerId||e+"-container",s=t.name||null,a=t.value||null,n=t.small||!1,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{id:i,class:"flex color-container"}),h=$("<div/>",{class:"color static"+(n?" small":"")}).appendTo(l),d=($("<div/>",{class:"color-preview",style:t.value?{backgroundColor:t.value}:null}).appendTo(h),$("<div/>",{class:"color-input-container"}).append($("<div/>",{class:"color-hex-indicator light code","aria-hidden":"true",text:"#"})).appendTo(l));return this.createTextInput({id:e,name:s,value:Craft.ltrim(a,"#"),size:10,class:"color-input",autofocus:r,disabled:o,"aria-label":Craft.t("app","Color hex value")}).appendTo(d),new Craft.ColorInput(l),l},createColorField:function(t){return t.fieldset=!0,o,t.id||(t.id="color"+Math.floor(1e9*Math.random())),this.createField(this.createColorInput(t),t)},createDateInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"date"+Math.floor(1e9*Math.random()))+"-date",s=t.name||null,a=s?s+"[date]":null,n=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"datewrapper"}),h=this.createTextInput({id:i,type:e?"date":"text",class:!(!e||n)&&"empty-value",name:a,value:n?e?n.toISOString().split("T")[0]:Craft.formatDate(n):"",placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="date"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?h.datetimeinput():h.datepicker($.extend({defaultDate:n||new Date},Craft.datepickerOptions)),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createDateField:function(t){return t.id||(t.id="date"+Math.floor(1e9*Math.random())),this.createField(this.createDateInput(t),t)},createDateRangePicker:function(t){var e=new Date,i=new Date(e.getFullYear(),e.getMonth(),e.getDate());t=$.extend({class:"",options:["today","thisWeek","thisMonth","thisYear","past7Days","past30Days","past90Days","pastYear"],onChange:$.noop,selected:null,startDate:null,endDate:null},t);var s,a,n=$("<div/>",{class:"menu"}),r=$("<ul/>",{class:"padded"}).appendTo(n),o=$("<a/>").addClass("sel").text(Craft.t("app","All")).data("handle","all");$("<li/>").append(o).appendTo(r);for(var l=0;l<t.options.length;l++){var h=t.options[l];switch(h){case"today":s={label:Craft.t("app","Today"),startDate:i,endDate:i};break;case"thisWeek":var d=e.getDay()-Craft.datepickerOptions.firstDay;d<0&&(d+=7),s={label:Craft.t("app","This week"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-d),endDate:i};break;case"thisMonth":s={label:Craft.t("app","This month"),startDate:new Date(e.getFullYear(),e.getMonth()),endDate:i};break;case"thisYear":s={label:Craft.t("app","This year"),startDate:new Date(e.getFullYear(),0),endDate:i};break;case"past7Days":s={label:Craft.t("app","Past {num} days",{num:7}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-7),endDate:i};break;case"past30Days":s={label:Craft.t("app","Past {num} days",{num:30}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-30),endDate:i};break;case"past90Days":s={label:Craft.t("app","Past {num} days",{num:90}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-90),endDate:i};break;case"pastYear":s={label:Craft.t("app","Past year"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-365),endDate:i}}var c=$("<li/>"),u=$("<a/>",{text:s.label}).data("handle",h).data("startDate",s.startDate).data("endDate",s.endDate).data("startTime",s.startDate?s.startDate.getTime():null).data("endTime",s.endDate?s.endDate.getTime():null);t.selected&&h==t.selected&&(a=u[0]),c.append(u),c.appendTo(r)}$("<hr/>").appendTo(n);var p=$("<div/>",{class:"flex flex-nowrap padded"}).appendTo(n),g=this.createDateField({label:Craft.t("app","From")}).appendTo(p).find("input"),f=this.createDateField({label:Craft.t("app","To")}).appendTo(p).find("input"),m=g.add(f);m.on("keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&$(this).data("datepicker")&&$(this).data("datepicker").dpDiv.is(":visible")&&t.stopPropagation()})),g.data("datepicker")&&g.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()})),f.data("datepicker")&&f.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()}));var v=new Garnish.Menu(n,{onOptionSelect:function(e){var i=$(e);b.text(i.text()),v.setPositionRelativeToAnchor(),n.find(".sel").removeClass("sel"),i.addClass("sel"),g.datepicker("setDate",i.data("startDate")),f.datepicker("setDate",i.data("endDate")),t.onChange(i.data("startDate")||null,i.data("endDate")||null,i.data("handle"))}});m.on("change",(function(){for(var e,i=g.datepicker("getDate"),s=f.datepicker("getDate"),a=i?i.getTime():null,o=s?s.getTime():null,l=r.find("a"),h=!1,d=0;d<l.length;d++)if(a===((e=l.eq(d)).data("startTime")||null)&&o===(e.data("endTime")||null)){v.selectOption(e[0]),h=!0,t.onChange(null,null,e.data("handle"));break}h||(n.find(".sel").removeClass("sel"),p.addClass("sel"),a||o?a&&o?b.text(g.val()+" - "+f.val()):a?b.text(Craft.t("app","From {date}",{date:g.val()})):b.text(Craft.t("app","To {date}",{date:f.val()})):b.text(Craft.t("app","All")),v.setPositionRelativeToAnchor(),t.onChange(i,s,"custom"))})),v.on("hide",(function(){g.datepicker("hide"),f.datepicker("hide")}));var C="btn menubtn";t.class&&(C=C+" "+t.class);var b=$("<button/>",{type:"button",class:C,"data-icon":"date",text:Craft.t("app","All")});return new Garnish.MenuBtn(b,v),a&&v.selectOption(a),t.startDate&&g.datepicker("setDate",t.startDate),t.endDate&&f.datepicker("setDate",t.endDate),(t.startDate||t.endDate)&&m.trigger("change"),b},createTimeInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"time"+Math.floor(1e9*Math.random()))+"-time",s=t.name||null,a=s?s+"[time]":null,n=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"timewrapper"}),h=this.createTextInput({id:i,type:e?"time":"text",class:!(!e||n)&&"empty-value",name:a,placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="time"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?(n&&h.val(n.toISOString().split("T")[1]),h.datetimeinput()):(h.timepicker(Craft.timepickerOptions),n&&h.timepicker("setTime",3600*n.getHours()+60*n.getMinutes()+n.getSeconds())),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createTimeField:function(t){return t.id||(t.id="time"+Math.floor(1e9*Math.random())),this.createField(this.createTimeInput(t),t)},createField:function(t,e){var i=e.label&&"__blank__"!==e.label?e.label:null,s=(Craft.isMultiSite&&e.siteId&&e.siteId,$(e.fieldset?"<fieldset/>":"<div/>",{class:"field",id:e.fieldId||(e.id?e.id+"-field":null)}));if(e.first&&s.addClass("first"),i){var a=$('<div class="heading"/>').appendTo(s);$(e.fieldset?"<legend/>":"<label/>",{id:e.labelId||(e.id?"".concat(e.id,"-").concat(e.fieldset?"legend":"label"):null),class:e.required?"required":null,for:!e.fieldset&&e.id,text:i}).appendTo(a)}if(e.instructions&&$('<div class="instructions"/>').text(e.instructions).appendTo(s),$('<div class="input"/>').append(t).appendTo(s),e.tip){var n=$('<p class="notice has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(n),$('<span class="visually-hidden"/>').text(Craft.t("app","Tip")+": ").appendTo(n),$("<span/>").text(e.tip).appendTo(n),n.appendTo(s)}if(e.warning){var r=$('<p class="warning has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(r),$('<span class="visually-hidden"/>').text(Craft.t("app","Warning")+": ").appendTo(r),$("<span/>").text(e.warning).appendTo(r),r.appendTo(s)}return e.errors&&this.addErrorsToField(s,e.errors),s},createErrorList:function(t){var e=$('<ul class="errors"/>');return t&&this.addErrorsToList(e,t),e},addErrorsToList:function(t,e){for(var i=0;i<e.length;i++)$("<li/>").text(e[i]).appendTo(t)},addErrorsToField:function(t,e){if(e){t.addClass("has-errors"),t.children(".input").addClass("errors");var i=t.children("ul.errors");i.length||(i=this.createErrorList().appendTo(t)),this.addErrorsToList(i,e)}},clearErrorsFromField:function(t){t.removeClass("has-errors"),t.children(".input").removeClass("errors"),t.children("ul.errors").remove()},getAutofocusValue:function(t){return t&&!Garnish.isMobileBrowser(!0)?"autofocus":null},getDisabledValue:function(t){return t?"disabled":null}}},1752:function(){Craft.Uploader=Garnish.Base.extend({uploader:null,allowedKinds:null,$element:null,settings:null,_rejectedFiles:{},_extensionList:null,_totalFileCounter:0,_validFileCounter:0,init:function(t,e){this._rejectedFiles={size:[],type:[],limit:[]},this.$element=t,this.allowedKinds=null,this._extensionList=null,this._totalFileCounter=0,this._validFileCounter=0;var i=(e=$.extend({},Craft.Uploader.defaults,e)).events;for(var s in delete e.events,e.allowedKinds&&e.allowedKinds.length&&("string"==typeof e.allowedKinds&&(e.allowedKinds=[e.allowedKinds]),this.allowedKinds=e.allowedKinds,delete e.allowedKinds),e.autoUpload=!1,this.uploader=this.$element.fileupload(e),i)i.hasOwnProperty(s)&&this.uploader.on(s,i[s]);this.settings=e,this.uploader.on("fileuploadadd",this.onFileAdd.bind(this))},setParams:function(t){void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t[Craft.csrfTokenName]=Craft.csrfTokenValue),this.uploader.fileupload("option",{formData:t})},getInProgress:function(){return this.uploader.fileupload("active")},isLastUpload:function(){return this.getInProgress()<2},onFileAdd:function(t,e){var i=this;t.stopPropagation();var s=!1;return this.allowedKinds&&(this._extensionList||this._createExtensionList(),s=!0),e.process().done((function(){var t=e.files[0],a=!0;if(s){var n=t.name.match(/\.([a-z0-4_]+)$/i)[1];-1===$.inArray(n.toLowerCase(),i._extensionList)&&(a=!1,i._rejectedFiles.type.push("“"+t.name+"”"))}t.size>i.settings.maxFileSize&&(i._rejectedFiles.size.push("“"+t.name+"”"),a=!1),a&&"function"==typeof i.settings.canAddMoreFiles&&!i.settings.canAddMoreFiles(i._validFileCounter)&&(i._rejectedFiles.limit.push("“"+t.name+"”"),a=!1),a&&(i._validFileCounter++,e.submit()),++i._totalFileCounter===e.originalFiles.length&&(i._totalFileCounter=0,i._validFileCounter=0,i.processErrorMessages())})),!0},processErrorMessages:function(){var t;this._rejectedFiles.type.length&&(t=1===this._rejectedFiles.type.length?"The file {files} could not be uploaded. The allowed file kinds are: {kinds}.":"The files {files} could not be uploaded. The allowed file kinds are: {kinds}.",t=Craft.t("app",t,{files:this._rejectedFiles.type.join(", "),kinds:this.allowedKinds.join(", ")}),this._rejectedFiles.type=[],alert(t)),this._rejectedFiles.size.length&&(t=1===this._rejectedFiles.size.length?"The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.":"The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.",t=Craft.t("app",t,{files:this._rejectedFiles.size.join(", "),size:this.humanFileSize(Craft.maxUploadSize)}),this._rejectedFiles.size=[],alert(t)),this._rejectedFiles.limit.length&&(t=1===this._rejectedFiles.limit.length?"The file {files} could not be uploaded, because the field limit has been reached.":"The files {files} could not be uploaded, because the field limit has been reached.",t=Craft.t("app",t,{files:this._rejectedFiles.limit.join(", ")}),this._rejectedFiles.limit=[],alert(t))},humanFileSize:function(t){var e=1024;if(t<e)return t+" B";var i=-1;do{t/=e,++i}while(t>=e);return t.toFixed(1)+" "+["kB","MB","GB","TB","PB","EB","ZB","YB"][i]},_createExtensionList:function(){this._extensionList=[];for(var t=0;t<this.allowedKinds.length;t++){var e=this.allowedKinds[t];if(void 0!==Craft.fileKinds[e])for(var i=0;i<Craft.fileKinds[e].extensions.length;i++){var s=Craft.fileKinds[e].extensions[i];this._extensionList.push(s)}}},destroy:function(){this.$element.fileupload("destroy"),this.base()}},{defaults:{dropZone:null,pasteZone:null,fileInput:null,sequentialUploads:!0,maxFileSize:Craft.maxUploadSize,allowedKinds:null,events:{},canAddMoreFiles:null,headers:{Accept:"application/json;q=0.9,*/*;q=0.8"},paramName:"assets-upload"}})},7e3:function(){Craft.UriFormatGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace("/<(.*?)>/g","")).toLowerCase(),t=(t=(t=Craft.asciiString(t)).replace(/^[^a-z]+/,"")).replace(/[^a-z0-9]+$/,"");var e=Craft.filterArray(t.split(/[^a-z0-9]+/)).join(Craft.slugWordSeparator);return e&&this.settings.suffix&&(e+=this.settings.suffix),e}})},8654:function(){Craft.UserIndex=Craft.BaseElementIndex.extend({init:function(t,e,i){this.on("selectSource",this.updateUrl.bind(this)),this.base(t,e,i)},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSourceSlug)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("slug")===defaultSourceSlug)return e.data("key")}return this.base()},updateUrl:function(){if("index"===this.settings.context&&"undefined"!=typeof history){var t="users",e=this.$source.data("slug");e&&(t+="/".concat(e)),history.replaceState({},"",Craft.getUrl(t))}}}),Craft.registerElementIndexClass("craft\\elements\\User",Craft.UserIndex)},5537:function(){},9383:function(){},6558:function(t,e,i){var s=i(5537);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("3790022a",s,!0,{})},2179:function(t,e,i){var s=i(9383);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("80058a3c",s,!0,{})},9673:function(t,e,i){"use strict";function s(t,e){for(var i=[],s={},a=0;a<e.length;a++){var n=e[a],r=n[0],o={id:t+":"+a,css:n[1],media:n[2],sourceMap:n[3]};s[r]?s[r].parts.push(o):i.push(s[r]={id:r,parts:[o]})}return i}i.d(e,{Z:function(){return g}});var a="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!a)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var n={},r=a&&(document.head||document.getElementsByTagName("head")[0]),o=null,l=0,h=!1,d=function(){},c=null,u="data-vue-ssr-id",p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function g(t,e,i,a){h=i,c=a||{};var r=s(t,e);return f(r),function(e){for(var i=[],a=0;a<r.length;a++){var o=r[a];(l=n[o.id]).refs--,i.push(l)}for(e?f(r=s(t,e)):r=[],a=0;a<i.length;a++){var l;if(0===(l=i[a]).refs){for(var h=0;h<l.parts.length;h++)l.parts[h]();delete n[l.id]}}}}function f(t){for(var e=0;e<t.length;e++){var i=t[e],s=n[i.id];if(s){s.refs++;for(var a=0;a<s.parts.length;a++)s.parts[a](i.parts[a]);for(;a<i.parts.length;a++)s.parts.push(v(i.parts[a]));s.parts.length>i.parts.length&&(s.parts.length=i.parts.length)}else{var r=[];for(a=0;a<i.parts.length;a++)r.push(v(i.parts[a]));n[i.id]={id:i.id,refs:1,parts:r}}}}function m(){var t=document.createElement("style");return t.type="text/css",r.appendChild(t),t}function v(t){var e,i,s=document.querySelector("style["+u+'~="'+t.id+'"]');if(s){if(h)return d;s.parentNode.removeChild(s)}if(p){var a=l++;s=o||(o=m()),e=b.bind(null,s,a,!1),i=b.bind(null,s,a,!0)}else s=m(),e=_.bind(null,s),i=function(){s.parentNode.removeChild(s)};return e(t),function(s){if(s){if(s.css===t.css&&s.media===t.media&&s.sourceMap===t.sourceMap)return;e(t=s)}else i()}}var $,C=($=[],function(t,e){return $[t]=e,$.filter(Boolean).join("\n")});function b(t,e,i,s){var a=i?"":s.css;if(t.styleSheet)t.styleSheet.cssText=C(e,a);else{var n=document.createTextNode(a),r=t.childNodes;r[e]&&t.removeChild(r[e]),r.length?t.insertBefore(n,r[e]):t.appendChild(n)}}function _(t,e){var i=e.css,s=e.media,a=e.sourceMap;if(s&&t.setAttribute("media",s),c.ssrId&&t.setAttribute(u,e.id),a&&(i+="\n/*# sourceURL="+a.sources[0]+" */",i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"),t.styleSheet)t.styleSheet.cssText=i;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(i))}}}},i={};function s(e){var a=i[e];if(void 0!==a)return a.exports;var n=i[e]={id:e,exports:{}};return t[e](n,n.exports,s),n.exports}s.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return s.d(e,{a:e}),e},s.d=function(t,e){for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},s.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},function(){"use strict";s(2179),s(6558),s(587),s(1504),s(5774),s(8495),s(5970),s(4993),s(8843),s(7745),s(7452),s(76),s(6872),s(2495),s(5077),s(4606),s(9222),s(525),s(3778),s(6617),s(9482),s(3352),s(691),s(1519),s(501),s(1923),s(2318),s(4755),s(8468),s(8895),s(4233),s(9699),s(1402),s(8201),s(3347),s(9478),s(2387),s(7966),s(657),s(4487),s(6966),s(5080),s(7439),s(5328),s(6419),s(872),s(1396),s(5759),s(4070),s(5763),s(5185),s(8030),s(3096),s(3331),s(53),s(5074),s(3958),s(1592),s(1752),s(7e3),s(8654)}()}();
+!function(){var t={7452:function(){Craft.AdminTable=Garnish.Base.extend({settings:null,totalItems:null,sorter:null,$noItems:null,$table:null,$tbody:null,$deleteBtns:null,init:function(t){this.setSettings(t,Craft.AdminTable.defaults),this.settings.allowDeleteAll||(this.settings.minItems=1),this.$noItems=$(this.settings.noItemsSelector),this.$table=$(this.settings.tableSelector),this.$tbody=this.$table.children("tbody"),this.totalItems=this.$tbody.children().length,this.settings.sortable&&(this.sorter=new Craft.DataTableSorter(this.$table,{onSortChange:this.reorderItems.bind(this)})),this.$deleteBtns=this.$table.find(".delete:not(.disabled)"),this.addListener(this.$deleteBtns,"click","handleDeleteBtnClick"),this.updateUI()},addRow:function(t){if(!(this.settings.maxItems&&this.totalItems>=this.settings.maxItems)){var e=$(t).appendTo(this.$tbody),i=e.find(".delete");this.settings.sortable&&this.sorter.addItems(e),this.$deleteBtns=this.$deleteBtns.add(i),this.addListener(i,"click","handleDeleteBtnClick"),this.totalItems++,this.updateUI()}},reorderItems:function(){var t=this;if(this.settings.sortable){for(var e=[],i=0;i<this.sorter.$items.length;i++){var s=$(this.sorter.$items[i]).attr(this.settings.idAttribute);e.push(s)}var a={ids:JSON.stringify(e)};Craft.postActionRequest(this.settings.reorderAction,a,(function(i,s){"success"===s&&(i.success?(t.onReorderItems(e),Craft.cp.displayNotice(Craft.t("app",t.settings.reorderSuccessMessage))):Craft.cp.displayError(Craft.t("app",t.settings.reorderFailMessage)))}))}},handleDeleteBtnClick:function(t){if(!(this.settings.minItems&&this.totalItems<=this.settings.minItems)){var e=$(t.target).closest("tr");this.confirmDeleteItem(e)&&this.deleteItem(e)}},confirmDeleteItem:function(t){var e=this.getItemName(t);return confirm(Craft.t("app",this.settings.confirmDeleteMessage,{name:e}))},deleteItem:function(t){var e=this,i={id:this.getItemId(t)};Craft.postActionRequest(this.settings.deleteAction,i,(function(i,s){"success"===s&&e.handleDeleteItemResponse(i,t)}))},handleDeleteItemResponse:function(t,e){var i=this.getItemId(e),s=this.getItemName(e);t.success?(this.sorter&&this.sorter.removeItems(e),e.remove(),this.totalItems--,this.updateUI(),this.onDeleteItem(i),Craft.cp.displayNotice(Craft.t("app",this.settings.deleteSuccessMessage,{name:s}))):Craft.cp.displayError(Craft.t("app",this.settings.deleteFailMessage,{name:s}))},onReorderItems:function(t){this.settings.onReorderItems(t)},onDeleteItem:function(t){this.settings.onDeleteItem(t)},getItemId:function(t){return t.attr(this.settings.idAttribute)},getItemName:function(t){return Craft.escapeHtml(t.attr(this.settings.nameAttribute))},updateUI:function(){if(0===this.totalItems?(this.$table.hide(),this.$noItems.removeClass("hidden")):(this.$table.show(),this.$noItems.addClass("hidden")),this.settings.sortable){var t=this.$table.find(".move");1===this.totalItems?t.addClass("disabled"):t.removeClass("disabled")}this.settings.minItems&&this.totalItems<=this.settings.minItems?this.$deleteBtns.addClass("disabled"):this.$deleteBtns.removeClass("disabled"),this.settings.newItemBtnSelector&&(this.settings.maxItems&&this.totalItems>=this.settings.maxItems?$(this.settings.newItemBtnSelector).addClass("hidden"):$(this.settings.newItemBtnSelector).removeClass("hidden"))}},{defaults:{tableSelector:null,noItemsSelector:null,newItemBtnSelector:null,idAttribute:"data-id",nameAttribute:"data-name",sortable:!1,allowDeleteAll:!0,minItems:0,maxItems:null,reorderAction:null,deleteAction:null,reorderSuccessMessage:Craft.t("app","New order saved."),reorderFailMessage:Craft.t("app","Couldn’t save new order."),confirmDeleteMessage:Craft.t("app","Are you sure you want to delete “{name}”?"),deleteSuccessMessage:Craft.t("app","“{name}” deleted."),deleteFailMessage:Craft.t("app","Couldn’t delete “{name}”."),onReorderItems:$.noop,onDeleteItem:$.noop}})},76:function(){Craft.AssetEditor=Craft.BaseElementEditor.extend({$filenameInput:null,originalBasename:null,originalExtension:null,reloadIndex:!1,init:function(t,e){var i=this;this.on("updateForm",(function(){i.addListener(i.$sidebar.find(".preview-thumb-container .edit-btn"),"click","showImageEditor"),i.addListener(i.$sidebar.find(".preview-thumb-container .preview-btn"),"click","showImagePreview"),i.$filenameInput=i.$sidebar.find(".filename"),i.addListener(i.$filenameInput,"focus","selectFilename")})),this.on("closeSlideout",(function(){i.reloadIndex&&(i.settings.elementIndex?i.settings.elementIndex.updateElements():i.settings.input&&i.settings.input.refreshThumbnail(i.$element.data("id")))})),this.base(t,e),this.settings.validators.push((function(){return i.validateExtension()}))},showImageEditor:function(){var t=this;new Craft.AssetImageEditor(this.$element.data("id"),{onSave:function(){t.reloadIndex=!0,t.load()}})},showImagePreview:function(){var t={};this.$element.data("image-width")&&(t.startingWidth=this.$element.data("image-width"),t.startingHeight=this.$element.data("image-height")),new Craft.PreviewFileModal(this.$element.data("id"),null,t)},selectFilename:function(){var t=this;if(void 0!==this.$filenameInput[0].selectionStart){var e=this._parseFilename(),i=e.basename,s=e.extension;null===this.originalBasename&&(this.originalBasename=i,this.originalExtension=s),this.$filenameInput[0].selectionStart=0,this.$filenameInput[0].selectionEnd=i.length,this.$filenameInput.one("mouseup.keepselection",(function(t){t.preventDefault()})),setTimeout((function(){t.$filenameInput.off("mouseup.keepselection")}),500)}},validateExtension:function(){if(null===this.originalBasename)return!0;var t=this._parseFilename(),e=t.basename,i=t.extension;return i===this.originalExtension||(i?confirm(Craft.t("app","Are you sure you want to change the extension from “.{oldExt}” to “.{newExt}”?",{oldExt:this.originalExtension,newExt:i})):this.originalFilename!==e?(this.$filenameInput.val("".concat(Craft.rtrim(e,"."),".").concat(this.originalExtension)),!0):confirm(Craft.t("app","Are you sure you want to remove the extension “.{ext}”?",{ext:this.originalExtension})))},_parseFilename:function(){var t=this.$filenameInput.val().split("."),e=t.length>1?t.pop():null;return{basename:t.join("."),extension:e}}}),Craft.registerElementEditorClass("craft\\elements\\Asset",Craft.AssetEditor)},6872:function(){Craft.AssetImageEditor=Garnish.Modal.extend({$body:null,$footer:null,$imageTools:null,$buttons:null,$cancelBtn:null,$replaceBtn:null,$saveBtn:null,$editorContainer:null,$straighten:null,$croppingCanvas:null,$spinnerCanvas:null,canvas:null,image:null,viewport:null,focalPoint:null,grid:null,croppingCanvas:null,clipper:null,croppingRectangle:null,cropperHandles:null,cropperGrid:null,croppingShade:null,imageStraightenAngle:0,viewportRotation:0,originalWidth:0,originalHeight:0,imageVerticeCoords:null,zoomRatio:1,animationInProgress:!1,currentView:"",assetId:null,cacheBust:null,draggingCropper:!1,scalingCropper:!1,draggingFocal:!1,previousMouseX:0,previousMouseY:0,shiftKeyHeld:!1,editorHeight:0,editorWidth:0,cropperState:!1,scaleFactor:1,flipData:{},focalPointState:!1,spinnerInterval:null,maxImageSize:null,lastLoadedDimensions:null,imageIsLoading:!1,mouseMoveEvent:null,croppingConstraint:!1,constraintOrientation:"landscape",showingCustomConstraint:!1,renderImage:null,renderCropper:null,init:function(t,e){this.cacheBust=Date.now(),this.setSettings(e,Craft.AssetImageEditor.defaults),null===this.settings.allowDegreeFractions&&(this.settings.allowDegreeFractions=Craft.isImagick),this.assetId=t,this.flipData={x:0,y:0},this.$container=$('<form class="modal fitted imageeditor"></form>').appendTo(Garnish.$bod),this.$body=$('<div class="body"></div>').appendTo(this.$container),this.$footer=$('<div class="footer"/>').appendTo(this.$container),this.base(this.$container,this.settings),this.$buttons=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn cancel",text:Craft.t("app","Cancel")}).appendTo(this.$buttons),this.$replaceBtn=$("<button/>",{type:"button",class:"btn submit save replace",text:Craft.t("app","Save")}).appendTo(this.$buttons),this.settings.allowSavingAsNew&&(this.$saveBtn=$("<button/>",{type:"button",class:"btn submit save copy",text:Craft.t("app","Save as a new asset")}).appendTo(this.$buttons),this.addListener(this.$saveBtn,"activate",this.saveImage)),this.addListener(this.$replaceBtn,"activate",this.saveImage),this.addListener(this.$cancelBtn,"activate",this.hide),this.removeListener(this.$shade,"click"),this.maxImageSize=this.getMaxImageSize(),Craft.postActionRequest("assets/image-editor",{assetId:t},this.loadEditor.bind(this))},getMaxImageSize:function(){var t=Garnish.$doc.get(0).documentElement.clientWidth,e=Garnish.$doc.get(0).documentElement.clientHeight;return Math.max(e,t)*(window.devicePixelRatio>1?2:1)},loadEditor:function(t){var e=this;t.html||alert(Craft.t("app","Could not load the image editor.")),this.$body.html(t.html),this.$tabs=$(".tabs li",this.$body),this.$viewsContainer=$(".views",this.$body),this.$views=$("> div",this.$viewsContainer),this.$imageTools=$(".image-container .image-tools",this.$body),this.$editorContainer=$(".image-container .image",this.$body),this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this._showSpinner(),this.updateSizeAndPosition(),this.canvas=new fabric.StaticCanvas("image-canvas"),this.$croppingCanvas=$("#cropping-canvas",this.$editorContainer),this.$croppingCanvas.width(this.editorWidth),this.$croppingCanvas.height(this.editorHeight),this.canvas.enableRetinaScaling=!0,this.renderImage=function(){Garnish.requestAnimationFrame(e.canvas.renderAll.bind(e.canvas))};var i=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});fabric.Image.fromURL(i,(function(i){e.image=i,e.image.set({originX:"center",originY:"center",left:e.editorWidth/2,top:e.editorHeight/2}),e.canvas.add(e.image),e.originalHeight=e.image.getHeight(),e.originalWidth=e.image.getWidth(),e.zoomRatio=1,e.lastLoadedDimensions=e.getScaledImageDimensions(),e._setFittedImageVerticeCoordinates(),e._repositionEditorElements();var s={imageDimensions:e.getScaledImageDimensions(),offsetX:0,offsetY:0},a=!1;if(t.focalPoint){var n=t.focalPoint,r=s.imageDimensions.width*n.x,o=s.imageDimensions.height*n.y;s.offsetX=r-s.imageDimensions.width/2,s.offsetY=o-s.imageDimensions.height/2,a=!0}e.storeFocalPointState(s),a&&e._createFocalPoint(),e._createViewport(),e.storeCropperState(),e._addControlListeners(),e.addListener(e.$croppingCanvas,"mousemove,touchmove",e._handleMouseMove),e.addListener(e.$croppingCanvas,"mousedown,touchstart",e._handleMouseDown),e.addListener(e.$croppingCanvas,"mouseup,touchend",e._handleMouseUp),e.addListener(e.$croppingCanvas,"mouseout,touchcancel",e._handleMouseOut),e._hideSpinner(),e.renderImage(),e.$tabs.first().trigger("click")}))},_reloadImage:function(){var t=this;if(!this.imageIsLoading){this.imageIsLoading=!0,this.maxImageSize=this.getMaxImageSize();var e=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});this.image.setSrc(e,(function(e){t.originalHeight=e.getHeight(),t.originalWidth=e.getWidth(),t.lastLoadedDimensions={width:t.originalHeight,height:t.originalWidth},t.updateSizeAndPosition(),t.renderImage(),t.imageIsLoading=!1}))}},updateSizeAndPosition:function(){if(this.$container){var t=window.innerWidth,e=window.innerHeight;this.$container.css({width:t,"min-width":t,left:0,height:e,"min-height":e,top:0}),this.$body.css({height:e-62}),t<e?this.$container.addClass("vertical"):this.$container.removeClass("vertical"),this.$spinnerCanvas&&this.$spinnerCanvas.css({left:this.$spinnerCanvas.parent().width()/2-this.$spinnerCanvas.width()/2+"px",top:this.$spinnerCanvas.parent().height()/2-this.$spinnerCanvas.height()/2+"px"}),this.$editorContainer&&this.image&&this._repositionEditorElements()}},_repositionEditorElements:function(){var t={width:this.editorWidth,height:this.editorHeight};this.editorHeight=this.$editorContainer.innerHeight(),this.editorWidth=this.$editorContainer.innerWidth(),this.canvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var e=this.getScaledImageDimensions();if("crop"===this.currentView){this.zoomRatio=this.getZoomToFitRatio(this.getScaledImageDimensions());var i=this._getBoundingRectangle(this.imageVerticeCoords);this._setFittedImageVerticeCoordinates(),this._repositionCropper(i)}else this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor;this._repositionImage(t),this._repositionViewport(),this._repositionFocalPoint(t),this._zoomImage(),this.renderImage(),(e.width/this.lastLoadedDimensions.width>1.5||e.height/this.lastLoadedDimensions.height>1.5)&&this._reloadImage()},_repositionImage:function(t){this.image.set({left:this.image.left-(t.width-this.editorWidth)/2,top:this.image.top-(t.height-this.editorHeight)/2})},_createViewport:function(){this.viewport=new fabric.Rect({width:this.image.width,height:this.image.height,fill:"rgba(127,0,0,1)",originX:"center",originY:"center",globalCompositeOperation:"destination-in",left:this.image.left,top:this.image.top}),this.canvas.add(this.viewport),this.renderImage()},_createFocalPoint:function(){var t=this.focalPointState,e=this.getScaledImageDimensions().width/t.imageDimensions.width,i=t.offsetX*e*this.zoomRatio*this.scaleFactor,s=t.offsetY*e*this.zoomRatio*this.scaleFactor;i+=this.image.left,s+=this.image.top;var a=0,n=0;this.viewport&&0===t.offsetX&&0===t.offsetY&&("crop"!==this.currentView?(a=this.viewport.left-this.image.left,n=this.viewport.top-this.image.top):(a=this.clipper.left-this.image.left,n=this.clipper.top-this.image.top),i+=a,s+=n,t.offsetX+=a/(e*this.zoomRatio*this.scaleFactor),t.offsetY+=n/(e*this.zoomRatio*this.scaleFactor)),this.focalPoint=new fabric.Group([new fabric.Circle({radius:8,fill:"rgba(0,0,0,0.5)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"}),new fabric.Circle({radius:1,fill:"rgba(255,255,255,0)",strokeWidth:2,stroke:"rgba(255,255,255,0.8)",left:0,top:0,originX:"center",originY:"center"})],{originX:"center",originY:"center",left:i,top:s}),this.storeFocalPointState(t),this.canvas.add(this.focalPoint)},toggleFocalPoint:function(){this.focalPoint?(this.canvas.remove(this.focalPoint),this.focalPoint=null):this._createFocalPoint(),this.renderImage()},_repositionViewport:function(){if(this.viewport){var t={left:this.editorWidth/2,top:this.editorHeight/2};if("crop"===this.currentView)t.width=this.editorWidth,t.height=this.editorHeight;else if(this.cropperState){var e=this.cropperState,i=this.getScaledImageDimensions().width/e.imageDimensions.width;t.width=e.width*i*this.zoomRatio,t.height=e.height*i*this.zoomRatio,this.image.set({left:this.editorWidth/2-e.offsetX*i,top:this.editorHeight/2-e.offsetY*i})}else $.extend(t,this.getScaledImageDimensions());this.viewport.set(t)}},_repositionFocalPoint:function(t){if(this.focalPoint){var e=this.focalPoint.left-this.editorWidth/2,i=this.focalPoint.top-this.editorHeight/2,s=this.image.width,a=this.getScaledImageDimensions().width*this.zoomRatio/s/this.scaleFactor;e-=(t.width-this.editorWidth)/2,i-=(t.height-this.editorHeight)/2,e*=a,i*=a,this.focalPoint.set({left:this.editorWidth/2+e,top:this.editorHeight/2+i})}},hasOrientationChanged:function(){return this.viewportRotation%180!=0},getScaledImageDimensions:function(){return void 0===this.getScaledImageDimensions._&&(this.getScaledImageDimensions._={}),this.getScaledImageDimensions._.imageRatio=this.originalHeight/this.originalWidth,this.getScaledImageDimensions._.editorRatio=this.editorHeight/this.editorWidth,this.getScaledImageDimensions._.dimensions={},this.getScaledImageDimensions._.imageRatio>this.getScaledImageDimensions._.editorRatio?(this.getScaledImageDimensions._.dimensions.height=Math.min(this.editorHeight,this.originalHeight),this.getScaledImageDimensions._.dimensions.width=Math.round(this.originalWidth/(this.originalHeight/this.getScaledImageDimensions._.dimensions.height))):(this.getScaledImageDimensions._.dimensions.width=Math.min(this.editorWidth,this.originalWidth),this.getScaledImageDimensions._.dimensions.height=Math.round(this.originalHeight*(this.getScaledImageDimensions._.dimensions.width/this.originalWidth))),this.getScaledImageDimensions._.dimensions},_zoomImage:function(){void 0===this._zoomImage._&&(this._zoomImage._={}),this._zoomImage._.imageDimensions=this.getScaledImageDimensions(),this.image.set({width:this._zoomImage._.imageDimensions.width*this.zoomRatio,height:this._zoomImage._.imageDimensions.height*this.zoomRatio})},_addControlListeners:function(){var t=this;this.addListener(this.$tabs,"click",this._handleTabClick),this.addListener($(".focal-point"),"click",this.toggleFocalPoint),this.addListener($(".rotate-left"),"click",(function(){this.rotateImage(-90)})),this.addListener($(".rotate-right"),"click",(function(){this.rotateImage(90)})),this.addListener($(".flip-vertical"),"click",(function(){this.flipImage("y")})),this.addListener($(".flip-horizontal"),"click",(function(){this.flipImage("x")})),this.straighteningInput=new Craft.SlideRuleInput("slide-rule",{onStart:function(){t._showGrid()},onChange:function(e){t.straighten(e)},onEnd:function(){t._hideGrid(),t._cleanupFocalPointAfterStraighten()}}),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!0)})),this.addListener(Garnish.$doc,"keyup",(function(t){t.keyCode===Garnish.SHIFT_KEY&&(this.shiftKeyHeld=!1)})),this.addListener($(".constraint-buttons .constraint",this.$container),"click",this._handleConstraintClick),this.addListener($(".orientation input",this.$container),"click",this._handleOrientationClick),this.addListener($(".constraint-buttons .custom-input input",this.$container),"keyup",this._applyCustomConstraint)},_handleConstraintClick:function(t){var e=$(t.currentTarget).data("constraint"),i=$(t.currentTarget);if(i.siblings().removeClass("active"),i.addClass("active"),"custom"==e)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(e),this.enforceCroppingConstraint()},_handleOrientationClick:function(t){if(t.currentTarget.value!==this.constraintOrientation){this.constraintOrientation=t.currentTarget.value;for(var e=$(".constraint.flip",this.$container),i=0;i<e.length;i++){var s=$(e[i]);s.data("constraint",1/s.data("constraint")),s.html(s.html().split(":").reverse().join(":"))}e.filter(".active").click()}},_applyCustomConstraint:function(){var t=this._getCustomConstraint();t.w>0&&t.h>0&&(this.setCroppingConstraint(t.w/t.h),this.enforceCroppingConstraint())},_getCustomConstraint:function(){var t=parseFloat($(".custom-constraint-w").val()),e=parseFloat($(".custom-constraint-h").val());return{w:isNaN(t)?0:t,h:isNaN(e)?0:e}},_setCustomConstraint:function(t,e){$(".custom-constraint-w").val(parseFloat(t)),$(".custom-constraint-h").val(parseFloat(e))},_hideCustomConstraint:function(){this.showingCustomConstraint=!1,$(".constraint.custom .custom-input",this.$container).addClass("hidden"),$(".constraint.custom .custom-label",this.$container).removeClass("hidden"),$(".orientation",this.$container).removeClass("hidden")},_showCustomConstraint:function(){this.showingCustomConstraint||(this.showingCustomConstraint=!0,$(".constraint.custom .custom-input",this.$container).removeClass("hidden"),$(".constraint.custom .custom-label",this.$container).addClass("hidden"),$(".orientation",this.$container).addClass("hidden"))},_handleTabClick:function(t){if(!this.animationInProgress){var e=$(t.currentTarget),i=e.data("view");this.$tabs.removeClass("selected"),e.addClass("selected"),this.showView(i)}},showView:function(t){this.currentView!==t&&(this.$views.addClass("hidden"),this.$views.filter('[data-view="'+t+'"]').removeClass("hidden"),"rotate"===t?this.enableSlider():this.disableSlider(),this.updateSizeAndPosition(),"crop"===this.currentView&&"crop"!==t?this.disableCropMode():"crop"!==this.currentView&&"crop"===t&&this.enableCropMode(),this.currentView=t)},storeCropperState:function(t){void 0===this.storeCropperState._&&(this.storeCropperState._={}),t?this.cropperState=t:this.clipper?(this.storeCropperState._.zoomFactor=1/this.zoomRatio,this.cropperState={offsetX:(this.clipper.left-this.image.left)*this.storeCropperState._.zoomFactor,offsetY:(this.clipper.top-this.image.top)*this.storeCropperState._.zoomFactor,height:this.clipper.height*this.storeCropperState._.zoomFactor,width:this.clipper.width*this.storeCropperState._.zoomFactor,imageDimensions:this.getScaledImageDimensions()}):(this.storeCropperState._.dimensions=this.getScaledImageDimensions(),this.cropperState={offsetX:0,offsetY:0,height:this.storeCropperState._.dimensions.height,width:this.storeCropperState._.dimensions.width,imageDimensions:this.storeCropperState._.dimensions})},storeFocalPointState:function(t){void 0===this.storeFocalPointState._&&(this.storeFocalPointState._={}),t?this.focalPointState=t:this.focalPoint&&(this.storeFocalPointState._.zoomFactor=1/this.zoomRatio,this.focalPointState={offsetX:(this.focalPoint.left-this.image.left)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,offsetY:(this.focalPoint.top-this.image.top)*this.storeFocalPointState._.zoomFactor/this.scaleFactor,imageDimensions:this.getScaledImageDimensions()})},rotateImage:function(t){var e=this;if(!this.animationInProgress){if(90!==t&&-90!==t)return!1;this.animationInProgress=!0,this.viewportRotation+=t,this.viewportRotation=parseInt((this.viewportRotation+360)%360,10);var i,s=this.image.angle+t,a=this.getScaledImageDimensions();i=this.hasOrientationChanged()?this.getZoomToCoverRatio({height:a.width,width:a.height}):this.getZoomToCoverRatio(a),this.zoomRatio>i&&(i=this.zoomRatio);var n={angle:90===t?"+=90":"-=90"},r={angle:s,width:a.width*i,height:a.height*i},o=1;this.scaleFactor<1?(o=1/this.scaleFactor,this.scaleFactor=1):(this.viewport.width>this.editorHeight?o=this.editorHeight/this.viewport.width:this.viewport.height>this.editorWidth&&(o=this.editorWidth/this.viewport.height),this.scaleFactor=o),o<1&&(r.width*=o,r.height*=o);var l=this.cropperState,h=l.offsetX,d=l.offsetY,c=t*(Math.PI/180),u=h*Math.cos(c)-d*Math.sin(c),p=h*Math.sin(c)+d*Math.cos(c),g=a.width/l.imageDimensions.width,f=u*g*this.zoomRatio*this.scaleFactor,m=p*g*this.zoomRatio*this.scaleFactor;r.left=this.editorWidth/2-f,r.top=this.editorHeight/2-m,l.offsetX=u,l.offsetY=p;var v=l.width;l.width=l.height,l.height=v,this.storeCropperState(l),this.focalPoint&&this.canvas.remove(this.focalPoint),this.viewport.animate(n,{duration:this.settings.animationDuration,onComplete:function(){var t=e.viewport.height*o;e.viewport.height=e.viewport.width*o,e.viewport.width=t,e.viewport.set({angle:0})}}),this.image.animate(r,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){var i=parseFloat((e.image.angle+360)%360);e.image.set({angle:i}),e.animationInProgress=!1,e.focalPoint?(e._adjustFocalPointByAngle(t),e.straighten(e.straighteningInput),e.canvas.add(e.focalPoint)):e._resetFocalPointPosition()}})}},flipImage:function(t){var e=this;if(!this.animationInProgress){this.animationInProgress=!0,this.hasOrientationChanged()&&(t="y"===t?"x":"y"),this.focalPoint?this.canvas.remove(this.focalPoint):this._resetFocalPointPosition();var i={x:this.editorWidth/2,y:this.editorHeight/2};this.straighteningInput.setValue(-this.imageStraightenAngle),this.imageStraightenAngle=-this.imageStraightenAngle;var s,a,n={angle:this.viewportRotation+this.imageStraightenAngle},r=this.cropperState,o=this.focalPointState;"y"===t&&this.hasOrientationChanged()||"y"!==t&&!this.hasOrientationChanged()?(r.offsetX=-r.offsetX,o.offsetX=-o.offsetX,a=this.image.left-i.x,n.left=i.x-a):(r.offsetY=-r.offsetY,o.offsetY=-o.offsetY,s=this.image.top-i.y,n.top=i.y-s),"y"===t?(n.scaleY=-1*this.image.scaleY,this.flipData.y=1-this.flipData.y):(n.scaleX=-1*this.image.scaleX,this.flipData.x=1-this.flipData.x),this.storeCropperState(r),this.storeFocalPointState(o),this.image.animate(n,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){e.animationInProgress=!1,e.focalPoint&&(e._adjustFocalPointByAngle(0),e.canvas.add(e.focalPoint))}})}},straighten:function(t){if(!this.animationInProgress){this.animationInProgress=!0;var e=this.image.angle;this.imageStraightenAngle=(this.settings.allowDegreeFractions?parseFloat(t.value):Math.round(parseFloat(t.value)))%360,this.image.set({angle:this.viewportRotation+this.imageStraightenAngle}),this.zoomRatio=this.getZoomToCoverRatio(this.getScaledImageDimensions())*this.scaleFactor,this._zoomImage(),this.cropperState&&this._adjustEditorElementsOnStraighten(e),this.renderImage(),this.animationInProgress=!1}},_adjustEditorElementsOnStraighten:function(t){var e,i,s,a,n,r=this.getScaledImageDimensions(),o=this.image.angle-t,l=this.cropperState,h=this.zoomRatio,d=1;do{var c=l.offsetX,u=l.offsetY,p=o*(Math.PI/180);s=c*Math.cos(p)-u*Math.sin(p),a=c*Math.sin(p)+u*Math.cos(p),e=s*h*(n=r.width/l.imageDimensions.width),i=a*h*n;var g=this.getImageVerticeCoords(h),f={width:this.viewport.width,height:this.viewport.height,left:this.editorWidth/2-this.viewport.width/2+e,top:this.editorHeight/2-this.viewport.height/2+i};h*=d=this._getZoomRatioToFitRectangle(f,g)}while(1!==d);this.image.set({left:this.editorWidth/2-e,top:this.editorHeight/2-i}),l.offsetX=s,l.offsetY=a,l.width=this.viewport.width/h/n,l.height=this.viewport.height/h/n,this.storeCropperState(l),this.zoomRatio=h,this.focalPoint?(this._adjustFocalPointByAngle(o),this._isCenterInside(this.focalPoint,this.viewport)?this.focalPoint.set({opacity:1}):this.focalPoint.set({opacity:0})):0!==o&&this._resetFocalPointPosition(),this._zoomImage()},_cleanupFocalPointAfterStraighten:function(){if(this.focalPoint&&!this._isCenterInside(this.focalPoint,this.viewport)){this.focalPoint.set({opacity:1});var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t),this.toggleFocalPoint()}},_resetFocalPointPosition:function(){var t=this.focalPointState;t.offsetX=0,t.offsetY=0,this.storeFocalPointState(t)},_isCenterInside:function(t,e){return t.left>e.left-e.width/2&&t.top>e.top-e.height/2&&t.left<e.left+e.width/2&&t.top<e.top+e.height/2},_adjustFocalPointByAngle:function(t){var e=t*(Math.PI/180),i=this.focalPointState,s=i.offsetX,a=i.offsetY,n=s*Math.cos(e)-a*Math.sin(e),r=s*Math.sin(e)+a*Math.cos(e),o=this.getScaledImageDimensions().width/i.imageDimensions.width,l=n*o*this.zoomRatio,h=r*o*this.zoomRatio;this.focalPoint.left=this.image.left+l,this.focalPoint.top=this.image.top+h,i.offsetX=n,i.offsetY=r,this.storeFocalPointState(i)},_getZoomRatioToFitRectangle:function(t,e){for(var i,s,a=this._getRectangleVertices(t),n=0;n<a.length&&(i=a[n],this.arePointsInsideRectangle([i],e));n++)i=!1;if(i){var r=this._getEdgeCrossed(e,i),o={x:t.left+t.width/2,y:t.top+t.height/2},l=Math.abs((r[1].y-r[0].y)*i.x-(r[1].x-r[0].x)*i.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2)),h=Math.abs((r[1].y-r[0].y)*o.x-(r[1].x-r[0].x)*o.y+r[1].x*r[0].y-r[1].y*r[0].x)/Math.sqrt(Math.pow(r[1].y-r[0].y,2)+Math.pow(r[1].x-r[0].x,2));s=(l+h)/h}else s=1;return s},saveImage:function(t){var e=this,i=$(t.currentTarget);if(i.hasClass("disabled"))return!1;$(".btn",this.$buttons).addClass("disabled"),this.$buttons.append('<div class="spinner"></div>');var s={assetId:this.assetId,viewportRotation:this.viewportRotation,imageRotation:this.imageStraightenAngle,replace:i.hasClass("replace")?1:0};if(this.cropperState){var a={};a.height=this.cropperState.height,a.width=this.cropperState.width,a.offsetX=this.cropperState.offsetX,a.offsetY=this.cropperState.offsetY,s.imageDimensions=this.cropperState.imageDimensions,s.cropData=a}else s.imageDimensions=this.getScaledImageDimensions();this.focalPoint&&(s.focalPoint=this.focalPointState),s.flipData=this.flipData,s.zoom=this.zoomRatio,Craft.postActionRequest("assets/save-image",s,(function(t){e.$buttons.find(".btn").removeClass("disabled").end().find(".spinner").remove(),t.error?alert(t.error):(e.onSave(),e.hide(),Craft.cp.runQueue())}))},getZoomToCoverRatio:function(t){var e=Math.abs(this.imageStraightenAngle)*(Math.PI/180),i=Math.sin(e)*t.height+Math.cos(e)*t.width,s=Math.sin(e)*t.width+Math.cos(e)*t.height;return Math.max(i/t.width,s/t.height)},getZoomToFitRatio:function(t){var e=this._getImageBoundingBox(t),i=1;if(e.height>this.editorHeight||e.width>this.editorWidth){var s=this.editorHeight/e.height,a=this.editorWidth/e.width;i=Math.min(a,s)}return i},getCombinedZoomRatio:function(t){return this.getZoomToCoverRatio(t)/this.getZoomToFitRatio(t)},_showGrid:function(){if(!this.grid){var t,e={strokeWidth:1,stroke:"rgba(255,255,255,0.5)"},i=this.viewport.width,s=this.viewport.height,a=i/9,n=s/9,r=[new fabric.Rect({strokeWidth:2,stroke:"rgba(255,255,255,1)",originX:"center",originY:"center",width:i,height:s,left:i/2,top:s/2,fill:"rgba(255,255,255,0)"})];for(t=1;t<=8;t++)r.push(new fabric.Line([t*a,0,t*a,s],e));for(t=1;t<=8;t++)r.push(new fabric.Line([0,t*n,i,t*n],e));this.grid=new fabric.Group(r,{left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",angle:this.viewport.angle}),this.canvas.add(this.grid),this.renderImage()}},_hideGrid:function(){this.canvas.remove(this.grid),this.grid=null,this.renderImage()},onFadeOut:function(){this.destroy()},show:function(){this.base(),Garnish.$bod.addClass("no-scroll")},hide:function(){this.removeAllListeners(),this.straighteningInput.removeAllListeners(),Garnish.$bod.removeClass("no-scroll"),this.base()},onSave:function(){this.settings.onSave(),this.trigger("save")},enableSlider:function(){this.$imageTools.removeClass("hidden")},disableSlider:function(){this.$imageTools.addClass("hidden")},enableCropMode:function(){var t=this,e=this.getScaledImageDimensions();this.zoomRatio=this.getZoomToFitRatio(e);var i={width:this.editorWidth,height:this.editorHeight},s={width:e.width*this.zoomRatio,height:e.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2};this._editorModeTransition((function(){t._setFittedImageVerticeCoordinates();var e=t.cropperState,i=t.getScaledImageDimensions(),s=i.width/e.imageDimensions.width,a={left:t.image.left+e.offsetX*s*t.zoomRatio,top:t.image.top+e.offsetY*s*t.zoomRatio,width:e.width*s*t.zoomRatio,height:e.height*s*t.zoomRatio};t._showCropper(a),t.focalPoint&&(s=i.width/t.focalPointState.imageDimensions.width,t.focalPoint.left=t.image.left+t.focalPointState.offsetX*s*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*s*t.zoomRatio,t.canvas.add(t.focalPoint))}),s,i)},disableCropMode:function(){var t=this,e={};this._hideCropper();var i=this.getScaledImageDimensions(),s=this.getZoomToCoverRatio(i)*this.scaleFactor,a=s/this.zoomRatio;this.zoomRatio=s;var n={width:i.width*this.zoomRatio,height:i.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},r=(this.clipper.left-this.image.left)*a,o=(this.clipper.top-this.image.top)*a;n.left=this.editorWidth/2-r,n.top=this.editorHeight/2-o,e.height=this.clipper.height*a,e.width=this.clipper.width*a,(!this.focalPoint||this.focalPoint&&!this._isCenterInside(this.focalPoint,this.clipper))&&(this.focalPoint&&this.toggleFocalPoint(),this._resetFocalPointPosition()),this._editorModeTransition((function(){if(t.focalPoint){var e=t.getScaledImageDimensions().width/t.focalPointState.imageDimensions.width;t.focalPoint.left=t.image.left+t.focalPointState.offsetX*e*t.zoomRatio,t.focalPoint.top=t.image.top+t.focalPointState.offsetY*e*t.zoomRatio,t.canvas.add(t.focalPoint)}}),n,e)},_editorModeTransition:function(t,e,i){var s=this;this.animationInProgress||(this.animationInProgress=!0,this.focalPoint&&(this.canvas.remove(this.focalPoint),this.renderImage()),this.image.animate(e,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){t(),s.animationInProgress=!1,s.renderImage()}}),this.viewport.animate(i,{duration:this.settings.animationDuration}))},_showSpinner:function(){this.$spinnerCanvas=$('<canvas id="spinner-canvas"></canvas>').appendTo($(".image",this.$container));var t=document.getElementById("spinner-canvas").getContext("2d"),e=new Date,i=t.canvas.width,s=t.canvas.height;this.spinnerInterval=window.setInterval((function(){var a=parseInt((new Date-e)/1e3*16)/16;t.save(),t.clearRect(0,0,i,s),t.translate(i/2,s/2),t.rotate(2*Math.PI*a);for(var n=0;n<16;n++)t.beginPath(),t.rotate(2*Math.PI/16),t.moveTo(i/10,0),t.lineTo(i/4,0),t.lineWidth=i/30,t.strokeStyle="rgba(255,255,255,"+n/16+")",t.stroke();t.restore()}),1e3/30)},_hideSpinner:function(){window.clearInterval(this.spinnerInterval),this.$spinnerCanvas.remove(),this.$spinnerCanvas=null},_showCropper:function(t){this._setupCropperLayer(t),this._redrawCropperElements(),this.renderCropper()},_hideCropper:function(){this.clipper&&(this.croppingCanvas.remove(this.clipper),this.croppingCanvas.remove(this.croppingShade),this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle),this.croppingCanvas=null,this.renderCropper=null)},_setupCropperLayer:function(t){var e=this;this.croppingCanvas=new fabric.StaticCanvas("cropping-canvas",{backgroundColor:"rgba(0,0,0,0)",hoverCursor:"default",selection:!1}),this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight}),this.renderCropper=function(){return Garnish.requestAnimationFrame(e.croppingCanvas.renderAll.bind(e.croppingCanvas))},$("#cropping-canvas",this.$editorContainer).css({position:"absolute",top:0,left:0}),this.croppingShade=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:this.editorWidth,height:this.editorHeight,fill:"rgba(0,0,0,0.7)"});var i=this.getScaledImageDimensions(),s=0===this.imageStraightenAngle?1:1.2*this.getCombinedZoomRatio(i),a=i.width/s,n=i.height/s;if(this.hasOrientationChanged()){var r=n;n=a,a=r}this.clipper=new fabric.Rect({left:this.editorWidth/2,top:this.editorHeight/2,originX:"center",originY:"center",width:a,height:n,stroke:"black",fill:"rgba(128,0,0,1)",strokeWidth:0}),t&&this.clipper.set(t),this.clipper.globalCompositeOperation="destination-out",this.croppingCanvas.add(this.croppingShade),this.croppingCanvas.add(this.clipper)},_redrawCropperElements:function(){void 0===this._redrawCropperElements._&&(this._redrawCropperElements._={}),this.cropperHandles&&(this.croppingCanvas.remove(this.cropperHandles),this.croppingCanvas.remove(this.cropperGrid),this.croppingCanvas.remove(this.croppingRectangle)),this._redrawCropperElements._.lineOptions={strokeWidth:4,stroke:"rgb(255,255,255)",fill:!1},this._redrawCropperElements._.gridOptions={strokeWidth:2,stroke:"rgba(255,255,255,0.5)"},this._redrawCropperElements._.pathGroup=[new fabric.Path("M 0,10 L 0,0 L 10,0",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width-8)+",0 L "+(this.clipper.width+4)+",0 L "+(this.clipper.width+4)+",10",this._redrawCropperElements._.lineOptions),new fabric.Path("M "+(this.clipper.width+4)+","+(this.clipper.height-8)+" L"+(this.clipper.width+4)+","+(this.clipper.height+4)+" L "+(this.clipper.width-8)+","+(this.clipper.height+4),this._redrawCropperElements._.lineOptions),new fabric.Path("M 10,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height+4)+" L 0,"+(this.clipper.height-8),this._redrawCropperElements._.lineOptions)],this.cropperHandles=new fabric.Group(this._redrawCropperElements._.pathGroup,{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this.croppingRectangle=new fabric.Rect({left:this.clipper.left,top:this.clipper.top,width:this.clipper.width,height:this.clipper.height,fill:"rgba(0,0,0,0)",stroke:"rgba(255,255,255,0.8)",strokeWidth:2,originX:"center",originY:"center"}),this.cropperGrid=new fabric.Group([new fabric.Line([.33*this.clipper.width,0,.33*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([.66*this.clipper.width,0,.66*this.clipper.width,this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.33*this.clipper.height,this.clipper.width,.33*this.clipper.height],this._redrawCropperElements._.gridOptions),new fabric.Line([0,.66*this.clipper.height,this.clipper.width,.66*this.clipper.height],this._redrawCropperElements._.gridOptions)],{left:this.clipper.left,top:this.clipper.top,originX:"center",originY:"center"}),this._redrawCropperElements._.cropTextTop=this.croppingRectangle.top+this.clipper.height/2+12,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0)",this._redrawCropperElements._.cropTextTop+12>this.editorHeight-2&&(this._redrawCropperElements._.cropTextTop-=24,this._redrawCropperElements._.cropTextBackgroundColor="rgba(0,0,0,0.5)"),this.croppingCanvas.add(this.cropperHandles),this.croppingCanvas.add(this.cropperGrid),this.croppingCanvas.add(this.croppingRectangle)},_repositionCropper:function(t){if(this.croppingCanvas){var e=this.clipper.left-this.croppingCanvas.width/2,i=this.clipper.top-this.croppingCanvas.height/2;this.croppingCanvas.setDimensions({width:this.editorWidth,height:this.editorHeight});var s=this._getBoundingRectangle(this.imageVerticeCoords).width/t.width;this.clipper.width=Math.round(this.clipper.width*s),this.clipper.height=Math.round(this.clipper.height*s),this.clipper.left=this.editorWidth/2+e*s,this.clipper.top=this.editorHeight/2+i*s,this.croppingShade.set({width:this.editorWidth,height:this.editorHeight,left:this.editorWidth/2,top:this.editorHeight/2}),this._redrawCropperElements(),this.renderCropper()}},_getBoundingRectangle:function(t){return{width:Math.max(t.a.x,t.b.x,t.c.x,t.d.x)-Math.min(t.a.x,t.b.x,t.c.x,t.d.x),height:Math.max(t.a.y,t.b.y,t.c.y,t.d.y)-Math.min(t.a.y,t.b.y,t.c.y,t.d.y)}},_handleMouseDown:function(t){var e=this.focalPoint&&this._isMouseOver(t,this.focalPoint),i=this.croppingCanvas&&this._isMouseOver(t,this.clipper),s=this.croppingCanvas&&this._cropperHandleHitTest(t);(s||i||e)&&(this.previousMouseX=t.pageX,this.previousMouseY=t.pageY,e?this.draggingFocal=!0:s?this.scalingCropper=s:i&&(this.draggingCropper=!0))},_handleMouseMove:function(t){null!==this.mouseMoveEvent&&Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this)),this.mouseMoveEvent=t},_handleMouseMoveInternal:function(){null!==this.mouseMoveEvent&&(this.focalPoint&&this.draggingFocal?(this._handleFocalDrag(this.mouseMoveEvent),this.storeFocalPointState(),this.renderImage()):this.draggingCropper||this.scalingCropper?(this.draggingCropper?this._handleCropperDrag(this.mouseMoveEvent):this._handleCropperResize(this.mouseMoveEvent),this._redrawCropperElements(),this.storeCropperState(),this.renderCropper()):this._setMouseCursor(this.mouseMoveEvent),this.previousMouseX=this.mouseMoveEvent.pageX,this.previousMouseY=this.mouseMoveEvent.pageY,this.mouseMoveEvent=null)},_handleMouseUp:function(t){this.draggingCropper=!1,this.scalingCropper=!1,this.draggingFocal=!1},_handleMouseOut:function(t){this._handleMouseUp(t),this.mouseMoveEvent=t,this._handleMouseMoveInternal()},_handleCropperDrag:function(t){if(void 0===this._handleCropperDrag._&&(this._handleCropperDrag._={}),this._handleCropperDrag._.deltaX=t.pageX-this.previousMouseX,this._handleCropperDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleCropperDrag._.deltaX&&0===this._handleCropperDrag._.deltaY)return!1;if(this._handleCropperDrag._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.deltaX,this._handleCropperDrag._.deltaY),!this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)){for(this._handleCropperDrag._.dxi=0,this._handleCropperDrag._.dyi=0,this._handleCropperDrag._.xStep=this._handleCropperDrag._.deltaX>0?-1:1,this._handleCropperDrag._.yStep=this._handleCropperDrag._.deltaY>0?-1:1,this._handleCropperDrag._.furthest=0,this._handleCropperDrag._.furthestDeltas={},this._handleCropperDrag._.dxi=Math.min(Math.abs(this._handleCropperDrag._.deltaX),10);this._handleCropperDrag._.dxi>=0;this._handleCropperDrag._.dxi--)for(this._handleCropperDrag._.dyi=Math.min(Math.abs(this._handleCropperDrag._.deltaY),10);this._handleCropperDrag._.dyi>=0;this._handleCropperDrag._.dyi--)this._handleCropperDrag._.vertices=this._getRectangleVertices(this._handleCropperDrag._.rectangle,this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)),this.arePointsInsideRectangle(this._handleCropperDrag._.vertices,this.imageVerticeCoords)&&this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi>this._handleCropperDrag._.furthest&&(this._handleCropperDrag._.furthest=this._handleCropperDrag._.dxi+this._handleCropperDrag._.dyi,this._handleCropperDrag._.furthestDeltas={x:this._handleCropperDrag._.dxi*(this._handleCropperDrag._.deltaX>0?1:-1),y:this._handleCropperDrag._.dyi*(this._handleCropperDrag._.deltaY>0?1:-1)});if(0==this._handleCropperDrag._.furthest)return;this._handleCropperDrag._.deltaX=this._handleCropperDrag._.furthestDeltas.x,this._handleCropperDrag._.deltaY=this._handleCropperDrag._.furthestDeltas.y}this.clipper.set({left:this.clipper.left+this._handleCropperDrag._.deltaX,top:this.clipper.top+this._handleCropperDrag._.deltaY})},_handleFocalDrag:function(t){if(void 0===this._handleFocalDrag._&&(this._handleFocalDrag._={}),this.focalPoint){if(this._handleFocalDrag._.deltaX=t.pageX-this.previousMouseX,this._handleFocalDrag._.deltaY=t.pageY-this.previousMouseY,0===this._handleFocalDrag._.deltaX&&0===this._handleFocalDrag._.deltaY)return;if(this._handleFocalDrag._.newX=this.focalPoint.left+this._handleFocalDrag._.deltaX,this._handleFocalDrag._.newY=this.focalPoint.top+this._handleFocalDrag._.deltaY,"crop"===this.currentView){if(!this.arePointsInsideRectangle([{x:this._handleFocalDrag._.newX,y:this._handleFocalDrag._.newY}],this.imageVerticeCoords))return}else if(!(this.viewport.left-this.viewport.width/2-this._handleFocalDrag._.newX<0&&this.viewport.left+this.viewport.width/2-this._handleFocalDrag._.newX>0&&this.viewport.top-this.viewport.height/2-this._handleFocalDrag._.newY<0&&this.viewport.top+this.viewport.height/2-this._handleFocalDrag._.newY>0))return;this.focalPoint.set({left:this.focalPoint.left+this._handleFocalDrag._.deltaX,top:this.focalPoint.top+this._handleFocalDrag._.deltaY})}},setCroppingConstraint:function(t){switch(this.updateSizeAndPosition(),t){case"none":this.croppingConstraint=!1;break;case"original":this.croppingConstraint=this.originalWidth/this.originalHeight;break;case"current":this.croppingConstraint=this.clipper.width/this.clipper.height;break;case"custom":break;default:this.croppingConstraint=parseFloat(t)}},enforceCroppingConstraint:function(){var t=this;void 0===this.enforceCroppingConstraint._&&(this.enforceCroppingConstraint._={}),!this.animationInProgress&&this.croppingConstraint&&(this.animationInProgress=!0,this.enforceCroppingConstraint._.rectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this.clipper.width>this.clipper.height*this.croppingConstraint?(this.enforceCroppingConstraint._.previousHeight=this.enforceCroppingConstraint._.rectangle.height,this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.top-=(this.enforceCroppingConstraint._.rectangle.height-this.enforceCroppingConstraint._.previousHeight)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.height=this.enforceCroppingConstraint._.rectangle.width/this.croppingConstraint)):(this.enforceCroppingConstraint._.previousWidth=this.enforceCroppingConstraint._.rectangle.width,this.enforceCroppingConstraint._.rectangle.width=this.clipper.height*this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.left-=(this.enforceCroppingConstraint._.rectangle.width-this.enforceCroppingConstraint._.previousWidth)/2,this.arePointsInsideRectangle(this._getRectangleVertices(this.enforceCroppingConstraint._.rectangle),this.imageVerticeCoords)||(this.enforceCroppingConstraint._.rectangle.height=this.clipper.width/this.croppingConstraint,this.enforceCroppingConstraint._.rectangle.width=this.enforceCroppingConstraint._.rectangle.height*this.croppingConstraint)),this.enforceCroppingConstraint._.properties={height:this.enforceCroppingConstraint._.rectangle.height,width:this.enforceCroppingConstraint._.rectangle.width},this.clipper.animate(this.enforceCroppingConstraint._.properties,{onChange:function(){t._redrawCropperElements(),t.croppingCanvas.renderAll()},duration:this.settings.animationDuration,onComplete:function(){t._redrawCropperElements(),t.animationInProgress=!1,t.renderCropper(),t.storeCropperState()}}))},_handleCropperResize:function(t){void 0===this._handleCropperResize._&&(this._handleCropperResize._={}),this._handleCropperResize._.deltaX=t.pageX-this.previousMouseX,this._handleCropperResize._.deltaY=t.pageY-this.previousMouseY,"b"!==this.scalingCropper&&"t"!==this.scalingCropper||(this._handleCropperResize._.deltaX=0),"l"!==this.scalingCropper&&"r"!==this.scalingCropper||(this._handleCropperResize._.deltaY=0),0===this._handleCropperResize._.deltaX&&0===this._handleCropperResize._.deltaY||(this._handleCropperResize._.startingRectangle={left:this.clipper.left-this.clipper.width/2,top:this.clipper.top-this.clipper.height/2,width:this.clipper.width,height:this.clipper.height},this._handleCropperResize._.rectangle=this._calculateNewCropperSizeByDeltas(this._handleCropperResize._.startingRectangle,this._handleCropperResize._.deltaX,this._handleCropperResize._.deltaY,this.scalingCropper),this._handleCropperResize._.rectangle.height<30||this._handleCropperResize._.rectangle.width<30||this.arePointsInsideRectangle(this._getRectangleVertices(this._handleCropperResize._.rectangle),this.imageVerticeCoords)&&(this.clipper.set({top:this._handleCropperResize._.rectangle.top+this._handleCropperResize._.rectangle.height/2,left:this._handleCropperResize._.rectangle.left+this._handleCropperResize._.rectangle.width/2,width:this._handleCropperResize._.rectangle.width,height:this._handleCropperResize._.rectangle.height}),this._redrawCropperElements()))},_calculateNewCropperSizeByDeltas:function(t,e,i,s){if(void 0===this._calculateNewCropperSizeByDeltas._&&(this._calculateNewCropperSizeByDeltas._={}),this._calculateNewCropperSizeByDeltas._.topDelta=0,this._calculateNewCropperSizeByDeltas._.leftDelta=0,this._calculateNewCropperSizeByDeltas._.rectangle=t,this._calculateNewCropperSizeByDeltas._.deltaX=e,this._calculateNewCropperSizeByDeltas._.deltaY=i,this.croppingConstraint){switch(this._calculateNewCropperSizeByDeltas._.change=0,s){case"t":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaY;break;case"b":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"r":this._calculateNewCropperSizeByDeltas._.change=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"l":this._calculateNewCropperSizeByDeltas._.change=-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?-this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX;break;case"br":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.change=Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY)>Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)?this._calculateNewCropperSizeByDeltas._.deltaY:-this._calculateNewCropperSizeByDeltas._.deltaX}switch(this.croppingConstraint>1?(this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this.croppingConstraint):(this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.change,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this.croppingConstraint),this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX,s){case"t":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"b":this._calculateNewCropperSizeByDeltas._.rectangle.left+=-this._calculateNewCropperSizeByDeltas._.deltaX/2;break;case"r":this._calculateNewCropperSizeByDeltas._.rectangle.top+=-this._calculateNewCropperSizeByDeltas._.deltaY/2;break;case"l":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY/2,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"tr":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY;break;case"tl":this._calculateNewCropperSizeByDeltas._.rectangle.top-=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX;break;case"bl":this._calculateNewCropperSizeByDeltas._.rectangle.left-=this._calculateNewCropperSizeByDeltas._.deltaX}}else!this.shiftKeyHeld||"tl"!==s&&"tr"!==s&&"bl"!==s&&"br"!==s||(this._calculateNewCropperSizeByDeltas._.ratio,Math.abs(e)>Math.abs(i)?(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaY=this._calculateNewCropperSizeByDeltas._.deltaX/this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaY*="tr"===s||"bl"===s?-1:1):(this._calculateNewCropperSizeByDeltas._.ratio=t.width/t.height,this._calculateNewCropperSizeByDeltas._.deltaX=this._calculateNewCropperSizeByDeltas._.deltaY*this._calculateNewCropperSizeByDeltas._.ratio,this._calculateNewCropperSizeByDeltas._.deltaX*="tr"===s||"bl"===s?-1:1)),s.match(/t/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.top+=this._calculateNewCropperSizeByDeltas._.deltaY,this._calculateNewCropperSizeByDeltas._.rectangle.height-=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/b/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.height+=this._calculateNewCropperSizeByDeltas._.deltaY),s.match(/r/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.width+=this._calculateNewCropperSizeByDeltas._.deltaX),s.match(/l/)&&(this._calculateNewCropperSizeByDeltas._.rectangle.left+=this._calculateNewCropperSizeByDeltas._.deltaX,this._calculateNewCropperSizeByDeltas._.rectangle.width-=this._calculateNewCropperSizeByDeltas._.deltaX);return this._calculateNewCropperSizeByDeltas._.rectangle.top=this._calculateNewCropperSizeByDeltas._.rectangle.top,this._calculateNewCropperSizeByDeltas._.rectangle.left=this._calculateNewCropperSizeByDeltas._.rectangle.left,this._calculateNewCropperSizeByDeltas._.rectangle.width=this._calculateNewCropperSizeByDeltas._.rectangle.width,this._calculateNewCropperSizeByDeltas._.rectangle.height=this._calculateNewCropperSizeByDeltas._.rectangle.height,this._calculateNewCropperSizeByDeltas._.rectangle},_setMouseCursor:function(t){void 0===this._setMouseCursor._&&(this._setMouseCursor._={}),Garnish.isMobileBrowser(!0)||(this._setMouseCursor._.cursor="default",this._setMouseCursor._.handle=this.croppingCanvas&&this._cropperHandleHitTest(t),this.focalPoint&&this._isMouseOver(t,this.focalPoint)?this._setMouseCursor._.cursor="pointer":this._setMouseCursor._.handle?"t"===this._setMouseCursor._.handle||"b"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ns-resize":"l"===this._setMouseCursor._.handle||"r"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="ew-resize":"tl"===this._setMouseCursor._.handle||"br"===this._setMouseCursor._.handle?this._setMouseCursor._.cursor="nwse-resize":"bl"!==this._setMouseCursor._.handle&&"tr"!==this._setMouseCursor._.handle||(this._setMouseCursor._.cursor="nesw-resize"):this.croppingCanvas&&this._isMouseOver(t,this.clipper)&&(this._setMouseCursor._.cursor="move"),$(".body").css("cursor",this._setMouseCursor._.cursor))},_cropperHandleHitTest:function(t){if(void 0===this._cropperHandleHitTest._&&(this._cropperHandleHitTest._={}),this._cropperHandleHitTest._.parentOffset=this.$croppingCanvas.offset(),this._cropperHandleHitTest._.mouseX=t.pageX-this._cropperHandleHitTest._.parentOffset.left,this._cropperHandleHitTest._.mouseY=t.pageY-this._cropperHandleHitTest._.parentOffset.top,this._cropperHandleHitTest._.lb=this.clipper.left-this.clipper.width/2,this._cropperHandleHitTest._.rb=this._cropperHandleHitTest._.lb+this.clipper.width,this._cropperHandleHitTest._.tb=this.clipper.top-this.clipper.height/2,this._cropperHandleHitTest._.bb=this._cropperHandleHitTest._.tb+this.clipper.height,this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tl";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+3&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"bl"}if(this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-13&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+3){if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-3)return"tr";if(this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-10)return"br"}return this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.lb+3&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb-3&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"l":this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb+1&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.rb-5&&this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb-10&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb+10?"r":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.tb+4&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.tb-2&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10?"t":this._cropperHandleHitTest._.mouseY<this._cropperHandleHitTest._.bb+2&&this._cropperHandleHitTest._.mouseY>this._cropperHandleHitTest._.bb-4&&this._cropperHandleHitTest._.mouseX>this._cropperHandleHitTest._.lb+10&&this._cropperHandleHitTest._.mouseX<this._cropperHandleHitTest._.rb-10&&"b"},_isMouseOver:function(t,e){return void 0===this._isMouseOver._&&(this._isMouseOver._={}),this._isMouseOver._.parentOffset=this.$croppingCanvas.offset(),this._isMouseOver._.mouseX=t.pageX-this._isMouseOver._.parentOffset.left,this._isMouseOver._.mouseY=t.pageY-this._isMouseOver._.parentOffset.top,this._isMouseOver._.lb=e.left-e.width/2,this._isMouseOver._.rb=this._isMouseOver._.lb+e.width,this._isMouseOver._.tb=e.top-e.height/2,this._isMouseOver._.bb=this._isMouseOver._.tb+e.height,this._isMouseOver._.mouseX>=this._isMouseOver._.lb&&this._isMouseOver._.mouseX<=this._isMouseOver._.rb&&this._isMouseOver._.mouseY>=this._isMouseOver._.tb&&this._isMouseOver._.mouseY<=this._isMouseOver._.bb},_getRectangleVertices:function(t,e,i){return void 0===this._getRectangleVertices._&&(this._getRectangleVertices._={}),void 0===e&&(e=0),void 0===i&&(i=0),this._getRectangleVertices._.topLeft={x:t.left+e,y:t.top+i},this._getRectangleVertices._.topRight={x:this._getRectangleVertices._.topLeft.x+t.width,y:this._getRectangleVertices._.topLeft.y},this._getRectangleVertices._.bottomRight={x:this._getRectangleVertices._.topRight.x,y:this._getRectangleVertices._.topRight.y+t.height},this._getRectangleVertices._.bottomLeft={x:this._getRectangleVertices._.topLeft.x,y:this._getRectangleVertices._.bottomRight.y},[this._getRectangleVertices._.topLeft,this._getRectangleVertices._.topRight,this._getRectangleVertices._.bottomRight,this._getRectangleVertices._.bottomLeft]},_setFittedImageVerticeCoordinates:function(){this.imageVerticeCoords=this.getImageVerticeCoords("fit")},getImageVerticeCoords:function(t){var e,i=-1*((this.hasOrientationChanged()?90:0)+this.imageStraightenAngle)*(Math.PI/180),s=this.getScaledImageDimensions();e="number"==typeof t?t:"cover"===t?this.getZoomToCoverRatio(s):this.getZoomToFitRatio(s);var a=s.height*e,n=s.width*e,r=Math.cos(i)*a,o=Math.sin(i)*n,l=Math.cos(i)*n,h=Math.sin(i)*a,d=(this.editorHeight-(r+o))/2,c=(this.editorWidth-(h+l))/2;return{a:{x:c+l,y:d},b:{x:this.editorWidth-c,y:d+r},c:{x:c+h,y:this.editorHeight-d},d:{x:c,y:d+o}}},_debug:function(t){this.canvas.remove(this.debugger),this.debugger=t,this.canvas.add(this.debugger)},arePointsInsideRectangle:function(t,e){for(void 0===this.arePointsInsideRectangle._&&(this.arePointsInsideRectangle._={}),this.arePointsInsideRectangle._.ab=this._getVector(e.a,e.b),this.arePointsInsideRectangle._.bc=this._getVector(e.b,e.c),this.arePointsInsideRectangle._.scalarAbAb=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ab),this.arePointsInsideRectangle._.scalarBcBc=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bc),this.arePointsInsideRectangle._.i=0;this.arePointsInsideRectangle._.i<t.length;this.arePointsInsideRectangle._.i++)if(this.arePointsInsideRectangle._.point=t[this.arePointsInsideRectangle._.i],this.arePointsInsideRectangle._.ap=this._getVector(e.a,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.bp=this._getVector(e.b,this.arePointsInsideRectangle._.point),this.arePointsInsideRectangle._.scalarAbAp=this._getScalarProduct(this.arePointsInsideRectangle._.ab,this.arePointsInsideRectangle._.ap),this.arePointsInsideRectangle._.scalarBcBp=this._getScalarProduct(this.arePointsInsideRectangle._.bc,this.arePointsInsideRectangle._.bp),this.arePointsInsideRectangle._.projectsOnAB=0<=this.arePointsInsideRectangle._.scalarAbAp&&this.arePointsInsideRectangle._.scalarAbAp<=this.arePointsInsideRectangle._.scalarAbAb,this.arePointsInsideRectangle._.projectsOnBC=0<=this.arePointsInsideRectangle._.scalarBcBp&&this.arePointsInsideRectangle._.scalarBcBp<=this.arePointsInsideRectangle._.scalarBcBc,!this.arePointsInsideRectangle._.projectsOnAB||!this.arePointsInsideRectangle._.projectsOnBC)return!1;return!0},_getVector:function(t,e){return{x:e.x-t.x,y:e.y-t.y}},_getScalarProduct:function(t,e){return t.x*e.x+t.y*e.y},_getVectorMagnitude:function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},_getAngleBetweenVectors:function(t,e){return Math.round(180*Math.acos(Math.min(1,this._getScalarProduct(t,e)/(this._getVectorMagnitude(t)*this._getVectorMagnitude(e))))/Math.PI*100)/100},_getEdgeCrossed:function(t,e){for(var i=[[t.a,t.b],[t.b,t.c],[t.c,t.d],[t.d,t.a]],s={x:this.editorWidth/2,y:this.editorHeight/2},a=180,n=null,r=0;r<i.length;r++){var o=i[r],l=this._getVector(o[0],s),h=this._getVector(o[0],o[1]),d=this._getVector(o[0],e),c=Math.abs(this._getAngleBetweenVectors(l,d)-(this._getAngleBetweenVectors(l,h)+this._getAngleBetweenVectors(h,d)));c<a&&(a=c,n=o)}return n},_getImageBoundingBox:function(t){var e={},i=Math.abs(this.imageStraightenAngle)*(Math.PI/180),s=t.height/t.width;if(e.height=t.width*(Math.sin(i)+Math.cos(i)*s),e.width=t.width*(Math.cos(i)+Math.sin(i)*s),this.hasOrientationChanged()){var a=e.width;e.width=e.height,e.height=a}return e}},{defaults:{animationDuration:100,allowSavingAsNew:!0,onSave:$.noop,allowDegreeFractions:null}})},2495:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}Craft.AssetIndex=Craft.BaseElementIndex.extend({$includeSubfoldersContainer:null,$includeSubfoldersCheckbox:null,showingIncludeSubfoldersCheckbox:!1,$uploadButton:null,$uploadInput:null,$progressBar:null,$folders:null,uploader:null,promptHandler:null,progressBar:null,_uploadTotalFiles:0,_uploadFileProgress:{},_currentUploaderSettings:{},_assetDrag:null,_folderDrag:null,_expandDropTargetFolderTimeout:null,_tempExpandedFolders:[],_fileConflictTemplate:{choices:[{value:"keepBoth",title:Craft.t("app","Keep both")},{value:"replace",title:Craft.t("app","Replace it")}]},_folderConflictTemplate:{choices:[{value:"replace",title:Craft.t("app","Replace the folder (all existing files will be deleted)")},{value:"merge",title:Craft.t("app","Merge the folder (any conflicting files will be replaced)")}]},init:function(t,e,i){this.base(t,e,i),"index"===this.settings.context?(this._folderDrag||this._initIndexPageMode(),this.addListener(Garnish.$win,"resize,scroll","_positionProgressBar")):(this.addListener(this.$main,"scroll","_positionProgressBar"),this.settings.modal&&this.settings.modal.on("updateSizeAndPosition",this._positionProgressBar.bind(this)))},initSources:function(){return"index"!==this.settings.context||this._folderDrag||this._initIndexPageMode(),this.base()},initSource:function(t){this.base(t),this._createFolderContextMenu(t),"index"===this.settings.context&&(this._folderDrag&&this._getSourceLevel(t)>1&&t.data("folder-id")&&this._folderDrag.addItems(t.parent()),this._assetDrag&&this._assetDrag.updateDropTargets())},deinitSource:function(t){this.base(t);var e=t.data("contextmenu");e&&e.destroy(),"index"===this.settings.context&&(this._folderDrag&&this._getSourceLevel(t)>1&&this._folderDrag.removeItems(t.parent()),this._assetDrag&&this._assetDrag.updateDropTargets())},_getSourceLevel:function(t){return t.parentsUntil("nav","ul").length},_initIndexPageMode:function(){var t=this;this._folderDrag||(this.settings.selectable=!0,this.settings.multiSelect=!0,this._assetDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,filter:function(){return t.view.getSelectedElements().has("div.element[data-movable]")},helper:function(e){return t._getFileDragHelper(e)},dropTargets:function(){var e;e=t._assetDrag.$draggee&&t._assetDrag.$draggee.has(".element[data-peer-file]").length?"data-can-move-peer-files-to":"data-can-move-to";for(var i=[],s=0;s<t.$sources.length;s++){var a=t.$sources.eq(s);Garnish.hasAttr(a,e)&&i.push(a)}return i},onDragStart:this._onDragStart.bind(this),onDropTargetChange:this._onDropTargetChange.bind(this),onDragStop:this._onFileDragStop.bind(this),helperBaseZindex:800}),this._folderDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,helper:function(e){var i=$('<div class="sidebar drag-helper"/>'),s=$("<nav/>").appendTo(i),a=$("<ul/>").appendTo(s);return e.appendTo(a).removeClass("expanded"),e.children("a").addClass("sel"),e.css({"padding-top":t._folderDrag.$draggee.css("padding-top"),"padding-right":t._folderDrag.$draggee.css("padding-right"),"padding-bottom":t._folderDrag.$draggee.css("padding-bottom"),"padding-left":t._folderDrag.$draggee.css("padding-left")}),i},dropTargets:function(){var e=[],i=[];t._folderDrag.$draggee.find("a[data-key]").each((function(){i.push($(this).data("key"))}));for(var s=0;s<t.$sources.length;s++){var a=t.$sources.eq(s),n=a.data("key");t._getFolderUidFromSourceKey(n)&&(Craft.inArray(n,i)||e.push(a))}return e},onDragStart:this._onDragStart.bind(this),onDropTargetChange:this._onDropTargetChange.bind(this),onDragStop:this._onFolderDragStop.bind(this)}))},_onFileDragStop:function(){var t=this;if(this._assetDrag.$activeDropTarget&&this._assetDrag.$activeDropTarget[0]!==this.$source[0]){for(var e=this.$source,i=this._assetDrag.$activeDropTarget.data("folder-id"),s=[],a=0;a<this._assetDrag.$draggee.length;a++){var n=Craft.getElementInfo(this._assetDrag.$draggee[a]).id;s.push(n)}if(s.length){this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(s.length),this.progressBar.showProgressBar();var r=[];for(a=0;a<s.length;a++)r.push({action:"assets/move-asset",params:{assetId:s[a],folderId:i}});return void this._performBatchRequests(r,(function a(n){t.promptHandler.resetPrompts();for(var r=0;r<n.length;r++){var o=n[r];o.conflict&&t.promptHandler.addPrompt({assetId:o.assetId,suggestedFilename:o.suggestedFilename,prompt:{message:o.conflict,choices:t._fileConflictTemplate.choices}}),o.error&&alert(o.error)}t.setIndexAvailable(),t.progressBar.hideProgressBar();var l=!1,h=function(){this.sourceSelect.selectItem(e),this._totalVisible-=this._assetDrag.$draggee.length;for(var t=0;t<s.length;t++)$("[data-id="+s[t]+"]").remove();this.view.deselectAllElements(),this._collapseExtraExpandedFolders(i),l&&this.updateElements()};t.promptHandler.getPromptCount()?(t._assetDrag.fadeOutHelpers(),t.promptHandler.showBatchPrompts((function(e){for(var s=[],n=0;n<e.length;n++)"cancel"!==e[n].choice?("keepBoth"===e[n].choice&&s.push({action:"assets/move-asset",params:{folderId:i,assetId:e[n].assetId,filename:e[n].suggestedFilename}}),"replace"===e[n].choice&&s.push({action:"assets/move-asset",params:{folderId:i,assetId:e[n].assetId,force:!0}})):l=!0;0===s.length?h.apply(t):(t.setIndexBusy(),t.progressBar.resetProgressBar(),t.progressBar.setItemCount(t.promptHandler.getPromptCount()),t.progressBar.showProgressBar(),t._performBatchRequests(s,a))}))):(h.apply(t),t._assetDrag.fadeOutHelpers())}))}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._assetDrag.returnHelpersToDraggees()},_onFolderDragStop:function(){var t=this;if(this._folderDrag.$activeDropTarget&&0===this._folderDrag.$activeDropTarget.siblings("ul").children("li").filter(this._folderDrag.$draggee).length){var e=this._folderDrag.$activeDropTarget.data("folder-id");this._collapseExtraExpandedFolders(e);for(var i=[],s=0;s<this._folderDrag.$draggee.length;s++){var a=this._folderDrag.$draggee.eq(s).children("a").data("folder-id");if(a!=e){i.push(a);break}}if(i.length){i.sort(),i.reverse(),this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(i.length),this.progressBar.showProgressBar();var n=[];for(s=0;s<i.length;s++)n.push({action:"assets/move-folder",params:{folderId:i[s],parentId:e}});this.requestId++;var r=[],o="";return void this._performBatchRequests(n,(function e(s){t.promptHandler.resetPrompts();for(var a=0;a<s.length;a++){var n=s[a];n.success&&(n.transferList&&(r=n.transferList),n.newFolderId&&(o=t._folderDrag.$activeDropTarget.data("key")+"/folder:"+n.newFolderUid)),n.conflict&&(n.prompt={message:n.conflict,choices:t._folderConflictTemplate.choices},t.promptHandler.addPrompt(n)),n.error&&alert(n.error)}t.promptHandler.getPromptCount()?(t.promptHandler.showBatchPrompts((function(s){t.promptHandler.resetPrompts();for(var a=[],l={},h=0;h<s.length;h++)"cancel"!==s[h].choice&&("replace"===s[h].choice&&(l.force=!0),"merge"===s[h].choice&&(l.merge=!0),l.folderId=n.folderId,l.parentId=n.parentId,a.push({action:"assets/move-folder",params:l}));0===a.length?t._performActualFolderMove(r,i,o):(t.setIndexBusy(),t.progressBar.resetProgressBar(),t.progressBar.setItemCount(t.promptHandler.getPromptCount()),t.progressBar.showProgressBar(),t._performBatchRequests(a,e))})),t.setIndexAvailable(),t.progressBar.hideProgressBar()):t._performActualFolderMove(r,i,o)}))}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._folderDrag.returnHelpersToDraggees()},_performActualFolderMove:function(t,e,i){var s=this;this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(1),this.progressBar.showProgressBar();var a=function(t){for(var e=0,a=t.length,n=0;n<t.length;n++)Craft.postActionRequest("assets/delete-folder",{folderId:t[n]},(function(){++e===a&&(s.setIndexAvailable(),s.progressBar.hideProgressBar(),s._folderDrag.returnHelpersToDraggees(),s.setInstanceState("selectedSource",i),s.refreshSources())}))};if(t.length>0){for(var n=[],r=0;r<t.length;r++)n.push({action:"assets/move-asset",params:t[r]});this._performBatchRequests(n,(function(){a(e)}))}else a(e)},_getRootSource:function(t){for(var e;(e=this._getParentSource(t))&&e.length;)t=e;return t},_getParentSource:function(t){if(this._getSourceLevel(t)>1)return t.parent().parent().siblings("a")},_selectSourceByFolderId:function(t){for(var e=this._getSourceByKey(t),i=e.parent().parents("li"),s=0;s<i.length;s++){var a=$(i[s]);a.hasClass("expanded")||a.children(".toggle").trigger("click")}this.selectSource(e),this.updateElements()},afterInit:function(){var t=this;this.$uploadButton||(this.$uploadButton=$("<button/>",{type:"button",class:"btn submit","data-icon":"upload",style:"position: relative; overflow: hidden;",text:Craft.t("app","Upload files")}),this.addButton(this.$uploadButton),this.$uploadInput=$('<input type="file" multiple="multiple" name="assets-upload" />').hide().insertBefore(this.$uploadButton)),this.promptHandler=new Craft.PromptHandler,this.progressBar=new Craft.ProgressBar(this.$main,!0);var e={url:Craft.getActionUrl("assets/upload"),fileInput:this.$uploadInput,dropZone:this.$container};e.events={fileuploadstart:this._onUploadStart.bind(this),fileuploadprogressall:this._onUploadProgress.bind(this),fileuploaddone:this._onUploadComplete.bind(this),fileuploadfail:this._onUploadFailure.bind(this)},this.settings.criteria&&void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),this._currentUploaderSettings=e,this.uploader=new Craft.Uploader(this.$uploadButton,e),this.$uploadButton.on("click",(function(){t.$uploadButton.hasClass("disabled")||t.isIndexBusy||t.$uploadButton.parent().find("input[name=assets-upload]").trigger("click")})),this.base()},getDefaultSourceKey:function(){var e=this;if("index"===this.settings.context&&void 0!==window.defaultSource){var i=function(){var t=window.defaultSource.split("/"),i=e.$sources.toArray().find((function(e){return $(e).data("volume-handle")===t[0]}));if(i){for(var s=$(i),a=function(i){var a=e._getChildSources(s).toArray().find((function(e){return $("> .label",e).text()===t[i]}));if(!a)return"break";e._expandSource(s),s=$(a)},n=1;n<t.length&&"break"!==a(n);n++);return{v:s.data("key")}}}();if("object"===t(i))return i.v}return this.base()},onSelectSource:function(){var t=this._getSourceByKey(this.sourceKey);t.data("folder-id")&&Garnish.hasAttr(this.$source,"data-can-upload")?(this.uploader.setParams({folderId:this.$source.attr("data-folder-id")}),this.$uploadButton.removeClass("disabled")):this.$uploadButton.addClass("disabled"),t.length&&"index"===this.settings.context&&this._updateUrl(t),this.base()},_updateUrl:function(t){if("undefined"!=typeof history){for(var e,i=[],s=t;(e=this._getParentSource(s))&&e.length;)i.unshift(s),s=e;var a="assets";s.data("volume-handle")&&(a+="/"+s.data("volume-handle"),i.forEach((function(t){a+="/"+t.children(".label").text()}))),history.replaceState({},"",Craft.getUrl(a))}},_getFolderUidFromSourceKey:function(t){var e=t.match(/\bfolder:([0-9a-f\-]+)$/);return e?e[1]:null},startSearching:function(){if(!this.settings.hideSidebar&&this.$source.siblings("ul").length){if(null===this.$includeSubfoldersContainer){var t="includeSubfolders-"+Math.floor(1e9*Math.random());this.$includeSubfoldersContainer=$('<div style="margin-bottom: -25px; opacity: 0;"/>').insertAfter(this.$search);var e=$('<div style="padding-top: 5px;"/>').appendTo(this.$includeSubfoldersContainer);this.$includeSubfoldersCheckbox=$('<input type="checkbox" id="'+t+'" class="checkbox"/>').appendTo(e),$('<label class="light smalltext" for="'+t+'"/>').text(" "+Craft.t("app","Search in subfolders")).appendTo(e),this.addListener(this.$includeSubfoldersCheckbox,"change",(function(){this.setSelecetedSourceState("includeSubfolders",this.$includeSubfoldersCheckbox.prop("checked")),this.updateElements()}))}else this.$includeSubfoldersContainer.velocity("stop");var i=this.getSelectedSourceState("includeSubfolders",!1);this.$includeSubfoldersCheckbox.prop("checked",i),this.$includeSubfoldersContainer.velocity({marginBottom:0,opacity:1},"fast"),this.showingIncludeSubfoldersCheckbox=!0}this.base()},stopSearching:function(){this.showingIncludeSubfoldersCheckbox&&(this.$includeSubfoldersContainer.velocity("stop"),this.$includeSubfoldersContainer.velocity({marginBottom:-25,opacity:0},"fast"),this.showingIncludeSubfoldersCheckbox=!1),this.base()},getViewParams:function(){var t=this.base();return this.showingIncludeSubfoldersCheckbox&&this.$includeSubfoldersCheckbox.prop("checked")&&(t.criteria.includeSubfolders=!0),t},_onUploadStart:function(){this.setIndexBusy(),this._positionProgressBar(),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar(),this.promptHandler.resetPrompts()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){var i=e.result,s=e.files[0].name,a=!0;i.success||i.conflict?(this.selectElementAfterUpdate(i.assetId),i.conflict&&(i.prompt={message:Craft.t("app",i.conflict,{file:i.filename}),choices:this._fileConflictTemplate.choices},this.promptHandler.addPrompt(i)),Craft.cp.runQueue()):(i.error?alert(Craft.t("app","Upload failed. The error message was: “{error}”",{error:i.error})):alert(Craft.t("app","Upload failed for {filename}.",{filename:s})),a=!1),this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.setIndexAvailable(),this.promptHandler.getPromptCount()?this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this)):a&&this._updateAfterUpload())},_onUploadFailure:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.progressBar.hideProgressBar(),this.setIndexAvailable())},_updateAfterUpload:function(){"index"!==this.settings.context&&(this.clearSearch(),this.setSortAttribute("dateCreated"),this.setSortDirection("desc")),this.updateElements()},_uploadFollowup:function(t){var e=this;this.setIndexBusy(),this.progressBar.resetProgressBar(),this.promptHandler.resetPrompts(),this.progressBar.setItemCount(t.length),this.progressBar.showProgressBar(),function t(i,s,a){var n={},r=null,o=function(n,r){"success"===r&&n.assetId?e.selectElementAfterUpdate(n.assetId):n.error&&alert(n.error),s++,e.progressBar.incrementProcessedItemCount(1),e.progressBar.updateProgressBar(),s===i.length?a():t(i,s,a)};"replace"===i[s].choice?(r="assets/replace-file",n.sourceAssetId=i[s].assetId,i[s].conflictingAssetId?n.assetId=i[s].conflictingAssetId:n.targetFilename=i[s].filename):"cancel"===i[s].choice&&(r="assets/delete-asset",n.assetId=i[s].assetId),r?Craft.postActionRequest(r,n,o):o({assetId:i[s].assetId},"success")}(t,0,(function(){e.progressBar.hideProgressBar(),e.setIndexAvailable(),e._updateAfterUpload()}))},onUpdateElements:function(){var t=this;this._onUpdateElements(!1,this.view.getAllElements()),this.view.on("appendElements",(function(e){t._onUpdateElements(!0,e.newElements)})),this.base()},_onUpdateElements:function(t,e){"index"===this.settings.context&&(t||this._assetDrag.removeAllItems(),this._assetDrag.addItems(e.has("div.element[data-movable]"))),this.base(t,e),this.removeListener(this.$elements,"keydown"),this.addListener(this.$elements,"keydown",this._onKeyDown.bind(this)),this.view.elementSelect.on("focusItem",this._onElementFocus.bind(this))},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var e=this.view.elementSelect.$focusedItem.find(".element");e.length&&this._loadPreview(e)}return t.stopPropagation(),!1}},_onElementFocus:function(t){var e=$(t.item).find(".element");Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.view.elementSelect,e)},_onDragStart:function(){this._tempExpandedFolders=[]},_getFileDragHelper:function(t){var e,i;switch(this.getSelectedSourceState("mode")){case"table":e=$('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),i=$('<div class="tableview"/>').appendTo(e);var s=$('<table class="data"/>').appendTo(i),a=$("<tbody/>").appendTo(s);t.appendTo(a),this._$firstRowCells=this.view.$table.children("tbody").children("tr:first").children();for(var n=t.children(),r=0;r<n.length;r++){var o=$(n[r]);if(o.hasClass("checkbox-cell"))o.remove(),e.css("margin-"+Craft.left,19);else{var l=$(this._$firstRowCells[r]),h=l.width();l.width(h),o.width(h)}}return e;case"thumbs":return e=$('<div class="elements thumbviewhelper"/>').appendTo(Garnish.$bod),i=$('<ul class="thumbsview"/>').appendTo(e),t.appendTo(i),e}return $()},_onDropTargetChange:function(t){if(clearTimeout(this._expandDropTargetFolderTimeout),t){var e=t.data("folder-id");e?(this.dropTargetFolder=this._getSourceByKey(e),this._hasSubfolders(this.dropTargetFolder)&&!this._isExpanded(this.dropTargetFolder)&&(this._expandDropTargetFolderTimeout=setTimeout(this._expandFolder.bind(this),500))):this.dropTargetFolder=null}t&&t[0]!==this.$source[0]?this.$source.removeClass("sel"):this.$source.addClass("sel")},_collapseExtraExpandedFolders:function(t){var e;clearTimeout(this._expandDropTargetFolderTimeout),t&&(e=this._getSourceByKey(t).parents("li").children("a"));for(var i=this._tempExpandedFolders.length-1;i>=0;i--){var s=this._tempExpandedFolders[i];void 0!==e&&0!==e.filter('[data-key="'+s.data("key")+'"]').length||(this._collapseFolder(s),this._tempExpandedFolders.splice(i,1))}},_getSourceByKey:function(t){return this.$sources.filter('[data-key$="'+t+'"]')},_hasSubfolders:function(t){return t.siblings("ul").find("li").length},_isExpanded:function(t){return t.parent("li").hasClass("expanded")},_expandFolder:function(){this._collapseExtraExpandedFolders(this.dropTargetFolder.data("folder-id")),this.dropTargetFolder.siblings(".toggle").trigger("click"),this._tempExpandedFolders.push(this.dropTargetFolder)},_collapseFolder:function(t){t.parent().hasClass("expanded")&&t.siblings(".toggle").trigger("click")},_createFolderContextMenu:function(t){var e=this;if(this._getFolderUidFromSourceKey(t.data("key"))){var i=[{label:Craft.t("app","New subfolder"),onClick:function(){e._createSubfolder(t)}}];"index"===this.settings.context&&this._getSourceLevel(t)>1&&(i.push({label:Craft.t("app","Rename folder"),onClick:function(){e._renameFolder(t)}}),i.push({label:Craft.t("app","Delete folder"),onClick:function(){e._deleteFolder(t)}})),new Garnish.ContextMenu(t,i,{menuClass:"menu"})}},_createSubfolder:function(t){var e=this,i=prompt(Craft.t("app","Enter the name of the folder"));if(i){var s={parentId:t.data("folder-id"),folderName:i};this.setIndexBusy(),Craft.postActionRequest("assets/create-folder",s,(function(i,s){if(e.setIndexAvailable(),"success"===s&&i.success){e._prepareParentForChildren(t);var a=$('<li><a data-key="'+t.data("key")+"/folder:"+i.folderUid+'"'+(Garnish.hasAttr(t,"data-has-thumbs")?" data-has-thumbs":"")+' data-folder-id="'+i.folderId+'"'+(Garnish.hasAttr(t,"data-can-upload")?" data-can-upload":"")+(Garnish.hasAttr(t,"data-can-move-to")?" data-can-move-to":"")+(Garnish.hasAttr(t,"data-can-move-peer-files-to")?" data-can-move-peer-files-to":"")+">"+i.folderName+"</a></li>"),n=a.children("a:first");e._appendSubfolder(t,a),e.initSource(n)}"success"===s&&i.error&&alert(i.error)}))}},_deleteFolder:function(t){var e=this;if(confirm(Craft.t("app","Really delete folder “{folder}”?",{folder:$.trim(t.text())}))){var i={folderId:t.data("folder-id")};this.setIndexBusy(),Craft.postActionRequest("assets/delete-folder",i,(function(i,s){if(e.setIndexAvailable(),"success"===s&&i.success){var a=e._getParentSource(t);e.deinitSource(t),t.parent().remove(),e._cleanUpTree(a)}"success"===s&&i.error&&alert(i.error)}))}},_renameFolder:function(t){var e=this,i=t.children(".label"),s=Craft.trim(i.text()),a=prompt(Craft.t("app","Rename folder"),s);a&&a!==s&&(this.setIndexBusy(),Craft.sendActionRequest("POST","assets/rename-folder",{data:{folderId:t.data("folder-id"),newName:a}}).then((function(s){s.data.success?(i.text(s.data.newName),t.data("key")===e.$source.data("key")&&(e.updateElements(),"index"===e.settings.context&&e._updateUrl(t))):s.data.error&&alert(s.data.error)})).finally((function(){e.setIndexAvailable()})))},_prepareParentForChildren:function(t){this._hasSubfolders(t)||(t.parent().addClass("expanded").append('<div class="toggle"></div><ul></ul>'),this.initSourceToggle(t))},_appendSubfolder:function(t,e){for(var i=t.siblings("ul").children("li"),s=$.trim(e.children("a:first").text()),a=!1,n=0;n<i.length;n++){var r=$(i[n]);if($.trim(r.children("a:first").text())>s){r.before(e),a=!0;break}}a||t.siblings("ul").append(e)},_cleanUpTree:function(t){null!==t&&0===t.siblings("ul").children("li").length&&(this.deinitSourceToggle(t),t.siblings("ul").remove(),t.siblings(".toggle").remove(),t.parent().removeClass("expanded"))},_positionProgressBar:function(){this.progressBar||(this.progressBar=new Craft.ProgressBar(this.$main,!0));var t=$(),e=0,i=0;"index"===this.settings.context?(t=this.progressBar.$progressBar.closest("#content"),e=Garnish.$win.scrollTop()):(t=this.progressBar.$progressBar.closest(".main"),e=this.$main.scrollTop());var s=e-t.offset().top,a=Garnish.$win.height();i=t.height()>a?a/2-6+s:t.height()/2-6,"index"!==this.settings.context&&(i=e+(t.height()/2-6)),this.progressBar.$progressBar.css({top:i})},_performBatchRequests:function(t,e){for(var i=this,s=[],a=t.length;t.length;){var n=t.shift();Craft.sendActionRequest("POST",n.action,{data:n.params}).then((function(t){s.push(t.data)})).finally((function(){i.progressBar.incrementProcessedItemCount(1),i.progressBar.updateProgressBar(),0==--a&&(Craft.cp.runQueue(),e(s))}))}}}),Craft.registerElementIndexClass("craft\\elements\\Asset",Craft.AssetIndex)},5077:function(){Craft.AssetSelectInput=Craft.BaseElementSelectInput.extend({requestId:0,hud:null,$uploadBtn:null,uploader:null,progressBar:null,init:function(){this.base.apply(this,arguments),this.settings.canUpload&&this._attachUploader(),this.addListener(this.$elementsContainer,"keydown",this._onKeyDown.bind(this)),this.elementSelect.on("focusItem",this._onElementFocus.bind(this))},_onKeyDown:function(t){if(t.keyCode===Garnish.SPACE_KEY&&t.shiftKey){if(Craft.PreviewFileModal.openInstance)Craft.PreviewFileModal.openInstance.selfDestruct();else{var e=this.elementSelect.$focusedItem;e.length&&this._loadPreview(e)}return t.stopPropagation(),!1}},_onElementFocus:function(t){var e=$(t.item);Craft.PreviewFileModal.openInstance&&e.length&&this._loadPreview(e)},_loadPreview:function(t){var e={};t.data("image-width")&&(e.startingWidth=t.data("image-width"),e.startingHeight=t.data("image-height")),new Craft.PreviewFileModal(t.data("id"),this.elementSelect,e)},createElementEditor:function(t){return this.base(t,{params:{defaultFieldLayoutId:this.settings.defaultFieldLayoutId},input:this})},_attachUploader:function(){var t=this;this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var e={url:Craft.getActionUrl("assets/upload"),dropZone:this.$container,formData:{fieldId:this.settings.fieldId}};this.settings.sourceElementId&&(e.formData.elementId=this.settings.sourceElementId),this.settings.criteria.siteId&&(e.formData.siteId=this.settings.criteria.siteId),this.$addElementBtn&&(this.$uploadBtn=$("<button/>",{type:"button",class:"btn dashed","data-icon":"upload","aria-label":1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files"),"aria-describedby":this.settings.describedBy,text:1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files")}).insertAfter(this.$addElementBtn),e.fileInput=$("<input/>",{type:"file",class:"hidden",multiple:1!=this.settings.limit}).insertAfter(this.$uploadBtn),Garnish.$win.trigger("resize")),void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(e.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),void 0!==this.settings.criteria.kind&&(e.allowedKinds=this.settings.criteria.kind),e.canAddMoreFiles=this.canAddMoreFiles.bind(this),e.events={},e.events.fileuploadstart=this._onUploadStart.bind(this),e.events.fileuploadprogressall=this._onUploadProgress.bind(this),e.events.fileuploaddone=this._onUploadComplete.bind(this),e.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,e),this.$uploadBtn&&this.$uploadBtn.on("click",(function(e){t.$uploadBtn.next("input[type=file]").trigger("click")}))},refreshThumbnail:function(t){var e=this,i={elementId:t,siteId:this.settings.criteria.siteId,size:this.settings.viewMode};Craft.postActionRequest("elements/get-element-html",i,(function(i){if(i.error)alert(i.error);else{var s=e.$elements.filter('[data-id="'+t+'"]');s.find(".elementthumb").replaceWith($(i.html).find(".elementthumb")),e.thumbLoader.load(s)}}))},selectUploadedFile:function(t){if(this.canAddMoreElements()){var e=t.$element;e.addClass("removable"),e.prepend('<input type="hidden" name="'+this.settings.name+'[]" value="'+t.id+'"><a class="delete icon" title="'+Craft.t("app","Remove")+'"></a>'),e.appendTo(this.$elementsContainer);var i=-(e.outerWidth()+10);this.$addElementBtn.css("margin-"+Craft.left,i+"px");var s={};s["margin-"+Craft.left]=0,this.$addElementBtn.velocity(s,"fast"),this.addElements(e),delete this.modal}},_onUploadStart:function(){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){var i=this;if(e.result.error)alert(e.result.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading");else{var s={elementId:e.result.assetId,siteId:this.settings.criteria.siteId,size:this.settings.viewMode};Craft.postActionRequest("elements/get-element-html",s,(function(t){if(t.error)alert(t.error);else{var e=$(t.html);Craft.appendHeadHtml(t.headHtml),i.selectUploadedFile(Craft.getElementInfo(e))}i.uploader.isLastUpload()&&(i.progressBar.hideProgressBar(),i.$container.removeClass("uploading"),window.draftEditor&&window.draftEditor.checkForm())})),Craft.cp.runQueue()}},_onUploadFailure:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},canAddMoreFiles:function(t){return!this.settings.limit||this.$elements.length+t<this.settings.limit}})},4606:function(){Craft.AssetSelectorModal=Craft.BaseElementSelectorModal.extend({$selectTransformBtn:null,_selectedTransform:null,init:function(t,e){e=$.extend({},Craft.AssetSelectorModal.defaults,e),this.base(t,e),e.transforms.length&&this.createSelectTransformButton(e.transforms)},createSelectTransformButton:function(t){if(t&&t.length){var e=$('<div class="btngroup"/>').appendTo(this.$primaryButtons);this.$selectBtn.appendTo(e),this.$selectTransformBtn=$("<button/>",{type:"button",class:"btn menubtn disabled",text:Craft.t("app","Select transform")}).appendTo(e);for(var i=$('<div class="menu" data-align="right"></div>').insertAfter(this.$selectTransformBtn),s=$("<ul></ul>").appendTo(i),a=0;a<t.length;a++)$('<li><a data-transform="'+t[a].handle+'">'+t[a].name+"</a></li>").appendTo(s);var n=new Garnish.MenuBtn(this.$selectTransformBtn,{onOptionSelect:this.onSelectTransform.bind(this)});n.disable(),this.$selectTransformBtn.data("menuButton",n)}},onSelectionChange:function(t){var e=this.elementIndex.getSelectedElements(),i=!1;if(e.length&&this.settings.transforms.length){i=!0;for(var s=0;s<e.length&&$(".element.hasthumb:first",e[s]).length;s++);}var a=null;this.$selectTransformBtn&&(a=this.$selectTransformBtn.data("menuButton")),i?(a&&a.enable(),this.$selectTransformBtn.removeClass("disabled")):this.$selectTransformBtn&&(a&&a.disable(),this.$selectTransformBtn.addClass("disabled")),this.base()},onSelectTransform:function(t){var e=$(t).data("transform");this.selectImagesWithTransform(e)},selectImagesWithTransform:function(t){var e=this;void 0===Craft.AssetSelectorModal.transformUrls[t]&&(Craft.AssetSelectorModal.transformUrls[t]={});for(var i=this.elementIndex.getSelectedElements(),s=[],a=0;a<i.length;a++){var n=$(i[a]),r=Craft.getElementInfo(n).id;void 0===Craft.AssetSelectorModal.transformUrls[t][r]&&s.push(r)}s.length?(this.showFooterSpinner(),this.fetchMissingTransformUrls(s,t,(function(){e.hideFooterSpinner(),e.selectImagesWithTransform(t)}))):(this._selectedTransform=t,this.selectElements(),this._selectedTransform=null)},fetchMissingTransformUrls:function(t,e,i){var s=this,a=t.pop(),n={assetId:a,handle:e};Craft.postActionRequest("assets/generate-transform",n,(function(n,r){Craft.AssetSelectorModal.transformUrls[e][a]=!1,"success"===r&&n.url&&(Craft.AssetSelectorModal.transformUrls[e][a]=n.url),t.length?s.fetchMissingTransformUrls(t,e,i):i()}))},getElementInfo:function(t){var e=this.base(t);if(this._selectedTransform)for(var i=0;i<e.length;i++){var s=e[i].id;void 0!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&!1!==Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s]&&(e[i].url=Craft.AssetSelectorModal.transformUrls[this._selectedTransform][s])}return e},onSelect:function(t){this.settings.onSelect(t,this._selectedTransform)}},{defaults:{canSelectImageTransforms:!1,transforms:[]},transformUrls:{}}),Craft.registerElementSelectorModalClass("craft\\elements\\Asset",Craft.AssetSelectorModal)},9222:function(){Craft.AuthManager=Garnish.Base.extend({remainingSessionTime:null,checkRemainingSessionTimer:null,showLoginModalTimer:null,decrementLogoutWarningInterval:null,showingLogoutWarningModal:!1,showingLoginModal:!1,logoutWarningModal:null,loginModal:null,$logoutWarningPara:null,$passwordInput:null,$passwordSpinner:null,$loginBtn:null,$loginErrorPara:null,submitLoginIfLoggedOut:!1,init:function(){this.updateRemainingSessionTime(Craft.remainingSessionTime)},setCheckRemainingSessionTimer:function(t){this.checkRemainingSessionTimer&&clearTimeout(this.checkRemainingSessionTimer),this.checkRemainingSessionTimer=setTimeout(this.checkRemainingSessionTime.bind(this),1e3*t)},checkRemainingSessionTime:function(t){var e=this;$.ajax({url:Craft.getActionUrl("users/session-info",t?null:"dontExtendSession=1"),type:"GET",dataType:"json",complete:function(t,i){"success"===i?(void 0!==t.responseJSON.csrfTokenValue&&void 0!==Craft.csrfTokenValue&&(Craft.csrfTokenValue=t.responseJSON.csrfTokenValue),e.updateRemainingSessionTime(t.responseJSON.timeout),e.submitLoginIfLoggedOut=!1):e.updateRemainingSessionTime(-1)}})},updateRemainingSessionTime:function(t){this.remainingSessionTime=parseInt(t),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime?(this.remainingSessionTime?(this.showingLogoutWarningModal||this.showLogoutWarningModal(),this.remainingSessionTime<Craft.AuthManager.checkInterval&&(this.showLoginModalTimer&&clearTimeout(this.showLoginModalTimer),this.showLoginModalTimer=setTimeout(this.showLoginModal.bind(this),1e3*this.remainingSessionTime))):this.showingLoginModal?this.submitLoginIfLoggedOut&&this.submitLogin():this.showLoginModal(),this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval)):(this.hideLogoutWarningModal(),this.hideLoginModal(),-1!==this.remainingSessionTime&&this.remainingSessionTime<Craft.AuthManager.minSafeSessionTime+Craft.AuthManager.checkInterval?this.setCheckRemainingSessionTimer(this.remainingSessionTime-Craft.AuthManager.minSafeSessionTime+1):this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval))},showLogoutWarningModal:function(){var t;if(this.showingLoginModal?(this.hideLoginModal(!0),t=!0):t=!1,this.showingLogoutWarningModal=!0,!this.logoutWarningModal){var e=$('<form id="logoutwarningmodal" class="modal alert fitted"/>'),i=$('<div class="body"/>').appendTo(e),s=$('<div class="buttons right"/>').appendTo(i),a=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Log out now")}).appendTo(s),n=$("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Keep me logged in")}).appendTo(s);this.$logoutWarningPara=$("<p/>").prependTo(i),this.logoutWarningModal=new Garnish.Modal(e,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark logoutwarningmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){n.trigger("focus")}),100)}}),this.addListener(a,"activate","logout"),this.addListener(e,"submit","renewSession")}t?this.logoutWarningModal.quickShow():this.logoutWarningModal.show(),this.updateLogoutWarningMessage(),this.decrementLogoutWarningInterval=setInterval(this.decrementLogoutWarning.bind(this),1e3)},updateLogoutWarningMessage:function(){this.$logoutWarningPara.text(Craft.t("app","Your session will expire in {time}.",{time:Craft.secondsToHumanTimeDuration(this.remainingSessionTime)})),this.logoutWarningModal.updateSizeAndPosition()},decrementLogoutWarning:function(){this.remainingSessionTime>0&&(this.remainingSessionTime--,this.updateLogoutWarningMessage()),0===this.remainingSessionTime&&clearInterval(this.decrementLogoutWarningInterval)},hideLogoutWarningModal:function(t){this.showingLogoutWarningModal=!1,this.logoutWarningModal&&(t?this.logoutWarningModal.quickHide():this.logoutWarningModal.hide(),this.decrementLogoutWarningInterval&&clearInterval(this.decrementLogoutWarningInterval))},showLoginModal:function(){var t,e=this;if(this.showingLogoutWarningModal?(this.hideLogoutWarningModal(!0),t=!0):t=!1,this.showingLoginModal=!0,!this.loginModal){var i=$('<form id="loginmodal" class="modal alert fitted"/>'),s=$('<div class="body"><h2>'+Craft.t("app","Your session has ended.")+"</h2><p>"+Craft.t("app","Enter your password to log back in.")+"</p></div>").appendTo(i),a=$('<div class="inputcontainer">').appendTo(s),n=$('<div class="flex"/>').appendTo(a),r=$('<div class="flex-grow"/>').appendTo(n),o=$("<div/>").appendTo(n),l=$('<div class="passwordwrapper"/>').appendTo(r);this.$passwordInput=$('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'"/>').appendTo(l),this.$passwordSpinner=$('<div class="spinner hidden"/>').appendTo(a),this.$loginBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Login")}).appendTo(o),this.$loginErrorPara=$('<p class="error"/>').appendTo(s),this.loginModal=new Garnish.Modal(i,{autoShow:!1,closeOtherModals:!1,hideOnEsc:!1,hideOnShadeClick:!1,shadeClass:"modal-shade dark loginmodalshade",onFadeIn:function(){Garnish.isMobileBrowser(!0)||setTimeout((function(){e.$passwordInput.trigger("focus")}),100)},onFadeOut:function(){e.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(t){e.$passwordInput=t}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(i,"submit","login")}t?this.loginModal.quickShow():this.loginModal.show()},hideLoginModal:function(t){this.showingLoginModal=!1,this.loginModal&&(t?this.loginModal.quickHide():this.loginModal.hide())},logout:function(){$.get({url:Craft.getActionUrl("users/logout"),dataType:"json",success:function(){Craft.redirectTo("")}})},renewSession:function(t){t&&t.preventDefault(),this.hideLogoutWarningModal(),this.checkRemainingSessionTime(!0)},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$loginBtn.removeClass("disabled"),!0):(this.$loginBtn.addClass("disabled"),!1)},login:function(t){t&&t.preventDefault(),this.validatePassword()&&(this.$passwordSpinner.removeClass("hidden"),this.clearLoginError(),void 0!==Craft.csrfTokenValue?(this.submitLoginIfLoggedOut=!0,this.checkRemainingSessionTime()):this.submitLogin())},submitLogin:function(){var t=this,e={loginName:Craft.username,password:this.$passwordInput.val()};Craft.postActionRequest("users/login",e,(function(e,i){t.$passwordSpinner.addClass("hidden"),"success"===i?e.success?(t.hideLoginModal(),t.checkRemainingSessionTime()):(t.showLoginError(e.error),Garnish.shake(t.loginModal.$container),Garnish.isMobileBrowser(!0)||t.$passwordInput.trigger("focus")):t.showLoginError()}))},showLoginError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$loginErrorPara.text(t),this.loginModal.updateSizeAndPosition()},clearLoginError:function(){this.showLoginError("")}},{checkInterval:60,minSafeSessionTime:120})},1504:function(){function t(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Craft.BaseElementEditor=Garnish.Base.extend({$element:null,elementId:null,siteId:null,deltaNames:null,initialData:null,$header:null,$toolbar:null,$tabContainer:null,$editLink:null,$sidebarBtn:null,$loadSpinner:null,$body:null,$fieldsContainer:null,$sidebar:null,$footer:null,$siteSelectContainer:null,$siteSelect:null,$siteSpinner:null,$cancelBtn:null,$saveBtn:null,$saveSpinner:null,slideout:null,tabManager:null,showingSidebar:!1,cancelToken:null,ignoreFailedRequest:!1,initialDeltaValues:null,init:function(t,e){var i=this;void 0===e&&$.isPlainObject(t)&&(e=t,t=null),this.$element=$(t),this.setSettings(e,Craft.BaseElementEditor.defaults),this.$header=$("<header/>",{class:"pane-header"}),this.$toolbar=$("<div/>",{class:"ee-toolbar"}).appendTo(this.$header),this.$tabContainer=$("<div/>",{class:"pane-tabs"}).appendTo(this.$toolbar),this.$loadSpinner=$("<div/>",{class:"spinner",title:Craft.t("app","Loading"),"aria-label":Craft.t("app","Loading")}).appendTo(this.$toolbar),this.$editLink=$("<a/>",{target:"_blank",class:"btn hidden",title:Craft.t("app","Open the full edit page in a new tab"),"aria-label":Craft.t("app","Open the full edit page in a new tab"),"data-icon":"external"}).appendTo(this.$toolbar),this.$sidebarBtn=$("<button/>",{type:"button",class:"btn hidden sidebar-btn",title:Craft.t("app","Show sidebar"),"aria-label":Craft.t("app","Show sidebar"),"data-icon":"sidebar-".concat(Garnish.ltr?"right":"left")}).appendTo(this.$toolbar),this.addListener(this.$sidebarBtn,"click",(function(t){t.preventDefault(),i.showingSidebar?i.hideSidebar():i.showSidebar()})),this.$body=$("<div/>",{class:"ee-body"}),this.$fieldsContainer=$("<div/>",{class:"fields"}).appendTo(this.$body),this.$sidebar=$("<div/>",{class:"ee-sidebar hidden"}).appendTo(this.$body),Craft.trapFocusWithin(this.$sidebar),this.$footer=$("<div/>",{class:"ee-footer hidden"});var s=$("<div/>",{class:"ee-site-select"}).appendTo(this.$footer);this.$siteSelectContainer=$("<div/>",{class:"select hidden"}).appendTo(s),this.$siteSelect=$("<select/>").appendTo(this.$siteSelectContainer),this.$siteSpinner=$("<div/>",{class:"spinner hidden"}).appendTo(s),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footer),this.$saveBtn=$("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Save")}).appendTo(this.$footer),this.$saveSpinner=$("<div/>",{class:"spinner hidden"}).appendTo(this.$footer);var a=this.$header.add(this.$body).add(this.$footer);this.slideout=new Craft.Slideout(a,{containerElement:"form",containerAttributes:{action:"",method:"post",novalidate:"",class:"element-editor"},closeOnEsc:!1,closeOnShadeClick:!1}),this.slideout.$container.data("elementEditor",this),this.slideout.on("beforeClose",(function(){i.hideSidebar()})),this.slideout.on("close",(function(){i.trigger("closeSlideout"),i.destroy()})),Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0},(function(){i.saveElement()})),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){i.maybeCloseSlideout()})),this.addListener(this.$cancelBtn,"click",(function(){i.maybeCloseSlideout()})),this.addListener(this.slideout.$shade,"click",(function(){i.maybeCloseSlideout()})),this.addListener(this.slideout.$container,"click",(function(t){var e=$(event.target);!i.showingSidebar||e.closest(i.$sidebarBtn).length||e.closest(i.$sidebar).length||i.hideSidebar()})),this.addListener(this.slideout.$container,"submit",(function(t){t.preventDefault(),i.saveElement()})),this.addListener(this.$siteSelect,"change","switchSite"),this.load().then((function(){i.onShowHud(),i.onCreateForm(i.$body)}))},setElementAttribute:function(t,e){this.settings.attributes||(this.settings.attributes={}),null===e?delete this.settings.attributes[t]:this.settings.attributes[t]=e},getBaseData:function(){var t=$.extend({},this.settings.params);return this.settings.siteId?t.siteId=this.settings.siteId:this.$element&&this.$element.data("site-id")&&(t.siteId=this.$element.data("site-id")),this.settings.elementId?t.elementId=this.settings.elementId:this.$element&&this.$element.data("id")&&(t.elementId=this.$element.data("id")),this.settings.elementType&&(t.elementType=this.settings.elementType),this.settings.attributes&&(t.attributes=this.settings.attributes),this.settings.prevalidate&&(t.prevalidate=1),t},load:function(t,e){var i=this;return new Promise((function(s,a){i.trigger("beforeLoad"),i.trigger("beginLoading"),i.showLoadSpinner(),i.onBeginLoading(),i.cancelToken&&(i.ignoreFailedRequest=!0,i.cancelToken.cancel()),i.cancelToken=axios.CancelToken.source(),Craft.sendActionRequest("POST","elements/get-editor-html",{cancelToken:i.cancelToken.token,data:$.extend(i.getBaseData(),t||{},{includeSites:Craft.isMultiSite&&i.settings.showSiteSwitcher})}).then((function(t){i.hideLoadSpinner(),i.trigger("load"),i.trigger("endLoading"),i.onEndLoading(),i.cancelToken=null,null===i.initialDeltaValues&&(i.initialDeltaValues=t.data.initialDeltaValues),i.updateForm(t.data,e),i.cancelToken=null,s()})).catch((function(t){i.hideLoadSpinner(),i.onEndLoading(),i.cancelToken=null,i.ignoreFailedRequest||(Craft.cp.displayError(),a(t)),i.ignoreFailedRequest=!1}))}))},showHeader:function(){this.$header.removeClass("hidden")},hideHeader:function(){this.$header.addClass("hidden")},showLoadSpinner:function(){this.showHeader(),this.$loadSpinner.removeClass("hidden")},hideLoadSpinner:function(){this.$loadSpinner.addClass("hidden")},switchSite:function(){var t=this;if(!this.isDirty()||confirm(Craft.t("app","Switching sites will lose unsaved changes. Are you sure you want to switch sites?"))){var e=this.$siteSelect.val();e!=this.siteId&&(this.$siteSpinner.removeClass("hidden"),this.load({siteId:e}).then((function(){t.$siteSpinner.addClass("hidden")})).catch((function(){t.$siteSpinner.addClass("hidden"),t.$siteSelect.val(t.siteId)})))}else this.$siteSelect.val(this.siteId)},updateForm:function(t,e){var i=this;this.tabManager&&(this.$tabContainer.html(""),this.tabManager.destroy(),this.tabManager=null),e=!1!==e,this.siteId=t.siteId,this.$fieldsContainer.html(t.fieldHtml);var s=!1;if(t.sites&&t.sites.length>1){s=!0,this.$siteSelectContainer.removeClass("hidden"),this.$siteSelect.html("");for(var a=0;a<t.sites.length;a++){var n=t.sites[a],r=$("<option/>",{value:n.id,text:n.name}).appendTo(this.$siteSelect);n.id==t.siteId&&r.attr("selected","selected")}}else this.$siteSelectContainer.addClass("hidden");t.tabHtml&&(s=!0,this.$tabContainer.replaceWith(this.$tabContainer=$(t.tabHtml)),this.tabManager=new Craft.Tabs(this.$tabContainer),this.tabManager.on("deselectTab",(function(t){$(t.$tab.attr("href")).addClass("hidden")})),this.tabManager.on("selectTab",(function(t){$(t.$tab.attr("href")).removeClass("hidden"),Garnish.$win.trigger("resize"),i.$body.trigger("scroll")}))),t.editUrl?(s=!0,this.$editLink.removeClass("hidden").attr("href",t.editUrl)):this.$editLink&&this.$editLink.addClass("hidden"),t.sidebarHtml?(s=!0,this.$sidebarBtn.removeClass("hidden"),this.$sidebar.html(t.sidebarHtml),Craft.initUiElements(this.$sidebar),(new Craft.ElementThumbLoader).load($(this.$sidebar)),this.$sidebar.find("a").each((function(){this.hostname.length&&void 0===$(this).attr("target")&&$(this).attr("target","_blank")}))):this.$sidebarBtn&&(this.$sidebarBtn.addClass("hidden"),this.$sidebar.addClass("hidden")),s?this.showHeader():this.hideHeader(),this.$footer.removeClass("hidden"),e&&(this.deltaNames=t.deltaNames),Garnish.requestAnimationFrame((function(){Craft.appendHeadHtml(t.headHtml),Craft.appendFootHtml(t.footHtml),Craft.initUiElements(i.$fieldsContainer),e&&(i.initialData=i.slideout.$container.serialize()),Garnish.isMobileBrowser()||Craft.setFocusWithin(i.$fieldsContainer),i.trigger("updateForm")}))},showSidebar:function(){var t=this;this.showingSidebar||(this.$body.scrollTop(0).addClass("no-scroll"),this.$sidebar.off("transitionend.element-editor").css(this._closedSidebarStyles()).removeClass("hidden"),this.$sidebar[0].offsetWidth,this.$sidebar.css(this._openedSidebarStyles()),Garnish.isMobileBrowser()||this.$sidebar.one("transitionend.element-editor",(function(){Craft.setFocusWithin(t.$sidebar)})),this.$sidebarBtn.addClass("active").attr({title:Craft.t("app","Hide sidebar"),"aria-label":Craft.t("app","Hide sidebar")}),Garnish.$win.trigger("resize"),this.$sidebar.trigger("scroll"),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.hideSidebar()})),this.showingSidebar=!0)},hideSidebar:function(){var t=this;this.showingSidebar&&(this.$body.removeClass("no-scroll"),this.$sidebar.off("transitionend.element-editor").css(this._closedSidebarStyles()).one("transitionend.element-editor",(function(){t.$sidebar.addClass("hidden")})),this.$sidebarBtn.removeClass("active").attr({title:Craft.t("app","Show sidebar"),"aria-label":Craft.t("app","Show sidebar")}),Garnish.uiLayerManager.removeLayer(),this.showingSidebar=!1)},_openedSidebarStyles:function(){return t({},Garnish.ltr?"right":"left","0")},_closedSidebarStyles:function(){return t({},Garnish.ltr?"right":"left","-350px")},saveElement:function(){var t=this,e=this.settings.validators;if($.isArray(e))for(var i=0;i<e.length;i++)if($.isFunction(e[i])&&!e[i].call())return!1;this.$saveSpinner.removeClass("hidden");var s=$.param(this.getBaseData())+"&"+this.slideout.$container.serialize();s=Craft.findDeltaData(this.initialData,s,this.deltaNames,null,this.initialDeltaValues),Craft.postActionRequest("elements/save-element",s,(function(e,i){if(t.$saveSpinner.addClass("hidden"),"success"===i)if(e.success){if(t.$element&&t.siteId==t.$element.data("site-id")){var s=t.$element.find(".title"),a=s.find("a");a.length&&e.cpEditUrl?(a.attr("href",e.cpEditUrl),a.text(e.newTitle)):s.text(e.newTitle)}t.settings.elementType&&Craft.elementTypeNames[t.settings.elementType]&&Craft.cp.displayNotice(Craft.t("app","{type} saved.",{type:Craft.elementTypeNames[t.settings.elementType][0]})),t.closeSlideout(),t.trigger("saveElement",{response:e}),t.onSaveElement(e),t.settings.onSaveElement(e),Craft.cp.runQueue()}else t.updateForm(e,!1),Garnish.shake(t.slideout.$container)}))},isDirty:function(){return null!==this.initialData&&this.slideout.$container.serialize()!==this.initialData},maybeCloseSlideout:function(){this.slideout.isOpen&&(this.isDirty()&&!confirm(Craft.t("app","Are you sure you want to close the editor? Any changes will be lost."))||this.closeSlideout())},closeSlideout:function(){this.slideout.close(),this.onHideHud(),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel())},destroy:function(){this.slideout.destroy(),delete this.slideout,this.base()},loadHud:function(){this.load()},maybeCloseHud:function(){this.maybeCloseSlideout()},closeHud:function(){this.closeSlideout()},reloadForm:function(t,e){this.load(t).then((function(){e("success")})).catch((function(){e("error")}))},onBeginLoading:function(){this.settings.onBeginLoading()},onEndLoading:function(){this.settings.onEndLoading()},onSaveElement:function(t){},onCreateForm:function(t){this.settings.onCreateForm(t)},onShowHud:function(){this.trigger("showHud"),this.settings.onShowHud()},onHideHud:function(){this.trigger("hideHud"),this.settings.onHideHud()}},{defaults:{showSiteSwitcher:!0,elementId:null,elementType:null,siteId:null,attributes:null,params:null,prevalidate:!1,elementIndex:null,onSaveElement:$.noop,validators:[],onShowHud:$.noop,onHideHud:$.noop,onBeginLoading:$.noop,onEndLoading:$.noop,onCreateForm:$.noop}})},5774:function(){function t(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(t,i)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}Craft.BaseElementIndex=Garnish.Base.extend({initialized:!1,elementType:null,instanceState:null,sourceStates:null,sourceStatesStorageKey:null,searchTimeout:null,sourceSelect:null,$container:null,$main:null,isIndexBusy:!1,$sidebar:null,showingSidebar:null,sourceKey:null,sourceViewModes:null,$source:null,sourcesByKey:null,$visibleSources:null,$customizeSourcesBtn:null,customizeSourcesModal:null,$toolbar:null,toolbarOffset:null,$search:null,searching:!1,searchText:null,trashed:!1,drafts:!1,$clearSearchBtn:null,$statusMenuBtn:null,$statusMenuContainer:null,statusMenu:null,status:null,$siteMenuBtn:null,siteMenu:null,siteId:null,$sortMenuBtn:null,sortMenu:null,$sortAttributesList:null,$sortDirectionsList:null,$scoreSortAttribute:null,$structureSortAttribute:null,$elements:null,$viewModeBtnContainer:null,viewModeBtns:null,viewMode:null,view:null,_autoSelectElements:null,$countSpinner:null,$countContainer:null,page:1,resultSet:null,totalResults:null,$exportBtn:null,actions:null,actionsHeadHtml:null,actionsFootHtml:null,$selectAllContainer:null,$selectAllCheckbox:null,showingActionTriggers:!1,exporters:null,exportersByType:null,_$detachedToolbarItems:null,_$triggers:null,_ignoreFailedRequest:!1,_cancelToken:null,init:function(t,e,i){var s=this;if(this.elementType=t,this.$container=e,this.setSettings(i,Craft.BaseElementIndex.defaults),this.instanceState=this.getDefaultInstanceState(),this.sourceStates={},this.settings.storageKey&&$.extend(this.instanceState,Craft.getLocalStorage(this.settings.storageKey),{}),this.sourceStatesStorageKey="BaseElementIndex."+this.elementType+"."+this.settings.context,$.extend(this.sourceStates,Craft.getLocalStorage(this.sourceStatesStorageKey,{})),this.$main=this.$container.find(".main"),this.$toolbar=this.$container.find(this.settings.toolbarSelector),this.$statusMenuBtn=this.$toolbar.find(".statusmenubtn:first"),this.$statusMenuContainer=this.$statusMenuBtn.parent(),this.$siteMenuBtn=this.$container.find(".sitemenubtn:first"),this.$sortMenuBtn=this.$toolbar.find(".sortmenubtn:first"),this.$search=this.$toolbar.find(".search:first input:first"),this.$clearSearchBtn=this.$toolbar.find(".search:first > .clear"),this.$sidebar=this.$container.find(".sidebar:first"),this.$customizeSourcesBtn=this.$sidebar.find(".customize-sources"),this.$elements=this.$container.find(".elements:first"),this.$countSpinner=this.$container.find("#count-spinner"),this.$countContainer=this.$container.find("#count-container"),this.$exportBtn=this.$container.find("#export-btn"),this.settings.hideSidebar&&(this.$sidebar.hide(),$(".body, .content",this.$container).removeClass("has-sidebar")),this.initSources()){if(this.$customizeSourcesBtn.length&&this.addListener(this.$customizeSourcesBtn,"click","createCustomizeSourcesModal"),this.$statusMenuBtn.length&&(this.statusMenu=this.$statusMenuBtn.menubtn().data("menubtn").menu,this.statusMenu.on("optionselect",this._handleStatusChange.bind(this))),this.$siteMenuBtn.length){this.siteMenu=this.$siteMenuBtn.menubtn().data("menubtn").menu;var a=this.siteMenu.$options.filter(".sel:first");if(a.length||(a=this.siteMenu.$options.first()),a.length?this._setSite(a.data("site-id")):this.settings.criteria={id:"0"},this.siteMenu.on("optionselect",this._handleSiteChange.bind(this)),this.siteId){var n=this.settings.defaultSiteId||Craft.cp.getSiteId();if(n&&n!=this.siteId){var r=this.siteMenu.$options.filter('[data-site-id="'+n+'"]:first');r.length&&r.trigger("click")}}}else this.settings.criteria&&this.settings.criteria.siteId&&"*"!==this.settings.criteria.siteId?this._setSite(this.settings.criteria.siteId):this._setSite(Craft.siteId);this.settings.criteria&&this.settings.criteria.siteId&&delete this.settings.criteria.siteId,this.addListener(this.$search,"input",(function(){!s.searching&&s.$search.val()?s.startSearching():s.searching&&!s.$search.val()&&s.stopSearching(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.searchTimeout=setTimeout(s.updateElementsIfSearchTextChanged.bind(s),500)})),this.addListener(this.$search,"keypress",(function(t){t.keyCode===Garnish.RETURN_KEY&&(t.preventDefault(),s.searchTimeout&&clearTimeout(s.searchTimeout),s.updateElementsIfSearchTextChanged())})),this.addListener(this.$clearSearchBtn,"click",(function(){s.clearSearch(!0),Garnish.isMobileBrowser(!0)||s.$search.trigger("focus")})),Garnish.isMobileBrowser(!0)||this.$search.trigger("focus"),this.$sortMenuBtn.length&&(this.sortMenu=this.$sortMenuBtn.menubtn().data("menubtn").menu,this.$sortAttributesList=this.sortMenu.$container.children(".sort-attributes"),this.$sortDirectionsList=this.sortMenu.$container.children(".sort-directions"),this.sortMenu.on("optionselect",this._handleSortChange.bind(this))),this.addListener(this.$exportBtn,"click","_showExportHud"),this.initialized=!0,this.afterInit(),this.selectDefaultSource(),this.setPage(Craft.pageNum),this.updateElements(!0)}},afterInit:function(){this.onAfterInit()},_createCancelToken:function(){return this._cancelToken=axios.CancelToken.source(),this._cancelToken.token},_cancelRequests:function(){var t=this;this._cancelToken&&(this._ignoreFailedRequest=!0,this._cancelToken.cancel(),Garnish.requestAnimationFrame((function(){t._ignoreFailedRequest=!1})))},getSourceContainer:function(){return this.$sidebar.find("nav > ul")},get $sources(){if(this.sourceSelect)return this.sourceSelect.$items},getSite:function(){var t=this;if(this.siteId)return Craft.sites.find((function(e){return e.id==t.siteId}))},initSources:function(){var t=this._getSourcesInList(this.getSourceContainer());if(0===t.length)return!1;this.sourceSelect||(this.sourceSelect=new Garnish.Select(this.$sidebar.find("nav"),{multi:!1,allowEmpty:!1,vertical:!0,onSelectionChange:this._handleSourceSelectionChange.bind(this)})),this.sourcesByKey={};for(var e=0;e<t.length;e++)this.initSource($(t[e]));return!0},selectDefaultSource:function(){var t,e=this.getDefaultSourceKey();return e&&(t=this.getSourceByKey(e),-1===this.$visibleSources.index(t)&&(t=null)),e&&t||(t=this.$visibleSources.first()),this.selectSource(t)},refreshSources:function(){var t=this;this.sourceSelect.removeAllItems(),this.setIndexBusy(),Craft.sendActionRequest("POST",this.settings.refreshSourcesAction,{data:{context:this.settings.context,elementType:this.elementType}}).then((function(e){t.setIndexAvailable(),t.getSourceContainer().replaceWith(e.data.html),t.initSources(),t.selectDefaultSource()})).catch((function(){t.setIndexAvailable(),t._ignoreFailedRequest||Craft.cp.displayError(Craft.t("app","A server error occurred."))}))},initSource:function(t){this.sourceSelect.addItems(t),this.initSourceToggle(t),this.sourcesByKey[t.data("key")]=t,t.data("hasNestedSources")&&-1!==this.instanceState.expandedSources.indexOf(t.data("key"))&&this._expandSource(t)},initSourceToggle:function(t){this.deinitSourceToggle(t);var e=this._getSourceToggle(t);e.length?(this.addListener(t,"dblclick","_handleSourceDblClick"),this.addListener(e,"click","_handleSourceToggleClick"),t.data("hasNestedSources",!0)):t.data("hasNestedSources",!1)},deinitSource:function(t){this.sourceSelect.removeItems(t),this.deinitSourceToggle(t),delete this.sourcesByKey[t.data("key")]},deinitSourceToggle:function(t){t.data("hasNestedSources")&&(this.removeListener(t,"dblclick"),this.removeListener(this._getSourceToggle(t),"click")),t.removeData("hasNestedSources")},getDefaultInstanceState:function(){return{selectedSource:null,expandedSources:[]}},getDefaultSourceKey:function(){if(this.settings.defaultSource){for(var t=this.settings.defaultSource.split("/"),e="",i=0;i<t.length;i++){e+=t[i];var s=this.getSourceByKey(e);if(!s)return this.instanceState.selectedSource;this._expandSource(s),e+="/"}return this._setSite(this.siteId),this.settings.defaultSource}return this.instanceState.selectedSource},getDefaultExpandedSources:function(){return this.instanceState.expandedSources},startSearching:function(){this.$clearSearchBtn.removeClass("hidden"),this.$scoreSortAttribute||(this.$scoreSortAttribute=$('<li><a data-attr="score">'+Craft.t("app","Score")+"</a></li>"),this.sortMenu.addOptions(this.$scoreSortAttribute.children())),this.$scoreSortAttribute.prependTo(this.$sortAttributesList),this.searching=!0,this._updateStructureSortOption(),this.setSortAttribute("score")},clearSearch:function(t){this.searching&&(this.$search.val(""),this.searchTimeout&&clearTimeout(this.searchTimeout),this.stopSearching(),t?this.updateElementsIfSearchTextChanged():this.searchText=null)},stopSearching:function(){this.$clearSearchBtn.addClass("hidden"),this.$scoreSortAttribute.detach(),this.searching=!1,this._updateStructureSortOption()},setInstanceState:function(t,e){"object"===i(t)?$.extend(this.instanceState,t):this.instanceState[t]=e,this.storeInstanceState()},storeInstanceState:function(){this.settings.storageKey&&Craft.setLocalStorage(this.settings.storageKey,this.instanceState)},getSourceState:function(t,e,i){return void 0===this.sourceStates[t]&&(this.sourceStates[t]={}),void 0===e?this.sourceStates[t]:void 0!==this.sourceStates[t][e]?this.sourceStates[t][e]:void 0!==i?i:null},getSelectedSourceState:function(t,e){return this.getSourceState(this.instanceState.selectedSource,t,e)},setSelecetedSourceState:function(t,e){var s=this.getSelectedSourceState();"object"===i(t)?$.extend(s,t):s[t]=e,this.sourceStates[this.instanceState.selectedSource]=s,Craft.setLocalStorage(this.sourceStatesStorageKey,this.sourceStates)},storeSortAttributeAndDirection:function(){var e=this.getSelectedSortAttribute();if("score"!==e){var i=[];if(e){var s=[e],a=this.getSelectedSourceState("order");a&&a!==e&&(i.push([a,this.getSelectedSourceState("sort")]),s.push(a));for(var n=this.getSelectedSourceState("orderHistory",[]),r=0;r<n.length;r++){var o=t(n[r],1)[0];if(!o||s.includes(o))break;i.push(n[r]),s.push(o)}}this.setSelecetedSourceState({order:e,sort:this.getSelectedSortDirection(),orderHistory:i})}},setPage:function(t){if("index"===this.settings.context){t=Math.max(t,1),this.page=t;var e=document.location.href.replace(/\?.*$/,"").replace(new RegExp("/"+Craft.pageTrigger.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\d+$"),"").replace(/\/+$/,"");1!==this.page&&("?"!==Craft.pageTrigger[0]&&(e+="/"),e+=Craft.pageTrigger+this.page),history.replaceState({},"",e)}},_resetCount:function(){this.resultSet=null,this.totalResults=null},getViewParams:function(){var t={siteId:this.siteId,search:this.searchText,offset:this.settings.batchSize*(this.page-1),limit:this.settings.batchSize};this.settings.canHaveDrafts&&(this.drafts||"index"===this.settings.context&&!this.status)&&(t.drafts=this.drafts||null,t.savedDraftsOnly=!0,this.drafts||(t.draftOf=!1)),this.trashed&&(t.trashed=!0),Garnish.hasAttr(this.$source,"data-override-status")||(t.status=this.status),$.extend(t,this.settings.criteria);var e={context:this.settings.context,elementType:this.elementType,source:this.instanceState.selectedSource,criteria:t,disabledElementIds:this.settings.disabledElementIds,viewState:$.extend({},this.getSelectedSourceState()),paginated:this._isViewPaginated()?1:0};return e.viewState.order=this.getSelectedSortAttribute(),e.viewState.sort=this.getSelectedSortDirection(),"structure"===this.getSelectedSortAttribute()&&(void 0===this.instanceState.collapsedElementIds&&(this.instanceState.collapsedElementIds=[]),e.collapsedElementIds=this.instanceState.collapsedElementIds),this.trigger("registerViewParams",{params:e}),e},updateElements:function(t){var e=this;if(this.initialized){this._cancelRequests(),this.setIndexBusy(),this.view&&(this.view.destroy(),delete this.view),!0!==t&&(this.setPage(1),this._resetCount());var i=this.getViewParams();Craft.sendActionRequest("POST",this.settings.updateElementsAction,{data:i,cancelToken:this._createCancelToken()}).then((function(t){e.setIndexAvailable(),("index"===e.settings.context?Garnish.$scrollContainer:e.$main).scrollTop(0),e._updateView(i,t.data)})).catch((function(t){e.setIndexAvailable(),e._ignoreFailedRequest||Craft.cp.displayError(Craft.t("app","A server error occurred."))}))}},updateElementsIfSearchTextChanged:function(){this.searchText!==(this.searchText=this.searching?this.$search.val():null)&&this.updateElements()},showActionTriggers:function(){this.showingActionTriggers||(this.$toolbar.css("min-height",this.$toolbar.height()),this._$detachedToolbarItems=this.$toolbar.children(),this._$detachedToolbarItems.detach(),this._$triggers?this._$triggers.appendTo(this.$toolbar):this._createTriggers(),this.showingActionTriggers=!0)},submitAction:function(t,e){var i=this,s=this.view.getSelectedElementIds();if(0!==s.length&&("string"==typeof t&&(t=this._findAction(t)),!t.confirm||confirm(t.confirm))){this._cancelRequests();var a=this.getViewParams();e=e?Craft.expandPostArray(e):{};var n=$.extend(a,t.settings||{},e,{elementAction:t.type,elementIds:s});this.setIndexBusy(),this._autoSelectElements=s,t.download?(Craft.csrfTokenName&&(n[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl(this.settings.submitActionsAction),n).then((function(t){i.setIndexAvailable()})).catch((function(t){i.setIndexAvailable()}))):Craft.sendActionRequest("POST",this.settings.submitActionsAction,{data:n,cancelToken:this._createCancelToken()}).then((function(e){i.setIndexAvailable(),e.data.success?(i._resetCount(),i._updateView(a,e.data),void 0!==e.data.badgeCounts&&i._updateBadgeCounts(e.data.badgeCounts),e.data.message&&Craft.cp.displayNotice(e.data.message),i.afterAction(t,n)):Craft.cp.displayError(e.data.message)})).catch((function(){i.setIndexAvailable()}))}},_findAction:function(t){for(var e=0;e<this.actions.length;e++)if(this.actions[e].type===t)return this.actions[e];throw"Invalid element action: ".concat(t)},afterAction:function(t,e){Craft.cp.runQueue(),this.onAfterAction(t,e)},hideActionTriggers:function(){this.showingActionTriggers&&(this._$detachedToolbarItems.appendTo(this.$toolbar),this._$triggers.detach(),this.$toolbar.css("min-height",""),this.showingActionTriggers=!1)},updateActionTriggers:function(){if(this.actions){var t=this.view.getSelectedElements().length;0!==t?(t===this.view.getEnabledElements().length?(this.$selectAllCheckbox.removeClass("indeterminate"),this.$selectAllCheckbox.addClass("checked"),this.$selectAllContainer.attr("aria-checked","true")):(this.$selectAllCheckbox.addClass("indeterminate"),this.$selectAllCheckbox.removeClass("checked"),this.$selectAllContainer.attr("aria-checked","mixed")),this.showActionTriggers()):(this.$selectAllCheckbox.removeClass("indeterminate checked"),this.$selectAllContainer.attr("aria-checked","false"),this.hideActionTriggers())}},getSelectedElements:function(){return this.view?this.view.getSelectedElements():$()},getSelectedElementIds:function(){return this.view?this.view.getSelectedElementIds():[]},setStatus:function(t){var e=this.statusMenu.$options.filter('a[data-status="'+t+'"]:first');e.length&&this.statusMenu.selectOption(e[0])},getSortAttributeOption:function(t){return this.$sortAttributesList.find('a[data-attr="'+t+'"]:first')},getSelectedSortAttribute:function(){return this.$sortAttributesList.find("a.sel:first").data("attr")},setSortAttribute:function(t){var e=this.getSortAttributeOption(t);if(e.length){this.$sortAttributesList.find("a.sel").removeClass("sel"),e.addClass("sel");var i=e.text();this.$sortMenuBtn.attr("title",Craft.t("app","Sort by {attribute}",{attribute:i})),this.$sortMenuBtn.text(i),"score"===t?this.setSortDirection("desc"):this.setSortDirection(e.data("default-dir")||"asc"),"structure"===t?this.$sortDirectionsList.find("a").addClass("disabled"):this.$sortDirectionsList.find("a").removeClass("disabled")}},getSortDirectionOption:function(t){return this.$sortDirectionsList.find("a[data-dir="+t+"]:first")},getSelectedSortDirection:function(){return this.$sortDirectionsList.find("a.sel:first").data("dir")},getSelectedViewMode:function(){return this.getSelectedSourceState("mode")||"table"},setSortDirection:function(t){"desc"!==t&&(t="asc"),this.$sortMenuBtn.attr("data-icon",t),this.$sortDirectionsList.find("a.sel").removeClass("sel"),this.getSortDirectionOption(t).addClass("sel")},getSourceByKey:function(t){return void 0===this.sourcesByKey[t]?null:this.sourcesByKey[t]},selectSource:function(t){if(!t||!t.length)return!1;if(this.$source&&this.$source[0]&&this.$source[0]===t[0]&&t.data("key")===this.sourceKey)return!1;this.hideActionTriggers(),this.$source=t,this.sourceKey=t.data("key"),this.setInstanceState("selectedSource",this.sourceKey),this.sourceSelect.selectItem(t),Craft.cp.updateSidebarMenuLabel(),this.searching&&(this.searchText=null,this.$search.val(""),this.stopSearching()),this.$sortAttributesList.children("li[data-extra]").remove();var e=this.$source.closest("nav > ul > li").children("a").data("sort-options");if(e)for(var i=0;i<e.length;i++){var s=$("<li/>",{"data-extra":!0}).append($("<a/>",{text:e[i][0],"data-attr":e[i][1]})).appendTo(this.$sortAttributesList);this.sortMenu.addOptions(s.children())}if(Garnish.hasAttr(this.$source,"data-has-structure")?(this.$structureSortAttribute||(this.$structureSortAttribute=$('<li><a data-attr="structure">'+Craft.t("app","Structure")+"</a></li>"),this.sortMenu.addOptions(this.$structureSortAttribute.children())),this.$structureSortAttribute.prependTo(this.$sortAttributesList)):this.$structureSortAttribute&&this.$structureSortAttribute.removeClass("sel").detach(),this.setStoredSortOptionsForSource(),this.$statusMenuBtn.length&&(Garnish.hasAttr(this.$source,"data-override-status")?this.$statusMenuContainer.addClass("hidden"):this.$statusMenuContainer.removeClass("hidden"),this.trashed)){var a=this.statusMenu.$options.first();this.setStatus(a.data("status"))}if(this.$viewModeBtnContainer&&this.$viewModeBtnContainer.remove(),this.viewModeBtns={},this.viewMode=null,this.sourceViewModes=this.getViewModesForSource(),this.sourceViewModes.length>1){this.$viewModeBtnContainer=$('<div class="btngroup"/>').appendTo(this.$toolbar);for(var n=0;n<this.sourceViewModes.length;n++){var r=this.sourceViewModes[n],o=$("<button/>",{type:"button",class:"btn"+(void 0!==r.className?" ".concat(r.className):""),"data-view":r.mode,"data-icon":r.icon,"aria-label":r.title,title:r.title}).appendTo(this.$viewModeBtnContainer);this.viewModeBtns[r.mode]=o,this.addListener(o,"click",{mode:r.mode},(function(t){this.selectViewMode(t.data.mode),this.updateElements()}))}}var l=this.getSelectedViewMode();return l&&this.doesSourceHaveViewMode(l)||(l=this.viewMode&&this.doesSourceHaveViewMode(this.viewMode)?this.viewMode:this.sourceViewModes[0].mode),this.selectViewMode(l),this.onSelectSource(),!0},selectSourceByKey:function(t){var e=this.getSourceByKey(t);return!!e&&this.selectSource(e)},setStoredSortOptionsForSource:function(){var t=this.getSelectedSourceState("order"),e=this.getSelectedSourceState("sort");t&&e||(t=this.getDefaultSort(),Garnish.isArray(t)&&(e=t[1],t=t[0])),"asc"!==e&&"desc"!==e&&(e="asc"),this.setSortAttribute(t),this.setSortDirection(e)},getDefaultSort:function(){return this.$source&&Garnish.hasAttr(this.$source,"data-default-sort")?this.$source.attr("data-default-sort").split(":"):[this.$sortAttributesList.find("a:first").data("attr"),"asc"]},getViewModesForSource:function(){var t=[{mode:"table",title:Craft.t("app","Display in a table"),icon:"list"}];return this.$source&&Garnish.hasAttr(this.$source,"data-has-thumbs")&&t.push({mode:"thumbs",title:Craft.t("app","Display as thumbnails"),icon:"grid"}),t},doesSourceHaveViewMode:function(t){for(var e=0;e<this.sourceViewModes.length;e++)if(this.sourceViewModes[e].mode===t)return!0;return!1},selectViewMode:function(t,e){e||this.doesSourceHaveViewMode(t)||(t=this.sourceViewModes[0].mode),t!==this.viewMode&&(this.viewMode&&void 0!==this.viewModeBtns[this.viewMode]&&this.viewModeBtns[this.viewMode].removeClass("active"),this.viewMode=t,this.setSelecetedSourceState("mode",this.viewMode),void 0!==this.viewModeBtns[this.viewMode]&&this.viewModeBtns[this.viewMode].addClass("active"))},createView:function(t,e){return new(this.getViewClass(t))(this,this.$elements,e)},getViewClass:function(t){switch(t){case"table":return Craft.TableElementIndexView;case"thumbs":return Craft.ThumbsElementIndexView;default:throw'View mode "'.concat(t,'" not supported.')}},rememberDisabledElementId:function(t){-1===$.inArray(t,this.settings.disabledElementIds)&&this.settings.disabledElementIds.push(t)},forgetDisabledElementId:function(t){var e=$.inArray(t,this.settings.disabledElementIds);-1!==e&&this.settings.disabledElementIds.splice(e,1)},enableElements:function(t){t.removeClass("disabled").parents(".disabled").removeClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.forgetDisabledElementId(i)}this.onEnableElements(t)},disableElements:function(t){t.removeClass("sel").addClass("disabled");for(var e=0;e<t.length;e++){var i=$(t[e]).data("id");this.rememberDisabledElementId(i)}this.onDisableElements(t)},getElementById:function(t){return this.view.getElementById(t)},enableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.enableElements(s):this.forgetDisabledElementId(i)}},disableElementsById:function(t){t=$.makeArray(t);for(var e=0;e<t.length;e++){var i=t[e],s=this.getElementById(i);s&&s.length?this.disableElements(s):this.rememberDisabledElementId(i)}},selectElementAfterUpdate:function(t){null===this._autoSelectElements&&(this._autoSelectElements=[]),this._autoSelectElements.push(t)},addButton:function(t){this.getButtonContainer().append(t)},isShowingSidebar:function(){return null===this.showingSidebar&&(this.showingSidebar=this.$sidebar.length&&!this.$sidebar.hasClass("hidden")),this.showingSidebar},getButtonContainer:function(){if(this.settings.buttonContainer)return $(this.settings.buttonContainer);var t=$("#action-button");return t.length||(t=$('<div id="action-button"/>').appendTo($("#header"))),t},setIndexBusy:function(){this.$elements.addClass("busy"),this.isIndexBusy=!0},setIndexAvailable:function(){this.$elements.removeClass("busy"),this.isIndexBusy=!1},createCustomizeSourcesModal:function(){var t=new Craft.CustomizeSourcesModal(this,{onHide:function(){t.destroy()}});return t},disable:function(){this.sourceSelect&&this.sourceSelect.disable(),this.view&&this.view.disable(),this.base()},enable:function(){this.sourceSelect&&this.sourceSelect.enable(),this.view&&this.view.enable(),this.base()},onAfterInit:function(){this.settings.onAfterInit(),this.trigger("afterInit")},onSelectSource:function(){this.settings.onSelectSource(this.sourceKey),this.trigger("selectSource",{sourceKey:this.sourceKey})},onSelectSite:function(){this.settings.onSelectSite(this.siteId),this.trigger("selectSite",{siteId:this.siteId})},onUpdateElements:function(){this.settings.onUpdateElements(),this.trigger("updateElements")},onSelectionChange:function(){this.settings.onSelectionChange(),this.trigger("selectionChange")},onEnableElements:function(t){this.settings.onEnableElements(t),this.trigger("enableElements",{elements:t})},onDisableElements:function(t){this.settings.onDisableElements(t),this.trigger("disableElements",{elements:t})},onAfterAction:function(t,e){this.settings.onAfterAction(t,e),this.trigger("afterAction",{action:t,params:e})},_handleSourceSelectionChange:function(){this.sourceSelect.totalSelected?this.selectSource(this.sourceSelect.$selectedItems)&&this.updateElements():this.sourceSelect.selectItem(this.$visibleSources.first())},_handleActionTriggerSubmit:function(t){t.preventDefault();var e=$(t.currentTarget);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"),Garnish.getPostData(e))},_handleMenuActionTriggerSubmit:function(t){var e=$(t.option);e.hasClass("disabled")||e.data("custom-handler")||this.submitAction(e.data("action"))},_handleStatusChange:function(t){this.statusMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$statusMenuBtn.html(e.html()),this.trashed=!1,this.drafts=!1,this.status=null,Garnish.hasAttr(e,"data-trashed")?this.trashed=!0:Garnish.hasAttr(e,"data-drafts")?this.drafts=!0:this.status=e.data("status"),this._updateStructureSortOption(),this.updateElements()},_handleSiteChange:function(t){this.siteMenu.$options.removeClass("sel");var e=$(t.selectedOption).addClass("sel");this.$siteMenuBtn.html(e.html()),this._setSite(e.data("site-id")),this.onSelectSite()},_setSite:function(t){var e,i,s=null===this.siteId;this.siteId=t,this.$visibleSources=$();for(var a=!(s||this.$source&&this.$source.length),n=0;n<this.$sources.length;n++)void 0===(i=this.$sources.eq(n)).data("sites")||-1!==i.data("sites").toString().split(",").indexOf(t.toString())?(i.parent().removeClass("hidden"),this.$visibleSources=this.$visibleSources.add(i),e||(e=i)):(i.parent().addClass("hidden"),this.$source&&this.$source.get(0)==i.get(0)&&(a=!0));this.initialized&&a&&this.selectSource(e);var r,o=this.getSourceContainer().children(".heading");for(n=0;n<o.length;n++)0!==(r=o.eq(n)).nextUntil(".heading",":not(.hidden)").length?r.removeClass("hidden"):r.addClass("hidden");this.initialized&&("index"===this.settings.context&&Craft.cp.setSiteId(t),this.updateElements())},_handleSortChange:function(t){var e=$(t.selectedOption);e.hasClass("disabled")||e.hasClass("sel")||(e.parent().parent().is(this.$sortAttributesList)?this.setSortAttribute(e.data("attr")):this.setSortDirection(e.data("dir")),this.storeSortAttributeAndDirection(),this.updateElements())},_handleSelectionChange:function(){this.updateActionTriggers(),this.onSelectionChange()},_handleSourceDblClick:function(t){this._toggleSource($(t.currentTarget)),t.stopPropagation()},_handleSourceToggleClick:function(t){this._toggleSource($(t.currentTarget).prev("a")),t.stopPropagation()},_updateStructureSortOption:function(){var t=this.getSortAttributeOption("structure");if(t.length)if(this.trashed||this.drafts||this.searching){if(t.addClass("disabled"),"structure"===this.getSelectedSortAttribute()){var e=this.$sortAttributesList.find("a:not(.disabled):first");this.setSortAttribute(e.data("attr")),this.setSortDirection("asc")}}else t.removeClass("disabled"),this.setStoredSortOptionsForSource()},_getSourcesInList:function(t){return t.children("li").children("a")},_getChildSources:function(t){var e=t.siblings("ul");return this._getSourcesInList(e)},_getSourceToggle:function(t){return t.siblings(".toggle")},_toggleSource:function(t){t.parent("li").hasClass("expanded")?this._collapseSource(t):this._expandSource(t)},_expandSource:function(t){t.next(".toggle").attr({"aria-expanded":"true","aria-label":Craft.t("app","Hide nested sources")}),t.parent("li").addClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.initSource($(e[i])),this.$visibleSources&&(this.$visibleSources=this.$visibleSources.add(e[i]));var s=t.data("key");-1===this.instanceState.expandedSources.indexOf(s)&&(this.instanceState.expandedSources.push(s),this.storeInstanceState())},_collapseSource:function(t){t.next(".toggle").attr({"aria-expanded":"false","aria-label":Craft.t("app","Show nested sources")}),t.parent("li").removeClass("expanded");for(var e=this._getChildSources(t),i=0;i<e.length;i++)this.deinitSource($(e[i])),this.$visibleSources=this.$visibleSources.not(e[i]);var s=this.instanceState.expandedSources.indexOf(t.data("key"));-1!==s&&(this.instanceState.expandedSources.splice(s,1),this.storeInstanceState())},_isViewPaginated:function(){return"index"===this.settings.context&&"structure"!==this.getSelectedSortAttribute()},_updateView:function(t,e){var i=this;this.actions&&(this.hideActionTriggers(),this.actions=this.actionsHeadHtml=this.actionsFootHtml=this._$triggers=null),this.$countContainer.length&&(this.$countSpinner.removeClass("hidden"),this.$countContainer.html(""),this._countResults().then((function(t){i.$countSpinner.addClass("hidden");var e=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][2]:"element",s=Craft.elementTypeNames[i.elementType]?Craft.elementTypeNames[i.elementType][3]:"elements";if(i._isViewPaginated()){var a=Math.min(i.settings.batchSize*(i.page-1)+1,t),n=Math.min(a+(i.settings.batchSize-1),t),r=Craft.t("app","{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}",{first:a,last:n,total:t,item:e,items:s}),o=$('<div class="flex pagination"/>').appendTo(i.$countContainer),l=Math.max(Math.ceil(t/i.settings.batchSize),1),h=$("<div/>",{class:"page-link prev-page"+(i.page>1?"":" disabled"),title:Craft.t("app","Previous Page")}).appendTo(o),d=$("<div/>",{class:"page-link next-page"+(i.page<l?"":" disabled"),title:Craft.t("app","Next Page")}).appendTo(o);$("<div/>",{class:"page-info",text:r}).appendTo(o),i.page>1&&i.addListener(h,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page-1),this.updateElements(!0)})),i.page<l&&i.addListener(d,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page+1),this.updateElements(!0)}))}else{var c=Craft.t("app","{total, number} {total, plural, =1{{item}} other{{items}}}",{total:t,item:e,items:s});i.$countContainer.text(c)}})).catch((function(){i.$countSpinner.addClass("hidden")}))),this.$elements.html(e.html),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),this.$selectAllContainer=this.$elements.find(".selectallcontainer:first"),e.actions&&e.actions.length?this.$selectAllContainer.length&&(this.actions=e.actions,this.actionsHeadHtml=e.actionsHeadHtml,this.actionsFootHtml=e.actionsFootHtml,this.$selectAllCheckbox=$('<div class="checkbox"/>').prependTo(this.$selectAllContainer),this.$selectAllContainer.attr({role:"checkbox",tabindex:"0","aria-checked":"false","aria-label":Craft.t("app","Select all")}),this.addListener(this.$selectAllContainer,"click",(function(){0===this.view.getSelectedElements().length?this.view.selectAllElements():this.view.deselectAllElements()})),this.addListener(this.$selectAllContainer,"keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(t.preventDefault(),$(t.currentTarget).trigger("click"))}))):(this.$selectAllContainer.siblings().length||this.$selectAllContainer.parent(".header").remove(),this.$selectAllContainer.remove()),this.exporters=e.exporters,this.exportersByType=Craft.index(this.exporters||[],(function(t){return t.type})),this.exporters&&this.exporters.length?this.$exportBtn.removeClass("hidden"):this.$exportBtn.addClass("hidden");var s=this.actions||this.settings.selectable;if(this.view=this.createView(this.getSelectedViewMode(),{context:this.settings.context,batchSize:"index"!==this.settings.context||"structure"===this.getSelectedSortAttribute()?this.settings.batchSize:null,params:t,selectable:s,multiSelect:this.actions||this.settings.multiSelect,checkboxMode:!!this.actions,onSelectionChange:this._handleSelectionChange.bind(this)}),this._autoSelectElements){if(s)for(var a=0;a<this._autoSelectElements.length;a++)this.view.selectElementById(this._autoSelectElements[a]);this._autoSelectElements=null}this.onUpdateElements()},_updateBadgeCounts:function(t){for(var e in t)if(t.hasOwnProperty(e)){var i=this.getSourceByKey(e);if(i){var s=i.children(".badge");null!==t[e]?(s.length||(s=$('<span class="badge"/>').appendTo(i)),s.text(t[e])):s&&s.remove()}}},_countResults:function(){var t=this;return new Promise((function(e,i){if(null!==t.totalResults)e(t.totalResults);else{var s=t.getViewParams();delete s.criteria.offset,delete s.criteria.limit,null===t.resultSet&&(t.resultSet=Math.floor(1e8*Math.random())),s.resultSet=t.resultSet,Craft.sendActionRequest("POST",t.settings.countElementsAction,{data:s,cancelToken:t._createCancelToken()}).then((function(s){s.data.resultSet==t.resultSet?(t.totalResults=s.data.count,e(s.data.count)):i()})).catch(i)}}))},_createTriggers:function(){var t,e,i=[],s=[],a=[];for(t=0;t<this.actions.length;t++){var n=this.actions[t];if(n.trigger){var r=$('<form id="'+Craft.formatInputId(n.type)+'-actiontrigger"/>').data("action",n).append(n.trigger);this.addListener(r,"submit","_handleActionTriggerSubmit"),i.push(r)}else n.destructive?a.push(n):s.push(n)}if(s.length||a.length){var o=$("<form/>");e=$("<button/>",{type:"button",class:"btn menubtn","data-icon":"settings",title:Craft.t("app","Actions")}).appendTo(o);var l=$('<ul class="menu"/>').appendTo(o),h=this._createMenuTriggerList(s,!1),d=this._createMenuTriggerList(a,!0);h&&h.appendTo(l),h&&d&&$("<hr/>").appendTo(l),d&&d.appendTo(l),i.push(o)}for(this._$triggers=$(),t=0;t<i.length;t++){var c=$("<div/>").append(i[t]);this._$triggers=this._$triggers.add(c)}this._$triggers.appendTo(this.$toolbar),Craft.appendHeadHtml(this.actionsHeadHtml),Craft.appendFootHtml(this.actionsFootHtml),Craft.initUiElements(this._$triggers),e&&e.data("menubtn").on("optionSelect",this._handleMenuActionTriggerSubmit.bind(this))},_showExportHud:function(){var t=this;this.$exportBtn.addClass("active");for(var e=$("<form/>",{class:"export-form"}),i=[],s=0;s<this.exporters.length;s++)i.push({label:this.exporters[s].name,value:this.exporters[s].type});var a=Craft.ui.createSelectField({label:Craft.t("app","Export Type"),options:i,class:"fullwidth"}).appendTo(e),n=Craft.ui.createSelectField({label:Craft.t("app","Format"),options:[{label:"CSV",value:"csv"},{label:"JSON",value:"json"},{label:"XML",value:"xml"}],class:"fullwidth"}).appendTo(e),r=a.find("select");this.addListener(r,"change",(function(){var e=r.val();t.exportersByType[e].formattable?n.removeClass("hidden"):n.addClass("hidden")})),r.trigger("change");var o=this.view.getSelectedElementIds();if(!o.length)var l=Craft.ui.createTextField({label:Craft.t("app","Limit"),placeholder:Craft.t("app","No limit"),type:"number",min:1}).appendTo(e);$("<button/>",{type:"submit",class:"btn submit fullwidth",text:Craft.t("app","Export")}).appendTo(e);var h=$("<div/>",{class:"spinner hidden"}).appendTo(e);new Garnish.HUD(this.$exportBtn,e).on("hide",(function(){t.$exportBtn.removeClass("active")}));var d=!1;this.addListener(e,"submit",(function(t){if(t.preventDefault(),!d){d=!0,h.removeClass("hidden");var e=this.getViewParams();if(delete e.criteria.offset,delete e.criteria.limit,delete e.collapsedElementIds,e.type=a.find("select").val(),e.format=n.find("select").val(),o.length)e.criteria.id=o;else{var i=parseInt(l.find("input").val());i&&!isNaN(i)&&(e.criteria.limit=i)}Craft.csrfTokenValue&&(e[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl("element-indexes/export"),e).then((function(){d=!1,h.addClass("hidden")})).catch((function(){d=!1,h.addClass("hidden"),this._ignoreFailedRequest||Craft.cp.displayError(Craft.t("app","A server error occurred."))}))}}))},_createMenuTriggerList:function(t,e){if(t&&t.length){for(var i=$("<ul/>"),s=0;s<t.length;s++)$("<li/>").append($("<a/>",{id:Craft.formatInputId(t[s].type)+"-actiontrigger",class:e?"error":null,data:{action:t[s]},text:t[s].name})).appendTo(i);return i}}},{defaults:{context:"index",modal:null,storageKey:null,criteria:null,batchSize:100,disabledElementIds:[],selectable:!1,multiSelect:!1,buttonContainer:null,hideSidebar:!1,toolbarSelector:".toolbar:first",refreshSourcesAction:"element-indexes/get-source-tree-html",updateElementsAction:"element-indexes/get-elements",countElementsAction:"element-indexes/count-elements",submitActionsAction:"element-indexes/perform-action",defaultSiteId:null,defaultSource:null,canHaveDrafts:!1,onAfterInit:$.noop,onSelectSource:$.noop,onSelectSite:$.noop,onUpdateElements:$.noop,onSelectionChange:$.noop,onEnableElements:$.noop,onDisableElements:$.noop,onAfterAction:$.noop}})},8495:function(){Craft.BaseElementIndexView=Garnish.Base.extend({$container:null,$loadingMoreSpinner:null,$elementContainer:null,$scroller:null,elementIndex:null,thumbLoader:null,elementSelect:null,loadingMore:!1,_totalVisible:null,_morePending:null,_handleEnableElements:null,_handleDisableElements:null,init:function(t,e,i){var s=this;this.elementIndex=t,this.$container=$(e),this.setSettings(i,Craft.BaseElementIndexView.defaults),this.$loadingMoreSpinner=$('<div class="centeralign hidden"><div class="spinner loadingmore"></div></div>').insertAfter(this.$container),this.$elementContainer=this.getElementContainer();var a=this.$elementContainer.children();this.setTotalVisible(a.length),this.setMorePending(this.settings.batchSize&&a.length==this.settings.batchSize),this.thumbLoader=new Craft.ElementThumbLoader,this.thumbLoader.load(a),this.settings.selectable&&(this.elementSelect=new Garnish.Select(this.$elementContainer,a.filter(":not(.disabled)"),{multi:this.settings.multiSelect,vertical:this.isVerticalList(),handle:"index"===this.settings.context?".checkbox, .element:first":null,filter:":not(a):not(.toggle)",checkboxMode:this.settings.checkboxMode,onSelectionChange:this.onSelectionChange.bind(this)}),this._handleEnableElements=function(t){s.elementSelect.addItems(t.elements)},this._handleDisableElements=function(t){s.elementSelect.removeItems(t.elements)},this.elementIndex.on("enableElements",this._handleEnableElements),this.elementIndex.on("disableElements",this._handleDisableElements)),"index"===this.settings.context&&(this._handleElementEditing=function(t){var e=$(t.target);if("A"!==e.prop("nodeName")){var i;if(e.hasClass("element"))i=e;else if(!(i=e.closest(".element")).length)return;Garnish.hasAttr(i,"data-editable")&&s.createElementEditor(i)}},this.elementIndex.trashed||(this.addListener(this.$elementContainer,"dblclick",this._handleElementEditing),$.isTouchCapable()&&this.addListener(this.$elementContainer,"taphold",this._handleElementEditing))),this.afterInit(),this.settings.batchSize&&("index"===this.settings.context?this.$scroller=Garnish.$scrollContainer:this.$scroller=this.elementIndex.$main,this.$scroller.scrollTop(0),this.addListener(this.$scroller,"scroll","maybeLoadMore"),this.maybeLoadMore())},getElementContainer:function(){throw"Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method."},afterInit:function(){},getAllElements:function(){return this.$elementContainer.children()},getEnabledElements:function(){return this.$elementContainer.children(":not(.disabled)")},getElementById:function(t){var e=this.$elementContainer.children('[data-id="'+t+'"]:first');return e.length?e:null},getSelectedElements:function(){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.$selectedItems},getSelectedElementIds:function(){var t;try{t=this.getSelectedElements()}catch(t){}var e=[];if(t)for(var i=0;i<t.length;i++)e.push(t.eq(i).data("id"));return e},selectElement:function(t){if(!this.elementSelect)throw"This view is not selectable.";return this.elementSelect.selectItem(t,!0),!0},selectElementById:function(t){if(!this.elementSelect)throw"This view is not selectable.";var e=this.getElementById(t);return!!e&&(this.elementSelect.selectItem(e,!0),!0)},selectAllElements:function(){this.elementSelect.selectAll()},deselectAllElements:function(){this.elementSelect.deselectAll()},isVerticalList:function(){return!1},getTotalVisible:function(){return this._totalVisible},setTotalVisible:function(t){this._totalVisible=t},getMorePending:function(){return this._morePending},setMorePending:function(t){this._morePending=t},maybeLoadMore:function(){this.canLoadMore()&&this.loadMore()},canLoadMore:function(){return!(!this.getMorePending()||!this.settings.batchSize)&&(this.$scroller[0]===Garnish.$win[0]?Garnish.$win.innerHeight()+Garnish.$win.scrollTop()>=this.$container.offset().top+this.$container.height():this.$scroller.prop("scrollHeight")-this.$scroller.scrollTop()<=this.$scroller.outerHeight()+15)},loadMore:function(){var t=this;this.getMorePending()&&!this.loadingMore&&this.settings.batchSize&&(this.loadingMore=!0,this.$loadingMoreSpinner.removeClass("hidden"),this.removeListener(this.$scroller,"scroll"),Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:this.getLoadMoreParams()}).then((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden");var i=$(e.data.html);t.appendElements(i),Craft.appendHeadHtml(e.data.headHtml),Craft.appendFootHtml(e.data.footHtml),t.elementSelect&&(t.elementSelect.addItems(i.filter(":not(.disabled)")),t.elementIndex.updateActionTriggers()),t.setTotalVisible(t.getTotalVisible()+i.length),t.setMorePending(i.length==t.settings.batchSize),t.addListener(t.$scroller,"scroll","maybeLoadMore"),t.maybeLoadMore()})).catch((function(e){t.loadingMore=!1,t.$loadingMoreSpinner.addClass("hidden")})))},getLoadMoreParams:function(){var t=$.extend(!0,{},this.settings.params);return t.criteria.offset=this.getTotalVisible(),t},appendElements:function(t){t.appendTo(this.$elementContainer),this.thumbLoader.load(t),this.onAppendElements(t)},onAppendElements:function(t){this.settings.onAppendElements(t),this.trigger("appendElements",{newElements:t})},onSelectionChange:function(){this.settings.onSelectionChange(),this.trigger("selectionChange")},createElementEditor:function(t){Craft.createElementEditor(t.data("type"),t,{elementIndex:this.elementIndex})},disable:function(){this.elementSelect&&this.elementSelect.disable()},enable:function(){this.elementSelect&&this.elementSelect.enable()},destroy:function(){this.$loadingMoreSpinner.remove(),this.thumbLoader.destroy(),delete this.thumbLoader,this.elementSelect&&(this.elementIndex.off("enableElements",this._handleEnableElements),this.elementIndex.off("disableElements",this._handleDisableElements),this.elementSelect.destroy(),delete this.elementSelect),this.base()}},{defaults:{context:"index",batchSize:null,params:null,selectable:!1,multiSelect:!1,checkboxMode:!1,loadMoreElementsAction:"element-indexes/get-more-elements",onAppendElements:$.noop,onSelectionChange:$.noop}})},5970:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.BaseElementSelectInput=Garnish.Base.extend({thumbLoader:null,elementSelect:null,elementSort:null,modal:null,elementEditor:null,fieldLabel:null,$container:null,$elementsContainer:null,$elements:null,$addElementBtn:null,$addElementBtnContainer:null,_initialized:!1,init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","elementType","sources","criteria","sourceElementId","limit","modalStorageKey","fieldId"],a=0;a<s.length&&void 0!==arguments[a];a++)i[s[a]]=arguments[a];t=i}this.setSettings(t,Craft.BaseElementSelectInput.defaults),this.settings.modalStorageKey&&(this.modalStorageKey="BaseElementSelectInput."+this.settings.modalStorageKey),1==this.settings.limit&&(this.settings.sortable=!1),this.$container=this.getContainer(),this.fieldLabel=this.getFieldLabel(),this.$container.data("elementSelect",this),this.$elementsContainer=this.getElementsContainer(),this.$addElementBtn=this.getAddElementsBtn(),this.$addElementBtn&&(this.$addElementBtnContainer=this.$addElementBtn.parent(".flex"),this.$addElementBtnContainer.length||(this.$addElementBtnContainer=null)),this.thumbLoader=new Craft.ElementThumbLoader,this.initElementSelect(),this.initElementSort(),this.resetElements(),this.$addElementBtn&&this.addListener(this.$addElementBtn,"activate","showModal"),Garnish.requestAnimationFrame((function(){e._initialized=!0}))},get totalSelected(){return this.$elements.length},getContainer:function(){return $("#"+this.settings.id)},getFieldLabel:function(){if(this.$container)return this.$container.closest("fieldset").find("legend").first().data("label")},getElementsContainer:function(){return this.$container.children(".elements")},getElements:function(){return this.$elementsContainer.children()},getAddElementsBtn:function(){return this.$container.find(".btn.add:first")},initElementSelect:function(){this.settings.selectable&&(this.elementSelect=new Garnish.Select({multi:this.settings.sortable,filter:":not(.delete)"}))},initElementSort:function(){var t=this;this.settings.sortable&&(this.elementSort=new Garnish.DragSort({container:this.$elementsContainer,filter:this.settings.selectable?function(){return t.elementSort.$targetItem.hasClass("sel")?t.elementSelect.getSelectedItems():t.elementSort.$targetItem}:null,ignoreHandleSelector:".delete",axis:this.getElementSortAxis(),collapseDraggees:!0,magnetStrength:4,helperLagBase:1.5,onSortChange:this.settings.selectable?function(){t.elementSelect.resetItemOrder()}:null}))},getElementSortAxis:function(){return"list"===this.settings.viewMode?"y":null},canAddMoreElements:function(){return!this.settings.limit||this.$elements.length<this.settings.limit},updateAddElementsBtn:function(){this.canAddMoreElements()?this.enableAddElementsBtn():this.disableAddElementsBtn()},disableAddElementsBtn:function(){var t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.addClass("hidden")},enableAddElementsBtn:function(){var t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.removeClass("hidden")},focusNextLogicalElement:function(){if(this.canAddMoreElements()){var t=this.$addElementBtn;t&&t.get(0).focus()}else this.focusLastRemoveBtn()},focusLastRemoveBtn:function(){var t=this.$container.find(".delete");t.length&&t.last()[0].focus()},resetElements:function(){null!==this.$elements?this.removeElements(this.$elements):this.$elements=$(),this.addElements(this.getElements())},addElements:function(t){var e=this;this.thumbLoader.load(t),this.settings.selectable&&this.elementSelect.addItems(t),this.settings.sortable&&this.elementSort.addItems(t),this.settings.editable&&(this._handleShowElementEditor=function(t){var i=$(t.currentTarget);!Garnish.hasAttr(i,"data-editable")||i.hasClass("disabled")||i.hasClass("loading")||(e.elementEditor=e.createElementEditor(i))},this.addListener(t,"dblclick",this._handleShowElementEditor),$.isTouchCapable()&&this.addListener(t,"taphold",this._handleShowElementEditor)),t.find(".delete").on("click dblclick",(function(t){e.removeElement($(t.currentTarget).closest(".element")),t.stopPropagation()})),this.$elements=this.$elements.add(t),this.updateAddElementsBtn()},createElementEditor:function(t,e){return e||(e={}),e.prevalidate=this.settings.prevalidate,Craft.createElementEditor(this.settings.elementType,t,e)},removeElements:function(t){if(this.settings.selectable&&this.elementSelect.removeItems(t),this.modal){for(var e=[],i=0;i<t.length;i++){var s=t.eq(i).data("id");s&&e.push(s)}e.length&&this.modal.elementIndex.enableElementsById(e)}var a;if(t.children("input").prop("disabled",!0),this.settings.selectable){var n=this.$elements.index(t.last());a=this.$elements.eq(n+1).find(".delete")}a.length?a.focus():this.focusNextLogicalElement(),this.$elements=this.$elements.not(t),this.updateAddElementsBtn(),this.onRemoveElements()},removeElement:function(t){this.removeElements(t),this.animateElementAway(t,(function(){t.remove()}))},animateElementAway:function(t,e){t.css("z-index",0);var i={opacity:-1};i["margin-"+Craft.left]=-(t.outerWidth()+parseInt(t.css("margin-"+Craft.right))),"list"!==this.settings.viewMode&&0!==this.$elements.length||(i["margin-bottom"]=-(t.outerHeight()+parseInt(t.css("margin-bottom")))),window.draftEditor&&window.draftEditor.pause(),t.velocity(i,Craft.BaseElementSelectInput.REMOVE_FX_DURATION,(function(){e&&e(),window.draftEditor&&window.draftEditor.resume()}))},showModal:function(){this.canAddMoreElements()&&(this.modal?this.modal.show():this.modal=this.createModal())},createModal:function(){return Craft.createElementSelectorModal(this.settings.elementType,this.getModalSettings())},getModalSettings:function(){return $.extend({closeOtherModals:!1,storageKey:this.modalStorageKey,sources:this.settings.sources,criteria:this.settings.criteria,multiSelect:1!=this.settings.limit,showSiteMenu:this.settings.showSiteMenu,disabledElementIds:this.getDisabledElementIds(),onSelect:this.onModalSelect.bind(this),onHide:this.onModalHide.bind(this),triggerElement:this.$addElementBtn,modalTitle:Craft.t("app","Select {element}",{element:this.fieldLabel})},this.settings.modalSettings)},getSelectedElementIds:function(){for(var t=[],e=0;e<this.$elements.length;e++)t.push(this.$elements.eq(e).data("id"));return t},getDisabledElementIds:function(){var e,i=this.getSelectedElementIds();return!this.settings.allowSelfRelations&&this.settings.sourceElementId&&i.push(this.settings.sourceElementId),this.settings.disabledElementIds&&i.push.apply(i,function(e){if(Array.isArray(e))return t(e)}(e=this.settings.disabledElementIds)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i},onModalSelect:function(t){if(this.settings.limit){var e=this.settings.limit-this.$elements.length;t.length>e&&(t=t.slice(0,e))}this.selectElements(t),this.updateDisabledElementsInModal()},onModalHide:function(){var t=this;this.canAddMoreElements()||setTimeout((function(){t.focusNextLogicalElement()}),200)},selectElements:function(t){for(var e=0;e<t.length;e++){var i=t[e],s=this.createNewElement(i);this.appendElement(s),this.addElements(s),this.animateElementIntoPlace(i.$element,s),i.$element=s}this.onSelectElements(t)},createNewElement:function(t){var e=t.$element.clone(),i=Craft.t("app","Remove {label}",{label:Craft.escapeHtml(t.label)});return Craft.setElementSize(e,"large"===this.settings.viewMode?"large":"small"),e.addClass("removable"),e.prepend('<input type="hidden" name="'.concat(this.settings.name).concat(this.settings.single?"":"[]",'" value="').concat(t.id,'">')+'<button type="button" class="delete icon" title="'+Craft.t("app","Remove")+'" aria-label="'+i+'"></button>'),e},appendElement:function(t){t.appendTo(this.$elementsContainer)},animateElementIntoPlace:function(t,e){var i=t.offset(),s=e.offset(),a=e.clone().appendTo(Garnish.$bod);e.css("visibility","hidden"),a.css({position:"absolute",zIndex:1e4,top:i.top,left:i.left});var n={top:s.top,left:s.left};a.velocity(n,Craft.BaseElementSelectInput.ADD_FX_DURATION,(function(){a.remove(),e.css("visibility","visible")}))},updateDisabledElementsInModal:function(){this.modal.elementIndex&&this.modal.elementIndex.disableElementsById(this.getDisabledElementIds())},getElementById:function(t){for(var e=0;e<this.$elements.length;e++){var i=this.$elements.eq(e);if(i.data("id")==t)return i}},onSelectElements:function(t){this.trigger("selectElements",{elements:t}),this.settings.onSelectElements(t),window.draftEditor&&window.draftEditor.checkForm()},onRemoveElements:function(){this.trigger("removeElements"),this.settings.onRemoveElements()}},{ADD_FX_DURATION:200,REMOVE_FX_DURATION:200,defaults:{id:null,name:null,fieldId:null,elementType:null,sources:null,criteria:{},allowSelfRelations:!1,sourceElementId:null,disabledElementIds:null,viewMode:"list",single:!1,limit:null,showSiteMenu:!1,modalStorageKey:null,modalSettings:{},onSelectElements:$.noop,onRemoveElements:$.noop,sortable:!0,selectable:!0,editable:!0,prevalidate:!1,editorSettings:{}}})},4993:function(){Craft.BaseElementSelectorModal=Garnish.Modal.extend({elementType:null,elementIndex:null,$body:null,$selectBtn:null,$sidebar:null,$sources:null,$sourceToggles:null,$main:null,$search:null,$elements:null,$tbody:null,$primaryButtons:null,$secondaryButtons:null,$cancelBtn:null,$footerSpinner:null,init:function(t,e){this.elementType=t,this.setSettings(e,Craft.BaseElementSelectorModal.defaults);var i="elementSelectorModalHeading-"+Date.now(),s=$('<div class="modal elementselectormodal" aria-labelledby="'+i+'"></div>').appendTo(Garnish.$bod),a=($('<h2 id="'+i+'" class="visually-hidden">'+this.settings.modalTitle+"</h2>").appendTo(s),$('<div class="body"><div class="spinner big"></div></div>').appendTo(s)),n=$('<div class="footer"/>').appendTo(s);this.settings.fullscreen&&(s.addClass("fullscreen"),this.settings.minGutter=0),this.base(s,this.settings),this.$footerSpinner=$('<div class="spinner hidden"/>').appendTo(n),this.$secondaryButtons=$('<div class="buttons left secondary-buttons"/>').appendTo(n),this.$primaryButtons=$('<div class="buttons right"/>').appendTo(n),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$primaryButtons),this.$selectBtn=$("<button/>",{type:"button",class:"btn disabled submit",text:Craft.t("app","Select")}).appendTo(this.$primaryButtons),this.$body=a,this.addListener(this.$cancelBtn,"activate","cancel"),this.addListener(this.$selectBtn,"activate","selectElements")},onFadeIn:function(){this.elementIndex?Garnish.isMobileBrowser(!0)||this.elementIndex.$search.trigger("focus"):this._createElementIndex(),this.base()},onSelectionChange:function(){this.updateSelectBtnState()},updateSelectBtnState:function(){this.$selectBtn&&(this.elementIndex.getSelectedElements().length?this.enableSelectBtn():this.disableSelectBtn())},enableSelectBtn:function(){this.$selectBtn.removeClass("disabled")},disableSelectBtn:function(){this.$selectBtn.addClass("disabled")},enableCancelBtn:function(){this.$cancelBtn.removeClass("disabled")},disableCancelBtn:function(){this.$cancelBtn.addClass("disabled")},showFooterSpinner:function(){this.$footerSpinner.removeClass("hidden")},hideFooterSpinner:function(){this.$footerSpinner.addClass("hidden")},cancel:function(){this.$cancelBtn.hasClass("disabled")||this.hide()},selectElements:function(){if(this.elementIndex&&this.elementIndex.getSelectedElements().length){this.elementIndex.view.elementSelect.clearMouseUpTimeout();var t=this.elementIndex.getSelectedElements(),e=this.getElementInfo(t);this.onSelect(e),this.settings.disableElementsOnSelect&&this.elementIndex.disableElements(this.elementIndex.getSelectedElements()),this.settings.hideOnSelect&&this.hide()}},getElementInfo:function(t){for(var e=[],i=0;i<t.length;i++){var s=$(t[i]),a=Craft.getElementInfo(s);e.push(a)}return e},show:function(){this.updateSelectBtnState(),this.base()},onSelect:function(t){this.settings.onSelect(t)},disable:function(){this.elementIndex&&this.elementIndex.disable(),this.base()},enable:function(){this.elementIndex&&this.elementIndex.enable(),this.base()},_createElementIndex:function(){var t=this,e={context:"modal",elementType:this.elementType,sources:this.settings.sources};null!==this.settings.showSiteMenu&&"auto"!==this.settings.showSiteMenu&&(e.showSiteMenu=this.settings.showSiteMenu?"1":"0"),Craft.postActionRequest(this.settings.bodyAction,e,(function(e,i){"success"===i&&(t.$body.html(e.html),t.$body.has(".sidebar:not(.hidden)").length&&t.$body.addClass("has-sidebar"),t.elementIndex=Craft.createElementIndex(t.elementType,t.$body,Object.assign({context:"modal",modal:t,storageKey:t.settings.storageKey,criteria:t.settings.criteria,disabledElementIds:t.settings.disabledElementIds,selectable:!0,multiSelect:t.settings.multiSelect,buttonContainer:t.$secondaryButtons,onSelectionChange:t.onSelectionChange.bind(t),hideSidebar:t.settings.hideSidebar,defaultSiteId:t.settings.defaultSiteId,defaultSource:t.settings.defaultSource},t.settings.indexSettings)),t.addListener(t.elementIndex.$elements,"doubletap",(function(t,e){e.firstTap.target===e.secondTap.target&&this.selectElements()})))}))}},{defaults:{fullscreen:!1,resizable:!0,storageKey:null,sources:null,criteria:null,multiSelect:!1,showSiteMenu:null,disabledElementIds:[],disableElementsOnSelect:!1,hideOnSelect:!0,modalTitle:Craft.t("app","Select element"),onCancel:$.noop,onSelect:$.noop,hideSidebar:!1,defaultSiteId:null,defaultSource:null,bodyAction:"elements/get-modal-body",indexSettings:{}}})},8843:function(){Craft.BaseInputGenerator=Garnish.Base.extend({$source:null,$target:null,$form:null,settings:null,listening:null,timeout:null,init:function(t,e,i){this.$source=$(t),this.$target=$(e),this.$form=this.$source.closest("form"),this.setSettings(i),this.startListening()},setNewSource:function(t){var e=this.listening;this.stopListening(),this.$source=$(t),e&&this.startListening()},startListening:function(){this.listening||(this.listening=!0,this.addListener(this.$source,"input","onSourceTextChange"),this.addListener(this.$target,"input","onTargetTextChange"),this.addListener(this.$form,"submit","onFormSubmit"))},stopListening:function(){this.listening&&(this.listening=!1,this.timeout&&clearTimeout(this.timeout),this.removeAllListeners(this.$source),this.removeAllListeners(this.$target),this.removeAllListeners(this.$form))},onSourceTextChange:function(){this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(this.updateTarget.bind(this),250)},onTargetTextChange:function(){this.$target.get(0)===document.activeElement&&this.stopListening()},onFormSubmit:function(){this.timeout&&clearTimeout(this.timeout),this.updateTarget()},updateTarget:function(){if(this.$target.is(":visible")){var t=this.$source.val();if(void 0!==t){var e=this.generateTargetValue(t);this.$target.val(e);for(var i=0;i<this.$target.length;i++)this.$target[i].dispatchEvent(new InputEvent("input",{inputType:"insertText"})),this.$target[i].dispatchEvent(new Event("input"));this.$target.is(":focus")&&Craft.selectFullValue(this.$target)}}},generateTargetValue:function(t){return t}})},525:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CP=Garnish.Base.extend({authManager:null,$nav:null,$navToggle:null,$globalSidebar:null,$globalContainer:null,$mainContainer:null,$alerts:null,$crumbs:null,$breadcrumbList:null,$breadcrumbItems:null,$notificationContainer:null,$main:null,$primaryForm:null,$headerContainer:null,$header:null,$mainContent:null,$details:null,$sidebarContainer:null,$sidebar:null,$contentContainer:null,$edition:null,$confirmUnloadForms:null,$deltaForms:null,$collapsibleTables:null,isMobile:null,fixedHeader:!1,breadcrumbListWidth:0,breadcrumbDisclosureItem:'<li class="breadcrumb-toggle-wrapper" data-disclosure-item><button data-disclosure-trigger aria-controls="breadcrumb-disclosure" aria-haspopup="true">'.concat(Craft.t("app","More…"),'</button><div id="breadcrumb-disclosure" class="menu menu--disclosure" data-disclosure-menu><ul></ul></div></li>'),tabManager:null,enableQueue:!0,totalJobs:0,jobInfo:null,displayedJobInfo:null,displayedJobInfoUnchanged:1,trackJobProgressTimeout:null,jobProgressIcon:null,checkingForUpdates:!1,forcingRefreshOnUpdatesCheck:!1,includingDetailsOnUpdatesCheck:!1,checkForUpdatesCallbacks:null,resizeTimeout:null,init:function(){var t=this;0!==Craft.remainingSessionTime&&(this.authManager=new Craft.AuthManager),this.$nav=$("#nav"),this.$navToggle=$("#nav-toggle"),this.$globalSidebar=$("#global-sidebar"),this.$globalContainer=$("#global-container"),this.$mainContainer=$("#main-container"),this.$alerts=$("#alerts"),this.$crumbs=$("#crumbs"),this.$breadcrumbList=$(".breadcrumb-list"),this.$breadcrumbItems=$(".breadcrumb-list li"),this.$notificationContainer=$("#notifications"),this.$main=$("#main"),this.$primaryForm=$("#main-form"),this.$headerContainer=$("#header-container"),this.$header=$("#header"),this.$mainContent=$("#main-content"),this.$details=$("#details"),this.$sidebarContainer=$("#sidebar-container"),this.$sidebar=$("#sidebar"),this.$contentContainer=$("#content-container"),this.$collapsibleTables=$("table.collapsible"),this.isMobile=Garnish.isMobileBrowser(),this.updateSidebarMenuLabel();for(var i=this.$details.find(".meta > .field > .instructions"),s=0;s<i.length;s++){var a=i.eq(s),n=a.siblings(".heading").children("label");$("<span/>",{class:"info",html:a.children().html()}).appendTo(n),a.remove()}!this.isMobile&&this.$header.length&&(this.addListener(Garnish.$win,"scroll","updateFixedHeader"),this.updateFixedHeader()),Garnish.$doc.ready((function(){t.addListener(Garnish.$win,"resize",(function(e){if(e.target===window){t.handleWindowResize(),clearTimeout(t.resizeTimeout);var i=t;t.resizeTimeout=setTimeout((function(){i.setSidebarNavAttributes()}),100)}})),t.handleWindowResize(),t.setSidebarNavAttributes();var e=t.$notificationContainer.children(".error"),i=t.$notificationContainer.children(":not(.error)");e.delay(2*Craft.CP.notificationDuration).velocity("fadeOut"),i.delay(Craft.CP.notificationDuration).velocity("fadeOut"),Garnish.requestAnimationFrame(t.initSpecialForms.bind(t))})),this.$alerts.length&&this.initAlerts(),this.addListener(this.$navToggle,"click","toggleNav"),this.addListener($("#sidebar-toggle"),"click","toggleSidebar"),this.$primaryForm.length||(this.$primaryForm=$("form[data-saveshortcut]:first")),this.$primaryForm.length&&Garnish.hasAttr(this.$primaryForm,"data-saveshortcut")&&function(){var e=[],i=t.$primaryForm.data("actions");if(void 0===i)e.push([{keyCode:Garnish.S_KEY,ctrl:!0},{redirect:t.$primaryForm.data("saveshortcut-redirect"),retainScroll:Garnish.hasAttr(t.$primaryForm,"saveshortcut-scroll")}]);else for(var s=0;s<i.length;s++){var a=i[s];a.shortcut&&e.push([{keyCode:Garnish.S_KEY,ctrl:!0,shift:!!a.shift},{action:a.action,redirect:a.redirect,confirm:a.confirm,params:a.params,data:a.data,retainScroll:a.retainScroll}])}for(var n=function(i){Garnish.uiLayerManager.registerShortcut(e[i][0],(function(){t.submitPrimaryForm(e[i][1])}))},r=0;r<e.length;r++)n(r)}(),this.initTabs();var r=Craft.getLocalStorage("scrollY");if(void 0!==r&&(Craft.removeLocalStorage("scrollY"),Garnish.$doc.ready((function(){Garnish.requestAnimationFrame((function(){window.scrollTo(0,r)}))}))),$.isTouchCapable()&&(this.$mainContainer.on("focus","input, textarea, .focusable-input",this._handleInputFocus.bind(this)),this.$mainContainer.on("blur","input, textarea, .focusable-input",this._handleInputBlur.bind(this))),Craft.announcements.length){var o,l=$("#announcements-btn").removeClass("hidden"),h=Craft.announcements.some((function(t){return t.unread}));h&&l.addClass("unread"),this.addListener(l,"click",(function(){if(o)o.show();else{var t="";Craft.group(Craft.announcements,"timestamp").forEach((function(i){var s=function(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(t,i)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(i,2),a=s[0];s[1],a.forEach((function(e,i){t+='<div class="announcement '.concat(e.unread?"unread":"",'">')+(0===i?'<div class="timestamp">'.concat(e.timestamp,"</div>"):"")+"<h2>".concat(e.heading,"</h2>")+"<p>".concat(e.body,"</p>")+"</div>"}))})),o=new Garnish.HUD(l,'<div id="announcements">'.concat(t,"</div>"),{onShow:function(){l.addClass("active")},onHide:function(){l.removeClass("active")}}),$("a",o.$main).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===$(this).attr("target")&&$(this).attr("rel","noopener").attr("target","_blank")})),h&&(l.removeClass("unread"),Craft.sendActionRequest("POST","users/mark-announcements-as-read",{data:{ids:Craft.announcements.map((function(t){return t.id}))}}))}}))}},initSpecialForms:function(){if(this.$confirmUnloadForms=$("form[data-confirm-unload]"),this.$deltaForms=$("form[data-delta]"),this.$confirmUnloadForms.length){for(var t,e,i=this.$confirmUnloadForms.add(this.$deltaForms),s=0;s<i.length;s++)(t=i.eq(s)).data("initialSerializedValue")||(e="function"==typeof t.data("serializer")?t.data("serializer")():t.serialize(),t.data("initialSerializedValue",e)),this.addListener(t,"submit",(function(e){if(Garnish.hasAttr(t,"data-confirm-unload")&&this.removeListener(Garnish.$win,"beforeunload"),Garnish.hasAttr(t,"data-delta")){var i;e.preventDefault(),i="function"==typeof t.data("serializer")?t.data("serializer")():t.serialize();var s=Craft.findDeltaData(t.data("initialSerializedValue"),i,Craft.deltaNames);Craft.createForm(s).appendTo(Garnish.$bod).submit()}}));this.addListener(Garnish.$win,"beforeunload",(function(t){var e,i,s=!1;if(void 0!==Craft.livePreview&&Craft.livePreview.inPreviewMode)s=!0;else for(var a=0;a<this.$confirmUnloadForms.length;a++)if(i="function"==typeof(e=this.$confirmUnloadForms.eq(a)).data("serializer")?e.data("serializer")():e.serialize(),e.data("initialSerializedValue")!==i){s=!0;break}if(s){var n=Craft.t("app","Any changes will be lost if you leave this page.");return t?t.originalEvent.returnValue=n:window.event.returnValue=n,n}}))}},_handleInputFocus:function(){this.updateFixedHeader()},_handleInputBlur:function(){this.updateFixedHeader()},submitPrimaryForm:function(e){this.trigger("beforeSaveShortcut"),"object"===t(e)&&$.isPlainObject(e)||(e={}),e.redirect||(e.redirect=this.$primaryForm.data("saveshortcut-redirect")),e.data||(e.data={}),e.data.saveShortcut=!0,Craft.submitForm(this.$primaryForm,e)},updateSidebarMenuLabel:function(){var t=this.$sidebar.find("a.sel:first"),e=t.children(".label");$("#selected-sidebar-item-label").text(e.length?e.text():t.text()),Garnish.$bod.removeClass("showing-sidebar")},toggleNav:function(){var t=this.navIsExpanded();null!==t&&(t?(this.disableGlobalSidebarLinks(),this.$navToggle.focus(),this.$navToggle.attr("aria-expanded","false"),Garnish.$bod.removeClass("showing-nav")):(this.enableGlobalSidebarLinks(),this.$globalSidebar.find(":focusable")[0].focus(),this.$navToggle.attr("aria-expanded","true"),Garnish.$bod.addClass("showing-nav")))},enableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");$(t).each((function(){$(this).attr("tabindex","0")}))},disableGlobalSidebarLinks:function(){var t=this.$globalSidebar.find(":focusable");$(t).each((function(){$(this).attr("tabindex","-1")}))},setSidebarNavAttributes:function(){var t=this.navIsExpanded();null!==t&&(t?this.enableGlobalSidebarLinks():this.disableGlobalSidebarLinks())},navIsExpanded:function(){if(!this.$globalSidebar[0])return null;var t=getComputedStyle(this.$globalSidebar[0]).getPropertyValue("--is-always-visible").trim();return"true"===this.$navToggle.attr("aria-expanded")||"true"===t},toggleSidebar:function(){Garnish.$bod.toggleClass("showing-sidebar")},initTabs:function(){this.tabManager&&(this.tabManager.destroy(),this.tabManager=null);var t=$("#tabs");if(t.length&&(this.tabManager=new Craft.Tabs(t),this.tabManager.on("selectTab",(function(t){var e=t.$tab.attr("href");if("#"===e.charAt(0)&&$(e).removeClass("hidden"),Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll"),e&&"#"===e.charAt(0)){var i=$("#context-btn").menubtn().data("menubtn");if(i)for(var s=0;s<i.menu.$options.length;s++){var a=i.menu.$options[s];a.href&&(a.href=a.href.match(/^[^#]*/)[0]+e)}}"undefined"!=typeof history&&Garnish.requestAnimationFrame((function(){history.replaceState(void 0,void 0,e)}))})),this.tabManager.on("deselectTab",(function(t){"#"===t.$tab.attr("href").charAt(0)&&$(t.$tab.attr("href")).addClass("hidden")})),window.LOCATION_HASH)){var e=this.tabManager.$tabs.filter('[href="#'.concat(window.LOCATION_HASH,'"]'));e.length&&this.tabManager.selectTab(e)}},get $tabsContainer(){return this.tabManager?this.tabManager.$container:void 0},get $tabsList(){return this.tabManager?this.tabManager.$ul:void 0},get $tabs(){return this.tabManager?this.tabManager.$ul.find("> li"):void 0},get $selectedTab(){return this.tabManager?this.tabManager.$selectedTab:void 0},get selectedTabIndex(){return this.tabManager?this.tabManager.$tabs.index(this.tabManager.$selectedTab):void 0},get $focusableTab(){return this.tabManager?this.tabManager.$focusableTab:void 0},selectTab:function(t){this.tabManager&&this.tabManager.selectTab(t)},deselectTab:function(){this.tabManager&&this.tabManager.deselectTab()},handleWindowResize:function(){this.updateResponsiveTables(),this.handleBreadcrumbVisibility()},breadcrumbItemsWrap:function(){if(this.$breadcrumbItems[0]){this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","");for(var t=this.$breadcrumbList[0].getBoundingClientRect().width,e=0,i=this.$breadcrumbList.find("li"),s=0;s<i.length;s++)e+=i.get(s).getBoundingClientRect().width;return this.breadcrumbListWidth=t,!(e<=t||e<t+1&&(this.$breadcrumbList.css("ltr"===Craft.orientation?"margin-right":"margin-left","-1px"),1))}},handleBreadcrumbVisibility:function(){if(this.breadcrumbItemsWrap()){0===this.$breadcrumbList.find("[data-disclosure-item]").length&&this.$breadcrumbList.append(this.breadcrumbDisclosureItem);var t,e=this.$breadcrumbList.find("[data-disclosure-item]")[0].offsetWidth,i=this.breadcrumbListWidth;this.$breadcrumbItems.each((function(s){if(!(e+this.offsetWidth<i))return!1;t=s,e+=this.offsetWidth}));var s=this.$breadcrumbItems.slice(0,t+1),a=this.$breadcrumbItems.slice(t+1);this.$breadcrumbList.html(""),this.$breadcrumbList.append(s),this.$breadcrumbList.append(this.breadcrumbDisclosureItem),this.$breadcrumbList.find("[data-disclosure-menu] ul").append(a),this.$breadcrumbList.find("[data-disclosure-trigger]").disclosureMenu()}},updateResponsiveTables:function(){for(this.updateResponsiveTables._i=0;this.updateResponsiveTables._i<this.$collapsibleTables.length;this.updateResponsiveTables._i++)this.updateResponsiveTables._$table=this.$collapsibleTables.eq(this.updateResponsiveTables._i),this.updateResponsiveTables._containerWidth=this.updateResponsiveTables._$table.parent().width(),this.updateResponsiveTables._check=!1,this.updateResponsiveTables._containerWidth>0&&(void 0===this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._check=!0:(this.updateResponsiveTables._isCollapsed=this.updateResponsiveTables._$table.hasClass("collapsed"),this.updateResponsiveTables._containerWidth>this.updateResponsiveTables._$table.data("lastContainerWidth")?this.updateResponsiveTables._isCollapsed&&(this.updateResponsiveTables._$table.removeClass("collapsed"),this.updateResponsiveTables._check=!0):this.updateResponsiveTables._isCollapsed||(this.updateResponsiveTables._check=!0)),this.updateResponsiveTables._check&&this.updateResponsiveTables._$table.width()-30>this.updateResponsiveTables._containerWidth&&this.updateResponsiveTables._$table.addClass("collapsed"),this.updateResponsiveTables._$table.data("lastContainerWidth",this.updateResponsiveTables._containerWidth))},updateFixedHeader:function(){if(!this.isMobile)if(this.$main.length&&this.$headerContainer[0].getBoundingClientRect().top<0){if(!this.fixedHeader){var t=this.$headerContainer.height();this.$contentContainer.css("min-height","calc(100vh - "+(t+14+48-1)+"px)"),this.$headerContainer.height(t),Garnish.$bod.addClass("fixed-header"),this.$contentContainer.outerHeight(),this.$details.outerHeight();var e={top:t+"px","max-height":"calc(100vh - "+t+"px)"};this.$sidebar.addClass("fixed").css(e),this.$details.addClass("fixed").css(e),this.fixedHeader=!0}}else this.fixedHeader&&(this.$headerContainer.height("auto"),Garnish.$bod.removeClass("fixed-header"),this.$contentContainer.css("min-height",""),this.$sidebar.removeClass("fixed").css({top:"","max-height":""}),this.$details.removeClass("fixed").css({top:"","max-height":""}),this.fixedHeader=!1)},displayNotification:function(t,e){var i=Craft.CP.notificationDuration;["cp-error","error"].includes(t)?(i*=2,icon="alert",label=Craft.t("app","Error")):(icon="info",label=Craft.t("app","Notice"));var s=$('\n            <div class="notification '.concat(t.replace("cp-",""),'">\n                <span data-icon="').concat(icon,'" aria-label="').concat(label,'"></span>\n                ').concat(e,"\n            </div>\n            ")).appendTo(this.$notificationContainer),a=-s.outerWidth()/2+"px";s.hide().css({opacity:0,"margin-left":a,"margin-right":a}).velocity({opacity:1,"margin-left":"2px","margin-right":"2px"},{display:"inline-block",duration:"fast"}).delay(i).velocity({opacity:0,"margin-left":a,"margin-right":a},{complete:function(){s.remove()}}),this.trigger("displayNotification",{notificationType:t,message:e})},displayNotice:function(t){this.displayNotification("notice",t)},displayError:function(t){t||(t=Craft.t("app","A server error occurred.")),this.displayNotification("error",t)},fetchAlerts:function(){var t={path:Craft.path};Craft.queueActionRequest("app/get-cp-alerts",t,this.displayAlerts.bind(this))},displayAlerts:function(t){if(this.$alerts.remove(),Garnish.isArray(t)&&t.length){this.$alerts=$('<ul id="alerts"/>').prependTo($("#page-container"));for(var e=0;e<t.length;e++)$('<li><span data-icon="alert" aria-label="'.concat(Craft.t("app","Error"),'"></span> ').concat(t[e],"</li>")).appendTo(this.$alerts);var i=this.$alerts.outerHeight();this.$alerts.css("margin-top",-i).velocity({"margin-top":0},"fast"),this.initAlerts()}},initAlerts:function(){for(var t=this,e=this.$alerts.find('a[class^="shun:"]'),i=0;i<e.length;i++)this.addListener(e[i],"click",(function(e){e.preventDefault();var i=$(e.currentTarget),s={message:i.prop("className").substr(5)};Craft.queueActionRequest("app/shun-cp-alert",s,(function(e,s){"success"===s&&(e.success?i.parent().remove():t.displayError(e.error))}))}))},checkForUpdates:function(t,e,i){var s=this;if("function"==typeof e&&(i=e,e=!1),this.checkingForUpdates&&(!0===t&&!this.forcingRefreshOnUpdatesCheck||!0===e&&!this.includingDetailsOnUpdatesCheck)){var a=i;i=function(){s.checkForUpdates(t,e,a)}}"function"==typeof i&&(Garnish.isArray(this.checkForUpdatesCallbacks)||(this.checkForUpdatesCallbacks=[]),this.checkForUpdatesCallbacks.push(i)),this.checkingForUpdates||(this.checkingForUpdates=!0,this.forcingRefreshOnUpdatesCheck=!0===t,this.includingDetailsOnUpdatesCheck=!0===e,this._checkForUpdates(t,e).then((function(t){if(s.updateUtilitiesBadge(),s.checkingForUpdates=!1,Garnish.isArray(s.checkForUpdatesCallbacks)){var e=s.checkForUpdatesCallbacks;s.checkForUpdatesCallbacks=null;for(var i=0;i<e.length;i++)e[i](t)}s.trigger("checkForUpdates",{updateInfo:t})})))},_checkForUpdates:function(t,e){var i=this;return new Promise((function(s,a){t?i._getUpdates(e).then((function(t){s(t)})):i._checkForCachedUpdates(e).then((function(t){!1!==t.cached&&s(t),i._getUpdates(e).then((function(t){s(t)}))}))}))},_checkForCachedUpdates:function(t){return new Promise((function(e,i){var s={onlyIfCached:!0,includeDetails:t};Craft.postActionRequest("app/check-for-updates",s,(function(t,i){e("success"===i?t:{cached:!1})}))}))},_getUpdates:function(t){var e=this;return new Promise((function(i,s){Craft.sendApiRequest("GET","updates").then((function(s){e._cacheUpdates(s,t).then(i)})).catch((function(t){e._cacheUpdates({}).then(i)}))}))},_cacheUpdates:function(t,e){return new Promise((function(i,s){Craft.postActionRequest("app/cache-updates",{updates:t,includeDetails:e},(function(t,e){"success"===e?i(t):s()}),{contentType:"json"})}))},updateUtilitiesBadge:function(){var t=$("#nav-utilities").find("> a:not(.sel)");t.length&&Craft.queueActionRequest("app/get-utilities-badge-count",(function(e){var i=t.children(".badge");e.badgeCount?(i.length||(i=$('<span class="badge"/>').appendTo(t)),i.text(e.badgeCount)):i.length&&i.remove()}))},runQueue:function(){var t=this;this.enableQueue&&(Craft.runQueueAutomatically?Craft.queueActionRequest("queue/run",(function(e,i){"success"===i&&t.trackJobProgress(!1,!0)})):this.trackJobProgress(!1,!0))},trackJobProgress:function(t,e){if(e&&this.trackJobProgressTimeout&&(clearTimeout(this.trackJobProgressTimeout),this.trackJobProgressTimeout=null),!this.trackJobProgressTimeout&&this.enableQueue)if(!0===t){var i=Math.min(6e4,500*this.displayedJobInfoUnchanged);this.trackJobProgressTimeout=setTimeout(this._trackJobProgressInternal.bind(this),i)}else this._trackJobProgressInternal()},_trackJobProgressInternal:function(){var t=this;Craft.queueActionRequest("queue/get-job-info?limit=50&dontExtendSession=1",(function(e,i){"success"===i&&(t.trackJobProgressTimeout=null,t.totalJobs=e.total,t.setJobInfo(e.jobs),t.jobInfo.length&&t.trackJobProgress(!0))}))},setJobInfo:function(t){if(this.enableQueue){this.jobInfo=t;var e=this.displayedJobInfo;this.displayedJobInfo=this.getDisplayedJobInfo(),e&&this.displayedJobInfo&&e.id===this.displayedJobInfo.id&&e.progress===this.displayedJobInfo.progress&&e.progressLabel===this.displayedJobInfo.progressLabel&&e.status===this.displayedJobInfo.status?this.displayedJobInfoUnchanged++:this.displayedJobInfoUnchanged=1,this.updateJobIcon(),this.trigger("setJobInfo")}},getDisplayedJobInfo:function(){if(!this.enableQueue)return null;for(var t=[Craft.CP.JOB_STATUS_RESERVED,Craft.CP.JOB_STATUS_FAILED,Craft.CP.JOB_STATUS_WAITING],e=0;e<t.length;e++)for(var i=0;i<this.jobInfo.length;i++)if(this.jobInfo[i].status===t[e]&&(t[e]!==Craft.CP.JOB_STATUS_WAITING||!this.jobInfo[i].delay))return this.jobInfo[i];return null},updateJobIcon:function(){this.enableQueue&&this.$nav.length&&(this.displayedJobInfo?(this.jobProgressIcon||(this.jobProgressIcon=new i),this.displayedJobInfo.status===Craft.CP.JOB_STATUS_RESERVED||this.displayedJobInfo.status===Craft.CP.JOB_STATUS_WAITING?(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.setDescription(this.displayedJobInfo.description,this.displayedJobInfo.progressLabel),this.jobProgressIcon.setProgress(this.displayedJobInfo.progress)):this.displayedJobInfo.status===Craft.CP.JOB_STATUS_FAILED&&this.jobProgressIcon.showFailMode(Craft.t("app","Failed"))):this.jobProgressIcon&&(this.jobProgressIcon.hideFailMode(),this.jobProgressIcon.complete(),delete this.jobProgressIcon))},getSiteId:function(){var t=Craft.getLocalStorage("BaseElementIndex.siteId");return void 0!==t?(Craft.removeLocalStorage("BaseElementIndex.siteId"),this.setSiteId(t),t):Craft.getCookie("siteId")},setSiteId:function(t){Craft.setCookie("siteId",t,{maxAge:31536e3})}},{notificationDuration:2e3,JOB_STATUS_WAITING:1,JOB_STATUS_RESERVED:2,JOB_STATUS_DONE:3,JOB_STATUS_FAILED:4}),Garnish.$scrollContainer=Garnish.$win,Craft.cp=new Craft.CP;var i=Garnish.Base.extend({$li:null,$a:null,$label:null,$progressLabel:null,progress:null,failMode:!1,_$bgCanvas:null,_$staticCanvas:null,_$hoverCanvas:null,_$failCanvas:null,_staticCtx:null,_hoverCtx:null,_canvasSize:null,_arcPos:null,_arcRadius:null,_lineWidth:null,_arcStartPos:0,_arcEndPos:0,_arcStartStepSize:null,_arcEndStepSize:null,_arcStep:null,_arcStepTimeout:null,_arcAnimateCallback:null,_progressBar:null,init:function(){this.$li=$("<li/>").appendTo(Craft.cp.$nav.children("ul")),this.$a=$("<a/>",{id:"job-icon",href:Craft.canAccessQueueManager?Craft.getUrl("utilities/queue-manager"):null}).appendTo(this.$li),this.$canvasContainer=$('<span class="icon"/>').appendTo(this.$a);var t=$('<span class="label"/>').appendTo(this.$a);this.$label=$("<span/>").appendTo(t),this.$progressLabel=$('<span class="progress-label"/>').appendTo(t).hide();var e=window.devicePixelRatio>1?2:1;this._canvasSize=18*e,this._arcPos=this._canvasSize/2,this._arcRadius=7*e,this._lineWidth=3*e,this._$bgCanvas=this._createCanvas("bg","#61666b"),this._$staticCanvas=this._createCanvas("static","#d7d9db"),this._$hoverCanvas=this._createCanvas("hover","#fff"),this._$failCanvas=this._createCanvas("fail","#da5a47").hide(),this._staticCtx=this._$staticCanvas[0].getContext("2d"),this._hoverCtx=this._$hoverCanvas[0].getContext("2d"),this._drawArc(this._$bgCanvas[0].getContext("2d"),0,1),this._drawArc(this._$failCanvas[0].getContext("2d"),0,1)},setDescription:function(t,e){this.$a.attr("title",t),this.$label.text(t),e?this.$progressLabel.text(e).show():this.$progressLabel.hide()},setProgress:function(t){0==t?(this._$staticCanvas.hide(),this._$hoverCanvas.hide()):(this._$staticCanvas.show(),this._$hoverCanvas.show(),this.progress&&t>this.progress?this._animateArc(0,t/100):this._setArc(0,t/100)),this.progress=t},complete:function(){var t=this;this._animateArc(0,1,(function(){t._$bgCanvas.velocity("fadeOut"),t._animateArc(1,1,(function(){t.$a.remove(),t.destroy()}))}))},showFailMode:function(t){this.failMode||(this.failMode=!0,this.progress=null,this._$bgCanvas.hide(),this._$staticCanvas.hide(),this._$hoverCanvas.hide(),this._$failCanvas.show(),this.setDescription(t))},hideFailMode:function(){this.failMode&&(this.failMode=!1,this._$bgCanvas.show(),this._$staticCanvas.show(),this._$hoverCanvas.show(),this._$failCanvas.hide())},_createCanvas:function(t,e){var i=$('<canvas id="job-icon-'+t+'" width="'+this._canvasSize+'" height="'+this._canvasSize+'"/>').appendTo(this.$canvasContainer),s=i[0].getContext("2d");return s.strokeStyle=e,s.lineWidth=this._lineWidth,s.lineCap="round",i},_setArc:function(t,e){this._arcStartPos=t,this._arcEndPos=e,this._drawArc(this._staticCtx,t,e),this._drawArc(this._hoverCtx,t,e)},_drawArc:function(t,e,i){t.clearRect(0,0,this._canvasSize,this._canvasSize),t.beginPath(),t.arc(this._arcPos,this._arcPos,this._arcRadius,(1.5+2*e)*Math.PI,(1.5+2*i)*Math.PI),t.stroke(),t.closePath()},_animateArc:function(t,e,i){this._arcStepTimeout&&clearTimeout(this._arcStepTimeout),this._arcStep=0,this._arcStartStepSize=(t-this._arcStartPos)/10,this._arcEndStepSize=(e-this._arcEndPos)/10,this._arcAnimateCallback=i,this._takeNextArcStep()},_takeNextArcStep:function(){this._setArc(this._arcStartPos+this._arcStartStepSize,this._arcEndPos+this._arcEndStepSize),this._arcStep++,this._arcStep<10?this._arcStepTimeout=setTimeout(this._takeNextArcStep.bind(this),50):this._arcAnimateCallback&&this._arcAnimateCallback()}})},3778:function(){Craft.CategoryIndex=Craft.BaseElementIndex.extend({editableGroups:null,$newCategoryBtnGroup:null,$newCategoryBtn:null,init:function(t,e,i){this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){this.editableGroups=[];for(var t=0;t<Craft.editableCategoryGroups.length;t++){var e=Craft.editableCategoryGroups[t];this.getSourceByKey("group:"+e.uid)&&this.editableGroups.push(e)}this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultGroupHandle)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultGroupHandle)return e.data("key")}return this.base()},updateButton:function(){var t=this;if(this.$source){var e,i,s,a=this.$source.data("handle");if(this.editableGroups.length){var n,r;if(this.$newCategoryBtnGroup&&this.$newCategoryBtnGroup.remove(),a)for(e=0;e<this.editableGroups.length;e++)if(this.editableGroups[e].handle===a){n=this.editableGroups[e];break}if(this.$newCategoryBtnGroup=$('<div class="btngroup submit"/>'),n?(i=this._getGroupTriggerHref(n),s="index"===this.settings.context?Craft.t("app","New category"):Craft.t("app","New {group} category",{group:n.name}),this.$newCategoryBtn=$('<a class="btn submit add icon" '+i+' role="button">'+Craft.escapeHtml(s)+"</a>").appendTo(this.$newCategoryBtnGroup),"index"!==this.settings.context&&this.addListener(this.$newCategoryBtn,"click",(function(t){this._openCreateCategoryModal(t.currentTarget.getAttribute("data-id"))})),this.editableGroups.length>1&&(r=$("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newCategoryBtnGroup))):this.$newCategoryBtn=r=$("<button/>",{type:"button",class:"btn submit add icon menubtn",text:Craft.t("app","New category")}).appendTo(this.$newCategoryBtnGroup),r){var o='<div class="menu"><ul>';for(e=0;e<this.editableGroups.length;e++){var l=this.editableGroups[e];"index"!==this.settings.context&&l===n||(i=this._getGroupTriggerHref(l),s="index"===this.settings.context?l.name:Craft.t("app","New {group} category",{group:l.name}),o+="<li><a "+i+">"+Craft.escapeHtml(s)+"</a></li>")}o+="</ul></div>",$(o).appendTo(this.$newCategoryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",(function(e){t._openCreateCategoryModal(e.option.getAttribute("data-id"))}))}this.addButton(this.$newCategoryBtnGroup)}if("index"===this.settings.context&&"undefined"!=typeof history){var d="categories";a&&(d+="/"+a),history.replaceState({},"",Craft.getUrl(d))}}},_getGroupTriggerHref:function(t){if("index"===this.settings.context){var e="categories/".concat(t.handle,"/new"),i=this.getSite(),s=i?{site:i.handle}:void 0;return'href="'.concat(Craft.getUrl(e,s),'"')}return'data-id="'.concat(t.id,'"')},_openCreateCategoryModal:function(t){var e=this;if(!this.$newCategoryBtn.hasClass("loading")){for(var i,s=0;s<this.editableGroups.length;s++)if(this.editableGroups[s].id==t){i=this.editableGroups[s];break}if(i){this.$newCategoryBtn.addClass("inactive");var a=this.$newCategoryBtn.text();this.$newCategoryBtn.text(Craft.t("app","New {group} category",{group:i.name})),Craft.createElementEditor(this.elementType,{hudTrigger:this.$newCategoryBtnGroup,siteId:this.siteId,attributes:{groupId:t},onHideHud:function(){e.$newCategoryBtn.removeClass("inactive").text(a)},onSaveElement:function(t){var s="group:"+i.uid;e.sourceKey!==s&&e.selectSourceByKey(s),e.clearSearch(),e.selectElementAfterUpdate(t.id),e.updateElements()}})}}}}),Craft.registerElementIndexClass("craft\\elements\\Category",Craft.CategoryIndex)},6617:function(){Craft.CategorySelectInput=Craft.BaseElementSelectInput.extend({setSettings:function(){this.base.apply(this,arguments),this.settings.sortable=!1},getModalSettings:function(){var t=this.base();return t.hideOnSelect=!1,t},getElements:function(){return this.$elementsContainer.find(".element")},onModalSelect:function(t){var e=this;this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<t.length;s++)i.push(t[s].id);var a={categoryIds:i,siteId:t[0].siteId,id:this.settings.id,name:this.settings.name,branchLimit:this.settings.branchLimit,selectionLabel:this.settings.selectionLabel};Craft.postActionRequest("elements/get-categories-input-html",a,(function(i,s){if(e.modal.enable(),e.modal.enableCancelBtn(),e.modal.enableSelectBtn(),e.modal.hideFooterSpinner(),"success"===s){var a=$(i.html).children(".elements");e.$elementsContainer.replaceWith(a),e.$elementsContainer=a,e.resetElements();for(var n=[],r=0;r<t.length;r++){var o=t[r],l=e.getElementById(o.id);l&&(e.animateElementIntoPlace(o.$element,l),n.push(o))}e.updateDisabledElementsInModal(),e.modal.hide(),e.onSelectElements(n)}}))},removeElement:function(t){var e=t.add(t.parent().siblings("ul").find(".element"));this.removeElements(e);for(var i=0;i<e.length;i++)this._animateCategoryAway(e,i)},_animateCategoryAway:function(t,e){var i,s=this;e===t.length-1&&(i=function(){var e=t.first().parent().parent(),i=e.parent();i[0]===s.$elementsContainer[0]||e.siblings().length?e.remove():i.remove()});var a=function(){s.animateElementAway(t.eq(e),i)};0===e?a():setTimeout(a,100*e)}})},9482:function(){Craft.charts={},Craft.charts.DataTable=Garnish.Base.extend({columns:null,rows:null,init:function(t){var e=t.columns,i=t.rows;i.forEach((function(t){$.each(t,(function(i){var s;switch(e[i].type){case"date":s=d3.timeParse("%Y-%m-%d"),t[i]=s(t[i]);break;case"datetime":s=d3.timeParse("%Y-%m-%d %H:00:00"),t[i]=s(t[i]);break;case"percent":t[i]=t[i]/100;break;case"number":t[i]=+t[i]}}))})),this.columns=e,this.rows=i}}),Craft.charts.Tip=Garnish.Base.extend({$container:null,$tip:null,init:function(t){this.$container=t,this.$tip=$('<div class="tooltip"></div>').appendTo(this.$container),this.hide()},setContent:function(t){this.$tip.html(t)},setPosition:function(t){this.$tip.css("left","".concat(t.left,"px")),this.$tip.css("top","".concat(t.top,"px"))},show:function(){this.$tip.css("display","block")},hide:function(){this.$tip.css("display","none")}}),Craft.charts.BaseChart=Garnish.Base.extend({$container:null,$chart:null,chartBaseClass:"cp-chart",dataTable:null,formatLocale:null,timeFormatLocale:null,orientation:null,svg:null,width:null,height:null,init:function(t,e){var i=this;this.$container=t,this.setSettings(Craft.charts.BaseChart.defaults),this.setSettings(e);var s={formats:window.d3Formats,formatLocaleDefinition:window.d3FormatLocaleDefinition,timeFormatLocaleDefinition:window.d3TimeFormatLocaleDefinition};this.setSettings(s),d3.select(window).on("resize",(function(){i.resize()}))},setSettings:function(t,e){var i=void 0===this.settings?{}:this.settings;this.settings=$.extend(!0,{},i,e,t)},draw:function(t,e){this.setSettings(e),this.dataTable=t,this.formatLocale=d3.formatLocale(this.settings.formatLocaleDefinition),this.timeFormatLocale=d3.timeFormatLocale(this.settings.timeFormatLocaleDefinition),this.orientation=this.settings.orientation,this.$chart&&this.$chart.remove();var i=this.chartBaseClass;this.settings.chartClass&&(i+=" "+this.settings.chartClass),this.$chart=$('<div class="'.concat(i,'" />')).appendTo(this.$container)},resize:function(){this.draw(this.dataTable,this.settings)},onAfterDrawTicks:function(){$(".tick",this.$chart).each((function(t,e){var i=$("text",e);i.clone().appendTo(e),i.attr("stroke","#ffffff"),i.attr("stroke-width",3)}))}},{defaults:{formatLocaleDefinition:null,timeFormatLocaleDefinition:null,formats:{numberFormat:",.2f",percentFormat:",.2%",currencyFormat:"$,.2f",shortDateFormats:{day:"%-m/%-d",month:"%-m/%y",year:"%Y"}},margin:{top:0,right:0,bottom:0,left:0},chartClass:null,colors:["#0594D1","#DE3800","#FF9A00","#009802","#9B009B"]}}),Craft.charts.Area=Craft.charts.BaseChart.extend({tip:null,drawingArea:null,init:function(t,e){this.base(t,Craft.charts.Area.defaults),this.setSettings(e)},draw:function(t,e){this.base(t,e),this.tip&&(this.tip=null);var i=this.getChartMargin();this.width=this.$chart.width()-i.left-i.right,this.height=this.$chart.height()-i.top-i.bottom;var s={width:this.width+(i.left+i.right),height:this.height+(i.top+i.bottom),translateX:"rtl"!==this.orientation?i.left:i.right,translateY:i.top};this.svg=d3.select(this.$chart.get(0)).append("svg").attr("width",s.width).attr("height",s.height),this.drawingArea=this.svg.append("g").attr("transform","translate(".concat(s.translateX,",").concat(s.translateY,")")),this.drawTicks(),this.drawAxes(),this.drawChart(),this.drawTipTriggers()},drawTicks:function(){var t=this.getX(!0),e=d3.axisBottom(t).tickFormat(this.getXFormatter()).ticks(3);this.drawingArea.append("g").attr("class","x ticks-axis").attr("transform","translate(0, ".concat(this.height,")")).call(e);var i,s=this.getY();"rtl"!==this.orientation?(i=d3.axisLeft(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").call(i)):(i=d3.axisRight(s).tickFormat(this.getYFormatter()).tickValues(this.getYTickValues()).ticks(2),this.drawingArea.append("g").attr("class","y ticks-axis").attr("transform","translate(".concat(this.width,",0)")).call(i)),this.onAfterDrawTicks()},drawAxes:function(){if(this.settings.xAxis.showAxis){var t=this.getX(),e=d3.axisBottom(t).ticks(0).tickSizeOuter(0);this.drawingArea.append("g").attr("class","x axis").attr("transform","translate(0, ".concat(this.height,")")).call(e)}if(this.settings.yAxis.showAxis){var i,s=this.getY();"rtl"===this.orientation?(i=d3.axisLeft(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(this.width-0,", 0)")).call(i)):(i=d3.axisRight(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(".concat(0,", 0)")).call(i))}},drawChart:function(){var t=this.getX(!0),e=this.getY();if(this.settings.xAxis.gridlines){var i=d3.axisBottom(t);this.drawingArea.append("g").attr("class","x grid-line").attr("transform","translate(0,".concat(this.height,")")).call(i.tickSize(-this.height,0,0).tickFormat(""))}if(this.settings.yAxis.gridlines){var s=d3.axisLeft(e);this.drawingArea.append("g").attr("class","y grid-line").attr("transform","translate(0 , 0)").call(s.tickSize(-this.width,0).tickFormat("").tickValues(this.getYTickValues()).ticks(2))}var a=d3.line().x((function(e){return t(e[0])})).y((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-line").append("path").datum(this.dataTable.rows).style("fill","none").style("stroke",this.settings.colors[0]).style("stroke-width","3px").attr("d",a);var n=d3.area().x((function(e){return t(e[0])})).y0(this.height).y1((function(t){return e(t[1])}));this.drawingArea.append("g").attr("class","chart-area").append("path").datum(this.dataTable.rows).style("fill",this.settings.colors[0]).style("fill-opacity","0.3").attr("d",n),this.settings.plots&&this.drawingArea.append("g").attr("class","plots").selectAll("circle").data(this.dataTable.rows).enter().append("circle").style("fill",this.settings.colors[0]).attr("class",(function(t,e){return"plot plot-".concat(e)})).attr("r",4).attr("cx",(function(e){return t(e[0])})).attr("cy",(function(t){return e(t[1])}))},drawTipTriggers:function(){var t=this;if(this.settings.tips){this.tip||(this.tip=new Craft.charts.Tip(this.$chart));var e=this.getChartMargin(),i=(this.drawingArea.select(".x path.domain").node().getTotalLength()-e.left-e.right-12)/(this.dataTable.rows.length-1),s=Math.max(0,i),a=this.getX(!0),n=this.getY();this.drawingArea.append("g").attr("class","tip-triggers").selectAll("rect").data(this.dataTable.rows).enter().append("rect").attr("class","tip-trigger").style("fill","transparent").style("fill-opacity","1").attr("width",s).attr("height",this.height).attr("x",(function(t){return a(t[0])-s/2})).on("mouseover",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",5);var s=$("<div />"),r=$('<div class="x-value" />').appendTo(s),o=$('<div class="y-value" />').appendTo(s);r.html(t.getXFormatter()(e[0])),o.html(t.getYFormatter()(e[1]));var l=s.get(0);t.tip.setContent(l);var h,d=t.getChartMargin(),c=24,u=n(e[1])+c;"rtl"!==t.orientation?(h=a(e[0])+d.left+c,t.$chart.offset().left+h+t.tip.$tip.width()>t.$chart.offset().left+t.$chart.width()-c&&(h=a(e[0])-(t.tip.$tip.width()+c))):h=a(e[0])-(t.tip.$tip.width()+d.left+c),h<0&&(h=a(e[0])+d.left+c);var p={top:u,left:h};t.tip.setPosition(p),t.tip.show()})).on("mouseout",(function(e,i){t.drawingArea.select(".plot-"+i).attr("r",4),t.tip.hide()}))}},getChartMargin:function(){var t=this,e=this.settings.margin,i=this.getYTickValues(),s=0;return $.each(i,(function(e,i){var a=8*t.getYFormatter()(i).length;a>s&&(s=a)})),s+=10,e.left=s,e},getX:function(t){var e=d3.min(this.dataTable.rows,(function(t){return t[0]})),i=d3.max(this.dataTable.rows,(function(t){return t[0]})),s=[e,i];"rtl"===this.orientation&&(s=[i,e]);var a=0,n=0;t&&(a=0,n=0);var r=d3.scaleTime().range([a,this.width-n]);return r.domain(s),r},getY:function(){var t=[0,this.getYMaxValue()],e=d3.scaleLinear().range([this.height,0]);return e.domain(t),e},getXFormatter:function(){return this.settings.xAxis.formatter!==$.noop?this.settings.xAxis.formatter(this):Craft.charts.utils.getTimeFormatter(this.timeFormatLocale,this.settings)},getYFormatter:function(){return this.settings.yAxis.formatter!==$.noop?this.settings.yAxis.formatter(this):Craft.charts.utils.getNumberFormatter(this.formatLocale,this.dataTable.columns[1].type,this.settings)},getYMaxValue:function(){return d3.max(this.dataTable.rows,(function(t){return t[1]}))},getYTickValues:function(){var t=this.getYMaxValue();return t>1?[t/2,t]:[0,t]}},{defaults:{chartClass:"area",margin:{top:25,right:5,bottom:25,left:0},plots:!0,tips:!0,xAxis:{gridlines:!1,showAxis:!0,formatter:$.noop},yAxis:{gridlines:!0,showAxis:!1,formatter:$.noop}}}),Craft.charts.utils={getDuration:function(t){var e=parseInt(t,10),i={hours:Math.floor(e/3600),minutes:Math.floor((e-3600*i.hours)/60),seconds:e-3600*i.hours-60*i.minutes};return i.hours<10&&(i.hours="0".concat(i.hours)),i.minutes<10&&(i.minutes="0".concat(i.minutes)),i.seconds<10&&(i.seconds="0".concat(i.seconds)),"".concat(i.hours,":").concat(i.minutes,":").concat(i.seconds)},getTimeFormatter:function(t,e){switch(e.dataScale){case"year":return t.format("%Y");case"month":return t.format(e.formats.shortDateFormats.month);case"hour":return t.format("".concat(e.formats.shortDateFormats.day," %H:00:00"));default:return t.format(e.formats.shortDateFormats.day)}},getNumberFormatter:function(t,e,i){switch(e){case"currency":return t.format(i.formats.currencyFormat);case"percent":return t.format(i.formats.percentFormat);case"time":return Craft.charts.utils.getDuration;case"number":return t.format(i.formats.numberFormat)}}}},3352:function(){Craft.ColorInput=Garnish.Base.extend({$container:null,$input:null,$colorContainer:null,$colorPreview:null,$colorInput:null,init:function(t){this.$container=$(t),this.$input=this.$container.find(".color-input"),this.$colorContainer=this.$container.children(".color"),this.$colorPreview=this.$colorContainer.children(".color-preview"),this.createColorInput(),this.handleTextChange(),this.addListener(this.$input,"input","handleTextChange")},createColorInput:function(){var t=document.createElement("input");t.setAttribute("type","color"),"color"===t.type&&(this.$colorContainer.removeClass("static"),this.$colorInput=$(t).addClass("color-preview-input").attr({"aria-controls":this.$input.attr("id"),"aria-label":Craft.t("app","Color picker")}).appendTo(this.$colorPreview),this.addListener(this.$colorInput,"click",(function(t){t.stopPropagation()})),this.addListener(this.$colorContainer,"click",(function(){this.$colorInput.trigger("click")})),this.addListener(this.$colorInput,"input","updateColor"))},updateColor:function(){this.$input.val(this.$colorInput.val()),this.handleTextChange()},handleTextChange:function(){var t=this.$input.val();t!==(t=Craft.trim(t))&&this.$input.val(t),t.length&&"#"===t[0]&&(t=t.substr(1),this.$input.val(t)),t.length?(3===t.length&&(t=t[0].repeat(2)+t[1].repeat(2)+t[2].repeat(2)),t.match(/^[0-9a-f]{6}$/i)?(this.$colorPreview.css("background-color","#".concat(t)),this.$colorInput&&this.$colorInput.val("#".concat(t))):this.$colorPreview.css("background-color","")):this.$colorPreview.css("background-color","")}},{_browserSupportsColorInputs:null,doesBrowserSupportColorInputs:function(){return Craft.ColorInput._browserSupportsColorInputs,Craft.ColorInput._browserSupportsColorInputs}})},587:function(){function t(t){return function(t){if(Array.isArray(t))return i(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}function s(t){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},s(t)}var a=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi;jQuery.htmlPrefilter=function(t){return t.replace(a,"<$1></$2>")},$.extend(Craft,{navHeight:48,index:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.index() must be an array.";return t.reduce((function(t,i,s){return t["string"==typeof e?i[e]:e(i,s)]=i,t}),{})},group:function(t,e){if(!$.isArray(t))throw"The first argument passed to Craft.group() must be an array.";var i={};return t.reduce((function(t,s,a){var n="string"==typeof e?s[e]:e(s,a);return i.hasOwnProperty(n)||(i[n]=[[],n],t.push(i[n])),i[n][0].push(s),t}),[])},t:function(t,e,i){return void 0!==Craft.translations[t]&&void 0!==Craft.translations[t][e]&&(e=Craft.translations[t][e]),i?this.formatMessage(e,i):e},formatMessage:function(t,e){var i;if(!1===(i=this._tokenizePattern(t)))throw"Message pattern is invalid.";for(var a=0;a<i.length;a++){var n=i[a];if("object"===s(n)&&!1===(i[a]=this._parseToken(n,e)))throw"Message pattern is invalid."}return i.join("")},_tokenizePattern:function(e){var i,s,a=1,n=t(e);if(-1===(i=s=n.indexOf("{")))return[e];for(var r=[n.slice(0,s).join("")];;){var o=n.indexOf("{",s+1),l=n.indexOf("}",s+1);if(-1===o&&(o=!1),-1===l&&(l=!1),!1===o&&!1===l)break;if(!1===o&&(o=n.length),l>o?(a++,s=o):(a--,s=l),0===a&&(r.push(n.slice(i+1,s).join("").split(",",3)),i=s+1,r.push(n.slice(i,o).join("")),i=o),0!==a&&(!1===o||!1===l))break}return 0===a&&r},_parseToken:function(e,i){var a=this,n=Craft.trim(e[0]);if(void 0===i[n])return"{".concat(e.join(","),"}");var r=i[n],o=void 0!==e[1]?Craft.trim(e[1]):"none";switch(o){case"number":return function(){var t=void 0!==e[2]?Craft.trim(e[2]):null;if(null!==t&&"integer"!==t)throw"Message format 'number' is only supported for integer values.";var i,s=Craft.formatNumber(r);return null===t&&-1!==(i="".concat(r).indexOf("."))&&(s+=".".concat(r.substr(i+1))),s}();case"none":return r;case"select":return function(){if(void 0===e[2])return!1;for(var t=a._tokenizePattern(e[2]),s=t.length,n=!1,o=0;o+1<s;o++){if(Garnish.isArray(t[o])||!Garnish.isArray(t[o+1]))return!1;var l=Craft.trim(t[o++]);(!1===n&&"other"===l||l==r)&&(n=t[o].join(","))}return!1!==n&&a.formatMessage(n,i)}();case"plural":return function(){if(void 0===e[2])return!1;for(var n=a._tokenizePattern(e[2]),o=n.length,l=!1,h=0,d=0;d+1<o;d++){if("object"===s(n[d])||"object"!==s(n[d+1]))return!1;var c=Craft.trim(n[d++]),u=t(c);if(1===d&&"offset:"===c.substring(0,7)){var p=t(c.replace(/[\n\r\t]/g," ")).indexOf(" ",7);if(-1===p)throw"Message pattern is invalid.";h=parseInt(Craft.trim(u.slice(7,p).join(""))),c=Craft.trim(u.slice(p+1,p+1+u.length).join(""))}(!1===l&&"other"===c||"="===c[0]&&parseInt(u.slice(1,1+u.length).join(""))===r||"one"===c&&r-h==1)&&(l=("string"==typeof n[d]?[n[d]]:n[d]).map((function(t){return t.replace("#",r-h)})).join(","))}return!1!==l&&a.formatMessage(l,i)}();default:throw"Message format '".concat(o,"' is not supported.")}},formatDate:function(t){return"object"!==s(t)&&(t=new Date(t)),$.datepicker.formatDate(Craft.datepickerOptions.dateFormat,t)},formatNumber:function(t,e){return void 0===e&&(e=",.0f"),d3.formatLocale(d3FormatLocaleDefinition).format(e)(t)},shortcutText:function(t,e,i){return"Mac"===Craft.clientOs?(i?"⌥":"")+(e?"⇧":"")+"⌘"+t:"Ctrl+"+(i?"Alt+":"")+(e?"Shift+":"")+t},escapeHtml:function(t){return $("<div/>").text(t).html()},escapeRegex:function(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},getText:function(t){return $("<div/>").html(t).text()},encodeUriComponent:function(t){t=encodeURIComponent(t);var e={"!":"%21","*":"%2A","'":"%27","(":"%28",")":"%29"};for(var i in e){var s=new RegExp("\\"+i,"g");t=t.replace(s,e[i])}return t},selectFullValue:function(t){var e=$(t),i=e.val();if(void 0!==e[0].setSelectionRange){var s=2*i.length;e[0].setSelectionRange(0,s)}else e.val(i)},formatInputId:function(t){return this.rtrim(t.replace(/[^\w]+/g,"-"),"-")},getUrl:function(t,e,i){"string"!=typeof t&&(t="");var s="";if($.isPlainObject(e)){var a=[];for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];"#"===n?s=r:null!==r&&""!==r&&a.push(n+"="+r)}e=a}e=Garnish.isArray(e)?e.join("&"):Craft.trim(e,"&?");var o=t.indexOf("#");-1!==o&&(s||(s=t.substr(o+1)),t=t.substr(0,o));var l,h=t.indexOf("?");if(-1!==h&&(e=t.substr(h+1)+(e?"&"+e:""),t=t.substr(0,h)),-1!==t.search("://")||"/"===t[0])return t+(e?"?"+e:"")+(s?"#"+s:"");if(t=Craft.trim(t,"/"),i){if(l=i,t&&Craft.pathParam){var d=l.match(new RegExp("[&?]"+Craft.escapeRegex(Craft.pathParam)+"=[^&]+"));d&&(l=l.replace(d[0],Craft.rtrim(d[0],"/")+"/"+t),t="")}}else l=Craft.baseUrl;if(-1!==(h=l.indexOf("?"))&&(e=l.substr(h+1)+(e?"&"+e:""),l=l.substr(0,h)),!Craft.omitScriptNameInUrls&&t)if(Craft.usePathInfo||!Craft.pathParam)-1===l.search(Craft.scriptName)&&(l=Craft.rtrim(l,"/")+"/"+Craft.scriptName);else{if(e&&e.substr(0,Craft.pathParam.length+1)===Craft.pathParam+"="){var c,u=e.indexOf("&");-1!==u?(c=e.substring(2,u),e=e.substr(u+1)):(c=e.substr(2),e=null),t=(c=Craft.rtrim(c))+(t?"/"+t:"")}e=Craft.pathParam+"="+t+(e?"&"+e:""),t=null}return t&&(l=Craft.rtrim(l,"/")+"/"+t),e&&(l+="?"+e),s&&(l+="#"+s),l},getCpUrl:function(t,e){return this.getUrl(t,e,Craft.baseCpUrl)},getSiteUrl:function(t,e){return this.getUrl(t,e,Craft.baseSiteUrl)},getActionUrl:function(t,e){return Craft.getUrl(t,e,Craft.actionUrl)},redirectTo:function(t){document.location.href=this.getUrl(t)},getCsrfInput:function(){return Craft.csrfTokenName?'<input type="hidden" name="'+Craft.csrfTokenName+'" value="'+Craft.csrfTokenValue+'"/>':""},postActionRequest:function(t,e,i,a){"function"==typeof e&&(a=i,i=e,e={}),(a=a||{}).contentType&&a.contentType.match(/\bjson\b/)&&("object"===s(e)&&(e=JSON.stringify(e)),a.contentType="application/json; charset=utf-8");var n=$.ajax($.extend({url:Craft.getActionUrl(t),type:"POST",dataType:"json",headers:this._actionHeaders(),data:e,success:i,error:function(t,e,s){4===t.readyState&&(void 0!==Craft.cp?Craft.cp.displayError():alert(Craft.t("app","A server error occurred.")),i&&i(null,e,t))}},a));return"function"==typeof a.send&&a.send(n),n},_waitingOnAjax:!1,_ajaxQueue:[],queueActionRequest:function(t,e,i,s){"function"==typeof e&&(s=i,i=e,e=void 0),Craft._ajaxQueue.push([t,e,i,s]),Craft._waitingOnAjax||Craft._postNextActionRequestInQueue()},_postNextActionRequestInQueue:function(){Craft._waitingOnAjax=!0;var t=Craft._ajaxQueue.shift();Craft.postActionRequest(t[0],t[1],(function(e,i,s){t[2]&&"function"==typeof t[2]&&t[2](e,i,s),Craft._ajaxQueue.length?Craft._postNextActionRequestInQueue():Craft._waitingOnAjax=!1}),t[3])},_actionHeaders:function(){var t={"X-Registered-Asset-Bundles":Object.keys(Craft.registeredAssetBundles).join(","),"X-Registered-Js-Files":Object.keys(Craft.registeredJsFiles).join(",")};return Craft.csrfTokenValue&&(t["X-CSRF-Token"]=Craft.csrfTokenValue),t},sendActionRequest:function(t,e,i){var s=this;return new Promise((function(a,n){(i=i?$.extend({},i):{}).method=t,i.url=Craft.getActionUrl(e),i.headers=$.extend({"X-Requested-With":"XMLHttpRequest"},i.headers||{},s._actionHeaders()),i.params=$.extend({},i.params||{},{v:(new Date).getTime()}),axios.request(i).then(a).catch(n)}))},sendApiRequest:function(t,e,i){var s=this;return new Promise((function(a,n){var r=(i=i?$.extend({},i):{}).cancelToken||null;s._getApiHeaders(r).then((function(o){i.method=t,i.baseURL=Craft.baseApiUrl,i.url=e,i.headers=$.extend(o,i.headers||{}),i.params=$.extend(Craft.apiParams||{},i.params||{},{v:(new Date).getTime()}),s._apiHeaders||(i.params.processCraftHeaders=1),Craft.httpProxy&&(i.proxy=Craft.httpProxy),axios.request(i).then((function(t){s._processApiHeaders(t.headers,r).then((function(){a(t.data)})).catch(n)})).catch(n)})).catch(n)}))},_loadingApiHeaders:!1,_apiHeaders:null,_apiHeaderWaitlist:[],_getApiHeaders:function(t){var i=this;return new Promise((function(s,a){i._loadingApiHeaders?i._apiHeaderWaitlist.push([s,a]):i._apiHeaders?s(i._apiHeaders):(i._loadingApiHeaders=!0,i.sendActionRequest("POST","app/api-headers",{cancelToken:t}).then((function(t){i._loadingApiHeaders?s(t.data):a(e)})).catch((function(t){i._rejectApiRequests(a,t)})))}))},_processApiHeaders:function(t,i){var s=this;return new Promise((function(a,n){s._apiHeaders?a():s.sendActionRequest("POST","app/process-api-response-headers",{data:{headers:t},cancelToken:i}).then((function(t){if(s._loadingApiHeaders)for(s._apiHeaders=t.data,s._loadingApiHeaders=!1,a();s._apiHeaderWaitlist.length;)s._apiHeaderWaitlist.shift()[0](s._apiHeaders);else n(e)})).catch((function(t){s._rejectApiRequests(n,t)}))}))},_rejectApiRequests:function(t,e){for(this._loadingApiHeaders=!1,t(e);this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1](e)},clearCachedApiHeaders:function(){for(this._apiHeaders=null,this._loadingApiHeaders=!1;this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[1]()},downloadFromUrl:function(t,e,i){return new Promise((function(a,n){var r=new XMLHttpRequest;r.open(t,e,!0),"object"===s(i)?(r.setRequestHeader("Content-Type","application/json; charset=UTF-8"),i=JSON.stringify(i)):r.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),r.responseType="blob",r.onload=function(){if(200===r.status){var t=r.getResponseHeader("content-disposition"),e=/"([^"]*)"/.exec(t),i=null!=e&&e[1]?e[1]:"Download",s=r.getResponseHeader("content-type"),o=new Blob([r.response],{type:s}),l=document.createElement("a");l.href=window.URL.createObjectURL(o),l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),a()}else n()},r.send(i)}))},stringToArray:function(t){if("string"!=typeof t)return t;for(var e=t.split(","),i=0;i<e.length;i++)e[i]=$.trim(e[i]);return e},findDeltaData:function(t,e,i,a,n){t="string"==typeof t?t:"",e="string"==typeof e?e:"",i.sort((function(t,e){return t.length===e.length?0:t.length>e.length?1:-1})),void 0===n&&(n=Craft.initialDeltaValues);for(var r=this._groupParamsByDeltaNames(t.split("&"),i,!1,n),o=this._groupParamsByDeltaNames(e.split("&"),i,!0,!1),l=o.__root__,h=0;h<i.length;h++)(Craft.inArray(i[h],Craft.modifiedDeltaNames)||"object"===s(o[i[h]])&&("object"!==s(r[i[h]])||JSON.stringify(r[i[h]])!==JSON.stringify(o[i[h]])))&&((l=l.concat(o[i[h]])).push("modifiedDeltaNames[]="+i[h]),a&&a(i[h],o[i[h]]));return l.join("&")},_groupParamsByDeltaNames:function(t,e,i,s){var a={};i&&(a.__root__=[]);var n=function(t){return encodeURIComponent(t).replace("%3D","=")};t=t.map((function(t){return decodeURIComponent(t)}));t:for(var r=0;r<t.length;r++){for(var o=e.length-1;o>=0;o--){var l=t[r].substr(0,e[o].length+1);if(l===e[o]+"="||l===e[o]+"["){void 0===a[e[o]]&&(a[e[o]]=[]),a[e[o]].push(n(t[r]));continue t}}i&&a.__root__.push(n(t[r]))}if(s){var h=function(t,e){return $.isArray(e)||$.isPlainObject(e)?e=$.param(e):"string"==typeof e?e=encodeURIComponent(e):null===e&&(e=""),"".concat(encodeURIComponent(t),"=").concat(e)};for(var d in s)if(s.hasOwnProperty(d))if($.isPlainObject(s[d]))for(var c in a[d]=[],s[d])s[d].hasOwnProperty(c)&&a[d].push(h("".concat(d,"[").concat(c,"]"),s[d][c]));else a[d]=[h(d,s[d])]}return a},expandPostArray:function(t){var e,i={};for(var a in t)if(t.hasOwnProperty(a)){var n,r=t[a],o=a.match(/^(\w+)(\[.*)?/);if(o[2])for(n=o[2].match(/\[[^\[\]]*\]/g),e=0;e<n.length;e++)n[e]=n[e].substring(1,n[e].length-1);else n=[];n.unshift(o[1]);var l=i;for(e=0;e<n.length;e++)e<n.length-1?("object"!==s(l[n[e]])&&(n[e+1]&&parseInt(n[e+1])!=n[e+1]?l[n[e]]={}:l[n[e]]=[]),l=l[n[e]]):(n[e]||(n[e]=l.length),l[n[e]]=r)}return i},createForm:function(t){var e=$("<form/>",{attr:{method:"post",action:"","accept-charset":"UTF-8"}});if("string"==typeof t)for(var i,s=t.split("&"),a=0;a<s.length;a++)i=s[a].split("=",2),$("<input/>",{type:"hidden",name:decodeURIComponent(i[0]),value:decodeURIComponent(i[1]||"")}).appendTo(e);return e},compare:function(t,e,i){if(s(t)!==s(e))return!1;if("object"===s(t)){if(t.length!==e.length)return!1;if(t instanceof Array!=e instanceof Array)return!1;if(!(t instanceof Array))if(void 0===i||!0===i){if(!Craft.compare(Craft.getObjectKeys(t).sort(),Craft.getObjectKeys(e).sort()))return!1}else if(!Craft.compare(Craft.getObjectKeys(t),Craft.getObjectKeys(e)))return!1;for(var a in t)if(t.hasOwnProperty(a)&&!Craft.compare(t[a],e[a]))return!1;return!0}return t===e},getObjectKeys:function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&e.push(i);return e},escapeChars:function(t){Garnish.isArray(t)||(t=t.split());for(var e="",i=0;i<t.length;i++)e+="\\"+t[i];return e},ltrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("^["+Craft.escapeChars(e)+"]+");return t.replace(i,"")},rtrim:function(t,e){if(!t)return t;void 0===e&&(e=" \t\n\r\0\v");var i=new RegExp("["+Craft.escapeChars(e)+"]+$");return t.replace(i,"")},trim:function(t,e){return t=Craft.ltrim(t,e),Craft.rtrim(t,e)},startsWith:function(t,e){return t.substr(0,e.length)===e},filterArray:function(t,e){for(var i=[],s=0;s<t.length;s++)("function"==typeof e?e(t[s],s):t[s])&&i.push(t[s]);return i},inArray:function(t,e){return $.isPlainObject(e)&&(e=Object.values(e)),e.includes(t)},removeFromArray:function(t,e){var i=$.inArray(t,e);return-1!==i&&(e.splice(i,1),!0)},getLast:function(t){return t.length?t[t.length-1]:null},uppercaseFirst:function(t){return t.charAt(0).toUpperCase()+t.slice(1)},lowercaseFirst:function(t){return t.charAt(0).toLowerCase()+t.slice(1)},parseUrl:function(t){var e=t.match(/^(?:(https?):\/\/|\/\/)([^\/\:]*)(?:\:(\d+))?(\/[^\?]*)?(?:\?([^#]*))?(#.*)?/);return e?{scheme:e[1],host:e[2]+(e[3]?":"+e[3]:""),hostname:e[2],port:e[3]||null,path:e[4]||"/",query:e[5]||null,hash:e[6]||null}:{}},isSameHost:function(t){var e=this.parseUrl(document.location.href);if(!e)return!1;var i=this.parseUrl(t);return!!i&&e.host===i.host},secondsToHumanTimeDuration:function(t,e){void 0===e&&(e=!0);var i=604800,s=Math.floor(t/i);t%=i;var a=Math.floor(t/86400);t%=86400;var n,r=Math.floor(t/3600);t%=3600,e?(n=Math.floor(t/60),t%=60):(n=Math.round(t/60),t=0);var o=[];return s&&o.push(s+" "+(1===s?Craft.t("app","week"):Craft.t("app","weeks"))),a&&o.push(a+" "+(1===a?Craft.t("app","day"):Craft.t("app","days"))),r&&o.push(r+" "+(1===r?Craft.t("app","hour"):Craft.t("app","hours"))),!n&&(e||s||a||r)||o.push(n+" "+(1===n?Craft.t("app","minute"):Craft.t("app","minutes"))),!t&&(!e||s||a||r||n)||o.push(t+" "+(1===t?Craft.t("app","second"):Craft.t("app","seconds"))),o.join(", ")},asciiString:function(t,e){t=t.normalize("NFC");for(var i,s="",a=0;a<t.length;a++)i=t.charAt(a),s+="string"==typeof(e||Craft.asciiCharMap)[i]?(e||Craft.asciiCharMap)[i]:i;return s},randomString:function(t){for(var e="",i=0;i<t;i++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e},createErrorList:function(t){for(var e=$(document.createElement("ul")).addClass("errors"),i=0;i<t.length;i++){var s=$(document.createElement("li"));s.appendTo(e),s.html(t[i])}return e},appendHeadHtml:function(t){if(t){var e=$("link[href]");if(e.length){for(var i,s=[],a=0;a<e.length;a++)i=e.eq(a).attr("href").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var n=new RegExp('<link\\s[^>]*href="(?:'+s.join("|")+')".*?></link>',"g");t=t.replace(n,"")}$("head").append(t)}},appendFootHtml:function(t){if(t){var e=$("script[src]");if(e.length){for(var i,s=[],a=0;a<e.length;a++)i=e.eq(a).attr("src").replace(/&/g,"&amp;"),s.push(Craft.escapeRegex(i));var n=new RegExp('<script\\s[^>]*src="(?:'+s.join("|")+')".*?><\/script>',"g");t=t.replace(n,"")}Garnish.$bod.append(t)}},initUiElements:function(t){$(".grid",t).grid(),$(".info",t).infoicon(),$(".checkbox-select",t).checkboxselect(),$(".fieldtoggle",t).fieldtoggle(),$(".lightswitch",t).lightswitch(),$(".nicetext",t).nicetext(),$(".formsubmit",t).formsubmit(),$(".menubtn:not([data-disclosure-trigger])",t).menubtn(),$("[data-disclosure-trigger]",t).disclosureMenu(),$(".datetimewrapper",t).datetime(),$('.datewrapper > input[type="date"], .timewrapper > input[type="time"]',t).datetimeinput(),$("a",t).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===$(this).attr("target")&&$(this).attr("rel","noopener").attr("target","_blank")}))},_elementIndexClasses:{},_elementSelectorModalClasses:{},_elementEditorClasses:{},registerElementIndexClass:function(t,e){if(void 0!==this._elementIndexClasses[t])throw"An element index class has already been registered for the element type “"+t+"”.";this._elementIndexClasses[t]=e},registerElementSelectorModalClass:function(t,e){if(void 0!==this._elementSelectorModalClasses[t])throw"An element selector modal class has already been registered for the element type “"+t+"”.";this._elementSelectorModalClasses[t]=e},registerElementEditorClass:function(t,e){if(void 0!==this._elementEditorClasses[t])throw"An element editor class has already been registered for the element type “"+t+"”.";this._elementEditorClasses[t]=e},createElementIndex:function(t,e,i){return new(void 0!==this._elementIndexClasses[t]?this._elementIndexClasses[t]:Craft.BaseElementIndex)(t,e,i)},createElementSelectorModal:function(t,e){return new(void 0!==this._elementSelectorModalClasses[t]?this._elementSelectorModalClasses[t]:Craft.BaseElementSelectorModal)(t,e)},createElementEditor:function(t,e,i){return void 0===i&&$.isPlainObject(e)?(i=e,e=null):"object"!==s(i)&&(i={}),i.elementType||(i.elementType=t),new(void 0!==this._elementEditorClasses[t]?this._elementEditorClasses[t]:Craft.BaseElementEditor)(e,i)},getLocalStorage:function(t,e){return t="Craft-"+Craft.systemUid+"."+t,"undefined"!=typeof localStorage&&void 0!==localStorage[t]?JSON.parse(localStorage[t]):e},setLocalStorage:function(t,e){if("undefined"!=typeof localStorage){t="Craft-"+Craft.systemUid+"."+t;try{localStorage[t]=JSON.stringify(e)}catch(t){}}},removeLocalStorage:function(t){"undefined"!=typeof localStorage&&localStorage.removeItem("Craft-".concat(Craft.systemUid,".").concat(t))},getCookie:function(t){return document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)Craft-".concat(Craft.systemUid,":").concat(t,"\\s*\\=\\s*([^;]*).*$)|^.*$")),"$1")},setCookie:function(t,e,i){i=$.extend({},this.defaultCookieOptions,i);var s="Craft-".concat(Craft.systemUid,":").concat(t,"=").concat(encodeURIComponent(e));i.path&&(s+=";path=".concat(i.path)),i.domain&&(s+=";domain=".concat(i.domain)),i.maxAge?s+=";max-age-in-seconds=".concat(i.maxAge):i.expires&&(s+=";expires=".concat(i.expires.toUTCString())),i.secure&&(s+=";secure"),document.cookie=s},removeCookie:function(t){this.setCookie(t,"",new Date("1970-01-01T00:00:00"))},getElementInfo:function(t){var e=$(t);return e.hasClass("element")||(e=e.find(".element:first")),{id:e.data("id"),siteId:e.data("site-id"),label:e.data("label"),status:e.data("status"),url:e.data("url"),hasThumb:e.hasClass("hasthumb"),$element:e}},setElementSize:function(t,e){var i=$(t);if("small"!==e&&"large"!==e&&(e="small"),!i.hasClass(e)){var s="small"===e?"large":"small";if(i.addClass(e).removeClass(s),i.hasClass("hasthumb")){var a=i.find("> .elementthumb > img"),n=$("<img/>",{sizes:("small"===e?"30":"100")+"px",srcset:a.attr("srcset")||a.attr("data-pfsrcset")});a.replaceWith(n),picturefill({elements:[n[0]]})}}},submitForm:function(t,e){if(void 0===e&&(e={}),!e.confirm||confirm(e.confirm)){if(e.action&&$("<input/>",{type:"hidden",name:"action",val:e.action}).appendTo(t),e.redirect&&$("<input/>",{type:"hidden",name:"redirect",val:e.redirect}).appendTo(t),e.params)for(var i in e.params){var s=e.params[i];$("<input/>",{type:"hidden",name:i,val:s}).appendTo(t)}e.retainScroll&&this.setLocalStorage("scrollY",window.scrollY),t.trigger($.extend({type:"submit"},e.data))}},trapFocusWithin:function(t){Garnish.trapFocusWithin(t)},setFocusWithin:function(t){Garnish.setFocusWithin(t)}}),$.extend($.fn,{animateLeft:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({left:t},e,i,s):this.velocity({right:t},e,i,s)},animateRight:function(t,e,i,s){return"ltr"===Craft.orientation?this.velocity({right:t},e,i,s):this.velocity({left:t},e,i,s)},disable:function(){return this.each((function(){var t=$(this);t.addClass("disabled"),t.data("activatable")&&t.removeAttr("tabindex")}))},enable:function(){return this.each((function(){var t=$(this);t.removeClass("disabled"),t.data("activatable")&&t.attr("tabindex","0")}))},grid:function(){return this.each((function(){var t=$(this),e={};t.data("item-selector")&&(e.itemSelector=t.data("item-selector")),t.data("cols")&&(e.cols=parseInt(t.data("cols"))),t.data("max-cols")&&(e.maxCols=parseInt(t.data("max-cols"))),t.data("min-col-width")&&(e.minColWidth=parseInt(t.data("min-col-width"))),t.data("mode")&&(e.mode=t.data("mode")),t.data("fill-mode")&&(e.fillMode=t.data("fill-mode")),t.data("col-class")&&(e.colClass=t.data("col-class")),t.data("snap-to-grid")&&(e.snapToGrid=!!t.data("snap-to-grid")),new Craft.Grid(this,e)}))},infoicon:function(){return this.each((function(){new Craft.InfoIcon(this)}))},checkboxselect:function(){return this.each((function(){$.data(this,"checkboxselect")||new Garnish.CheckboxSelect(this)}))},fieldtoggle:function(){return this.each((function(){$.data(this,"fieldtoggle")||new Craft.FieldToggle(this)}))},lightswitch:function(t,e,i){return"settings"===t?("string"==typeof e?(t={})[e]=i:t=e,this.each((function(){var e=$.data(this,"lightswitch");e&&e.setSettings(t)}))):($.isPlainObject(t)||(t={}),this.each((function(){var e=$.extend({},t);Garnish.hasAttr(this,"data-value")&&(e.value=$(this).attr("data-value")),Garnish.hasAttr(this,"data-indeterminate-value")&&(e.indeterminateValue=$(this).attr("data-indeterminate-value")),$.data(this,"lightswitch")||new Craft.LightSwitch(this,e)})))},nicetext:function(){return this.each((function(){$.data(this,"nicetext")||new Garnish.NiceText(this)}))},formsubmit:function(){return this.on("click",(function(t){var e=$(t.currentTarget),i=e.data("params")||{};e.data("param")&&(i[e.data("param")]=e.data("value"));var s=e.data("menu")?e.data("menu").$anchor:e,a=s.attr("data-form")?$("#"+s.attr("data-form")):s.closest("form");Craft.submitForm(a,{confirm:e.data("confirm"),action:e.data("action"),redirect:e.data("redirect"),params:i,data:$.extend({customTrigger:e},e.data("event-data"))})}))},menubtn:function(){return this.each((function(){var t=$(this);if(!t.data("menubtn")&&t.next().hasClass("menu")){var e={};t.data("menu-anchor")&&(e.menuAnchor=t.data("menu-anchor")),new Garnish.MenuBtn(t,e)}}))},disclosureMenu:function(){return this.each((function(){var t=$(this);!t.data("trigger")&&t.attr("aria-controls")&&new Garnish.DisclosureMenu(t)}))},datetime:function(){return this.each((function(){var t=$(this),e=t.find('input:not([name$="[timezone]"])'),i=function(){for(var i=!1,s=0;s<e.length;s++)if(e.eq(s).val()){i=!0;break}if(i){if(!t.children(".clear-btn").length)var a=$("<button/>",{type:"button",class:"clear-btn",title:Craft.t("app","Clear"),"aria-label":Craft.t("app","Clear")}).appendTo(t).on("click",(function(){for(var t=0;t<e.length;t++)e.eq(t).val("").trigger("input").trigger("change");a.remove(),e.first().filter('[type="text"]').focus()}))}else t.children(".clear-btn").remove()};e.on("change",i),i()}))},datetimeinput:function(){return this.each((function(){var t=$(this),e=function(){""===t.val()?t.addClass("empty-value"):t.removeClass("empty-value")};t.on("input",e),e()}))}}),Garnish.NiceText.charsLeftHtml=function(t){return Craft.t("app",'<span class="visually-hidden">Characters left:</span> {chars, number}',{chars:t})},Garnish.$doc.ready((function(){Craft.initUiElements()}))},691:function(){function t(t,i){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(t,i)||e(t,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function e(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.CustomizeSourcesModal=Garnish.Modal.extend({elementIndex:null,$elementIndexSourcesContainer:null,$sidebar:null,$sourcesContainer:null,$sourceSettingsContainer:null,$newHeadingBtn:null,$footer:null,$footerBtnContainer:null,$saveBtn:null,$cancelBtn:null,$saveSpinner:null,$loadingSpinner:null,sourceSort:null,sources:null,selectedSource:null,updateSourcesOnSave:!1,availableTableAttributes:null,init:function(t,e){var i=this;this.base(),this.setSettings(e,{resizable:!0}),this.elementIndex=t,this.$elementIndexSourcesContainer=this.elementIndex.$sidebar.children("nav").children("ul");var s=$('<form class="modal customize-sources-modal"/>').appendTo(Garnish.$bod);this.$sidebar=$('<div class="cs-sidebar block-types"/>').appendTo(s),this.$sourcesContainer=$('<div class="sources">').appendTo(this.$sidebar),this.$sourceSettingsContainer=$('<div class="source-settings">').appendTo(s),this.$footer=$('<div class="footer"/>').appendTo(s),this.$footerBtnContainer=$('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footerBtnContainer),this.$saveBtn=$("<button/>",{type:"button",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(this.$footerBtnContainer),this.$saveSpinner=$('<div class="spinner hidden"/>').appendTo(this.$footerBtnContainer),this.$newHeadingBtn=$("<button/>",{type:"button",class:"btn submit add icon",text:Craft.t("app","New heading")}).appendTo($('<div class="buttons left secondary-buttons"/>').appendTo(this.$footer)),this.$loadingSpinner=$('<div class="spinner"/>').appendTo(s),this.setContainer(s),this.show();var a={elementType:this.elementIndex.elementType};Craft.postActionRequest("element-index-settings/get-customize-sources-modal-data",a,(function(t,e){i.$loadingSpinner.remove(),"success"===e&&(i.$saveBtn.removeClass("disabled"),i.buildModal(t))})),this.addListener(this.$newHeadingBtn,"click","handleNewHeadingBtnClick"),this.addListener(this.$cancelBtn,"click","hide"),this.addListener(this.$saveBtn,"click","save"),this.addListener(this.$container,"submit","save")},buildModal:function(t){var e=this;this.availableTableAttributes=t.availableTableAttributes,this.sourceSort=new Garnish.DragSort({handle:".move",axis:"y",onSortChange:function(){e.updateSourcesOnSave=!0}}),this.sources=[];for(var i=0;i<t.sources.length;i++){var s=this.addSource(t.sources[i]);this.sources.push(s)}this.selectedSource||void 0===this.sources[0]||this.sources[0].select()},addSource:function(t){var e,i=$('<div class="customize-sources-item"/>').appendTo(this.$sourcesContainer),s=$('<div class="label"/>').appendTo(i),a=$('<input type="hidden"/>').appendTo(i);return $('<a class="move icon" title="'+Craft.t("app","Reorder")+'" role="button"></a>').appendTo(i),void 0!==t.heading?(i.addClass("heading"),a.attr("name","sourceOrder[][heading]"),(e=new Craft.CustomizeSourcesModal.Heading(this,i,s,a,t)).updateItemLabel(t.heading)):(a.attr("name","sourceOrder[][key]").val(t.key),(e=new Craft.CustomizeSourcesModal.Source(this,i,s,a,t)).updateItemLabel(t.label),(this.elementIndex.sourceKey+"/").substr(0,t.key.length+1)===t.key+"/"&&e.select()),this.sourceSort.addItems(i),e},handleNewHeadingBtnClick:function(){var t=this.addSource({heading:""});Garnish.scrollContainerToElement(this.$sidebar,t.$item),t.select(),this.updateSourcesOnSave=!0},save:function(t){var e=this;if(t&&t.preventDefault(),!this.$saveBtn.hasClass("disabled")&&this.$saveSpinner.hasClass("hidden")){this.$saveSpinner.removeClass("hidden");var i=this.$container.serialize()+"&elementType="+this.elementIndex.elementType;Craft.postActionRequest("element-index-settings/save-customize-sources-modal-settings",i,(function(t,i){if(e.$saveSpinner.addClass("hidden"),"success"===i&&t.success){if(e.updateSourcesOnSave&&e.$elementIndexSourcesContainer.length){for(var s,a=null,n=0;n<e.sourceSort.$items.length;n++){var r=e.sourceSort.$items.eq(n).data("source"),o=r.getIndexSource();o&&(r.isHeading()?s=o:(s&&(e.appendSource(s,a),a=s,s=null),e.appendSource(o,a),a=o))}if(a){var l=a.nextAll();e.elementIndex.sourceSelect.removeItems(l),l.remove()}}e.selectedSource&&e.selectedSource.sourceData.key&&(e.elementIndex.selectSourceByKey(e.selectedSource.sourceData.key),e.elementIndex.updateElements()),Craft.cp.displayNotice(Craft.t("app","Source settings saved")),e.hide()}else{var h="success"===i&&t.error?t.error:Craft.t("app","A server error occurred.");Craft.cp.displayError(h)}}))}},appendSource:function(t,e){e?t.insertAfter(e):t.prependTo(this.$elementIndexSourcesContainer)},destroy:function(){for(var t=0;t<this.sources.length;t++)this.sources[t].destroy();delete this.sources,this.base()}}),Craft.CustomizeSourcesModal.BaseSource=Garnish.Base.extend({modal:null,$item:null,$itemLabel:null,$itemInput:null,$settingsContainer:null,sourceData:null,init:function(t,e,i,s,a){this.modal=t,this.$item=e,this.$itemLabel=i,this.$itemInput=s,this.sourceData=a,this.$item.data("source",this),this.addListener(this.$item,"click","select")},isHeading:function(){return!1},isSelected:function(){return this.modal.selectedSource===this},select:function(){this.isSelected()||(this.modal.selectedSource&&this.modal.selectedSource.deselect(),this.$item.addClass("sel"),this.modal.selectedSource=this,this.$settingsContainer?this.$settingsContainer.removeClass("hidden"):this.$settingsContainer=this.createSettings().appendTo(this.modal.$sourceSettingsContainer),this.modal.$sourceSettingsContainer.scrollTop(0))},createSettings:function(){return $("<div/>")},getIndexSource:function(){},deselect:function(){this.$item.removeClass("sel"),this.modal.selectedSource=null,this.$settingsContainer.addClass("hidden")},updateItemLabel:function(t){this.$itemLabel.text(t)},destroy:function(){this.$item.data("source",null),this.base()}}),Craft.CustomizeSourcesModal.Source=Craft.CustomizeSourcesModal.BaseSource.extend({createSettings:function(){var t=$("<div/>").append(Craft.ui.createTextField({label:Craft.t("app","Header Column Heading"),id:"defaultHeaderColHeading"+Math.floor(1e5*Math.random()),name:"sources[".concat(this.sourceData.key,"][headerColHeading]"),value:this.sourceData.headerColHeading,placeholder:this.sourceData.defaultHeaderColHeading}));return this.sourceData.tableAttributes.length&&t.append(this.createTableColumnsField()),t},createTableColumnsField:function(){var s=t(this.sourceData.tableAttributes[0],2),a=s[0],n=s[1],r=this.createTableColumnOption(a,n,!0,!0),o=$("<div/>"),l=[a];$('<input type="hidden" name="sources['+this.sourceData.key+'][tableAttributes][]" value=""/>').appendTo(o);for(var h=1;h<this.sourceData.tableAttributes.length;h++){var d=t(this.sourceData.tableAttributes[h],2),c=d[0],u=d[1];o.append(this.createTableColumnOption(c,u,!1,!0)),l.push(c)}var p,g=this.modal.availableTableAttributes.slice(0);g.push.apply(g,function(t){if(Array.isArray(t))return i(t)}(p=this.sourceData.availableTableAttributes)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(p)||e(p)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}());for(var f=0;f<g.length;f++){var m=t(g[f],2),v=m[0],C=m[1];Craft.inArray(v,l)||o.append(this.createTableColumnOption(v,C,!1,!1))}return new Garnish.DragSort(o.children(),{handle:".move",axis:"y"}),Craft.ui.createField($([r[0],o[0]]),{label:Craft.t("app","Table Columns"),instructions:Craft.t("app","Choose which table columns should be visible for this source, and in which order.")})},createTableColumnOption:function(t,e,i,s){var a=$('<div class="customize-sources-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(e),name:"sources["+this.sourceData.key+"][tableAttributes][]",value:t,checked:s,disabled:i}));return i&&a.children(".move").addClass("disabled"),a},getIndexSource:function(){var t=this.modal.elementIndex.getSourceByKey(this.sourceData.key);if(t)return t.closest("li")}}),Craft.CustomizeSourcesModal.Heading=Craft.CustomizeSourcesModal.BaseSource.extend({$labelField:null,$labelInput:null,$deleteBtn:null,isHeading:function(){return!0},select:function(){this.base(),this.$labelInput.trigger("focus")},createSettings:function(){var t=$("<div/>");return this.$labelField=Craft.ui.createTextField({label:Craft.t("app","Heading"),instructions:Craft.t("app","This can be left blank if you just want an unlabeled separator."),value:this.sourceData.heading}).appendTo(t),this.$labelInput=this.$labelField.find(".text"),t.append("<hr/>"),this.$deleteBtn=$('<a class="error delete"/>').text(Craft.t("app","Delete heading")).appendTo(t),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","deleteHeading"),t},handleLabelInputChange:function(){this.updateItemLabel(this.$labelInput.val()),this.modal.updateSourcesOnSave=!0},updateItemLabel:function(t){this.$itemLabel.html((t?Craft.escapeHtml(t):'<em class="light">'+Craft.t("app","(blank)")+"</em>")+"&nbsp;"),this.$itemInput.val(t)},deleteHeading:function(){this.modal.sourceSort.removeItems(this.$item),this.modal.sources.splice($.inArray(this,this.modal.sources),1),this.modal.updateSourcesOnSave=!0,this.isSelected()&&(this.deselect(),this.modal.sources.length&&this.modal.sources[0].select()),this.$item.remove(),this.$settingsContainer.remove(),this.destroy()},getIndexSource:function(){var t=this.$labelInput?this.$labelInput.val():this.sourceData.heading;return $('<li class="heading"/>').append($("<span/>").text(t))}})},1519:function(){Craft.DataTableSorter=Garnish.DragSort.extend({$table:null,init:function(t,e){this.$table=$(t);var i=this.$table.children("tbody").children(":not(.filler)");(e=$.extend({},Craft.DataTableSorter.defaults,e)).container=this.$table.children("tbody"),e.helper=this.getHelper.bind(this),e.caboose="<tr/>",e.axis=Garnish.Y_AXIS,e.magnetStrength=4,e.helperLagBase=1.5,this.base(i,e)},getHelper:function(t){var e=$('<div class="'+this.settings.helperClass+'"/>').appendTo(Garnish.$bod),i=$("<table/>").appendTo(e),s=$("<tbody/>").appendTo(i);t.appendTo(s),i.width(this.$table.width()),i.prop("className",this.$table.prop("className"));for(var a=this.$table.find("tr:first").children(),n=t.children(),r=0;r<n.length;r++)$(n[r]).width($(a[r]).width());return e}},{defaults:{handle:".move",helperClass:"datatablesorthelper"}})},501:function(){Craft.DeleteUserModal=Garnish.Modal.extend({id:null,userId:null,$deleteActionRadios:null,$deleteSpinner:null,userSelect:null,_deleting:!1,init:function(t,e){var i=this;this.id=Math.floor(1e9*Math.random()),this.userId=t,e=$.extend(Craft.DeleteUserModal.defaults,e);var s,a=$('<form class="modal fitted deleteusermodal" method="post" accept-charset="UTF-8">'+Craft.getCsrfInput()+'<input type="hidden" name="action" value="users/delete-user"/>'+(Garnish.isArray(this.userId)?"":'<input type="hidden" name="userId" value="'+this.userId+'"/>')+(e.redirect?'<input type="hidden" name="redirect" value="'+e.redirect+'"/>':"")+"</form>").appendTo(Garnish.$bod),n=$('<div class="body"><div class="content-summary"><p>'+Craft.t("app","What do you want to do with their content?")+'</p><ul class="bullets"></ul></div><div class="options"><label><input type="radio" name="contentAction" value="transfer"/> '+Craft.t("app","Transfer it to:")+'</label><div id="transferselect'+this.id+'" class="elementselect"><div class="elements"></div><button type="button" class="btn add icon dashed">'+Craft.t("app","Choose a user")+'</button></div></div><div><label class="error"><input type="radio" name="contentAction" value="delete"/> '+Craft.t("app","Delete their content")+"</label></div></div>").appendTo(a),r=$('<div class="buttons right"/>').appendTo(n),o=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(r);if(e.contentSummary.length)for(var l=0;l<e.contentSummary.length;l++)n.find("ul").append($("<li/>",{text:e.contentSummary[l]}));else n.find("ul").remove();if(this.$deleteActionRadios=n.find("input[type=radio]"),this.$deleteSubmitBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:this._submitBtnLabel(!1)}).appendTo(r),this.$deleteSpinner=$('<div class="spinner hidden"/>').appendTo(r),Garnish.isArray(this.userId)){s=["and"];for(var h=0;h<this.userId.length;h++)s.push("not "+this.userId[h])}else s="not "+this.userId;this.userSelect=new Craft.BaseElementSelectInput({id:"transferselect"+this.id,name:"transferContentTo",elementType:"craft\\elements\\User",criteria:{id:s},limit:1,modalSettings:{closeOtherModals:!1},onSelectElements:function(){i.updateSizeAndPosition(),i.$deleteActionRadios.first().prop("checked")?i.validateDeleteInputs():i.$deleteActionRadios.first().trigger("click")},onRemoveElements:this.validateDeleteInputs.bind(this),selectable:!1,editable:!1}),this.addListener(o,"click","hide"),this.addListener(this.$deleteActionRadios,"change","validateDeleteInputs"),this.addListener(a,"submit","handleSubmit"),this.base(a,e)},_submitBtnLabel:function(t){var e=t?"Delete {num, plural, =1{user} other{users}} and content":"Delete {num, plural, =1{user} other{users}}";return Craft.t("app",e,{num:Garnish.isArray(this.userId)?this.userId.length:1})},validateDeleteInputs:function(){var t=!1;return this.$deleteActionRadios.eq(1).prop("checked")?(t=!0,this.$deleteSubmitBtn.text(this._submitBtnLabel(!0))):(this.$deleteSubmitBtn.text(this._submitBtnLabel(!1)),this.$deleteActionRadios.eq(0).prop("checked")&&(t=!!this.userSelect.totalSelected)),this.updateSizeAndPosition(),t?this.$deleteSubmitBtn.removeClass("disabled"):this.$deleteSubmitBtn.addClass("disabled"),t},handleSubmit:function(t){if(!this._deleting&&this.validateDeleteInputs()){this.$deleteSubmitBtn.addClass("active"),this.$deleteSpinner.removeClass("hidden"),this.disable(),this.userSelect.disable(),this._deleting=!0;try{!1===this.settings.onSubmit()&&t.preventDefault()}catch(e){throw t.preventDefault(),this.$deleteSpinner.addClass("hidden"),e}}else t.preventDefault()},onFadeIn:function(){Garnish.isMobileBrowser(!0)||this.$deleteActionRadios.first().trigger("focus"),this.base()}},{defaults:{contentSummary:[],onSubmit:$.noop,redirect:null}})},1923:function(){function t(t,i){if(t){if("string"==typeof t)return e(t,i);var s=Object.prototype.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.DraftEditor=Garnish.Base.extend({$revisionBtn:null,$revisionLabel:null,$spinner:null,$expandSiteStatusesBtn:null,$statusIcon:null,$editMetaBtn:null,metaHud:null,$nameTextInput:null,$saveMetaBtn:null,$siteStatusPane:null,$globalLightswitch:null,$siteLightswitches:null,$addlSiteField:null,siteIds:null,newSiteIds:null,enableAutosave:null,lastSerializedValue:null,listeningForChanges:!1,pauseLevel:0,timeout:null,saving:!1,cancelToken:null,ignoreFailedRequest:!1,queue:null,submittingForm:!1,duplicatedElements:null,errors:null,httpStatus:null,httpError:null,openingPreview:!1,preview:null,activatingPreviewToken:!1,activatedPreviewToken:!1,previewTokenQueue:null,previewLinks:null,scrollY:null,createdProvisionalDraft:!1,bc:null,init:function(e){var i,s,a=this;if(this.setSettings(e,Craft.DraftEditor.defaults),this.queue=[],this.previewTokenQueue=[],this.duplicatedElements={},this.enableAutosave=Craft.autosaveDrafts,this.previewLinks=[],this.siteIds=Object.keys(this.settings.siteStatuses).map((function(t){return parseInt(t)})),this.$revisionBtn=$("#context-btn"),this.$revisionLabel=$("#revision-label"),this.$spinner=$("#revision-spinner"),this.$expandSiteStatusesBtn=$("#expand-status-btn"),this.$statusIcon=$("#revision-status"),this.$statusMessage=$("#revision-status-message"),this.settings.canEditMultipleSites&&this.addListener(this.$expandSiteStatusesBtn,"click","expandSiteStatuses"),this.settings.previewTargets.length){this.settings.enablePreview&&this.addListener($("#preview-btn"),"click","openPreview");var n=$("#preview-btn-container");if(1===this.settings.previewTargets.length){var r=(i=this.settings.previewTargets,s=1,function(t){if(Array.isArray(t))return t}(i)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(i,s)||t(i,s)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())[0];this.createPreviewLink(r).attr("id","share-btn").addClass("btn").appendTo(n)}else this.createShareMenu(n)}this.settings.revisionId||(Craft.cp.$primaryForm.data("serializer",(function(){return a.serializeForm(!0)})),this.addListener(Craft.cp.$primaryForm,"submit","handleFormSubmit"),this.settings.isProvisionalDraft?this.initForProvisionalDraft():this.settings.draftId&&!this.settings.isUnpublishedDraft?this.initForDraft():this.settings.canUpdateSource||this.addListener(Craft.cp.$primaryForm,"submit.saveShortcut",(function(t){t.saveShortcut&&(t.preventDefault(),a.createDraft(),a.removeListener(Craft.cp.$primaryForm,"submit.saveShortcut"))})),this.listenForChanges(),this.addListener(this.$statusIcon,"click",(function(){a.showStatusHud(a.$statusIcon)})),"undefined"==typeof BroadcastChannel||this.settings.revisionId||(this.bc=new BroadcastChannel("DraftEditor"),this.bc.onmessage=function(t){"saveDraft"===t.data.event&&t.data.canonicalId===a.settings.sourceId&&(t.data.draftId===a.settings.draftId||t.data.isProvisionalDraft&&!a.settings.draftId)&&window.location.reload()}))},listenForChanges:function(){this.listeningForChanges||this.pauseLevel>0||!this.enableAutosave||!this.settings.saveDraftAction||(this.listeningForChanges=!0,this.addListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(t){$(t.target).is(this.statusIcons())||(clearTimeout(this.timeout),["keypress","keyup","change"].includes(t.type)?this.timeout=setTimeout(this.checkForm.bind(this),500):this.checkForm())})))},stopListeningForChanges:function(){this.listeningForChanges&&(this.removeListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup"),clearTimeout(this.timeout),this.listeningForChanges=!1)},pause:function(){this.pauseLevel++,this.stopListeningForChanges()},resume:function(){if(0===this.pauseLevel)throw"Craft.DraftEditor::resume() should only be called after pause().";this.pauseLevel--,0===this.pauseLevel&&this.enableAutosave&&(this.checkForm(),this.listenForChanges())},initForProvisionalDraft:function(){var t=this,e=$("#discard-changes");e.length||(e=this.$revisionBtn.data("menubtn")?this.$revisionBtn.data("menubtn").menu.$container.find("#discard-changes"):null),e&&e.length&&this.addListener(e,"click",(function(){confirm(Craft.t("app","Are you sure you want to discard your changes?"))&&Craft.submitForm(Craft.cp.$primaryForm,{action:t.settings.deleteDraftAction,redirect:t.settings.hashedCpEditUrl,params:{draftId:t.settings.draftId,provisional:t.settings.isProvisionalDraft}})}))},initForDraft:function(){var t=this;this.createEditMetaBtn(),this.settings.canUpdateSource&&Garnish.uiLayerManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0,alt:!0},(function(){Craft.submitForm(Craft.cp.$primaryForm,{action:t.settings.publishDraftAction,redirect:t.settings.hashedCpEditUrl})}),0)},expandSiteStatuses:function(){var t=this;this.removeListener(this.$expandSiteStatusesBtn,"click"),this.$expandSiteStatusesBtn.velocity({opacity:0},"fast",(function(){t.$expandSiteStatusesBtn.remove()}));var e=$("#enabledForSite-".concat(this.settings.siteId,"-field"));if(this.$siteStatusPane=e.parent(),this.settings.revisionId)this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));else{e.addClass("nested");var i=Craft.ui.createLightswitchField({id:"enabled",label:Craft.t("app","Enabled"),name:"enabled"}).insertBefore(e);i.find("label").css("font-weight","bold"),this.$globalLightswitch=i.find(".lightswitch"),this.settings.revisionId||this._showField(i);var s=Object.values(this.settings.siteStatuses),a=s.includes(!0),n=s.includes(!1),r=a&&n?"-":a?"1":"",o=encodeURIComponent("enabledForSite[".concat(this.settings.siteId,"]"))+"="+(this.settings.enabledForSite?"1":"");this.$siteLightswitches=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this)),this._getOtherSupportedSites().forEach((function(e){return t._createSiteStatusField(e)}));for(var l="enabled=".concat(r),h=0;h<this.$siteLightswitches.length;h++){var d=this.$siteLightswitches.eq(h).data("lightswitch").$input;l+="&"+encodeURIComponent(d.attr("name"))+"="+d.val()}Craft.cp.$primaryForm.data("initialSerializedValue",Craft.cp.$primaryForm.data("initialSerializedValue").replace(o,l)),this.lastSerializedValue&&(this.lastSerializedValue=this.lastSerializedValue.replace(o,l)),this.settings.addlSites&&this.settings.addlSites.length&&this._createAddlSiteField(),this.$globalLightswitch.on("change",this._updateSiteStatuses.bind(this)),this._updateGlobalStatus()}},_getOtherSupportedSites:function(){var t=this;return Craft.sites.filter((function(e){return e.id!=t.settings.siteId&&t.siteIds.includes(e.id)}))},_showField:function(t){var e=t.height();t.css("overflow","hidden").height(0).velocity({height:e},"fast",(function(){t.css({overflow:"",height:""})}))},_removeField:function(t){t.height(),t.css("overflow","hidden").velocity({height:0},"fast",(function(){t.remove()}))},_updateGlobalStatus:function(){var t=!0,e=!0;this.$siteLightswitches.each((function(){if($(this).data("lightswitch").on?e=!1:t=!1,!t&&!e)return!1})),t?this.$globalLightswitch.data("lightswitch").turnOn(!0):e?this.$globalLightswitch.data("lightswitch").turnOff(!0):this.$globalLightswitch.data("lightswitch").turnIndeterminate(!0)},_updateSiteStatuses:function(){var t=this.$globalLightswitch.data("lightswitch").on;this.$siteLightswitches.each((function(){t?$(this).data("lightswitch").turnOn(!0):$(this).data("lightswitch").turnOff(!0)}))},_createSiteStatusField:function(t,e){var i=Craft.ui.createLightswitchField({id:"enabledForSite-".concat(t.id),label:Craft.t("app","Enabled for {site}",{site:t.name}),name:"enabledForSite[".concat(t.id,"]"),on:void 0!==e?e:!this.settings.siteStatuses.hasOwnProperty(t.id)||this.settings.siteStatuses[t.id],disabled:!!this.settings.revisionId});if(this.$addlSiteField?i.insertBefore(this.$addlSiteField):i.appendTo(this.$siteStatusPane),!this.settings.revisionId){i.addClass("nested");var s=i.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this));this.$siteLightswitches=this.$siteLightswitches.add(s)}return this._showField(i),i},_createAddlSiteField:function(){var i,s=this,a=Craft.sites.filter((function(t){return!s.siteIds.includes(t.id)&&s.settings.addlSites.some((function(e){return e.siteId==t.id}))}));if(a.length){var n=Craft.ui.createSelect({options:[{label:Craft.t("app","Add a site…")}].concat((i=a.map((function(t){return{label:t.name,value:t.id}})),function(t){if(Array.isArray(t))return e(t)}(i)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(i)||t(i)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()))}).addClass("fullwidth");this.$addlSiteField=Craft.ui.createField(n,{}).addClass("nested add").appendTo(this.$siteStatusPane);var r=n.find("select");r.on("change",(function(){var t=parseInt(r.val()),e=Craft.sites.find((function(e){return e.id===t}));if(e){var i=s.settings.addlSites.find((function(t){return t.siteId==e.id}));s._createSiteStatusField(e,i.enabledByDefault),s._updateGlobalStatus(),r.val("").find('option[value="'.concat(t,'"]')).remove(),null===s.newSiteIds&&(s.newSiteIds=[]),s.siteIds.push(t),s.newSiteIds.push(t),1===r.find("option").length&&s._removeField(s.$addlSiteField)}})),this._showField(this.$addlSiteField)}},showStatusHud:function(t){var e;null===this.errors?e="<p>".concat(this._saveSuccessMessage(),"</p>"):(e='<p class="error"><strong>'.concat(this._saveFailMessage(),"</strong></p>"),this.errors.length&&(e+='<ul class="errors">'+this.errors.map((function(t){return"<li>".concat(Craft.escapeHtml(t),"</li>")})).join("")+"</ul>"),this.httpError&&(e+='<p class="http-error code">'.concat(Craft.escapeHtml(this.httpError),"</p>")),400===this.httpStatus&&(e+='<button class="btn refresh-btn">'.concat(Craft.t("app","Refresh"),"</button>")));var i=new Garnish.HUD(t,e,{hudClass:"hud revision-status-hud",onHide:function(){i.destroy()}});i.$mainContainer.find(".refresh-btn").on("click",(function(){window.location.reload()}))},_saveSuccessMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes have been stored."):Craft.t("app","The draft has been saved.")},_saveFailMessage:function(){return this.settings.isProvisionalDraft||this.settings.isUnpublishedDraft?Craft.t("app","Your changes could not be stored."):Craft.t("app","The draft could not be saved.")},spinners:function(){return this.preview?this.$spinner.add(this.preview.$spinner):this.$spinner},statusIcons:function(){return this.preview?this.$statusIcon.add(this.preview.$statusIcon):this.$statusIcon},statusMessage:function(){return this.preview?this.$statusMessage.add(this.preview.$statusMessage):this.$statusMessage},createEditMetaBtn:function(){var t=$("#context-btngroup");this.$editMetaBtn=$("<button/>",{type:"button",class:"btn edit icon",title:Craft.t("app","Edit draft settings")}).appendTo(t),t.find(".btngroup-btn-last").removeClass("btngroup-btn-last"),this.addListener(this.$editMetaBtn,"click","showMetaHud")},createPreviewLink:function(t,e){var i=this,s=$("<a/>",{href:this.getTokenizedPreviewUrl(t.url,null,!1),text:e||Craft.t("app","View"),target:"_blank",data:{targetUrl:t.url,targetLabel:t.label}});return this.addListener(s,"click",(function(){setTimeout((function(){i.activatePreviewToken()}),1)})),this.previewLinks.push(s),s},updatePreviewLinks:function(){var t=this;this.previewLinks.forEach((function(e){t.updatePreviewLinkHref(e),t.activatedPreviewToken&&t.removeListener(e,"click")}))},updatePreviewLinkHref:function(t){t.attr("href",this.getTokenizedPreviewUrl(t.data("targetUrl"),null,!1))},activatePreviewToken:function(){this.settings.isLive||(this.activatedPreviewToken=!0,this.updatePreviewLinks())},createShareMenu:function(t){var e=this;$("<button/>",{id:"share-btn",type:"button",class:"btn menubtn",text:Craft.t("app","View")}).appendTo(t);var i=$("<div/>",{class:"menu"}).appendTo(t),s=$("<ul/>").appendTo(i);this.settings.previewTargets.forEach((function(t){$("<li/>").append(e.createPreviewLink(t,t.label)).appendTo(s)}))},getPreviewTokenParams:function(){var t={elementType:this.settings.elementType,sourceId:this.settings.sourceId,siteId:this.settings.siteId,revisionId:this.settings.revisionId,previewToken:this.settings.previewToken};return this.settings.draftId&&!this.settings.isProvisionalDraft&&(t.draftId=this.settings.draftId),t},getPreviewToken:function(){var t=this;return new Promise((function(e,i){t.activatedPreviewToken?e(t.settings.previewToken):t.activatingPreviewToken?t.previewTokenQueue.push(e):(t.activatingPreviewToken=!0,Craft.sendActionRequest("POST","preview/create-token",{data:t.getPreviewTokenParams()}).then((function(){for(t.activatingPreviewToken=!1,t.activatePreviewToken(),e(t.settings.previewToken);t.previewTokenQueue.length;)t.previewTokenQueue.shift()(t.settings.previewToken)})).catch(i))}))},getTokenizedPreviewUrl:function(t,e,i){var s=this;void 0===i&&(i=!0);var a={};if(!e&&this.settings.isLive||(a[e||"x-craft-preview"]=Craft.randomString(10)),this.settings.siteToken&&(a[Craft.siteToken]=this.settings.siteToken),this.settings.isLive){var n=Craft.getUrl(t,a);return i?new Promise((function(t){t(n)})):n}if(!this.settings.previewToken)throw"Missing preview token";a[Craft.tokenParam]=this.settings.previewToken;var r=Craft.getUrl(t,a);if(this.activatedPreviewToken)return i?new Promise((function(t){t(r)})):r;if(i)return new Promise((function(t,e){s.getPreviewToken().then((function(){t(r)})).catch(e)}));var o=this.getPreviewTokenParams();return o.redirect=encodeURIComponent(r),Craft.getActionUrl("preview/create-token",o)},getPreview:function(){var t=this;return this.preview||(this.preview=new Craft.Preview(this),this.enableAutosave||(this.preview.on("open",(function(){t.enableAutosave=!0,t.listenForChanges()})),this.preview.on("close",(function(){t.enableAutosave=!1,t.stopListeningForChanges();var e=t.statusIcons();e.hasClass("checkmark-icon")&&e.addClass("hidden")}))),this.preview.on("close",(function(){t.scrollY&&(window.scrollTo(0,t.scrollY),t.scrollY=null)}))),this.preview},openPreview:function(){var t=this;return new Promise((function(e,i){t.openingPreview=!0,t.ensureIsDraftOrRevision(!0).then((function(){t.scrollY=window.scrollY,t.getPreview().open(),t.openingPreview=!1,e()})).catch(i)}))},ensureIsDraftOrRevision:function(t){var e=this;return new Promise((function(i,s){if(e.settings.draftId||e.settings.revisionId)i();else{if(t&&e.serializeForm(!0)===Craft.cp.$primaryForm.data("initialSerializedValue"))return void i();e.createDraft().then(i).catch(s)}}))},serializeForm:function(t){var e=Craft.cp.$primaryForm.serialize();return this.isPreviewActive()&&(e=e.replace("__PREVIEW_FIELDS__=1",this.preview.$editor.serialize())),t&&!this.settings.isUnpublishedDraft&&(e=(e=e.replace(/&action=[^&]*/,"")).replace(/&redirect=[^&]*/,"")),e},checkForm:function(t){if(!(this.settings.revisionId||this.pauseLevel>0)&&this.enableAutosave&&this.settings.saveDraftAction)if(clearTimeout(this.timeout),this.timeout=null,void 0!==Craft.cp.$primaryForm.data("initialSerializedValue")){var e=this.serializeForm(!0);if(t||e!==(this.lastSerializedValue||Craft.cp.$primaryForm.data("initialSerializedValue"))){var i=(!this.settings.draftId||this.settings.isProvisionalDraft)&&!this.settings.revisionId;this.saveDraft(e,i).catch((function(t){console.warn("Couldn’t save draft:",t)}))}}else this.timeout=setTimeout(this.checkForm.bind(this),500)},isPreviewActive:function(){return this.preview&&this.preview.isActive},createDraft:function(){var t=this;return new Promise((function(e,i){t.saveDraft(t.serializeForm(!0)).then(e).catch(i)}))},saveDraft:function(t){var e=this;return new Promise((function(i,s){if(e.submittingForm)s("Form already being submitted.");else if(e.saving)e.queue.push((function(){e.checkForm()}));else{e.lastSerializedValue=t,e.saving=!0,e.errors=null,e.httpStatus=null,e.httpError=null,e.cancelToken=axios.CancelToken.source(),e.spinners().removeClass("hidden"),e.statusIcons().velocity("stop").css("opacity","").removeClass("invisible checkmark-icon alert-icon fade-out").addClass("hidden"),e.statusMessage().empty(),e.$saveMetaBtn&&e.$saveMetaBtn.addClass("active");var a=[],n=e.prepareData(t,e.settings.isUnpublishedDraft?void 0:function(t,e){e.length&&a.push(decodeURIComponent(e[0].split("=")[0]))});!e.settings.isProvisionalDraft&&e.settings.draftId||(n+="&provisional=1"),Craft.sendActionRequest("POST",e.settings.saveDraftAction,{cancelToken:e.cancelToken.token,headers:{"content-type":"application/x-www-form-urlencoded"},data:n}).then((function(n){e._afterSaveRequest(),n.data.errors&&(e.errors=n.data.errors,e._showFailStatus(),s(n.data.errors));var r=!e.settings.draftId;r&&(e.settings.isProvisionalDraft=!0,e.createdProvisionalDraft=!0),n.data.title&&$("#header h1").text(n.data.title),n.data.docTitle&&(document.title=n.data.docTitle),e.settings.isProvisionalDraft?r&&e.$revisionLabel.append($("<span/>",{text:" — ".concat(Craft.t("app","Edited"))})):(e.$revisionLabel.text(n.data.draftName),e.settings.draftName=n.data.draftName);var o=e.$revisionBtn.data("menubtn")?e.$revisionBtn.data("menubtn").menu:null;for(var l in e.newSiteIds&&(o||(e.$revisionBtn.removeClass("disabled").addClass("menubtn"),new Garnish.MenuBtn(e.$revisionBtn),(o=e.$revisionBtn.data("menubtn").menu).$container.removeClass("hidden")),e.newSiteIds.forEach((function(t){var i=o.$options.filter("[data-site-id=".concat(t,"]")),s=e.settings.addlSites.find((function(e){return e.siteId==t}));s&&void 0!==s.enabledByDefault&&!s.enabledByDefault||i.find(".status").removeClass("disabled").addClass("enabled"),i.parent().removeClass("hidden").closest(".site-group").removeClass("hidden")})),o.$container.find(".revision-hr").removeClass("hidden"),e.newSiteIds=null),e.settings.isProvisionalDraft?r&&($("#action").attr("value",e.settings.publishDraftAction),e.settings.draftId=n.data.draftId,e.settings.isLive=!1,e.previewToken=null,o&&o.$container.find("#current-revision").append($("<div/>",{class:"edited-desc"}).append($("<p/>",{text:Craft.t("app","Showing your unsaved changes.")})).append($("<button/>",{id:"discard-changes",class:"btn",text:Craft.t("app","Discard changes")}))),e.initForProvisionalDraft()):o&&(o.$options.filter(".sel").find(".draft-name").text(n.data.draftName),o.$options.filter(".sel").find(".draft-meta").text(n.data.creator?Craft.t("app","Saved {timestamp} by {creator}",{timestamp:n.data.timestamp,creator:n.data.creator}):Craft.t("app","Saved {timestamp}",{timestamp:n.data.timestamp}))),n.data.previewTargets&&JSON.stringify(n.data.previewTargets)!==JSON.stringify(e.settings.previewTargets)&&e.updatePreviewTargets(n.data.previewTargets),r&&(e.updatePreviewLinks(),e.trigger("createProvisionalDraft")),e.$nameTextInput&&e.checkMetaValues(),n.data.duplicatedElements)l!=e.settings.sourceId&&n.data.duplicatedElements.hasOwnProperty(l)&&(e.duplicatedElements[l]=n.data.duplicatedElements[l]);for(var h=n.data.modifiedAttributes.map((function(t){return'[name="'.concat(t,'"],[name^="').concat(t,'["]')})).concat(a.map((function(t){return'[name="'.concat(t,'"]')}))),d=$(h.join(",")).parents().filter(".field:not(:has(> .status-badge))"),c=0;c<d.length;c++)d.eq(c).prepend($("<div/>",{class:"status-badge modified",title:Craft.t("app","This field has been modified.")}).append($("<span/>",{class:"visually-hidden",html:Craft.t("app","This field has been modified.")})));e.afterUpdate(t),e.bc&&e.bc.postMessage({event:"saveDraft",canonicalId:e.settings.sourceId,draftId:e.settings.draftId,isProvisionalDraft:e.settings.isProvisionalDraft}),i()})).catch((function(t){e._afterSaveRequest(),e.ignoreFailedRequest||(e.errors=[],t&&t.response&&(e.httpStatus=t.response.status,e.httpError=t.response.data?t.response.data.error:null),e._showFailStatus(),s(t)),e.ignoreFailedRequest=!1}))}}))},_afterSaveRequest:function(){this.spinners().addClass("hidden"),this.$saveMetaBtn&&this.$saveMetaBtn.removeClass("active"),this.saving=!1},_showFailStatus:function(){this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden checkmark-icon").addClass("alert-icon"),this.setStatusMessage(this._saveFailMessage())},prepareData:function(t,e){return t=Craft.findDeltaData(Craft.cp.$primaryForm.data("initialSerializedValue"),t,Craft.deltaNames,e),t=this.swapDuplicatedElementIds(t),this.settings.draftId&&(t+="&draftId=".concat(this.settings.draftId),this.settings.isProvisionalDraft&&(t+="&provisional=1")),null!==this.settings.draftName&&(t+="&draftName=".concat(this.settings.draftName)),t},swapDuplicatedElementIds:function(t){var e=this,i=Object.keys(this.duplicatedElements).join("|");if(""===i)return t;for(var s=encodeURIComponent("["),a=encodeURIComponent("]");t!==(t=t.replace(new RegExp("(&fields".concat(s,"[^=]+").concat(a).concat(s,")(").concat(i,")(").concat(a,")"),"g"),(function(t,i,s,a){return i+e.duplicatedElements[s]+a})).replace(new RegExp("&(fields".concat(s,"[^=]+)=(").concat(i,")\\b"),"g"),(function(t,i,n){return i.match(new RegExp("".concat(s,"(enabled|sortOrder|type|typeId)").concat(a,"$")))?t:"&".concat(i,"=").concat(e.duplicatedElements[n])}))););return t},updatePreviewTargets:function(t){var e=this;t.forEach((function(t){var i=e.settings.previewTargets.find((function(e){return e.label===t.label}));i&&(i.url=t.url);var s=e.previewLinks.find((function(e){return e.data("targetLabel")===t.label}));s&&(s.data("targetUrl",t.url),e.updatePreviewLinkHref(s))}))},afterUpdate:function(t){Craft.cp.$primaryForm.data("initialSerializedValue",t),Craft.initialDeltaValues={};var e=this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden").addClass("checkmark-icon");this.setStatusMessage(this._saveSuccessMessage()),Craft.autosaveDrafts||e.velocity("stop").velocity({opacity:0},{delay:2e3,complete:function(){e.addClass("hidden")}}),this.trigger("update"),this.nextInQueue()},setStatusMessage:function(t){this.statusIcons().attr("title",t),this.statusMessage().empty().append($("<span/>",{class:"visually-hidden",text:t}))},nextInQueue:function(){this.queue.length&&this.queue.shift()()},showMetaHud:function(){this.metaHud?this.metaHud.show():(this.createMetaHud(),this.onMetaHudShow()),Garnish.isMobileBrowser(!0)||this.$nameTextInput.trigger("focus")},createMetaHud:function(){var t=$("<div/>"),e=$('<div class="field"><div class="heading"><label for="draft-name">'+Craft.t("app","Draft Name")+"</label></div></div>").appendTo(t),i=$('<div class="input"/>').appendTo(e);this.$nameTextInput=$('<input type="text" class="text fullwidth" id="draft-name"/>').appendTo(i).val(this.settings.draftName);var s=$('<div class="hud-footer flex flex-center"/>').appendTo(t);$('<div class="flex-grow"></div>').appendTo(s),this.$saveMetaBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(s),this.metaHud=new Garnish.HUD(this.$editMetaBtn,t,{onSubmit:this.saveMeta.bind(this)}),this.addListener(this.$nameTextInput,"input","checkMetaValues"),this.metaHud.on("show",this.onMetaHudShow.bind(this)),this.metaHud.on("hide",this.onMetaHudHide.bind(this)),this.metaHud.on("escape",this.onMetaHudEscape.bind(this))},onMetaHudShow:function(){this.$editMetaBtn.addClass("active")},onMetaHudHide:function(){this.$editMetaBtn.removeClass("active")},onMetaHudEscape:function(){this.$nameTextInput.val(this.settings.draftName)},checkMetaValues:function(){return this.$nameTextInput.val()&&this.$nameTextInput.val()!==this.settings.draftName?(this.$saveMetaBtn.removeClass("disabled"),!0):(this.$saveMetaBtn.addClass("disabled"),!1)},shakeMetaHud:function(){Garnish.shake(this.metaHud.$hud)},saveMeta:function(){this.checkMetaValues()?(this.settings.draftName=this.$nameTextInput.val(),this.metaHud.hide(),this.checkForm(!0)):this.shakeMetaHud()},handleFormSubmit:function(t){if(t.preventDefault(),!this.submittingForm)if(!this.settings.draftId||this.settings.isUnpublishedDraft||this.settings.isProvisionalDraft||void 0!==t.autosave&&!t.autosave||!(t.saveShortcut||t.customTrigger&&t.customTrigger.data("action")===this.settings.saveDraftAction)||!this.enableAutosave){Craft.cp.$confirmUnloadForms=Craft.cp.$confirmUnloadForms.not(Craft.cp.$primaryForm),this.cancelToken&&(this.ignoreFailedRequest=!0,this.cancelToken.cancel());var e=this.prepareData(this.serializeForm(!1)),i=Craft.createForm(e);i.appendTo(Garnish.$bod),i.submit(),this.submittingForm=!0}else this.checkForm(!0)}},{defaults:{elementType:null,sourceId:null,siteId:null,isUnpublishedDraft:!1,enabled:!1,enabledForSite:!1,isLive:!1,isProvisionalDraft:!1,siteStatuses:null,addlSites:[],cpEditUrl:null,draftId:null,revisionId:null,draftName:null,canEditMultipleSites:!1,canUpdateSource:!1,saveDraftAction:null,deleteDraftAction:null,publishDraftAction:null,hashedCpEditUrl:null,hashedAddAnotherRedirectUrl:null,enablePreview:!1,previewTargets:[],previewToken:null,siteToken:null}})},2318:function(){Craft.DynamicGenerator=Craft.BaseInputGenerator.extend({callback:$.noop,init:function(t,e,i){this.callback=i,this.base(t,e)},generateTargetValue:function(t){return this.callback(t)}})},4755:function(){Craft.EditableTable=Garnish.Base.extend({initialized:!1,id:null,baseName:null,columns:null,sorter:null,biggestId:-1,$table:null,$tbody:null,$addRowBtn:null,$tableParent:null,$statusMessage:null,rowCount:0,hasMaxRows:!1,hasMinRows:!1,radioCheckboxes:null,init:function(t,e,i,s){var a=this;if(this.id=t,this.baseName=e,this.columns=i,this.setSettings(s,Craft.EditableTable.defaults),this.radioCheckboxes={},this.$table=$("#"+t),this.$tbody=this.$table.children("tbody"),this.$tableParent=this.$table.parent(),this.$statusMessage=this.$tableParent.find("[data-status-message]"),this.rowCount=this.$tbody.find("tr").length,this.$table.data("editable-table")&&(console.warn("Double-instantiating an editable table on an element"),this.$table.data("editable-table").destroy()),this.$table.data("editable-table",this),this.sorter=new Craft.DataTableSorter(this.$table,{helperClass:"editabletablesorthelper",copyDraggeeInputValuesToHelper:!0,onSortChange:function(){a.updateAllRows()}}),this.isVisible()?this.initialize():setTimeout(this.initializeIfVisible.bind(this),500),this.settings.minRows&&this.rowCount<this.settings.minRows)for(var n=this.rowCount;n<this.settings.minRows;n++)this.addRow()},isVisible:function(){return this.$table.parent().height()>0},initialize:function(){if(this.initialized)return!1;this.initialized=!0,this.removeListener(Garnish.$win,"resize");for(var t=this.$tbody.children(),e=0;e<t.length;e++)this.createRowObj(t[e]);var i=this.$table.parent(".input");return i.length&&this.$table.width()>i.width()&&i.css("overflow-x","auto"),this.$addRowBtn=this.$table.next(".add"),this.updateAddRowButton(),this.addListener(this.$addRowBtn,"activate","addRow"),!0},initializeIfVisible:function(){this.removeListener(Garnish.$win,"resize"),this.isVisible()?this.initialize():this.addListener(Garnish.$win,"resize","initializeIfVisible")},updateAddRowButton:function(){this.canAddRow()?(this.$addRowBtn.css("opacity","1"),this.$addRowBtn.css("pointer-events","auto"),this.$addRowBtn.attr("aria-disabled","false")):(this.$addRowBtn.css("opacity","0.2"),this.$addRowBtn.css("pointer-events","none"),this.$addRowBtn.attr("aria-disabled","true"))},updateAllRows:function(){if(!this.settings.staticRows)for(var t=this.$table.find("> tbody > tr"),e=0;e<t.length;e++)this.updateRow(t.eq(e))},updateRow:function(t){if(!this.settings.staticRows){var e=t.find("button.delete");e.length&&(e.attr("aria-label",Craft.t("app","Delete row {index}",{index:t.index()+1})),this.canDeleteRow()?e.removeAttr("disabled").removeClass("disabled"):e.attr("disabled","disabled").addClass("disabled"))}},updateDeleteRowButton:function(t){this.updateRow(this.$table.find('tr[data-id="'.concat(t,'"]')))},updateStatusMessage:function(){var t,e=this;this.$statusMessage.empty(),t=this.canAddRow()?Craft.t("app","Row could not be deleted. Minimum number of rows reached."):Craft.t("app","Row could not be added. Maximum number of rows reached."),setTimeout((function(){e.$statusMessage.text(t)}),250)},canDeleteRow:function(){return this.rowCount>this.settings.minRows},deleteRow:function(t){this.canDeleteRow()?(this.sorter.removeItems(t.$tr),t.$tr.remove(),this.rowCount--,this.updateAllRows(),this.updateAddRowButton(),0===this.rowCount&&this.$table.addClass("hidden"),this.settings.onDeleteRow(t.$tr),t.destroy()):this.updateStatusMessage()},canAddRow:function(){return!this.settings.staticRows&&(!this.settings.maxRows||this.rowCount<this.settings.maxRows)},addRow:function(t,e){if(this.canAddRow()){var i=this.settings.rowIdPrefix+(this.biggestId+1),s=this.createRow(i,this.columns,this.baseName,$.extend({},this.settings.defaultValues));e?s.prependTo(this.$tbody):s.appendTo(this.$tbody);var a=this.createRowObj(s);return this.sorter.addItems(s),!1!==t&&s.find("input:visible,textarea:visible,select:visible").first().trigger("focus"),this.rowCount++,this.updateAllRows(),this.updateAddRowButton(),this.$table.removeClass("hidden"),this.settings.onAddRow(s),a}this.updateStatusMessage()},createRow:function(t,e,i,s){return Craft.EditableTable.createRow(t,e,i,s)},createRowObj:function(t){return new Craft.EditableTable.Row(this,t)},focusOnPrevRow:function(t,e,i){var s,a=t.prev("tr");if((s=a.length?a.data("editable-table-row"):this.addRow(!1,!0))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))a&&this.focusOnPrevRow(a,e,i);else{var n=$("textarea,input.text",s.$tds[e]);n.length&&($(i).trigger("blur"),n.trigger("focus"))}},focusOnNextRow:function(t,e,i){var s,a=t.next("tr");if((s=a.length?a.data("editable-table-row"):this.addRow(!1))&&s.$tds[e])if($(s.$tds[e]).hasClass("disabled"))a&&this.focusOnNextRow(a,e,i);else{var n=$("textarea,input.text",s.$tds[e]);n.length&&($(i).trigger("blur"),n.trigger("focus"))}},importData:function(t,e,i){for(var s=t.split(/\r?\n|\r/),a=0;a<s.length;a++){for(var n=s[a].split("\t"),r=0;r<n.length;r++){var o=n[r];e.$tds.eq(i+r).find("textarea,input[type!=hidden]").val(o).trigger("input")}var l=e.$tr.next("tr");e=l.length?l.data("editable-table-row"):this.addRow(!1)}},destroy:function(){this.$table.removeData("editable-table"),this.base()}},{textualColTypes:["autosuggest","color","date","email","multiline","number","singleline","template","time","url"],defaults:{rowIdPrefix:"",defaultValues:{},staticRows:!1,minRows:null,maxRows:null,onAddRow:$.noop,onDeleteRow:$.noop},createRow:function(t,e,i,s){var a=$("<tr/>",{"data-id":t});for(var n in e)if(e.hasOwnProperty(n)){var r,o=e[n],l=void 0!==s[n]?s[n]:"";if("heading"===o.type)r=$("<th/>",{scope:"row",class:o.class,html:l});else{var h=i+"["+t+"]["+n+"]";switch(r=$("<td/>",{class:"".concat(o.class," ").concat(o.type,"-cell"),width:o.width}),Craft.inArray(o.type,Craft.EditableTable.textualColTypes)&&r.addClass("textual"),o.code&&r.addClass("code"),o.type){case"checkbox":$('<div class="checkbox-wrapper"/>').append(Craft.ui.createCheckbox({name:h,value:o.value||"1",checked:!!l})).appendTo(r);break;case"color":Craft.ui.createColorInput({name:h,value:l,small:!0}).appendTo(r);break;case"date":Craft.ui.createDateInput({name:h,value:l}).appendTo(r);break;case"lightswitch":Craft.ui.createLightswitch({name:h,value:o.value||"1",on:!!l,small:!0}).appendTo(r);break;case"select":Craft.ui.createSelect({name:h,options:o.options,value:l||function(){for(var t in o.options)if(o.options.hasOwnProperty(t)&&o.options[t].default)return void 0!==o.options[t].value?o.options[t].value:t;return null}(),class:"small"}).appendTo(r);break;case"time":Craft.ui.createTimeInput({name:h,value:l}).appendTo(r);break;case"email":case"url":Craft.ui.createTextInput({name:h,value:l,type:o.type,placeholder:o.placeholder||null}).appendTo(r);break;default:$("<textarea/>",{name:h,rows:o.rows||1,val:l,placeholder:o.placeholder}).appendTo(r)}}r.appendTo(a)}return $("<td/>",{class:"thin action"}).append($("<a/>",{class:"move icon",title:Craft.t("app","Reorder")})).appendTo(a),$("<td/>",{class:"thin action"}).append($("<button/>",{class:"delete icon",title:Craft.t("app","Delete"),type:"button"})).appendTo(a),a}}),Craft.EditableTable.Row=Garnish.Base.extend({table:null,id:null,niceTexts:null,$tr:null,$tds:null,tds:null,$textareas:null,$deleteBtn:null,init:function(t,e){this.table=t,this.$tr=$(e),this.$tds=this.$tr.children(),this.tds=[],this.id=this.$tr.attr("data-id"),this.$tr.data("editable-table-row",this);var i=parseInt(this.id.substr(this.table.settings.rowIdPrefix.length));i>this.table.biggestId&&(this.table.biggestId=i),this.$textareas=$(),this.niceTexts=[];var s,a,n,r,o,l={},h=0;for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(a=this.table.columns[s],n=this.tds[s]=this.$tds[h],Craft.inArray(a.type,Craft.EditableTable.textualColTypes)?(r=$("textarea",n),this.$textareas=this.$textareas.add(r),this.addListener(r,"focus","onTextareaFocus"),this.addListener(r,"mousedown","ignoreNextTextareaFocus"),this.niceTexts.push(new Garnish.NiceText(r,{onHeightChange:this.onTextareaHeightChange.bind(this)})),this.addListener(r,"keypress",{tdIndex:h,type:a.type},"handleKeypress"),this.addListener(r,"input",{type:a.type},"validateValue"),r.trigger("input"),"multiline"!==a.type&&this.addListener(r,"paste",{tdIndex:h,type:a.type},"handlePaste"),l[s]=r):"checkbox"===a.type&&(o=$('input[type="checkbox"]',n),a.radioMode&&(void 0===this.table.radioCheckboxes[s]&&(this.table.radioCheckboxes[s]=[]),this.table.radioCheckboxes[s].push(o[0]),this.addListener(o,"change",{colId:s},"onRadioCheckboxChange")),a.toggle&&this.addListener(o,"change",{colId:s},(function(t){this.applyToggleCheckbox(t.data.colId)}))),$(n).hasClass("disabled")||this.addListener(n,"click",{td:n},(function(t){t.target===t.data.td&&$(t.data.td).find("textarea,input,select,.lightswitch").focus()})),h++);for(s in this.onTextareaHeightChange(),this.table.columns)this.table.columns.hasOwnProperty(s)&&"checkbox"===(a=this.table.columns[s]).type&&a.toggle&&this.applyToggleCheckbox(s);for(s in this.table.columns)this.table.columns.hasOwnProperty(s)&&(a=this.table.columns[s]).autopopulate&&void 0!==l[a.autopopulate]&&!l[s].val()&&new Craft.HandleGenerator(l[s],l[a.autopopulate],{allowNonAlphaStart:!0});var d=this.$tr.children().last().find(".delete");this.addListener(d,"click","deleteRow");var c=this.$tr.find("input,textarea,select,.lightswitch");this.addListener(c,"focus",(function(t){$(t.currentTarget).closest("td:not(.disabled)").addClass("focus")})),this.addListener(c,"blur",(function(t){$(t.currentTarget).closest("td").removeClass("focus")}))},onTextareaFocus:function(t){this.onTextareaHeightChange();var e=$(t.currentTarget);e.data("ignoreNextFocus")?e.data("ignoreNextFocus",!1):setTimeout((function(){Craft.selectFullValue(e)}),0)},onRadioCheckboxChange:function(t){if(t.currentTarget.checked)for(var e=0;e<this.table.radioCheckboxes[t.data.colId].length;e++){var i=this.table.radioCheckboxes[t.data.colId][e];i.checked=i===t.currentTarget}},applyToggleCheckbox:function(t){for(var e,i,s=this.table.columns[t],a=$('input[type="checkbox"]',this.tds[t]).prop("checked"),n=0;n<s.toggle.length;n++)e=s.toggle[n],this.table.colum,(i="!"===e[0])&&(e=e.substr(1)),a&&!i||!a&&i?$(this.tds[e]).removeClass("disabled").find("textarea, input").prop("disabled",!1):$(this.tds[e]).addClass("disabled").find("textarea, input").prop("disabled",!0)},ignoreNextTextareaFocus:function(t){$.data(t.currentTarget,"ignoreNextFocus",!0)},handleKeypress:function(t){var e=t.keyCode?t.keyCode:t.charCode,i=Garnish.isCtrlKeyPressed(t);if(e===Garnish.RETURN_KEY&&("multiline"!==t.data.type||i))return t.preventDefault(),void(t.shiftKey?this.table.focusOnPrevRow(this.$tr,t.data.tdIndex,t.currentTarget):this.table.focusOnNextRow(this.$tr,t.data.tdIndex,t.currentTarget));"number"!==t.data.type||i||Craft.inArray(e,Craft.EditableTable.Row.numericKeyCodes)||t.preventDefault()},handlePaste:function(t){var e=Craft.trim(t.originalEvent.clipboardData.getData("Text")," \n\r");e.match(/[\t\r\n]/)&&(t.preventDefault(),this.table.importData(e,this,t.data.tdIndex))},validateValue:function(t){if("multiline"!==t.data.type){var e;if("number"===t.data.type){var i=t.currentTarget.value.match(/^\s*(-?[\d\\.]*)/);e=null!==i?i[1]:""}else e=t.currentTarget.value.replace(/[\r\n]/g,"");e!==t.currentTarget.value&&(t.currentTarget.value=e)}},onTextareaHeightChange:function(){for(var t=-1,e=0;e<this.niceTexts.length;e++)this.niceTexts[e].height>t&&(t=this.niceTexts[e].height);this.$textareas.css("min-height",t);var i=this.$textareas.filter(":visible").first().parent().height();i>t&&this.$textareas.css("min-height",i)},deleteRow:function(){this.table.deleteRow(this)}},{numericKeyCodes:[9,8,37,38,39,40,45,91,46,190,48,49,50,51,52,53,54,55,56,57]})},8468:function(){Craft.ElementActionTrigger=Garnish.Base.extend({maxLevels:null,newChildUrl:null,$trigger:null,$selectedItems:null,triggerEnabled:!0,init:function(t){this.setSettings(t,Craft.ElementActionTrigger.defaults),this.$trigger=$("#"+t.type.replace(/[\[\]\\]+/g,"-")+"-actiontrigger"),this.settings.activate&&(this.$trigger.data("custom-handler",!0),"FORM"===this.$trigger.prop("nodeName")?this.addListener(this.$trigger,"submit","handleTriggerActivation"):this.addListener(this.$trigger,"click","handleTriggerActivation")),this.updateTrigger(),Craft.elementIndex.on("selectionChange",this.updateTrigger.bind(this))},updateTrigger:function(){0!==Craft.elementIndex.getSelectedElements().length&&(this.validateSelection()?this.enableTrigger():this.disableTrigger())},validateSelection:function(){var t=!0;return this.$selectedItems=Craft.elementIndex.getSelectedElements(),!this.settings.batch&&this.$selectedItems.length>1?t=!1:"function"==typeof this.settings.validateSelection&&(t=this.settings.validateSelection(this.$selectedItems)),t},enableTrigger:function(){this.triggerEnabled||(this.$trigger.removeClass("disabled"),this.triggerEnabled=!0)},disableTrigger:function(){this.triggerEnabled&&(this.$trigger.addClass("disabled"),this.triggerEnabled=!1)},handleTriggerActivation:function(t){t.preventDefault(),t.stopPropagation(),this.triggerEnabled&&this.settings.activate(this.$selectedItems)}},{defaults:{type:null,batch:!0,validateSelection:null,activate:null}})},8895:function(){function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,s=new Array(e);i<e;i++)s[i]=t[i];return s}Craft.ElementThumbLoader=Garnish.Base.extend({queue:null,workers:[],init:function(){this.queue=[];for(var t=0;t<3;t++)this.workers.push(new Craft.ElementThumbLoader.Worker(this))},load:function(t){for(var e=this,i=t.find(".elementthumb"),s=function(t){var s=i.eq(t),a=s.scrollParent();if("FIELDSET"===a.prop("nodeName")&&(a=a.scrollParent()),a[0]===document.body&&(a=Garnish.$doc),e.isVisible(s,a))e.addToQueue(s[0]);else{var n="thumb"+Math.floor(1e6*Math.random());Craft.ElementThumbLoader.invisibleThumbs[n]=[e,s,a],a.on("scroll.".concat(n),{$thumb:s,$scrollParent:a,key:n},(function(t){e.isVisible(t.data.$thumb,t.data.$scrollParent)&&(delete Craft.ElementThumbLoader.invisibleThumbs[t.data.key],a.off("scroll.".concat(t.data.key)),e.addToQueue(t.data.$thumb[0]))}))}},a=0;a<i.length;a++)s(a)},addToQueue:function(t){this.queue.push(t);for(var e=0;e<this.workers.length;e++)this.workers[e].active||this.workers[e].loadNext()},isVisible:function(t,e){var i,s,a=t.offset().top;return e[0]===document?(i=e.scrollTop(),s=Garnish.$win.height()):(i=e.offset().top,s=e.height()),a>i&&a<i+s+1e3},destroy:function(){for(var t=0;t<this.workers.length;t++)this.workers[t].destroy();this.base()}},{invisibleThumbs:{},retryAll:function(){for(var e in Craft.ElementThumbLoader.invisibleThumbs){var i=(r=Craft.ElementThumbLoader.invisibleThumbs[e],o=3,function(t){if(Array.isArray(t))return t}(r)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var s,a,n=[],r=!0,o=!1;try{for(i=i.call(t);!(r=(s=i.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==i.return||i.return()}finally{if(o)throw a}}return n}}(r,o)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(e,i):void 0}}(r,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),s=i[0],a=i[1],n=i[2];delete Craft.ElementThumbLoader.invisibleThumbs[e],n.off("scroll.".concat(e)),s.load(a.parent())}var r,o}}),Craft.ElementThumbLoader.Worker=Garnish.Base.extend({loader:null,active:!1,init:function(t){this.loader=t},loadNext:function(){var t=this.loader.queue.shift();if(void 0!==t){this.active=!0;var e=$(t);if(e.find("img").length)this.loadNext();else{var i=$("<img/>",{sizes:e.attr("data-sizes"),srcset:e.attr("data-srcset"),alt:""});this.addListener(i,"load,error","loadNext"),i.appendTo(e),picturefill({elements:[i[0]]})}}else this.active=!1}})},4233:function(){Craft.ElevatedSessionForm=Garnish.Base.extend({$form:null,inputs:null,init:function(t,e){if(this.$form=$(t),void 0!==e){this.inputs=[],e=$.makeArray(e);for(var i=0;i<e.length;i++)for(var s=$(e[i]),a=0;a<s.length;a++){var n=s.eq(a);this.inputs.push({input:n,val:Garnish.getInputPostVal(n)})}}this.addListener(this.$form,"submit","handleFormSubmit")},handleFormSubmit:function(t){if(Craft.elevatedSessionManager.fetchingTimeout)return t.preventDefault(),void t.stopImmediatePropagation();if(this.inputs){for(var e,i=!1,s=0;s<this.inputs.length;s++)if((e=this.inputs[s].input).data("passwordInput")&&(e=e.data("passwordInput").$currentInput),Garnish.getInputPostVal(e)!==this.inputs[s].val){i=!0;break}if(!i)return}t.preventDefault(),t.stopImmediatePropagation(),Craft.elevatedSessionManager.requireElevatedSession(this.submitForm.bind(this))},submitForm:function(){this.disable(),this.$form.trigger("submit"),this.enable()}})},9699:function(){Craft.ElevatedSessionManager=Garnish.Base.extend({fetchingTimeout:!1,passwordModal:null,$passwordInput:null,$passwordSpinner:null,$submitBtn:null,$errorPara:null,callback:null,requireElevatedSession:function(t){var e=this;this.callback=t,this.fetchingTimeout=!0,Craft.postActionRequest("users/get-elevated-session-timeout",(function(t,i){e.fetchingTimeout=!1,"success"===i&&(!1===t.timeout||t.timeout>=Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout?e.callback():e.showPasswordModal())}))},showPasswordModal:function(){var t=this;if(this.passwordModal)this.passwordModal.show();else{var e=$('<form id="elevatedsessionmodal" class="modal secure fitted"/>'),i=$('<div class="body"><p>'+Craft.t("app","Enter your password to continue.")+"</p></div>").appendTo(e),s=$('<div class="inputcontainer">').appendTo(i),a=$('<div class="flex"/>').appendTo(s),n=$('<div class="flex-grow"/>').appendTo(a),r=$("<td/>").appendTo(a),o=$('<div class="passwordwrapper"/>').appendTo(n);this.$passwordInput=$('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'" autocomplete="current-password"/>').appendTo(o),this.$passwordSpinner=$('<div class="spinner hidden"/>').appendTo(s),this.$submitBtn=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Submit")}).appendTo(r),this.$errorPara=$('<p class="error"/>').appendTo(i),this.passwordModal=new Garnish.Modal(e,{closeOtherModals:!1,onFadeIn:function(){setTimeout(t.focusPasswordInput.bind(t),100)},onFadeOut:function(){t.$passwordInput.val("")}}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:function(e){t.$passwordInput=e}}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(e,"submit","submitPassword")}},focusPasswordInput:function(){Garnish.isMobileBrowser(!0)||this.$passwordInput.trigger("focus")},validatePassword:function(){return this.$passwordInput.val().length>=6?(this.$submitBtn.removeClass("disabled"),!0):(this.$submitBtn.addClass("disabled"),!1)},submitPassword:function(t){var e=this;if(t&&t.preventDefault(),this.validatePassword()){this.$passwordSpinner.removeClass("hidden"),this.clearLoginError();var i={currentPassword:this.$passwordInput.val()};Craft.postActionRequest("users/start-elevated-session",i,(function(t,i){e.$passwordSpinner.addClass("hidden"),"success"===i?t.success?(e.passwordModal.hide(),e.callback()):(e.showPasswordError(t.message||Craft.t("app","Incorrect password.")),Garnish.shake(e.passwordModal.$container),e.focusPasswordInput()):e.showPasswordError()}))}},showPasswordError:function(t){null==t&&(t=Craft.t("app","A server error occurred.")),this.$errorPara.text(t),this.passwordModal.updateSizeAndPosition()},clearLoginError:function(){this.showPasswordError("")}},{minSafeElevatedSessionTimeout:5}),Craft.elevatedSessionManager=new Craft.ElevatedSessionManager},1402:function(){Craft.EntryIndex=Craft.BaseElementIndex.extend({publishableSections:null,$newEntryBtnGroup:null,$newEntryBtn:null,init:function(t,e,i){this.on("selectSource",this.updateButton.bind(this)),this.on("selectSite",this.updateButton.bind(this)),this.base(t,e,i)},afterInit:function(){this.publishableSections=[];for(var t=0;t<Craft.publishableSections.length;t++){var e=Craft.publishableSections[t];this.getSourceByKey("section:"+e.uid)&&this.publishableSections.push(e)}this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSectionHandle){if("singles"===defaultSectionHandle)return"singles";for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("handle")===defaultSectionHandle)return e.data("key")}}return this.base()},updateButton:function(){var t=this;if(this.$source){var e,i,s,a;if(e="singles"===this.$source.data("key")?"singles":this.$source.data("handle"),this.publishableSections.length){var n,r;if(this.$newEntryBtnGroup&&this.$newEntryBtnGroup.remove(),e)for(i=0;i<this.publishableSections.length;i++)if(this.publishableSections[i].handle===e){n=this.publishableSections[i];break}if(this.$newEntryBtnGroup=$('<div class="btngroup submit"/>'),n?(s=this._getSectionTriggerHref(n),a="index"===this.settings.context?Craft.t("app","New entry"):Craft.t("app","New {section} entry",{section:n.name}),this.$newEntryBtn=$('<a class="btn submit add icon" '+s+' role="button" tabindex="0">'+Craft.escapeHtml(a)+"</a>").appendTo(this.$newEntryBtnGroup),"index"!==this.settings.context&&this.addListener(this.$newEntryBtn,"click",(function(t){this._openCreateEntryModal(t.currentTarget.getAttribute("data-id"))})),this.publishableSections.length>1&&(r=$("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newEntryBtnGroup))):this.$newEntryBtn=r=$("<button/>",{type:"button",class:"btn submit add icon menubtn",text:Craft.t("app","New entry")}).appendTo(this.$newEntryBtnGroup),r){var o='<div class="menu"><ul>';for(i=0;i<this.publishableSections.length;i++){var l=this.publishableSections[i];("index"===this.settings.context&&-1!==$.inArray(this.siteId,l.sites)||"index"!==this.settings.context&&l!==n)&&(s=this._getSectionTriggerHref(l),a="index"===this.settings.context?l.name:Craft.t("app","New {section} entry",{section:l.name}),o+="<li><a "+s+">"+Craft.escapeHtml(a)+"</a></li>")}o+="</ul></div>",$(o).appendTo(this.$newEntryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",(function(e){t._openCreateEntryModal(e.option.getAttribute("data-id"))}))}this.addButton(this.$newEntryBtnGroup)}if("index"===this.settings.context&&"undefined"!=typeof history){var d="entries";e&&(d+="/"+e),history.replaceState({},"",Craft.getUrl(d))}}},_getSectionTriggerHref:function(t){if("index"===this.settings.context){var e="entries/".concat(t.handle,"/new"),i=this.getSite(),s=i?{site:i.handle}:void 0;return'href="'.concat(Craft.getUrl(e,s),'"')}return'data-id="'.concat(t.id,'"')},_openCreateEntryModal:function(t){var e=this;if(!this.$newEntryBtn.hasClass("loading")){for(var i,s=0;s<this.publishableSections.length;s++)if(this.publishableSections[s].id==t){i=this.publishableSections[s];break}if(i){this.$newEntryBtn.addClass("inactive");var a=this.$newEntryBtn.text();this.$newEntryBtn.text(Craft.t("app","New {section} entry",{section:i.name})),Craft.createElementEditor(this.elementType,{hudTrigger:this.$newEntryBtnGroup,siteId:this.siteId,attributes:{sectionId:t,typeId:i.entryTypes[0].id,enabled:i.canPublish?1:0},onHideHud:function(){e.$newEntryBtn.removeClass("inactive").text(a)},onSaveElement:function(t){var s="section:"+i.uid;e.sourceKey!==s&&e.selectSourceByKey(s),e.clearSearch(),e.setSortAttribute("dateCreated"),e.setSortDirection("desc"),e.selectElementAfterUpdate(t.id),e.updateElements()}})}}}}),Craft.registerElementIndexClass("craft\\elements\\Entry",Craft.EntryIndex)},8201:function(){Craft.FieldLayoutDesigner=Garnish.Base.extend({$container:null,$tabContainer:null,$newTabBtn:null,$sidebar:null,$libraryToggle:null,$selectedLibrary:null,$fieldLibrary:null,$uiLibrary:null,$uiLibraryElements:null,$fieldSearch:null,$clearFieldSearchBtn:null,$fieldGroups:null,$fields:null,tabGrid:null,elementDrag:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.FieldLayoutDesigner.defaults);var s=this.$container.children(".fld-workspace");this.$tabContainer=s.children(".fld-tabs"),this.$newTabBtn=s.children(".fld-new-tab-btn"),this.$sidebar=this.$container.children(".fld-sidebar"),this.$fieldLibrary=this.$selectedLibrary=this.$sidebar.children(".fld-field-library");var a=this.$fieldLibrary.children(".search");this.$fieldSearch=a.children("input"),this.$clearFieldSearchBtn=a.children(".clear"),this.$fieldGroups=this.$sidebar.find(".fld-field-group"),this.$fields=this.$fieldGroups.children(".fld-element"),this.$uiLibrary=this.$sidebar.children(".fld-ui-library"),this.$uiLibraryElements=this.$uiLibrary.children(),this.tabGrid=new Craft.Grid(this.$tabContainer,{itemSelector:".fld-tab",minColWidth:264,fillMode:"grid",snapToGrid:24});for(var n=this.$tabContainer.children(),r=0;r<n.length;r++)this.initTab($(n[r]));if($("<input/>",{type:"hidden",name:this.settings.elementPlacementInputName.replace("[__TAB_NAME__][]",""),value:""}).insertBefore(this.$container),this.elementDrag=new Craft.FieldLayoutDesigner.ElementDrag(this),this.settings.customizableTabs&&(this.tabDrag=new Craft.FieldLayoutDesigner.TabDrag(this),this.addListener(this.$newTabBtn,"activate","addTab")),this.settings.customizableUi){var o=this.$sidebar.children(".btngroup");new Craft.Listbox(o,{onChange:function(t){i.$selectedLibrary.addClass("hidden"),i.$selectedLibrary=i["$".concat(t.data("library"),"Library")].removeClass("hidden")}})}this.addListener(this.$fieldSearch,"input",(function(){var t=i.$fieldSearch.val().toLowerCase().replace(/['"]/g,"");if(!t)return i.$fieldLibrary.find(".filtered").removeClass("filtered"),void i.$clearFieldSearchBtn.addClass("hidden");i.$clearFieldSearchBtn.removeClass("hidden");var e=i.$fields.filter('[data-keywords*="'.concat(t,'"]')).add(i.$fieldGroups.filter('[data-name*="'.concat(t,'"]')).children(".fld-element")).removeClass("filtered");i.$fields.not(e).addClass("filtered");for(var s=0;s<i.$fieldGroups.length;s++){var a=i.$fieldGroups.eq(s);a.find(".fld-element:not(.hidden):not(.filtered)").length?a.removeClass("filtered"):a.addClass("filtered")}})),this.addListener(this.$fieldSearch,"keydown",(function(t){switch(t.keyCode){case Garnish.ESC_KEY:i.$fieldSearch.val("").trigger("input");break;case Garnish.RETURN_KEY:t.preventDefault()}})),this.addListener(this.$clearFieldSearchBtn,"click",(function(){i.$fieldSearch.val("").trigger("input")}))},initTab:function(t){if(this.settings.customizableTabs){var e=t.find(".tabs .settings");$('<div class="menu" data-align="center"/>').insertAfter(e).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"rename",text:Craft.t("app","Rename")}))).append($("<li/>").append($("<a/>",{"data-action":"remove",text:Craft.t("app","Remove")})))).append($("<hr/>")).append($("<ul/>").append($("<li/>").append($("<a/>",{"data-action":"moveLeft",text:Craft.t("app","Move to the left")}))).append($("<li/>").append($("<a/>",{"data-action":"moveRight",text:Craft.t("app","Move to the right")}))));var i=new Garnish.MenuBtn(e,{onOptionSelect:this.onTabOptionSelect.bind(this)});i.menu.on("show",(function(){t.prev(".fld-tab").length?i.menu.$container.find("[data-action=moveLeft]").removeClass("disabled"):i.menu.$container.find("[data-action=moveLeft]").addClass("disabled"),t.next(".fld-tab").length?i.menu.$container.find("[data-action=moveRight]").removeClass("disabled"):i.menu.$container.find("[data-action=moveRight]").addClass("disabled")}))}for(var s=t.children(".fld-tabcontent").children(),a=0;a<s.length;a++)this.initElement($(s[a]))},initElement:function(t){new Craft.FieldLayoutDesigner.Element(this,t)},onTabOptionSelect:function(t){if(this.settings.customizableTabs){var e=$(t),i=e.data("menu").$anchor.parent().parent().parent();switch(e.data("action")){case"rename":this.renameTab(i);break;case"remove":this.removeTab(i);break;case"moveLeft":var s=i.prev(".fld-tab");s.length&&i.insertBefore(s);break;case"moveRight":var a=i.next(".fld-tab");a.length&&i.insertAfter(a)}}},renameTab:function(t){if(this.settings.customizableTabs){var e=t.find(".tabs .tab span"),i=e.text(),s=this.promptForTabName(i);s&&s!==i&&(e.text(s),t.find(".placement-input").attr("name",this.getElementPlacementInputName(s)))}},promptForTabName:function(t){return Craft.escapeHtml(prompt(Craft.t("app","Give your tab a name."),t))},removeTab:function(t){if(this.settings.customizableTabs){for(var e=t.find(".fld-element"),i=0;i<e.length;i++){var s=$(e[i]).attr("data-attribute");this.removeFieldByHandle(s)}this.tabGrid.removeItems(t),this.tabDrag.removeItems(t),t.remove()}},removeField:function(t){var e=t.attr("data-attribute");t.remove(),this.removeFieldByHandle(e),this.tabGrid.refreshCols(!0)},removeFieldByHandle:function(t){this.$fields.filter('[data-attribute="'.concat(t,'"]:first')).removeClass("hidden").closest(".fld-field-group").removeClass("hidden")},addTab:function(){if(this.settings.customizableTabs){var t=this.promptForTabName();if(t){var e=$('\n<div class="fld-tab">\n  <div class="tabs">\n    <div class="tab sel draggable">\n      <span>'.concat(t,'</span>\n      <a class="settings icon" title="').concat(Craft.t("app","Rename"),'"></a>\n    </div>\n  </div>\n  <div class="fld-tabcontent"></div>\n</div>\n')).appendTo(this.$tabContainer);this.tabGrid.addItems(e),this.tabDrag.addItems(e),this.initTab(e)}}},getElementPlacementInputName:function(t){return this.settings.elementPlacementInputName.replace(/__TAB_NAME__/g,Craft.encodeUriComponent(t))}},{defaults:{customizableTabs:!0,customizableUi:!0,elementPlacementInputName:"elementPlacements[__TAB_NAME__][]",elementConfigInputName:"elementConfigs[__ELEMENT_KEY__]"}}),Craft.FieldLayoutDesigner.Element=Garnish.Base.extend({designer:null,$container:null,$placementInput:null,$configInput:null,$settingsContainer:null,$editBtn:null,config:null,isField:!1,attribute:null,requirable:!1,key:null,hasCustomWidth:!1,hasSettings:!1,hud:null,init:function(t,e){var i=this;this.designer=t,this.$container=e,this.$container.data("fld-element",this),this.config=this.$container.data("config"),$.isPlainObject(this.config)||(this.config={}),this.config.type=this.$container.data("type"),this.isField=this.$container.hasClass("fld-field"),this.requirable=this.isField&&Garnish.hasAttr(this.$container,"data-requirable"),this.key=Craft.randomString(10),this.isField&&(this.attribute=this.$container.data("attribute"));var s=this.$container.data("settings-html"),a=this.requirable&&this.$container.hasClass("fld-required");this.hasCustomWidth=this.designer.settings.customizableUi&&Garnish.hasAttr(this.$container,"data-has-custom-width"),this.hasSettings=s||this.requirable,this.hasSettings&&(s=s?s.replace(/\b__ELEMENT_KEY__\b/g,this.key):"",this.$settingsContainer=$("<div/>",{class:"hidden"}),this.$editBtn=$("<a/>",{role:"button",tabindex:0,class:"settings icon",title:Craft.t("app","Edit")}),this.$editBtn.on("click",(function(){i.hud?(i.hud.show(),i.hud.updateSizeAndPosition(!0)):i.createSettingsHud(s,a)}))),this.initUi(),this.$container.attr("data-config",null),this.$container.attr("data-keywords",null),this.$container.attr("data-settings-html",null)},initUi:function(){var t=this;this.$placementInput=$("<input/>",{class:"placement-input",type:"hidden",name:"",value:this.key}).appendTo(this.$container),this.updatePlacementInput(),this.$configInput=$("<input/>",{type:"hidden",name:this.designer.settings.elementConfigInputName.replace(/\b__ELEMENT_KEY__\b/g,this.key)}).appendTo(this.$container),this.updateConfigInput(),this.hasCustomWidth&&new Craft.SlidePicker(this.config.width||100,{min:25,max:100,step:25,valueLabel:function(t){return Craft.t("app","{pct} width",{pct:"".concat(t,"%")})},onChange:function(e){t.config.width=e,t.updateConfigInput()}}).$container.appendTo(this.$container),this.hasSettings&&this.$editBtn.appendTo(this.$container)},createSettingsHud:function(t,e){var i=this,s='\n<div class="fld-element-settings">\n  '.concat(t,'\n  <div class="hud-footer">\n    <div class="buttons right">\n      <button class="btn submit" type="submit">').concat(Craft.t("app","Apply"),'</button>\n      <div class="spinner hidden"></div>\n    </div>\n  </div>\n</div>\n');this.hud=new Garnish.HUD(this.$container,s,{onShow:function(t){Garnish.requestAnimationFrame((function(){i.hud.$main.find(".text:first").trigger("focus")}))},onSubmit:function(){i.applyHudSettings()}}),Craft.initUiElements(this.hud.$main),this.requirable&&Craft.ui.createLightswitchField({label:Craft.t("app","Required"),id:"".concat(this.key,"-required"),name:"required",on:e}).prependTo(this.hud.$main),this.trigger("createSettingsHud")},applyHudSettings:function(){var t=this;this.hud.$body.serializeArray().forEach((function(e){var i=e.name,s=e.value;t.config[i]=s})),this.updateConfigInput();var e=this.hud.$body.find(".spinner").removeClass("hidden");Craft.sendActionRequest("POST","fields/render-layout-element-selector",{data:{config:this.config}}).then((function(i){e.addClass("hidden"),t.$editBtn.detach(),t.$container.html($(i.data.html).html()),t.initUi(),t.updateRequiredClass(),t.hud.hide()})).catch((function(i){console.error(i),e.addClass("hidden"),t.updateRequiredClass(),t.hud.hide()}))},updatePlacementInput:function(){var t=this.$container.closest(".fld-tab").find(".tab span");if(t.length){var e=this.designer.getElementPlacementInputName(t.text());this.$placementInput.attr("name",e)}},updateConfigInput:function(){this.$configInput.val(JSON.stringify(this.config))},updateRequiredClass:function(){this.requirable&&(this.config.required?this.$container.addClass("fld-required"):this.$container.removeClass("fld-required"))}}),Craft.FieldLayoutDesigner.BaseDrag=Garnish.Drag.extend({designer:null,$insertion:null,showingInsertion:!1,$caboose:null,init:function(t,e){this.designer=t,this.base(this.findItems(),e)},onDragStart:function(){this.base(),this.$insertion=this.createInsertion(),this.$caboose=this.createCaboose(),this.$items=$().add(this.$items.add(this.$caboose)),Garnish.$bod.addClass("dragging")},removeCaboose:function(){this.$items=this.$items.not(this.$caboose),this.$caboose.remove()},swapDraggeeWithInsertion:function(){this.$insertion.insertBefore(this.$draggee),this.$draggee.detach(),this.$items=$().add(this.$items.not(this.$draggee).add(this.$insertion)),this.showingInsertion=!0},swapInsertionWithDraggee:function(){this.$insertion.replaceWith(this.$draggee),this.$items=$().add(this.$items.not(this.$insertion).add(this.$draggee)),this.showingInsertion=!1},setMidpoints:function(){for(var t=0;t<this.$items.length;t++){var e=$(this.$items[t]),i=e.offset();e.hasClass("unused")||e.data("midpoint",{left:i.left+e.outerWidth()/2,top:i.top+e.outerHeight()/2})}},getClosestItem:function(){for(this.getClosestItem._closestItem=null,this.getClosestItem._closestItemMouseDiff=null,this.getClosestItem._i=0;this.getClosestItem._i<this.$items.length;this.getClosestItem._i++)this.getClosestItem._$item=$(this.$items[this.getClosestItem._i]),this.getClosestItem._midpoint=this.getClosestItem._$item.data("midpoint"),this.getClosestItem._midpoint&&(this.getClosestItem._mouseDiff=Garnish.getDist(this.getClosestItem._midpoint.left,this.getClosestItem._midpoint.top,this.mouseX,this.mouseY),(null===this.getClosestItem._closestItem||this.getClosestItem._mouseDiff<this.getClosestItem._closestItemMouseDiff)&&(this.getClosestItem._closestItem=this.getClosestItem._$item[0],this.getClosestItem._closestItemMouseDiff=this.getClosestItem._mouseDiff));return this.getClosestItem._closestItem},checkForNewClosestItem:function(){this.checkForNewClosestItem._closestItem=this.getClosestItem(),this.checkForNewClosestItem._closestItem!==this.$insertion[0]&&(this.showingInsertion&&$.inArray(this.$insertion[0],this.$items)<$.inArray(this.checkForNewClosestItem._closestItem,this.$items)&&-1===$.inArray(this.checkForNewClosestItem._closestItem,this.$caboose)?this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem):this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem),this.$items=$().add(this.$items.add(this.$insertion)),this.showingInsertion=!0,this.designer.tabGrid.refreshCols(!0),this.setMidpoints())},onDragStop:function(){var t=this;this.showingInsertion&&this.swapInsertionWithDraggee(),this.removeCaboose(),this.designer.tabGrid.refreshCols(!0);var e=this.$draggee.offset();!e||0===e.top&&0===e.left?(this.$draggee.css({display:this.draggeeDisplay,visibility:"visible",opacity:0}).velocity({opacity:1},Garnish.FX_DURATION),this.helpers[0].velocity({opacity:0},Garnish.FX_DURATION,(function(){t._showDraggee()}))):this.returnHelpersToDraggees(),this.base(),Garnish.$bod.removeClass("dragging")}}),Craft.FieldLayoutDesigner.TabDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({init:function(t){this.base(t,{handle:".tab"})},findItems:function(){return this.designer.$tabContainer.find("> div.fld-tab")},onDragStart:function(){this.base(),this.swapDraggeeWithInsertion(),this.setMidpoints()},swapDraggeeWithInsertion:function(){this.base(),this.designer.tabGrid.removeItems(this.$draggee),this.designer.tabGrid.addItems(this.$insertion)},swapInsertionWithDraggee:function(){this.base(),this.designer.tabGrid.removeItems(this.$insertion),this.designer.tabGrid.addItems(this.$draggee)},onDrag:function(){this.checkForNewClosestItem(),this.base()},onDragStop:function(){this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:"hidden"})},createCaboose:function(){var t=$('<div class="fld-tab fld-tab-caboose"/>').appendTo(this.designer.$tabContainer);return this.designer.tabGrid.addItems(t),t},removeCaboose:function(){this.base(),this.designer.tabGrid.removeItems(this.$caboose)},createInsertion:function(){var t=this.$draggee.find(".tab");return $('\n<div class="fld-tab fld-insertion" style="height: '.concat(this.$draggee.height(),'px;">\n  <div class="tabs"><div class="tab sel draggable" style="width: ').concat(t.width(),"px; height: ").concat(t.height(),'px;"></div></div>\n  <div class="fld-tabcontent" style="height: ').concat(this.$draggee.find(".fld-tabcontent").height(),'px;"></div>\n</div>\n'))}}),Craft.FieldLayoutDesigner.ElementDrag=Craft.FieldLayoutDesigner.BaseDrag.extend({draggingLibraryElement:!1,draggingField:!1,onDragStart:function(){this.base(),this.draggingLibraryElement=this.$draggee.hasClass("unused"),this.draggingField=this.$draggee.hasClass("fld-field"),this.draggingLibraryElement&&!this.draggingField&&this.$draggee.css({display:this.draggeeDisplay,visibility:"visible"}),this.draggingLibraryElement||this.swapDraggeeWithInsertion(),this.setMidpoints()},onDrag:function(){this.isDraggeeMandatory()||this.isHoveringOverTab()?this.checkForNewClosestItem():this.showingInsertion&&(this.$insertion.remove(),this.$items=$().add(this.$items.not(this.$insertion)),this.showingInsertion=!1,this.designer.tabGrid.refreshCols(!0),this.setMidpoints()),this.base()},isDraggeeMandatory:function(){return Garnish.hasAttr(this.$draggee,"data-mandatory")},isHoveringOverTab:function(){for(var t=0;t<this.designer.tabGrid.$items.length;t++)if(Garnish.hitTest(this.mouseX,this.mouseY,this.designer.tabGrid.$items.eq(t)))return!0;return!1},findItems:function(){return this.designer.$tabContainer.find(".fld-element").add(this.designer.$sidebar.find(".fld-element"))},createCaboose:function(){for(var t=$(),e=this.designer.$tabContainer.find("> .fld-tab > .fld-tabcontent"),i=0;i<e.length;i++)t=t.add($("<div/>").appendTo(e[i]));return t},createInsertion:function(){return $('<div class="fld-element fld-insertion" style="height: '.concat(this.$draggee.outerHeight(),'px;"/>'))},onDragStop:function(){var t=this.showingInsertion;if(t){if(this.draggingLibraryElement){var e=this.$draggee.clone().removeClass("unused");this.designer.initElement(e),this.draggingField&&(this.$draggee.css({visibility:"inherit",display:"field"}).addClass("hidden"),0===this.$draggee.siblings(".fld-field:not(.hidden)").length&&this.$draggee.closest(".fld-field-group").addClass("hidden")),this.$draggee=e,this.addItems(e)}}else if(!this.draggingLibraryElement){var i=this.draggingField?this.designer.$fields.filter('[data-attribute="'.concat(this.$draggee.data("attribute"),'"]:first')):this.designer.$uiLibraryElements.filter('[data-type="'.concat(this.$draggee.data("type").replace(/\\/g,"\\\\"),'"]:first'));this.draggingField&&(i.removeClass("hidden"),i.closest(".fld-field-group").removeClass("hidden")),this.removeItems(this.$draggee),this.$draggee=i}this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:this.draggingField||t?"hidden":"visible"}),t&&this.$draggee.data("fld-element").updatePlacementInput()}})},3347:function(){Craft.FieldToggle=Garnish.Base.extend({$toggle:null,targetPrefix:null,targetSelector:null,reverseTargetSelector:null,_$target:null,_$reverseTarget:null,type:null,init:function(t){switch(this.$toggle=$(t),this.$toggle.data("fieldtoggle")&&(console.warn("Double-instantiating a field toggle on an element"),this.$toggle.data("fieldtoggle").destroy()),this.$toggle.data("fieldtoggle",this),this.type=this.getType(),"select"===this.type||"fieldset"===this.type?this.targetPrefix=this.$toggle.attr("data-target-prefix")||"":(this.targetSelector=this.normalizeTargetSelector(this.$toggle.data("target")),this.reverseTargetSelector=this.normalizeTargetSelector(this.$toggle.data("reverse-target"))),this.findTargets(),this.type){case"link":this.addListener(this.$toggle,"click","onToggleChange");break;case"fieldset":this.addListener(this.$toggle.find("input"),"change","onToggleChange");break;default:this.addListener(this.$toggle,"change","onToggleChange"),this.onToggleChange()}},normalizeTargetSelector:function(t){return t&&!t.match(/^[#\.]/)&&(t="#"+t),t},getType:function(){var t=this.$toggle.prop("nodeName");if("INPUT"===t&&"checkbox"===this.$toggle.attr("type")||"checkbox"===this.$toggle.attr("role")||"switch"===this.$toggle.attr("role"))return"checkbox";switch(t){case"SELECT":return Garnish.hasAttr(this.$toggle,"data-boolean-menu")?"booleanMenu":"select";case"A":return"link";case"FIELDSET":return"fieldset"}console.warn("Unexpected field toggle:",this.$toggle[0])},findTargets:function(){"select"===this.type||"fieldset"===this.type?(this.getToggleVal(),this._$target=$(this.normalizeTargetSelector(this.targetPrefix+this.getToggleVal()))):(this.targetSelector&&(this._$target=$(this.targetSelector)),this.reverseTargetSelector&&(this._$reverseTarget=$(this.reverseTargetSelector)))},getToggleVal:function(){switch(this.type){case"checkbox":return void 0!==this.$toggle.prop("checked")?this.$toggle.prop("checked"):"true"===this.$toggle.attr("aria-checked");case"booleanMenu":var t=this.$toggle.data("boolean");if(void 0!==t)return t;var e=this.$toggle.val();return e&&"0"!==e;default:var i;return null==(i="fieldset"===this.type?this.$toggle.find("input:checked:first").val():Garnish.getInputPostVal(this.$toggle))?null:i.replace(/[^\w]+/g,"-")}},onToggleChange:function(){"select"===this.type||"fieldset"===this.type?(this.hideTarget(this._$target),this.findTargets(),this.showTarget(this._$target)):(this.findTargets(),"link"===this.type?this.onToggleChange._show=this.$toggle.hasClass("collapsed")||!this.$toggle.hasClass("expanded"):this.onToggleChange._show=!!this.getToggleVal(),this.onToggleChange._show?(this.showTarget(this._$target),this.hideTarget(this._$reverseTarget)):(this.hideTarget(this._$target),this.showTarget(this._$reverseTarget)),delete this.onToggleChange._show)},showTarget:function(t){var e=this;if(t&&t.length){if(this.showTarget._currentHeight=t.height(),t.removeClass("hidden"),"select"!==this.type&&"fieldset"!==this.type){"link"===this.type&&(this.$toggle.removeClass("collapsed"),this.$toggle.addClass("expanded"));for(var i=0;i<t.length;i++)!function(t){"SPAN"!==t.prop("nodeName")&&(t.height("auto"),e.showTarget._targetHeight=t.height(),t.css({height:e.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:e.showTarget._targetHeight},"fast",(function(){t.css({height:"",overflow:""})})))}(t.eq(i));delete this.showTarget._targetHeight}delete this.showTarget._currentHeight,Garnish.$win.trigger("resize")}},hideTarget:function(t){if(t&&t.length)if("select"===this.type||"fieldset"===this.type)t.addClass("hidden");else{"link"===this.type&&(this.$toggle.removeClass("expanded"),this.$toggle.addClass("collapsed"));for(var e=0;e<t.length;e++)!function(t){t.hasClass("hidden")||("SPAN"===t.prop("nodeName")?t.addClass("hidden"):(t.css("overflow","hidden"),t.velocity("stop"),t.velocity({height:0},"fast",(function(){t.addClass("hidden")}))))}(t.eq(e))}},destroy:function(){this.$toggle.removeData("fieldtoggle"),this.base()}})},9478:function(){Craft.Grid=Garnish.Base.extend({$container:null,$items:null,items:null,totalCols:null,colGutterDrop:null,colPctWidth:null,possibleItemColspans:null,possibleItemPositionsByColspan:null,itemPositions:null,itemColspansByPosition:null,layouts:null,layout:null,itemHeights:null,leftPadding:null,_refreshingCols:!1,_refreshColsAfterRefresh:!1,_forceRefreshColsAfterRefresh:!1,init:function(t,e){var i=this;this.$container=$(t),this.$container.data("grid")&&(console.warn("Double-instantiating a grid on an element"),this.$container.data("grid").destroy()),this.$container.data("grid",this),this.setSettings(e,Craft.Grid.defaults),this.handleContainerHeightProxy=function(){i.refreshCols(!1,!0)},this.$items=this.$container.children(this.settings.itemSelector),this.setItems(),this.refreshCols(!0,!1),Garnish.$doc.ready((function(){i.refreshCols(!1,!1)}))},addItems:function(t){this.$items=$().add(this.$items.add(t)),this.setItems(),this.refreshCols(!0,!0)},removeItems:function(t){this.$items=$().add(this.$items.not(t)),this.setItems(),this.refreshCols(!0,!0)},resetItemOrder:function(){this.$items=$().add(this.$items),this.setItems(),this.refreshCols(!0,!0)},setItems:function(){for(this.setItems._={},this.items=[],this.setItems._.i=0;this.setItems._.i<this.$items.length;this.setItems._.i++)this.items.push($(this.$items[this.setItems._.i]));delete this.setItems._},refreshCols:function(t){if(this._refreshingCols)return this._refreshColsAfterRefresh=!0,void(t&&(this._forceRefreshColsAfterRefresh=!0));if(this._refreshingCols=!0,this.items.length)if(this.refreshCols._={},this.refreshCols._.oldHeight=this.$container[0].style.height,this.$container[0].style.height=1,this.refreshCols._.scrollHeight=this.$container[0].scrollHeight,this.$container[0].style.height=this.refreshCols._.oldHeight,0!==this.refreshCols._.scrollHeight)if(this.settings.cols?this.refreshCols._.totalCols=this.settings.cols:(this.refreshCols._.totalCols=Math.floor(this.$container.width()/this.settings.minColWidth),null!==this.totalCols&&this.refreshCols._.totalCols>this.totalCols&&(this.refreshCols._.totalCols=Math.floor((this.$container.width()-20)/this.settings.minColWidth)),this.settings.maxCols&&this.refreshCols._.totalCols>this.settings.maxCols&&(this.refreshCols._.totalCols=this.settings.maxCols)),0===this.refreshCols._.totalCols&&(this.refreshCols._.totalCols=1),!0===t||this.totalCols!==this.refreshCols._.totalCols){if(this.totalCols=this.refreshCols._.totalCols,this.colGutterDrop=this.settings.gutter*(this.totalCols-1)/this.totalCols,this.removeListener(this.$container,"resize"),"grid"===this.settings.fillMode)for(this.refreshCols._.itemIndex=0;this.refreshCols._.itemIndex<this.items.length;){for(this.refreshCols._.tallestItemHeight=-1,this.refreshCols._.colIndex=0,this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.itemHeight=this.items[this.refreshCols._.i].height("auto").height(),this.refreshCols._.itemHeight>this.refreshCols._.tallestItemHeight&&(this.refreshCols._.tallestItemHeight=this.refreshCols._.itemHeight),this.refreshCols._.colIndex++;for(this.settings.snapToGrid&&(this.refreshCols._.remainder=this.refreshCols._.tallestItemHeight%this.settings.snapToGrid,this.refreshCols._.remainder&&(this.refreshCols._.tallestItemHeight+=this.settings.snapToGrid-this.refreshCols._.remainder)),this.refreshCols._.i=this.refreshCols._.itemIndex;this.refreshCols._.i<this.refreshCols._.itemIndex+this.totalCols&&this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.items[this.refreshCols._.i].height(this.refreshCols._.tallestItemHeight);this.refreshCols._.itemIndex+=this.totalCols}else if(this.removeListener(this.$items,"resize"),1===this.totalCols)this.$container.height("auto"),this.$items.show().css({position:"relative",width:"auto",top:0}).css(Craft.left,0);else{for(this.$items.css("position","absolute"),this.colPctWidth=100/this.totalCols,this.layouts=[],this.itemPositions=[],this.itemColspansByPosition=[],this.possibleItemColspans=[],this.possibleItemPositionsByColspan=[],this.itemHeightsByColspan=[],this.refreshCols._.item=0;this.refreshCols._.item<this.items.length;this.refreshCols._.item++)for(this.possibleItemColspans[this.refreshCols._.item]=[],this.possibleItemPositionsByColspan[this.refreshCols._.item]={},this.itemHeightsByColspan[this.refreshCols._.item]={},this.refreshCols._.$item=this.items[this.refreshCols._.item].show(),this.refreshCols._.positionRight="right"===this.refreshCols._.$item.data("position"),this.refreshCols._.positionLeft="left"===this.refreshCols._.$item.data("position"),this.refreshCols._.minColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("min-colspan")?this.refreshCols._.$item.data("min-colspan"):1,this.refreshCols._.maxColspan=this.refreshCols._.$item.data("colspan")?this.refreshCols._.$item.data("colspan"):this.refreshCols._.$item.data("max-colspan")?this.refreshCols._.$item.data("max-colspan"):this.totalCols,this.refreshCols._.minColspan>this.totalCols&&(this.refreshCols._.minColspan=this.totalCols),this.refreshCols._.maxColspan>this.totalCols&&(this.refreshCols._.maxColspan=this.totalCols),this.refreshCols._.colspan=this.refreshCols._.minColspan;this.refreshCols._.colspan<=this.refreshCols._.maxColspan;this.refreshCols._.colspan++)for(this.refreshCols._.$item.css("width",this.getItemWidthCss(this.refreshCols._.colspan)),this.itemHeightsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=this.refreshCols._.$item.outerHeight(),this.possibleItemColspans[this.refreshCols._.item].push(this.refreshCols._.colspan),this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan]=[],this.refreshCols._.positionLeft?(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=0):this.refreshCols._.positionRight?(this.refreshCols._.minPosition=this.totalCols-this.refreshCols._.colspan,this.refreshCols._.maxPosition=this.refreshCols._.minPosition):(this.refreshCols._.minPosition=0,this.refreshCols._.maxPosition=this.totalCols-this.refreshCols._.colspan),this.refreshCols._.position=this.refreshCols._.minPosition;this.refreshCols._.position<=this.refreshCols._.maxPosition;this.refreshCols._.position++)this.possibleItemPositionsByColspan[this.refreshCols._.item][this.refreshCols._.colspan].push(this.refreshCols._.position);for(this.refreshCols._.colHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.totalCols;this.refreshCols._.i++)this.refreshCols._.colHeights.push(0);for(this.createLayouts(0,[],[],this.refreshCols._.colHeights,0),this.refreshCols._.layoutTotalCols=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)for(this.refreshCols._.layoutTotalCols[this.refreshCols._.i]=0,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j]&&this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;for(this.refreshCols._.highestTotalCols=Math.max.apply(null,this.refreshCols._.layoutTotalCols),this.refreshCols._.i=this.layouts.length-1;this.refreshCols._.i>=0;this.refreshCols._.i--)this.refreshCols._.layoutTotalCols[this.refreshCols._.i]!==this.refreshCols._.highestTotalCols&&this.layouts.splice(this.refreshCols._.i,1);for(this.refreshCols._.layoutHeights=[],this.refreshCols._.i=0;this.refreshCols._.i<this.layouts.length;this.refreshCols._.i++)this.refreshCols._.layoutHeights.push(Math.max.apply(null,this.layouts[this.refreshCols._.i].colHeights));for(this.refreshCols._.shortestHeight=Math.min.apply(null,this.refreshCols._.layoutHeights),this.refreshCols._.shortestLayouts=[],this.refreshCols._.emptySpaces=[],this.refreshCols._.i=0;this.refreshCols._.i<this.refreshCols._.layoutHeights.length;this.refreshCols._.i++)if(this.refreshCols._.layoutHeights[this.refreshCols._.i]===this.refreshCols._.shortestHeight){for(this.refreshCols._.shortestLayouts.push(this.layouts[this.refreshCols._.i]),this.refreshCols._.emptySpace=this.layouts[this.refreshCols._.i].emptySpace,this.refreshCols._.j=0;this.refreshCols._.j<this.totalCols;this.refreshCols._.j++)this.refreshCols._.emptySpace+=this.refreshCols._.shortestHeight-this.layouts[this.refreshCols._.i].colHeights[this.refreshCols._.j];this.refreshCols._.emptySpaces.push(this.refreshCols._.emptySpace)}for(this.layout=this.refreshCols._.shortestLayouts[$.inArray(Math.min.apply(null,this.refreshCols._.emptySpaces),this.refreshCols._.emptySpaces)],this.refreshCols._.i=0;this.refreshCols._.i<this.items.length;this.refreshCols._.i++)this.refreshCols._.css={width:this.getItemWidthCss(this.layout.colspans[this.refreshCols._.i])},this.refreshCols._.css[Craft.left]=this.getItemLeftPosCss(this.layout.positions[this.refreshCols._.i]),this.items[this.refreshCols._.i].css(this.refreshCols._.css);this.isSimpleLayout()?(this.$container.height("auto"),this.$items.css({position:"relative",top:0,"margin-bottom":this.settings.gutter+"px"})):(this.$items.css("position","absolute"),this.positionItems(),this.addListener(this.$items,"resize","onItemResize"))}this.completeRefreshCols(),this.addListener(this.$container,"resize",this.handleContainerHeightProxy),this.onRefreshCols()}else this.completeRefreshCols();else this.completeRefreshCols();else this.completeRefreshCols()},completeRefreshCols:function(){var t=this;if(void 0!==this.refreshCols._&&delete this.refreshCols._,this._refreshingCols=!1,this._refreshColsAfterRefresh){var e=this._forceRefreshColsAfterRefresh;this._refreshColsAfterRefresh=!1,this._forceRefreshColsAfterRefresh=!1,Garnish.requestAnimationFrame((function(){t.refreshCols(e)}))}},getItemWidth:function(t){return this.colPctWidth*t},getItemWidthCss:function(t){return"calc("+this.getItemWidth(t)+"% - "+this.colGutterDrop+"px)"},getItemWidthInPx:function(t){return this.getItemWidth(t)/100*this.$container.width()-this.colGutterDrop},getItemLeftPosCss:function(t){return"calc(("+this.getItemWidth(1)+"% + "+(this.settings.gutter-this.colGutterDrop)+"px) * "+t+")"},getItemLeftPosInPx:function(t){return(this.getItemWidth(1)/100*this.$container.width()+(this.settings.gutter-this.colGutterDrop))*t},createLayouts:function(t,e,i,s,a){new Craft.Grid.LayoutGenerator(this).createLayouts(t,e,i,s,a)},isSimpleLayout:function(){for(this.isSimpleLayout._={},this.isSimpleLayout._.i=0;this.isSimpleLayout._.i<this.layout.positions.length;this.isSimpleLayout._.i++)if(0!==this.layout.positions[this.isSimpleLayout._.i])return delete this.isSimpleLayout._,!1;return delete this.isSimpleLayout._,!0},positionItems:function(){for(this.positionItems._={},this.positionItems._.colHeights=[],this.positionItems._.i=0;this.positionItems._.i<this.totalCols;this.positionItems._.i++)this.positionItems._.colHeights.push(0);for(this.positionItems._.i=0;this.positionItems._.i<this.items.length;this.positionItems._.i++){for(this.positionItems._.endingCol=this.layout.positions[this.positionItems._.i]+this.layout.colspans[this.positionItems._.i]-1,this.positionItems._.affectedColHeights=[],this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.affectedColHeights.push(this.positionItems._.colHeights[this.positionItems._.col]);for(this.positionItems._.top=Math.max.apply(null,this.positionItems._.affectedColHeights),this.positionItems._.top>0&&(this.positionItems._.top+=this.settings.gutter),this.items[this.positionItems._.i].css("top",this.positionItems._.top),this.positionItems._.col=this.layout.positions[this.positionItems._.i];this.positionItems._.col<=this.positionItems._.endingCol;this.positionItems._.col++)this.positionItems._.colHeights[this.positionItems._.col]=this.positionItems._.top+this.itemHeightsByColspan[this.positionItems._.i][this.layout.colspans[this.positionItems._.i]]}this.$container.height(Math.max.apply(null,this.positionItems._.colHeights)),delete this.positionItems._},onItemResize:function(t){this.onItemResize._={},t.stopPropagation(),this.onItemResize._.item=$.inArray(t.currentTarget,this.$items),-1!==this.onItemResize._.item&&(this.onItemResize._.newHeight=this.items[this.onItemResize._.item].outerHeight(),this.onItemResize._.newHeight!==this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]&&(this.itemHeightsByColspan[this.onItemResize._.item][this.layout.colspans[this.onItemResize._.item]]=this.onItemResize._.newHeight,this.positionItems(!1))),delete this.onItemResize._},onRefreshCols:function(){this.trigger("refreshCols"),this.settings.onRefreshCols()},destroy:function(){this.$container.removeData("grid"),this.base()}},{defaults:{itemSelector:".item",cols:null,maxCols:null,minColWidth:320,gutter:14,fillMode:"top",colClass:"col",snapToGrid:null,onRefreshCols:$.noop}}),Craft.Grid.LayoutGenerator=Garnish.Base.extend({grid:null,_:null,init:function(t){this.grid=t},createLayouts:function(t,e,i,s,a){for(this._={},this._.c=0;this._.c<this.grid.possibleItemColspans[t].length;this._.c++){for(this._.colspan=this.grid.possibleItemColspans[t][this._.c],this._.tallestColHeightsByPosition=[],this._.p=0;this._.p<this.grid.possibleItemPositionsByColspan[t][this._.colspan].length;this._.p++){for(this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.colHeightsForPosition=[],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.colHeightsForPosition.push(s[this._.col]);this._.tallestColHeightsByPosition[this._.p]=Math.max.apply(null,this._.colHeightsForPosition)}for(this._.p=$.inArray(Math.min.apply(null,this._.tallestColHeightsByPosition),this._.tallestColHeightsByPosition),this._.position=this.grid.possibleItemPositionsByColspan[t][this._.colspan][this._.p],this._.positions=e.slice(0),this._.colspans=i.slice(0),this._.colHeights=s.slice(0),this._.emptySpace=a,this._.positions.push(this._.position),this._.colspans.push(this._.colspan),this._.tallestColHeight=this._.tallestColHeightsByPosition[this._.p],this._.endingCol=this._.position+this._.colspan-1,this._.col=this._.position;this._.col<=this._.endingCol;this._.col++)this._.emptySpace+=this._.tallestColHeight-this._.colHeights[this._.col],this._.colHeights[this._.col]=this._.tallestColHeight+this.grid.itemHeightsByColspan[t][this._.colspan];t===this.grid.items.length-1?this.grid.layouts.push({positions:this._.positions,colspans:this._.colspans,colHeights:this._.colHeights,emptySpace:this._.emptySpace}):this.grid.createLayouts(t+1,this._.positions,this._.colspans,this._.colHeights,this._.emptySpace)}delete this._}})},2387:function(){Craft.HandleGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){var e=t.replace("/<(.*?)>/g","");e=(e=e.replace(/['"‘’“”\[\]\(\)\{\}:]/g,"")).toLowerCase(),e=Craft.asciiString(e),this.settings.allowNonAlphaStart||(e=e.replace(/^[^a-z]+/,""));var i=Craft.filterArray(e.split(/[^a-z0-9]+/));if(e="","snake"===Craft.handleCasing)return i.join("_");for(var s=0;s<i.length;s++)"pascal"!==Craft.handleCasing&&0===s?e+=i[s]:e+=i[s].charAt(0).toUpperCase()+i[s].substr(1);return e}})},7966:function(){Craft.ImageUpload=Garnish.Base.extend({$container:null,progressBar:null,uploader:null,init:function(t){this.setSettings(t,Craft.ImageUpload.defaults),this.initImageUpload()},initImageUpload:function(){this.$container=$(this.settings.containerSelector),this.progressBar=new Craft.ProgressBar($('<div class="progress-shade"></div>').appendTo(this.$container));var t={url:Craft.getActionUrl(this.settings.uploadAction),formData:this.settings.postParameters,fileInput:this.$container.find(this.settings.fileInputSelector),paramName:this.settings.uploadParamName};void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),t.events={},t.events.fileuploadstart=this._onUploadStart.bind(this),t.events.fileuploadprogressall=this._onUploadProgress.bind(this),t.events.fileuploaddone=this._onUploadComplete.bind(this),t.events.fileuploadfail=this._onUploadFailure.bind(this),this.uploader=new Craft.Uploader(this.$container,t),this.initButtons()},initButtons:function(){var t=this;this.$container.find(this.settings.uploadButtonSelector).on("click",(function(e){t.$container.find(t.settings.fileInputSelector).trigger("click")})),this.$container.find(this.settings.deleteButtonSelector).on("click",(function(e){confirm(Craft.t("app","Are you sure you want to delete this image?"))&&($(e.currentTarget).parent().append('<div class="blocking-modal"></div>'),Craft.postActionRequest(t.settings.deleteAction,t.settings.postParameters,(function(e,i){"success"===i&&t.refreshImage(e)})))}))},refreshImage:function(t){$(this.settings.containerSelector).replaceWith(t.html),this.settings.onAfterRefreshImage(t),this.initImageUpload()},_onUploadStart:function(t){this.progressBar.$progressBar.css({top:Math.round(this.$container.outerHeight()/2)-6}),this.$container.addClass("uploading"),this.progressBar.resetProgressBar(),this.progressBar.showProgressBar()},_onUploadProgress:function(t,e){var i=parseInt(e.loaded/e.total*100,10);this.progressBar.setProgressPercentage(i)},_onUploadComplete:function(t,e){e.result.error?alert(e.result.error):($(e.result.html),this.refreshImage(e.result)),this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},_onUploadFailure:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))}},{defaults:{postParameters:{},uploadAction:"",deleteAction:"",fileInputSelector:"",onAfterRefreshImage:$.noop,containerSelector:null,uploadButtonSelector:null,deleteButtonSelector:null,uploadParamName:"files"}})},657:function(){Craft.InfoIcon=Garnish.Base.extend({$icon:null,content:null,hud:null,init:function(t){var e=this;if(this.$icon=$(t),this.$icon.data("infoicon")?(console.warn("Double-instantiating an info icon on an element"),this.content=this.$icon.data("infoicon").content,this.$icon.data("infoicon").destroy()):(this.content=this.$icon.html(),this.$icon.html("").attr({tabindex:0,role:"button","aria-label":Craft.t("app","Information")})),this.$icon.data("infoicon",this),this.$icon[0].previousSibling&&this.$icon[0].previousSibling.nodeType===Node.TEXT_NODE&&!this.$icon.parent().hasClass("nowrap")){var i=this.$icon[0].previousSibling.nodeValue.match(/[^\s\-]+\s*$/);i&&(this.$icon[0].previousSibling.nodeValue=this.$icon[0].previousSibling.nodeValue.substr(0,i.index),$("<span/>",{class:"nowrap",html:i[0].replace(/\s+$/,"")+" "}).insertAfter(this.$icon[0].previousSibling).append(this.$icon))}this.addListener(this.$icon,"click",(function(t){t.preventDefault(),t.stopPropagation(),e.showHud()})),this.addListener(this.$icon,"keydown",(function(t){e.hud&&e.hud.showing||![Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)||(t.preventDefault(),t.stopPropagation(),e.showHud())}))},showHud:function(t){var e=this;this.hud?this.hud.show():(this.hud=new Garnish.HUD(this.$icon,this.content,{hudClass:"hud info-hud",closeOtherHUDs:!1,onShow:function(){Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY,(function(){e.hud.hide()}))}}),Craft.initUiElements(this.hud.$body))},destroy:function(){this.$icon.removeData("infoicon"),this.base()}})},4487:function(){Craft.LightSwitch=Garnish.Base.extend({settings:null,$outerContainer:null,$innerContainer:null,$input:null,small:!1,on:!1,indeterminate:!1,dragger:null,dragStartMargin:null,init:function(t,e){if(this.$outerContainer=$(t),this.$outerContainer.data("lightswitch")&&(console.warn("Double-instantiating a lightswitch on an element"),this.$outerContainer.data("lightswitch").destroy()),this.$outerContainer.data("lightswitch",this),this.small=this.$outerContainer.hasClass("small"),this.setSettings(e,Craft.LightSwitch.defaults),this.$innerContainer=this.$outerContainer.find(".lightswitch-container:first"),this.$input=this.$outerContainer.find("input:first"),!this.$input.prop("disabled")){this.on=this.$outerContainer.hasClass("on"),this.indeterminate=this.$outerContainer.hasClass("indeterminate"),this.addListener(this.$outerContainer,"mousedown","_onMouseDown"),this.addListener(this.$outerContainer,"keydown","_onKeyDown"),this.dragger=new Garnish.BaseDrag(this.$outerContainer,{axis:Garnish.X_AXIS,ignoreHandleSelector:null,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)});var i=this.$outerContainer.parent(".lightswitch-inner-container");i.length&&(this.addListener(i.children('span[data-toggle="off"]'),"click",this.turnOff),this.addListener(i.children('span[data-toggle="on"]'),"click",this.turnOn))}},turnOn:function(t){var e=!this.on;if(this.on=!0,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,0);else{var i={};i["margin-"+Craft.left]=0,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(this.settings.value),this.$outerContainer.addClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","true"),e&&!0!==t&&this.onChange()},turnOff:function(t){var e=this.on||this.indeterminate;if(this.on=!1,this.indeterminate=!1,this.$outerContainer.addClass("dragging"),Garnish.prefersReducedMotion())this.$innerContainer.css("margin-"+Craft.left,this._getOffMargin());else{var i={};i["margin-"+Craft.left]=this._getOffMargin(),this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this))}this.$input.val(""),this.$outerContainer.removeClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","false"),e&&!0!==t&&this.onChange()},turnIndeterminate:function(t){var e=!this.indeterminate;this.on=!1,this.indeterminate=!0,this.$outerContainer.addClass("dragging");var i={};i["margin-"+Craft.left]=this._getOffMargin()/2,this.$innerContainer.velocity("stop").velocity(i,Craft.LightSwitch.animationDuration,this._onSettle.bind(this)),this.$input.val(this.settings.indeterminateValue),this.$outerContainer.removeClass("on"),this.$outerContainer.addClass("indeterminate"),this.$outerContainer.attr("aria-checked","mixed"),e&&!0!==t&&this.onChange()},toggle:function(){this.indeterminate||!this.on?this.turnOn():this.turnOff()},onChange:function(){this.trigger("change"),this.settings.onChange(this.on),this.$outerContainer.trigger("change")},_onMouseDown:function(){this.addListener(Garnish.$doc,"mouseup","_onMouseUp")},_onMouseUp:function(){this.removeListener(Garnish.$doc,"mouseup"),this.dragger.dragging||this.toggle()},_onKeyDown:function(t){switch(t.keyCode){case Garnish.SPACE_KEY:this.toggle(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.turnOn():this.turnOff(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.turnOff():this.turnOn(),t.preventDefault()}},_getMargin:function(){return parseInt(this.$innerContainer.css("margin-"+Craft.left))},_onDragStart:function(){this.$outerContainer.addClass("dragging"),this.dragStartMargin=this._getMargin()},_onDrag:function(){var t;(t="ltr"===Craft.orientation?this.dragStartMargin+this.dragger.mouseDistX:this.dragStartMargin-this.dragger.mouseDistX)<this._getOffMargin()?t=this._getOffMargin():t>0&&(t=0),this.$innerContainer.css("margin-"+Craft.left,t)},_onDragStop:function(){var t=this._getMargin();console.log(t),t>this._getOffMargin()/2?this.turnOn():this.turnOff()},_onSettle:function(){this.$outerContainer.removeClass("dragging")},destroy:function(){this.$outerContainer.removeData("lightswitch"),this.base(),this.dragger.destroy()},_getOffMargin:function(){return this.small?-10:-12}},{animationDuration:100,defaults:{value:"1",indeterminateValue:"-",onChange:$.noop}})},6966:function(){Craft.Listbox=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,selectedOptionIndex:null,init:function(t,e){var i=this;this.$container=$(t),this.setSettings(e,Craft.Listbox.defaults),this.$container.data("listbox")&&(console.warn("Double-instantiating a listbox on an element"),this.$container.data("listbox").destroy()),this.$container.data("listbox",this),this.$options=this.$container.find("[role=option]"),this.$selectedOption=this.$options.filter("[aria-selected=true]"),this.$selectedOption.length?this.selectedOptionIndex=this.$options.index(this.$selectedOption):this.$selectedOption=null,this.addListener(this.$container,"keydown",(function(t){switch(t.keyCode){case Garnish.UP_KEY:i.selectPrev(),t.preventDefault();break;case Garnish.DOWN_KEY:i.selectNext(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?i.selectPrev():i.selectNext(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?i.selectNext():i.selectPrev(),t.preventDefault()}})),this.addListener(this.$options,"click",(function(t){i.select(i.$options.index($(t.currentTarget))),t.preventDefault()}))},select:function(t){t<0||t>=this.$options.length||t===this.selectedOptionIndex||(this.$selectedOption.removeClass(this.settings.selectedClass).attr("aria-selected","false"),this.$selectedOption=this.$options.eq(t).addClass(this.settings.selectedClass).attr("aria-selected","true"),this.selectedOptionIndex=t,this.settings.onChange(this.$selectedOption,t),this.trigger("change",{$selectedOption:this.$selectedOption,selectedOptionIndex:t}))},selectPrev:function(){null===this.selectedOptionIndex?this.select(0):this.select(this.selectedOptionIndex-1)},selectNext:function(){null===this.selectedOptionIndex?this.select(0):this.select(this.selectedOptionIndex+1)},destroy:function(){this.$container.removeData("listbox"),this.base()}},{defaults:{selectedClass:"active",focusClass:"focus",onChange:$.noop}})},5080:function(){Craft.LivePreview=Garnish.Base.extend({$extraFields:null,$trigger:null,$shade:null,$editorContainer:null,$editor:null,$dragHandle:null,$previewContainer:null,$iframeContainer:null,$iframe:null,$fieldPlaceholder:null,previewUrl:null,token:null,basePostData:null,inPreviewMode:!1,fields:null,lastPostData:null,updateIframeInterval:null,loading:!1,checkAgain:!1,dragger:null,dragStartEditorWidth:null,_slideInOnIframeLoad:!1,_forceUpdateIframeProxy:null,_scrollX:null,_scrollY:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){var e=this;this.setSettings(t,Craft.LivePreview.defaults),this.settings.previewUrl?this.previewUrl=this.settings.previewUrl:this.previewUrl=Craft.baseSiteUrl.replace(/\/+$/,"")+"/","https:"===document.location.protocol&&(this.previewUrl=this.previewUrl.replace(/^http:/,"https:")),this.basePostData=$.extend({},this.settings.previewParams),this._forceUpdateIframeProxy=this.forceUpdateIframe.bind(this),this.$extraFields=$(this.settings.extraFields),this.$trigger=$(this.settings.trigger),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.LivePreview.defaultEditorWidth),this.addListener(this.$trigger,"activate","toggle"),Craft.cp.on("beforeSaveShortcut",(function(){e.inPreviewMode&&e.moveFieldsBack()}))},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.LivePreview.minEditorWidthInPx&&(t=(e=Craft.LivePreview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},toggle:function(){this.inPreviewMode?this.exit():this.enter()},enter:function(){var t=this;if(!this.inPreviewMode)if(this.token){if(this.trigger("beforeEnter"),$(document.activeElement).trigger("blur"),!this.$editor){this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=$("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);$("<div/>",{class:"flex-grow"}).appendTo(e);var s=$("<button/>",{type:"button",class:"btn submit",text:Craft.t("app","Save")}).appendTo(e);this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(i,"click","exit"),this.addListener(s,"click","save")}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];for(var a=$(this.settings.fields),n=0;n<a.length;n++){var r=$(a[n]),o=this._getClone(r);this.$fieldPlaceholder.insertAfter(r),r.detach(),this.$fieldPlaceholder.replaceWith(o),r.appendTo(this.$editor),this.fields.push({$field:r,$clone:o})}this.updateIframe()?this._slideInOnIframeLoad=!0:this.slideIn(),Garnish.on(Craft.BaseElementEditor,"saveElement",this._forceUpdateIframeProxy),Garnish.on(Craft.AssetImageEditor,"save",this._forceUpdateIframeProxy),Craft.ElementThumbLoader.retryAll(),Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.exit()})),this.inPreviewMode=!0,this.trigger("enter")}else this.createToken()},createToken:function(){var t=this;Craft.postActionRequest("live-preview/create-token",{previewAction:this.settings.previewAction},(function(e,i){"success"===i&&(t.token=e.token,t.enter())}))},save:function(){Craft.cp.submitPrimaryForm()},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;$("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",(function(){t.updateIframeInterval=setInterval(t.updateIframe.bind(t),1e3)}))},exit:function(){var t=this;this.inPreviewMode&&(this.trigger("beforeExit"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),this.updateIframeInterval&&clearInterval(this.updateIframeInterval),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",(function(){t.$previewContainer.hide()})),Garnish.off(Craft.BaseElementEditor,"saveElement",this._forceUpdateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.inPreviewMode=!1,this.trigger("exit"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth())},updateIframe:function(t){if(t&&(this.lastPostData=null),!this.inPreviewMode)return!1;if(this.loading)return this.checkAgain=!0,!1;var e=$.extend(Garnish.getPostData(this.$editor),Garnish.getPostData(this.$extraFields));if(this.lastPostData&&Craft.compare(e,this.lastPostData,!1))return!1;this.lastPostData=e,this.loading=!0;var i=this.$iframe?$(this.$iframe[0].contentWindow.document):null;return this._scrollX=i?i.scrollLeft():0,this._scrollY=i?i.scrollTop():0,$.ajax({url:this.previewUrl+(-1!==this.previewUrl.indexOf("?")?"&":"?")+Craft.tokenParam+"="+this.token,method:"POST",data:$.extend({},e,this.basePostData),headers:{"X-Craft-Token":this.token},xhrFields:{withCredentials:!0},crossDomain:!0,success:this.handleSuccess.bind(this),error:this.handleError.bind(this)}),!0},forceUpdateIframe:function(){return this.updateIframe(!0)},handleSuccess:function(t){var e=this,i=t+'<script type="text/javascript">window.scrollTo('+this._scrollX+", "+this._scrollY+");<\/script>",s=$('<iframe class="lp-preview" frameborder="0"/>');this.$iframe?s.insertBefore(this.$iframe):s.appendTo(this.$iframeContainer),this.addListener(s,"load",(function(){this.$iframe&&this.$iframe.remove(),this.$iframe=s,this._slideInOnIframeLoad&&(this.slideIn(),this._slideInOnIframeLoad=!1),this.removeListener(s,"load")})),Garnish.requestAnimationFrame((function(){s[0].contentWindow.document.open(),s[0].contentWindow.document.write(i),s[0].contentWindow.document.close(),e.onResponse()}))},handleError:function(){this.onResponse()},onResponse:function(){this.loading=!1,this.checkAgain&&(this.checkAgain=!1,this.updateIframe())},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)}},{defaultEditorWidth:.33,minEditorWidthInPx:320,defaults:{trigger:".livepreviewbtn",fields:null,extraFields:null,previewUrl:null,previewAction:null,previewParams:{}}}),Craft.LivePreview.init=function(t){Craft.livePreview=new Craft.LivePreview(t)}},7439:function(){Craft.PasswordInput=Garnish.Base.extend({$passwordWrapper:null,$passwordInput:null,$textInput:null,$currentInput:null,$showPasswordToggle:null,showingPassword:null,init:function(t,e){this.$passwordInput=$(t),this.$passwordWrapper=this.$passwordInput.parent(".passwordwrapper"),this.settings=$.extend({},Craft.PasswordInput.defaults,e),this.$passwordInput.data("passwordInput")&&(console.warn("Double-instantiating a password input on an element"),this.$passwordInput.data("passwordInput").destroy()),this.$passwordInput.data("passwordInput",this),this.$showPasswordToggle=$('<button type="button" class="invisible" />'),this.$showPasswordToggle.addClass("password-toggle"),this.$showPasswordToggle.insertAfter(this.$passwordInput),this.initInputFocusEvents(this.$passwordInput),this.addListener(this.$showPasswordToggle,"click","onClick"),this.hidePassword(),this.addListener(this.$passwordWrapper.closest("form"),"submit","hidePassword")},setCurrentInput:function(t){this.$currentInput&&(t.insertAfter(this.$currentInput),this.$currentInput.detach(),t.trigger("focus"),t.val(this.$currentInput.val())),this.$currentInput=t,this.addListener(this.$currentInput,"keypress,keyup,change,blur","onInputChange")},updateToggleLabel:function(t){this.$showPasswordToggle.text(t)},initInputFocusEvents:function(t){this.addListener(t,"focus",(function(){this.$passwordWrapper.addClass("focus")})),this.addListener(t,"blur",(function(){this.$passwordWrapper.removeClass("focus")}))},showPassword:function(){this.showingPassword||(this.$textInput||(this.$textInput=this.$passwordInput.clone(!0),this.$textInput.attr({type:"text",autocapitalize:"off"}),this.initInputFocusEvents(this.$textInput)),this.setCurrentInput(this.$textInput),this.updateToggleLabel(Craft.t("app","Hide")),this.showingPassword=!0)},hidePassword:function(){!1!==this.showingPassword&&(this.setCurrentInput(this.$passwordInput),this.updateToggleLabel(Craft.t("app","Show")),this.showingPassword=!1,this.addListener(this.$passwordInput,"keydown","onKeyDown"))},togglePassword:function(){this.showingPassword?this.hidePassword():this.showPassword(),this.settings.onToggleInput(this.$currentInput)},onKeyDown:function(t){t.keyCode===Garnish.ALT_KEY&&this.$currentInput.val()&&(this.showPassword(),this.$showPasswordToggle.addClass("invisible"),this.addListener(this.$textInput,"keyup","onKeyUp"))},onKeyUp:function(t){t.preventDefault(),t.keyCode===Garnish.ALT_KEY&&(this.hidePassword(),this.$showPasswordToggle.removeClass("invisible"))},onInputChange:function(){this.$currentInput.val()?this.$showPasswordToggle.removeClass("invisible"):this.$showPasswordToggle.addClass("invisible")},onClick:function(t){if(this.$currentInput[0].setSelectionRange){var e=this.$currentInput[0].selectionStart,i=this.$currentInput[0].selectionEnd;this.togglePassword(),this.$currentInput[0].setSelectionRange(e,i)}else this.togglePassword()},destroy:function(){this.$passwordInput.removeData("passwordInput"),this.base()}},{defaults:{onToggleInput:$.noop}})},5328:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}Craft.Preview=Garnish.Base.extend({draftEditor:null,$shade:null,$editorContainer:null,$editor:null,$spinner:null,$statusIcon:null,$dragHandle:null,$previewContainer:null,$iframeContainer:null,$previewHeader:null,$targetBtn:null,$targetMenu:null,$deviceTypeContainer:null,$orientationBtn:null,$refreshBtn:null,$deviceMask:null,$devicePreviewContainer:null,$iframe:null,iframeLoaded:!1,$tempInput:null,$fieldPlaceholder:null,isActive:!1,isVisible:!1,activeTarget:0,currentDeviceType:"desktop",deviceOrientation:null,deviceWidth:"",deviceHeight:"",deviceMaskDimensions:{phone:{width:375,height:753},tablet:{width:768,height:1110}},draftId:null,url:null,fields:null,iframeHeight:null,scrollTop:null,dragger:null,dragStartEditorWidth:null,_updateIframeProxy:null,_editorWidth:null,_editorWidthInPx:null,init:function(t){this.draftEditor=t,this._updateIframeProxy=this.updateIframe.bind(this),this.$tempInput=$("<input/>",{type:"hidden",name:"__PREVIEW_FIELDS__",value:"1"}),this.$fieldPlaceholder=$("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.Preview.defaultEditorWidth)},get editorWidth(){return this._editorWidth},get editorWidthInPx(){return this._editorWidthInPx},set editorWidth(t){var e;t>=1?(e=t,t/=Garnish.$win.width()):e=Math.round(t*Garnish.$win.width()),e<Craft.Preview.minEditorWidthInPx&&(t=(e=Craft.Preview.minEditorWidthInPx)/Garnish.$win.width()),this._editorWidth=t,this._editorWidthInPx=e},open:function(){var t=this;if(!this.isActive){if(this.isActive=!0,this.trigger("beforeOpen"),$(document.activeElement).trigger("blur"),!this.$editor){this.$shade=$("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=$("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$editorContainer=$("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=$("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=$("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=$("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);if($("<div/>",{class:"flex-grow"}).appendTo(e),this.$spinner=$("<div/>",{class:"spinner hidden",title:Craft.t("app","Saving")}).appendTo(e),this.$statusIcon=$("<div/>",{class:"invisible"}).appendTo(e),this.$statusMessage=$("<span/>",{class:"visually-hidden","aria-live":"polite"}).appendTo(e),Craft.Pro){if(this.$previewHeader=$("<header/>",{class:"lp-preview-header"}).appendTo(this.$previewContainer),this.draftEditor.settings.previewTargets.length>1){this.$targetBtn=$("<button/>",{type:"button",class:"btn menubtn",text:this.draftEditor.settings.previewTargets[0].label}).appendTo(this.$previewHeader),this.$targetMenu=$("<div/>",{class:"menu lp-target-menu"}).insertAfter(this.$targetBtn);for(var s,a=$("<ul/>",{class:"padded"}).appendTo(this.$targetMenu),n=0;n<this.draftEditor.settings.previewTargets.length;n++)s=$("<li/>").appendTo(a),$("<a/>",{data:{target:n},text:this.draftEditor.settings.previewTargets[n].label,class:0===n?"sel":null}).appendTo(s);new Garnish.MenuBtn(this.$targetBtn,{onOptionSelect:function(e){t.switchTarget($(e).data("target"))}}),$('<div class="flex-grow"/>').appendTo(this.$previewHeader)}this._buildDeviceTypeFieldset(),$('<div class="flex-grow"/>').appendTo(this.$previewHeader);var r=$('<div class="buttons"/>').appendTo(this.$previewHeader);this.$orientationBtn=$("<button/>",{type:"button",class:"btn disabled","data-icon":"rotate",disabled:"",text:Craft.t("app","Rotate"),"aria-label":Craft.t("app","Rotate")}).appendTo(r),this.addListener(this.$orientationBtn,"click","switchOrientation"),this.$refreshBtn=$("<button/>",{type:"button",class:"btn hidden",text:Craft.t("app","Refresh"),"data-icon":"refresh"}).appendTo(r),this._updateRefreshBtn(),this.addListener(this.$refreshBtn,"click",(function(){t.updateIframe(!1,!0)})),this.deviceOrientation=Craft.getLocalStorage("LivePreview.orientation"),this.addListener($("input",this.$deviceTypeContainer),"change","switchDeviceType")}this.$iframeContainer=$("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$devicePreviewContainer=$("<div/>",{class:"lp-device-preview-container"}).appendTo(this.$iframeContainer),this.$deviceMask=$("<div/>",{class:"lp-device-mask"}).appendTo(this.$iframeContainer),this.dragger=new Garnish.BaseDrag(this.$dragHandle,{axis:Garnish.X_AXIS,onDragStart:this._onDragStart.bind(this),onDrag:this._onDrag.bind(this),onDragStop:this._onDragStop.bind(this)}),this.addListener(i,"click","close"),this.addListener(this.$statusIcon,"click",(function(){t.draftEditor.showStatusHud(t.$statusIcon)}))}this.handleWindowResize(),this.addListener(Garnish.$win,"resize","handleWindowResize"),this.$editorContainer.css(Craft.left,-this.editorWidthInPx+"px"),this.$previewContainer.css(Craft.right,-this.getIframeWidth()),this.fields=[];var o=$("#content .field").not($("#content .field .field"));if(o.length){this.$tempInput.insertBefore(o.get(0));for(var l=0;l<o.length;l++){var h=$(o[l]),d=this._getClone(h);this.$fieldPlaceholder.insertAfter(h),h.detach(),this.$fieldPlaceholder.replaceWith(d),h.appendTo(this.$editor),this.fields.push({$field:h,$clone:d})}}this.updateIframe(),this.draftEditor.on("update",this._updateIframeProxy),Garnish.on(Craft.BaseElementEditor,"saveElement",this._updateIframeProxy),Garnish.on(Craft.AssetImageEditor,"save",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.trigger("open")}},_buildDeviceTypeFieldset:function(){this.$deviceTypeContainer=$("<fieldset/>",{class:"lp-device-type"}).appendTo(this.$previewHeader),$("<legend/>",{text:Craft.t("app","Device type"),class:"visually-hidden"}).appendTo(this.$deviceTypeContainer);var t=$("<div/>",{class:"lp-device-type__radio-group"}).appendTo(this.$deviceTypeContainer),e=$("<div/>",{class:"lp-device-type__item"}).appendTo(t);$("<input/>",{class:"lp-device-type__input visually-hidden",type:"radio",name:"device",value:"desktop",id:"device-desktop",checked:!0,data:{width:"",height:""}}).appendTo(e);var i=$("<label/>",{for:"device-desktop",class:"btn lp-device-type__label lp-device-type__label--desktop active",title:Craft.t("app","Desktop")}).appendTo(e);$("<span/>",{class:"visually-hidden",text:Craft.t("app","Desktop")}).appendTo(i);var s=$("<div/>",{class:"lp-device-type__item"}).appendTo(t);$("<input/>",{class:"lp-device-type__input visually-hidden",type:"radio",name:"device",value:"tablet",id:"device-tablet",data:{width:768,height:1024}}).appendTo(s);var a=$("<label/>",{for:"device-tablet",class:"btn lp-device-type__label lp-device-type__label--tablet",title:Craft.t("app","Tablet")}).appendTo(s);$("<span/>",{class:"visually-hidden",text:Craft.t("app","Tablet")}).appendTo(a);var n=$("<div/>",{class:"lp-device-type__item"}).appendTo(t);$("<input/>",{class:"lp-device-type__input visually-hidden",type:"radio",name:"device",value:"phone",id:"device-phone",data:{width:375,height:667}}).appendTo(n);var r=$("<label/>",{for:"device-phone",class:"btn lp-device-type__label lp-device-type__label--phone",title:Craft.t("app","Mobile")}).appendTo(n);$("<span/>",{class:"visually-hidden",text:Craft.t("app","Mobile")}).appendTo(r)},_activeTarget:function(){return this.draftEditor.settings.previewTargets[this.activeTarget]},_autoRefresh:function(){var e=this._activeTarget();return void 0===t(e.refresh)||!!e.refresh},_updateRefreshBtn:function(){this._autoRefresh()?this.$refreshBtn.addClass("hidden"):this.$refreshBtn.removeClass("hidden")},switchTarget:function(t){this.activeTarget=t,this.$targetBtn.text(this.draftEditor.settings.previewTargets[t].label),this.$targetMenu.find("a.sel").removeClass("sel"),this.$targetMenu.find("a").eq(t).addClass("sel"),this.updateIframe(!0),this._updateRefreshBtn(),this.trigger("switchTarget",{previewTarget:this.draftEditor.settings.previewTargets[t]})},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){var t=this;this.isActive&&!this.isVisible&&($("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",(function(){t.trigger("slideIn"),Garnish.$win.trigger("resize")})),this.$previewContainer.show().velocity("stop").animateRight(0,"slow"),this.isVisible=!0,Garnish.uiLayerManager.addLayer(this.$sidebar),Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})))},close:function(){var t=this;this.isActive&&this.isVisible&&(this.trigger("beforeClose"),$("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),Garnish.uiLayerManager.removeLayer(),this.$tempInput.detach(),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",(function(){for(var e=0;e<t.fields.length;e++)t.fields[e].$newClone.remove();t.$editorContainer.hide(),t.trigger("slideOut")})),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",(function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating"),t.$previewContainer.hide()})),this.draftEditor.off("update",this._updateIframeProxy),Garnish.off(Craft.BaseElementEditor,"saveElement",this._updateIframeProxy),Garnish.off(Craft.AssetImageEditor,"save",this._updateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.isActive=!1,this.isVisible=!1,this.trigger("close"))},moveFieldsBack:function(){for(var t=0;t<this.fields.length;t++){var e=this.fields[t];e.$newClone=this._getClone(e.$field),this.$fieldPlaceholder.insertAfter(e.$field),e.$field.detach(),this.$fieldPlaceholder.replaceWith(e.$newClone),e.$clone.replaceWith(e.$field)}Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll")},getIframeWidth:function(){return Garnish.$win.width()-this.editorWidthInPx},updateWidths:function(){this.$editorContainer.css("width",this.editorWidthInPx+"px"),this.$previewContainer.width(this.getIframeWidth()),this._devicePreviewIsActive()&&this.updateDevicePreview()},_useIframeResizer:function(){return!1!==Craft.previewIframeResizerOptions},updateIframe:function(t,e){var i=this;if(!this.isActive)return!1;t=!0===t,this.draftId===(this.draftId=this.draftEditor.settings.draftId)&&this.$iframe||(e=!0);var s=this._activeTarget();void 0===e&&(e=t||this._autoRefresh()),this.trigger("beforeUpdateIframe",{previewTarget:s,resetScroll:t,refresh:e}),e?this.draftEditor.getTokenizedPreviewUrl(s.url,"x-craft-live-preview").then((function(e){var s;t?i.scrollTop=null:i.iframeLoaded&&i.$iframe&&(i._useIframeResizer()?(i.iframeHeight=i.$iframe.height(),i.scrollTop=i.$iframeContainer.scrollTop()):(s=Craft.isSameHost(e))&&i.$iframe[0].contentWindow&&(i.scrollTop=$(i.$iframe[0].contentWindow.document).scrollTop())),i.iframeLoaded=!1;var a=$("<iframe/>",{class:"lp-preview",frameborder:0,src:e,title:Craft.t("app","Preview")});i.$iframe?i.$iframe.replaceWith(a):a.appendTo(i.$devicePreviewContainer),i._useIframeResizer()?(t||null===i.iframeHeight||(a.height(i.iframeHeight),i.$iframeContainer.scrollTop(i.scrollTop)),iFrameResize($.extend({checkOrigin:!1,scrolling:!0,onInit:function(t){i.iframeLoaded=!0,i.iframeHeight=null,i.scrollTop=null,t.scrolling="no"}},Craft.previewIframeResizerOptions||{}),a[0])):a.on("load",(function(){i.iframeLoaded=!0,!t&&s&&null!==i.scrollTop&&$(a[0].contentWindow.document).scrollTop(i.scrollTop)})),i.url=e,i.$iframe=a,i._devicePreviewIsActive()&&i.updateDevicePreview(),i.trigger("afterUpdateIframe",{previewTarget:i.draftEditor.settings.previewTargets[i.activeTarget],$iframe:i.$iframe}),i.slideIn()})):this.slideIn()},_devicePreviewIsActive:function(){return"desktop"!==this.currentDeviceType},switchDeviceType:function(t){this.$iframeContainer.removeClass("lp-iframe-container--rotating");var e=$(t.target),i=e.closest(".lp-device-type__item"),s=e.val();if(s===this.currentDeviceType)return!1;this.currentDeviceType=s,this.deviceWidth=e.data("width"),this.deviceHeight=e.data("height"),this.$deviceTypeContainer.find(".btn").removeClass("active"),i.find(".btn").addClass("active"),"desktop"===this.currentDeviceType?(this.$orientationBtn.addClass("disabled").attr("disabled",""),this.$iframeContainer.removeClass("lp-iframe-container--has-device-preview")):(this.$orientationBtn.removeClass("disabled").removeAttr("disabled"),this.$iframeContainer.addClass("lp-iframe-container--has-device-preview")),"tablet"===this.currentDeviceType?this.$iframeContainer.addClass("lp-iframe-container--tablet"):this.$iframeContainer.removeClass("lp-iframe-container--tablet"),"desktop"!==this.currentDeviceType&&this.updateDevicePreview()},switchOrientation:function(){var t=this;if(!this._devicePreviewIsActive())return!1;this.deviceOrientation&&"portrait"!==this.deviceOrientation?this.deviceOrientation="portrait":this.deviceOrientation="landscape",Craft.setLocalStorage("LivePreview.orientation",this.deviceOrientation),this.$iframeContainer.addClass("lp-iframe-container--rotating"),this.updateDevicePreview(),setTimeout((function(){t.$iframeContainer.removeClass("lp-iframe-container--rotating")}),300)},updateDevicePreview:function(){var t=1,e=1,i=1,s=this.$previewContainer.height()-50-48,a=this.$previewContainer.width()-48,n=this.deviceMaskDimensions[this.currentDeviceType].height,r=this.deviceMaskDimensions[this.currentDeviceType].width;"landscape"===this.deviceOrientation?(a<n&&(t=a/n),s<r&&(e=s/r)):(s<n&&(t=s/n),a<r&&(e=a/r)),i=t,e<t&&(i=e);var o=-100/i/2,l="landscape"===this.deviceOrientation?"-90deg":"0deg";this.$deviceMask.css({width:this.deviceMaskDimensions[this.currentDeviceType].width+"px",height:this.deviceMaskDimensions[this.currentDeviceType].height+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%) rotate("+l+")"}),"landscape"===this.deviceOrientation?this.$devicePreviewContainer.css({width:this.deviceHeight+"px",height:this.deviceWidth+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:0,marginLeft:"-"+12*i+"px"}):this.$devicePreviewContainer.css({width:this.deviceWidth+"px",height:this.deviceHeight+"px",transform:"scale("+i+") translate("+o+"%, "+o+"%)",marginTop:"-"+12*i+"px",marginLeft:0})},_getClone:function(t){var e=t.clone();return Garnish.copyInputValues(t,e),e.attr("id",""),e.find("[id]").attr("id",""),e.find("[name]").prop("disabled",!0),e},_onDragStart:function(){this.dragStartEditorWidth=this.editorWidthInPx,this.$previewContainer.addClass("dragging")},_onDrag:function(){"ltr"===Craft.orientation?this.editorWidth=this.dragStartEditorWidth+this.dragger.mouseDistX:this.editorWidth=this.dragStartEditorWidth-this.dragger.mouseDistX,this.updateWidths()},_onDragStop:function(){this.$previewContainer.removeClass("dragging"),Craft.setLocalStorage("LivePreview.editorWidth",this.editorWidth)}},{defaultEditorWidth:.33,minEditorWidthInPx:320})},6419:function(){Craft.PreviewFileModal=Garnish.Modal.extend({assetId:null,$spinner:null,elementSelect:null,type:null,loaded:null,requestId:0,init:function(t,e,i){if((i=$.extend(this.defaultSettings,i)).onHide=this._onHide.bind(this),Craft.PreviewFileModal.openInstance){var s=Craft.PreviewFileModal.openInstance;return s.assetId!==t&&(s.loadAsset(t,i.startingWidth,i.startingHeight),s.elementSelect=e),this.destroy()}Craft.PreviewFileModal.openInstance=this,this.elementSelect=e,this.$container=$('<div class="modal previewmodal loading"/>').appendTo(Garnish.$bod),this.base(this.$container,$.extend({resizable:!0},i)),this.$container&&(this.$container.velocity("stop"),this.$container.show().css("opacity",1),this.$shade.velocity("stop"),this.$shade.show().css("opacity",1)),this.loadAsset(t,i.startingWidth,i.startingHeight)},_onHide:function(){return Craft.PreviewFileModal.openInstance=null,this.elementSelect&&this.elementSelect.focusItem(this.elementSelect.$focusedItem),this.$shade.remove(),this.destroy()},selfDestruct:function(){var t=Craft.PreviewFileModal.openInstance;return t.hide(),t.$shade.remove(),t.destroy(),Craft.PreviewFileModal.openInstance=null,!0},loadAsset:function(t,e,i){var s=this;this.assetId=t,this.$container.empty(),this.loaded=!1,this.desiredHeight=null,this.desiredWidth=null;var a=.66*Garnish.$win.height(),n=Math.min(a/3*4,Garnish.$win.width()-2*this.settings.minGutter);if(a=n/4*3,e&&i){var r=e/i;n=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter),(n=(a=Math.min(n/r,Garnish.$win.height()-2*this.settings.minGutter))*r)>Math.min(e,Garnish.$win.width()-2*this.settings.minGutter)&&(a=(n=Math.min(e,Garnish.$win.width()-2*this.settings.minGutter))/r)}this._resizeContainer(n,a),this.$spinner=$('<div class="spinner centeralign"></div>').appendTo(this.$container);var o=this.$container.height()/2-this.$spinner.height()/2+"px",l=this.$container.width()/2-this.$spinner.width()/2+"px";this.$spinner.css({left:l,top:o,position:"absolute"}),this.requestId++,Craft.postActionRequest("assets/preview-file",{assetId:t,requestId:this.requestId},(function(t,e){if(s.$container.removeClass("loading"),s.$spinner.remove(),s.loaded=!0,"success"===e)if(t.success){if(t.requestId!=s.requestId)return;if(!t.previewHtml)return s.$container.addClass("zilch"),void s.$container.append($("<p/>",{text:Craft.t("app","No preview available.")}));s.$container.removeClass("zilch"),s.$container.append(t.previewHtml),Craft.appendHeadHtml(t.headHtml),Craft.appendFootHtml(t.footHtml)}else alert(t.error),s.hide()}))},_resizeContainer:function(t,e){this.$container.css({width:t,"min-width":t,"max-width":t,height:e,"min-height":e,"max-height":e,top:(Garnish.$win.height()-e)/2,left:(Garnish.$win.width()-t)/2})}},{defaultSettings:{startingWidth:null,startingHeight:null}})},872:function(){Craft.ProgressBar=Garnish.Base.extend({$progressBar:null,$innerProgressBar:null,$progressBarStatus:null,_itemCount:0,_processedItemCount:0,_displaySteps:!1,init:function(t,e){e&&(this._displaySteps=!0),this.$progressBar=$('<div class="progressbar pending hidden"/>').appendTo(t),this.$innerProgressBar=$('<div class="progressbar-inner"/>').appendTo(this.$progressBar),this.$progressBarStatus=$('<div class="progressbar-status hidden" />').insertAfter(this.$progressBar),this.resetProgressBar()},resetProgressBar:function(){this.setProgressPercentage(100),this.$progressBar.addClass("pending"),this.setItemCount(1),this.setProcessedItemCount(0),this.$progressBarStatus.html(""),this._displaySteps&&this.$progressBar.addClass("has-status")},hideProgressBar:function(){var t=this;this.$progressBar.fadeTo("fast",.01,(function(){t.$progressBar.addClass("hidden").fadeTo(1,1,$.noop)})),this.$progressBarStatus.fadeTo("fast",.01,(function(){t.$progressBarStatus.addClass("hidden").fadeTo(1,1,$.noop)}))},showProgressBar:function(){this.$progressBar.removeClass("hidden"),this.$progressBarStatus.removeClass("hidden")},setItemCount:function(t){this._itemCount=t},incrementItemCount:function(t){this._itemCount+=t},setProcessedItemCount:function(t){this._processedItemCount=t},incrementProcessedItemCount:function(t){this._processedItemCount+=t},updateProgressBar:function(){this._itemCount=Math.max(this._itemCount,1);var t=Math.min(100,Math.round(100*this._processedItemCount/this._itemCount));this.setProgressPercentage(t),this._displaySteps&&this.$progressBarStatus.html(this._processedItemCount+" / "+this._itemCount)},setProgressPercentage:function(t,e){0===t?this.$progressBar.addClass("pending"):(this.$progressBar.removeClass("pending"),e?this.$innerProgressBar.velocity("stop").velocity({width:t+"%"},"fast"):this.$innerProgressBar.velocity("stop").width(t+"%"))}})},1396:function(){Craft.PromptHandler=Garnish.Base.extend({modal:null,$modalContainerDiv:null,$prompt:null,$promptApplyToRemainingContainer:null,$promptApplyToRemainingCheckbox:null,$promptApplyToRemainingLabel:null,$pomptChoices:null,_prompts:[],_promptBatchCallback:$.noop,_promptBatchReturnData:[],_promptBatchNum:0,resetPrompts:function(){this._prompts=[],this._promptBatchCallback=$.noop,this._promptBatchReturnData=[],this._promptBatchNum=0},addPrompt:function(t){this._prompts.push(t)},getPromptCount:function(){return this._prompts.length},showBatchPrompts:function(t){this._promptBatchCallback=t,this._promptBatchReturnData=[],this._promptBatchNum=0,this._showNextPromptInBatch()},_showNextPromptInBatch:function(){var t=this._prompts[this._promptBatchNum].prompt,e=this._prompts.length-(this._promptBatchNum+1);this._showPrompt(t.message,t.choices,this._handleBatchPromptSelection.bind(this),e)},_handleBatchPromptSelection:function(t,e){var i=this._prompts[this._promptBatchNum],s=this._prompts.length-(this._promptBatchNum+1),a=$.extend(i,{choice:t});this._promptBatchReturnData.push(a),s?(this._promptBatchNum++,e?this._handleBatchPromptSelection(t,!0):this._showNextPromptInBatch()):"function"==typeof this._promptBatchCallback&&this._promptBatchCallback(this._promptBatchReturnData)},_showPrompt:function(t,e,i,s){this._promptCallback=i,null===this.modal&&(this.modal=new Garnish.Modal({closeOtherModals:!1})),null===this.$modalContainerDiv&&(this.$modalContainerDiv=$('<div class="modal fitted prompt-modal"></div>').addClass().appendTo(Garnish.$bod)),this.$prompt=$('<div class="body"></div>').appendTo(this.$modalContainerDiv.empty()),this.$promptMessage=$('<p class="prompt-msg"/>').appendTo(this.$prompt),this.$promptChoices=$('<div class="options"></div>').appendTo(this.$prompt),this.$promptApplyToRemainingContainer=$('<label class="assets-applytoremaining"/>').appendTo(this.$prompt).hide(),this.$promptApplyToRemainingCheckbox=$('<input type="checkbox"/>').appendTo(this.$promptApplyToRemainingContainer),this.$promptApplyToRemainingLabel=$("<span/>").appendTo(this.$promptApplyToRemainingContainer),this.$promptButtons=$('<div class="buttons right"/>').appendTo(this.$prompt),this.modal.setContainer(this.$modalContainerDiv),this.$promptMessage.html(t);for(var a=$("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$promptButtons),n=$("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","OK")}).appendTo(this.$promptButtons),r=0;r<e.length;r++){var o=$('<div><label><input type="radio" name="promptAction" value="'+e[r].value+'"/> '+e[r].title+"</label></div>").appendTo(this.$promptChoices).find("input");this.addListener(o,"click",(function(){n.removeClass("disabled")}))}this.addListener(n,"activate",(function(t){var e=$(t.currentTarget).parents(".modal").find("input[name=promptAction]:checked").val(),i=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice(e,i)})),this.addListener(a,"activate",(function(){var t=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice("cancel",t)})),s&&(this.$promptApplyToRemainingContainer.show(),this.$promptApplyToRemainingLabel.html(" "+Craft.t("app","Apply this to the {number} remaining conflicts?",{number:s}))),this.modal.show(),this.modal.removeListener(Garnish.Modal.$shade,"click"),this.addListener(Garnish.Modal.$shade,"click","_cancelPrompt")},_selectPromptChoice:function(t,e){var i=this;this.$prompt.fadeOut("fast",(function(){i.modal.hide(),i._promptCallback(t,e)}))},_cancelPrompt:function(){this._selectPromptChoice("cancel",!0)}})},4070:function(){!function(t){Craft.SlidePicker=Garnish.Base.extend({min:null,max:null,totalSteps:null,value:null,$container:null,$buttons:null,init:function(e,i){var s=this;this.setSettings(i,Craft.SlidePicker.defaults),this.$container=t("<div/>",{class:"slide-picker",role:"slider",tabindex:0}),this.refresh(),this.setValue(e,!1),this.addListener(this.$container,"keydown",(function(t){switch(t.keyCode){case Garnish.UP_KEY:s.setValue(s.value+s.settings.step),t.preventDefault();break;case Garnish.DOWN_KEY:s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?s.setValue(s.value+s.settings.step):s.setValue(s.value-s.settings.step),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?s.setValue(s.value-s.settings.step):s.setValue(s.value+s.settings.step),t.preventDefault()}}))},refresh:function(){var e=this;if(this.min=this._min(),this.max=this._max(),this.totalSteps=(this.max-this.min)/this.settings.step,!Number.isInteger(this.totalSteps))throw"Invalid SlidePicker config";this.$buttons&&this.$buttons.remove(),this.$container.attr("aria-valuemin",this.min),this.$container.attr("aria-valuemax",this.max),this.$buttons=t();for(var i=this.min;i<=this.max;i+=this.settings.step)this.$buttons=this.$buttons.add(t("<a/>",{title:this.settings.valueLabel(i),data:{value:i}}));if(this.$buttons.appendTo(this.$container),null!==this.value){var s=this.value;this.value=null,this.setValue(s,!1)}this.addListener(this.$buttons,"mouseover",(function(i){e.$buttons.removeClass("active-hover last-active-hover"),t(i.currentTarget).addClass("active-hover last-active-hover").prevAll().addClass("active-hover")})),this.addListener(this.$buttons,"mouseout",(function(){e.$buttons.removeClass("active-hover")})),this.addListener(this.$buttons,"click",(function(i){e.setValue(t.data(i.currentTarget,"value")),i.stopPropagation(),e.$container.focus()}))},setValue:function(t,e){if(t=Math.max(Math.min(t,this.max),this.min),this.value!==(this.value=t)){this.$container.attr({"aria-valuenow":this.value,"aria-valuetext":this.settings.valueLabel(this.value)}),this.$buttons.removeClass("last-active active");var i=this.$buttons.eq((this.value-this.min)/this.settings.step);i.add(i.prevAll()).addClass("active"),i.addClass("last-active"),!1!==e&&this.settings.onChange(t)}},_min:function(){return"function"==typeof this.settings.min?this.settings.min():this.settings.min},_max:function(){return"function"==typeof this.settings.max?this.settings.max():this.settings.max}},{defaults:{min:0,max:100,step:10,valueLabel:null,onChange:t.noop}})}(jQuery)},5763:function(){Craft.SlideRuleInput=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,$input:null,value:null,startPositionX:null,init:function(t,e){var i=this;this.setSettings(e,Craft.SlideRuleInput.defaultSettings),this.value=0,this.graduationsMin=-70,this.graduationsMax=70,this.slideMin=-45,this.slideMax=45,this.$container=$("#"+t),this.$overlay=$('<div class="overlay"></div>').appendTo(this.$container),this.$cursor=$('<div class="cursor"></div>').appendTo(this.$container),this.$graduations=$('<div class="graduations"></div>').appendTo(this.$container),this.$graduationsUl=$("<ul></ul>").appendTo(this.$graduations);for(var s=this.graduationsMin;s<=this.graduationsMax;s++){var a=$('<li class="graduation" data-graduation="'+s+'"><div class="label">'+s+"</div></li>").appendTo(this.$graduationsUl);s%5==0&&a.addClass("main-graduation"),0===s&&a.addClass("selected")}this.$options=this.$container.find(".graduation"),this.addListener(this.$container,"resize",this._handleResize.bind(this)),this.addListener(this.$container,"tapstart",this._handleTapStart.bind(this)),this.addListener(Garnish.$bod,"tapmove",this._handleTapMove.bind(this)),this.addListener(Garnish.$bod,"tapend",this._handleTapEnd.bind(this)),setTimeout((function(){i.graduationsCalculatedWidth=10*(i.$options.length-1),i.$graduationsUl.css("left",-i.graduationsCalculatedWidth/2+i.$container.width()/2)}),50)},_handleResize:function(){var t=this.valueToPosition(this.value);this.$graduationsUl.css("left",t)},_handleTapStart:function(t,e){t.preventDefault(),this.startPositionX=e.position.x,this.startLeft=this.$graduationsUl.position().left,this.dragging=!0,this.onStart()},_handleTapMove:function(t,e){if(this.dragging){t.preventDefault();var i=this.startPositionX-e.position.x,s=this.startLeft-i,a=this.positionToValue(s);this.setValue(a),this.onChange()}},setValue:function(t){var e=this.valueToPosition(t);t<this.slideMin?(t=this.slideMin,e=this.valueToPosition(t)):t>this.slideMax&&(t=this.slideMax,e=this.valueToPosition(t)),this.$graduationsUl.css("left",e),t>=this.slideMin&&t<=this.slideMax&&(this.$options.removeClass("selected"),$.each(this.$options,(function(e,i){$(i).data("graduation")>0&&$(i).data("graduation")<=t&&$(i).addClass("selected"),$(i).data("graduation")<0&&$(i).data("graduation")>=t&&$(i).addClass("selected"),0==$(i).data("graduation")&&$(i).addClass("selected")}))),this.value=t},_handleTapEnd:function(t){this.dragging&&(t.preventDefault(),this.dragging=!1,this.onEnd())},positionToValue:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return(this.$graduations.width()/2+-1*t)/this.graduationsCalculatedWidth*i-e},valueToPosition:function(t){var e=-1*this.graduationsMin,i=-1*(this.graduationsMin-this.graduationsMax);return-((t+e)*this.graduationsCalculatedWidth/i-this.$graduations.width()/2)},onStart:function(){"function"==typeof this.settings.onChange&&this.settings.onStart(this)},onChange:function(){"function"==typeof this.settings.onChange&&this.settings.onChange(this)},onEnd:function(){"function"==typeof this.settings.onChange&&this.settings.onEnd(this)},defaultSettings:{onStart:$.noop,onChange:$.noop,onEnd:$.noop}})},5759:function(){!function(t){Craft.Slideout=Garnish.Base.extend({$outerContainer:null,$container:null,$shade:null,isOpen:!1,init:function(e,i){var s=this;this.setSettings(i,Craft.Slideout.defaults),Garnish.isMobileBrowser()||(this.$shade=t('<div class="slideout-shade"/>').appendTo(Garnish.$bod),this.settings.closeOnShadeClick&&this.addListener(this.$shade,"click",(function(t){t.stopPropagation(),s.close()}))),this.$outerContainer=t("<div/>",{class:"slideout-container hidden"}),this.$container=t("<".concat(this.settings.containerElement,"/>"),this.settings.containerAttributes).addClass("slideout").append(e).data("slideout",this).appendTo(this.$outerContainer),Garnish.addModalAttributes(this.$outerContainer),Garnish.isMobileBrowser()&&this.$container.addClass("so-mobile"),Craft.trapFocusWithin(this.$container),this.settings.autoOpen&&this.open()},open:function(){var t=this;this.isOpen||(this.setTriggerElement(document.activeElement),this._cancelTransitionListeners(),this.$shade&&this.$shade.appendTo(Garnish.$bod).show(),this.$outerContainer.appendTo(Garnish.$bod).removeClass("hidden"),Garnish.isMobileBrowser()?this.$container.css("top","100vh"):this.$container.css(Garnish.ltr?"left":"right","100vw"),this.$container.one("transitionend.slideout",(function(){Craft.setFocusWithin(t.$container)})),this.$shade&&(this.$shade[0].offsetWidth,this.$shade.addClass("so-visible")),this.$container[0].offsetWidth,Craft.Slideout.addPanel(this),this.enable(),Garnish.uiLayerManager.addLayer(this.$outerContainer),Garnish.hideModalBackgroundLayers(this.$outerContainer),this.settings.closeOnEsc&&Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY,(function(){t.close()})),this.isOpen=!0,this.trigger("open"))},setTriggerElement:function(t){this.settings.triggerElement=t},close:function(){var t=this;this.isOpen&&(this.trigger("beforeClose"),this.disable(),this.isOpen=!1,this._cancelTransitionListeners(),this.$shade&&this.$shade.removeClass("so-visible").one("transitionend.slideout",(function(){t.$shade.hide()})),Craft.Slideout.removePanel(this),Garnish.uiLayerManager.removeLayer(),Garnish.resetModalBackgroundLayerVisibility(this.$outerContainer),this.$container.one("transitionend.slideout",(function(){t.$outerContainer.addClass("hidden"),t.trigger("close")})),this.settings.triggerElement&&this.settings.triggerElement.focus())},_cancelTransitionListeners:function(){this.$shade&&this.$shade.off("transitionend.slideout"),this.$container.off("transitionend.slideout")},destroy:function(){this.$shade&&(this.$shade.remove(),this.$shade=null),this.$outerContainer.remove(),this.$outerContainer=null,this.$container=null,this.base()}},{defaults:{containerElement:"div",containerAttributes:{},autoOpen:!0,closeOnEsc:!0,closeOnShadeClick:!0,triggerElement:null},openPanels:[],addPanel:function(t){Craft.Slideout.openPanels.unshift(t),Garnish.isMobileBrowser()?t.$container.css("top",0):Craft.Slideout.updateStyles()},removePanel:function(t){Craft.Slideout.openPanels=Craft.Slideout.openPanels.filter((function(e){return e!==t})),Garnish.isMobileBrowser()?t.$container.css("top","100vh"):(t.$container.css(Garnish.ltr?"left":"right","100vw"),Craft.Slideout.updateStyles())},updateStyles:function(){var t=Craft.Slideout.openPanels.length;Craft.Slideout.openPanels.forEach((function(e,i){e.$container.css(Garnish.ltr?"left":"right","".concat((t-i)/t*50,"vw"))})),0!==t?Garnish.$bod.addClass("no-scroll"):Garnish.$bod.removeClass("no-scroll")}})}(jQuery)},5185:function(){Craft.SlugGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace(/<(.*?)>/g,"")).replace(/['"‘’“”\[\]\(\)\{\}:]/g,""),Craft.allowUppercaseInSlug||(t=t.toLowerCase()),Craft.limitAutoSlugsToAscii&&(t=Craft.asciiString(t,this.settings.charMap));var e=Craft.filterArray(XRegExp.matchChain(t,[XRegExp("[\\p{L}\\p{N}\\p{M}]+")]));return e.length?e.join(Craft.slugWordSeparator):""}})},8030:function(){Craft.Structure=Garnish.Base.extend({id:null,$container:null,state:null,structureDrag:null,init:function(t,e,i){this.id=t,this.$container=$(e),this.setSettings(i,Craft.Structure.defaults),this.$container.data("structure")&&(console.warn("Double-instantiating a structure on an element"),this.$container.data("structure").destroy()),this.$container.data("structure",this),this.state={},this.settings.storageKey&&$.extend(this.state,Craft.getLocalStorage(this.settings.storageKey,{})),void 0===this.state.collapsedElementIds&&(this.state.collapsedElementIds=[]);for(var s=this.$container.find("ul").prev(".row"),a=0;a<s.length;a++){var n=$(s[a]),r=n.parent(),o=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(n);-1!==$.inArray(n.children(".element").data("id"),this.state.collapsedElementIds)&&r.addClass("collapsed"),this.initToggle(o)}this.settings.sortable&&(this.structureDrag=new Craft.StructureDrag(this,this.settings.maxLevels)),this.settings.newChildUrl&&this.initNewChildMenus(this.$container.find(".add"))},initToggle:function(t){var e=this;t.on("click",(function(t){var i=$(t.currentTarget).closest("li"),s=i.children(".row").find(".element:first").data("id"),a=$.inArray(s,e.state.collapsedElementIds);i.hasClass("collapsed")?(i.removeClass("collapsed"),-1!==a&&e.state.collapsedElementIds.splice(a,1)):(i.addClass("collapsed"),-1===a&&e.state.collapsedElementIds.push(s)),e.settings.storageKey&&Craft.setLocalStorage(e.settings.storageKey,e.state)}))},initNewChildMenus:function(t){this.addListener(t,"click","onNewChildMenuClick")},onNewChildMenuClick:function(t){var e=$(t.currentTarget);if(!e.data("menubtn")){var i=e.parent().children(".element").data("id"),s=Craft.getUrl(this.settings.newChildUrl,"parentId="+i);$('<div class="menu"><ul><li><a href="'+s+'">'+Craft.t("app","New child")+"</a></li></ul></div>").insertAfter(e),new Garnish.MenuBtn(e).showMenu()}},getIndent:function(t){return Craft.Structure.baseIndent+(t-1)*Craft.Structure.nestedIndent},addElement:function(t){var e=$('<li data-level="1"/>').appendTo(this.$container),i=$('<div class="row" style="margin-'+Craft.left+": -"+Craft.Structure.baseIndent+"px; padding-"+Craft.left+": "+Craft.Structure.baseIndent+'px;">').appendTo(e);if(i.append(t),this.settings.sortable&&(i.append('<a class="move icon" title="'+Craft.t("app","Move")+'"></a>'),this.structureDrag.addItems(e)),this.settings.newChildUrl){var s=$('<a class="add icon" title="'+Craft.t("app","New child")+'"></a>').appendTo(i);this.initNewChildMenus(s)}i.css("margin-bottom",-30),i.velocity({"margin-bottom":0},"fast")},removeElement:function(t){var e,i=this,s=t.parent().parent();this.settings.sortable&&this.structureDrag.removeItems(s),s.siblings().length||(e=s.parent()),s.css("visibility","hidden").velocity({marginBottom:-s.height()},"fast",(function(){s.remove(),void 0!==e&&i._removeUl(e)}))},_removeUl:function(t){t.siblings(".row").children(".toggle").remove(),t.remove()},destroy:function(){this.$container.removeData("structure"),this.base()}},{baseIndent:8,nestedIndent:35,defaults:{storageKey:null,sortable:!1,newChildUrl:null,maxLevels:null}})},3096:function(){Craft.StructureDrag=Garnish.Drag.extend({structure:null,maxLevels:null,draggeeLevel:null,$helperLi:null,$targets:null,draggeeHeight:null,init:function(t,e){this.structure=t,this.maxLevels=e,this.$insertion=$('<li class="draginsertion"/>');var i=this.structure.$container.find("li");this.base(i,{handle:".element:first, .move:first",helper:this.getHelper.bind(this)})},getHelper:function(t){this.$helperLi=t;var e=$('<ul class="structure draghelper"/>').append(t);return t.css("padding-"+Craft.left,this.$draggee.css("padding-"+Craft.left)),t.find(".move").removeAttr("title"),e},onDragStart:function(){var t=this;this.$targets=$(),this.findTargets(this.structure.$container),this.draggeeLevel=0;var e=this.$draggee;do{this.draggeeLevel++,e=e.find("> ul > li")}while(e.length);this.draggeeHeight=this.$draggee.height(),this.$draggee.velocity({height:0},"fast",(function(){t.$draggee.addClass("hidden")})),this.base(),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&this.cancelDrag()}))},findTargets:function(t){for(var e=t.children().not(this.$draggee),i=0;i<e.length;i++){var s=$(e[i]);this.$targets=this.$targets.add(s.children(".row")),s.hasClass("collapsed")||this.findTargets(s.children("ul"))}},onDrag:function(){for(this._.$closestTarget&&(this._.$closestTarget.removeClass("draghover"),this.$insertion.remove()),this._.$closestTarget=null,this._.closestTargetPos=null,this._.closestTargetYDiff=null,this._.closestTargetOffset=null,this._.closestTargetHeight=null,this._.i=0;this._.i<this.$targets.length&&(this._.$target=$(this.$targets[this._.i]),this._.targetOffset=this._.$target.offset(),this._.targetHeight=this._.$target.outerHeight(),this._.targetYMidpoint=this._.targetOffset.top+this._.targetHeight/2,this._.targetYDiff=Math.abs(this.mouseY-this._.targetYMidpoint),0===this._.i||this.mouseY>=this._.targetOffset.top+5&&this._.targetYDiff<this._.closestTargetYDiff);this._.i++)this._.$closestTarget=this._.$target,this._.closestTargetPos=this._.i,this._.closestTargetYDiff=this._.targetYDiff,this._.closestTargetOffset=this._.targetOffset,this._.closestTargetHeight=this._.targetHeight;if(this._.$closestTarget)if(0===this._.closestTargetPos&&this.mouseY<this._.closestTargetOffset.top+5)this.$insertion.prependTo(this.structure.$container);else if(this._.$closestTargetLi=this._.$closestTarget.parent(),this._.closestTargetLevel=this._.$closestTargetLi.data("level"),this._.closestTargetPos<this.$targets.length-1?(this._.$nextTargetLi=$(this.$targets[this._.closestTargetPos+1]).parent(),this._.nextTargetLevel=this._.$nextTargetLi.data("level")):(this._.$nextTargetLi=null,this._.nextTargetLevel=null),this._.hoveringBetweenRows=this.mouseY>=this._.closestTargetOffset.top+this._.closestTargetHeight-5,this._.$nextTargetLi&&this._.nextTargetLevel==this._.closestTargetLevel)this._.hoveringBetweenRows?(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel-1)&&this.$insertion.insertAfter(this._.$closestTargetLi):(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover");else if(this._.$nextTargetLi&&this._.nextTargetLevel>this._.closestTargetLevel)(!this.maxLevels||this.maxLevels>=this._.nextTargetLevel+this.draggeeLevel-1)&&(this._.hoveringBetweenRows?this.$insertion.insertBefore(this._.$nextTargetLi):(this._.$closestTarget.addClass("draghover"),this.$insertion.appendTo(this._.$closestTargetLi.children("ul"))));else if(this._.hoveringBetweenRows){for(this._.draggeeX=this.mouseX-this.targetItemMouseDiffX,"rtl"===Craft.orientation&&(this._.draggeeX+=this.$helperLi.width()),this._.$parentLis=this._.$closestTarget.parentsUntil(this.structure.$container,"li"),this._.$closestParentLi=null,this._.closestParentLiXDiff=null,this._.closestParentLevel=null,this._.i=0;this._.i<this._.$parentLis.length;this._.i++)this._.$parentLi=$(this._.$parentLis[this._.i]),this._.parentLiX=this._.$parentLi.offset().left,"rtl"===Craft.orientation&&(this._.parentLiX+=this._.$parentLi.width()),this._.parentLiXDiff=Math.abs(this._.parentLiX-this._.draggeeX),this._.parentLevel=this._.$parentLi.data("level"),(!this.maxLevels||this.maxLevels>=this._.parentLevel+this.draggeeLevel-1)&&(!this._.$closestParentLi||this._.parentLiXDiff<this._.closestParentLiXDiff&&(!this._.$nextTargetLi||this._.parentLevel>=this._.nextTargetLevel))&&(this._.$closestParentLi=this._.$parentLi,this._.closestParentLiXDiff=this._.parentLiXDiff,this._.closestParentLevel=this._.parentLevel);this._.$closestParentLi&&this.$insertion.insertAfter(this._.$closestParentLi)}else(!this.maxLevels||this.maxLevels>=this._.closestTargetLevel+this.draggeeLevel)&&this._.$closestTarget.addClass("draghover")},cancelDrag:function(){this.$insertion.remove(),this._.$closestTarget&&this._.$closestTarget.removeClass("draghover"),this.onMouseUp()},onDragStop:function(){var t=this;if(this._.$closestTarget&&(this.$insertion.parent().length||this._.$closestTarget.hasClass("draghover"))){var e,i;if(this.$draggee.siblings().length||(e=this.$draggee.parent()),this.$insertion.parent().length){var s=this.$insertion.next().add(this.$insertion.prev());-1===$.inArray(this.$draggee[0],s)?(this.$insertion.replaceWith(this.$draggee),i=!0):(this.$insertion.remove(),i=!1)}else{var a=this._.$closestTargetLi.children("ul");if(e&&a.length&&a[0]===e[0])i=!1;else{if(a.length)this._.$closestTargetLi.hasClass("collapsed")&&this._.$closestTarget.children(".toggle").trigger("click");else{var n=$('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(this._.$closestTarget);this.structure.initToggle(n),a=$("<ul>").appendTo(this._.$closestTargetLi)}this.$draggee.appendTo(a),i=!0}}if(this._.$closestTarget.removeClass("draghover"),i){e&&this.structure._removeUl(e);var r,o=this.$draggee.parentsUntil(this.structure.$container,"li").length+1;o!=this.$draggee.data("level")&&(1==this.$draggee.data("level")?((r={})["padding-"+Craft.left]=38,this.$helperLi.velocity(r,"fast")):1==o&&((r={})["padding-"+Craft.left]=Craft.Structure.baseIndent,this.$helperLi.velocity(r,"fast")),this.setLevel(this.$draggee,o));var l=this.$draggee.children(".row").children(".element"),h={structureId:this.structure.id,elementId:l.data("id"),siteId:l.data("site-id"),prevId:this.$draggee.prev().children(".row").children(".element").data("id"),parentId:this.$draggee.parent("ul").parent("li").children(".row").children(".element").data("id")};Craft.postActionRequest("structures/move-element",h,(function(t,e){"success"===e&&Craft.cp.displayNotice(Craft.t("app","New order saved."))}))}}this.$draggee.velocity("stop").removeClass("hidden").velocity({height:this.draggeeHeight},"fast",(function(){t.$draggee.css("height","auto")})),this.returnHelpersToDraggees(),this.base()},setLevel:function(t,e){t.data("level",e);var i=this.structure.getIndent(e),s={};s["margin-"+Craft.left]="-"+i+"px",s["padding-"+Craft.left]=i+"px",this.$draggee.children(".row").css(s);for(var a=t.children("ul").children(),n=0;n<a.length;n++)this.setLevel($(a[n]),e+1)}})},3331:function(){Craft.StructureTableSorter=Garnish.DragSort.extend({tableView:null,structureId:null,maxLevels:null,_basePadding:null,_helperMargin:null,_$firstRowCells:null,_$titleHelperCell:null,_titleHelperCellOuterWidth:null,_ancestors:null,_updateAncestorsFrame:null,_draggeeLevel:null,_draggeeLevelDelta:null,draggingLastElements:null,_loadingDraggeeLevelDelta:!1,_targetLevel:null,_targetLevelBounds:null,_positionChanged:null,init:function(t,e,i){this.tableView=t,this.structureId=this.tableView.$table.data("structure-id"),this.maxLevels=parseInt(this.tableView.$table.attr("data-max-levels")),this._basePadding=14+(this.tableView.elementIndex.actions?14:24),this._helperMargin=this.tableView.elementIndex.actions?54:0,i=$.extend({},Craft.StructureTableSorter.defaults,i,{handle:".move",collapseDraggees:!0,singleHelper:!0,helperSpacingY:2,magnetStrength:4,helper:this.getHelper.bind(this),helperLagBase:1.5,axis:Garnish.Y_AXIS}),this.base(e,i)},findDraggee:function(){var t=this;this._draggeeLevel=this._targetLevel=this.$targetItem.data("level"),this._draggeeLevelDelta=0;for(var e=$(this.$targetItem),i=this.$targetItem.next();i.length;){var s=i.data("level");if(s<=this._draggeeLevel)break;var a=s-this._draggeeLevel;a>this._draggeeLevelDelta&&(this._draggeeLevelDelta=a),e=e.add(i),i=i.next()}if(this.draggingLastElements=!i.length,this.maxLevels&&this.draggingLastElements&&this.tableView.getMorePending()){this._loadingDraggeeLevelDelta=!0;var n=this._getAjaxBaseData(this.$targetItem);Craft.postActionRequest("structures/get-element-level-delta",n,(function(e,i){"success"===i&&(t._loadingDraggeeLevelDelta=!1,t.dragging&&(t._draggeeLevelDelta=e.delta,t.drag(!1)))}))}return e},getHelper:function(t){var e=$('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),i=$('<div class="tableview"/>').appendTo(e),s=$('<table class="data"/>').appendTo(i),a=$("<tbody/>").appendTo(s);t.appendTo(a),this._$firstRowCells=this.tableView.$elementContainer.children("tr:first").children();for(var n=t.children(),r=0;r<n.length;r++){var o=$(n[r]);if(o.hasClass("checkbox-cell"))o.remove();else{var l=$(this._$firstRowCells[r]),h=l[0].getBoundingClientRect().width;l.css("width",h+"px"),o.css("width",h+"px"),Garnish.hasAttr(l,"data-titlecell")&&(this._$titleHelperCell=o,parseInt(l.css("padding-"+Craft.left)),this._titleHelperCellOuterWidth=h,o.css("padding-"+Craft.left,this._basePadding))}}return e},canInsertBefore:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t.prev(),t)},canInsertAfter:function(t){return!this._loadingDraggeeLevelDelta&&!1!==this._getLevelBounds(t,t.next())},onDragStart:function(){this._ancestors=this._getAncestors(this.$targetItem,this.$targetItem.data("level")),this._setTargetLevelBounds(),this.tableView.maybeLoadMore(),this.base()},onDrag:function(){this.base(),this._updateIndent()},onInsertionPointChange:function(){this._setTargetLevelBounds(),this._updateAncestorsBeforeRepaint(),this.base()},onDragStop:function(){var t=this;if(this._positionChanged=!1,this.base(),this._targetLevel!=this._draggeeLevel){for(var e=this._targetLevel-this._draggeeLevel,i=0;i<this.$draggee.length;i++){var s=$(this.$draggee[i]),a=s.data("level")+e,n=this._basePadding+this._getLevelIndent(a);s.data("level",a),s.find(".element").data("level",a),s.children("[data-titlecell]:first").css("padding-"+Craft.left,n)}this._positionChanged=!0}if(this._positionChanged){for(var r=this._getAjaxBaseData(this.$draggee),o=this.$draggee.first().prev();o.length;){var l=o.data("level");if(l==this._targetLevel){r.prevId=o.data("id");break}if(l<this._targetLevel){r.parentId=o.data("id");var h=o.find("> th > .toggle");if(!h.hasClass("expanded")){h.addClass("expanded");var d=this.tableView._createSpinnerRowAfter(o);this.tableView.elementSelect&&this.tableView.elementSelect.removeItems(this.$targetItem),this.removeItems(this.$targetItem),this.$targetItem.remove(),this.tableView._totalVisible--}break}o=o.prev()}Craft.postActionRequest("structures/move-element",r,(function(e,i){if("success"===i){if(!e.success)return Craft.cp.displayError(Craft.t("app","A server error occurred.")),void t.tableView.elementIndex.updateElements();Craft.cp.displayNotice(Craft.t("app","New position saved.")),t.onPositionChange(),d&&d.parent().length&&(d.remove(),t.tableView._expandElement(h,!0)),Craft.cp.runQueue()}}))}},onSortChange:function(){this.tableView.elementSelect&&this.tableView.elementSelect.resetItemOrder(),this._positionChanged=!0,this.base()},onPositionChange:function(){var t=this;Garnish.requestAnimationFrame((function(){t.trigger("positionChange"),t.settings.onPositionChange()}))},onReturnHelpersToDraggees:function(){if(this._$firstRowCells.css("width",""),this.draggingLastElements&&this.tableView.getMorePending()){this.tableView._totalVisible+=this.newDraggeeIndexes[0]-this.oldDraggeeIndexes[0];var t=this.$draggee.last().nextAll();t.length&&(this.removeItems(t),t.remove(),this.tableView.maybeLoadMore())}this.base()},_getLevelBounds:function(t,e){if(e&&e.length?this._getLevelBounds._minLevel=e.data("level"):this._getLevelBounds._minLevel=1,t&&t.length?this._getLevelBounds._maxLevel=t.data("level")+1:this._getLevelBounds._maxLevel=1,this.maxLevels){if(1!=this._getLevelBounds._minLevel&&this._getLevelBounds._minLevel+this._draggeeLevelDelta>this.maxLevels)return!1;this._getLevelBounds._maxLevel+this._draggeeLevelDelta>this.maxLevels&&(this._getLevelBounds._maxLevel=this.maxLevels-this._draggeeLevelDelta,this._getLevelBounds._maxLevel<this._getLevelBounds._minLevel&&(this._getLevelBounds._maxLevel=this._getLevelBounds._minLevel))}return{min:this._getLevelBounds._minLevel,max:this._getLevelBounds._maxLevel}},_setTargetLevelBounds:function(){this._targetLevelBounds=this._getLevelBounds(this.$draggee.first().prev(),this.$draggee.last().next())},_updateIndent:function(t){this._updateIndent._mouseDist=this.realMouseX-this.mousedownX,"rtl"===Craft.orientation&&(this._updateIndent._mouseDist*=-1),this._updateIndent._indentationDist=Math.round(this._updateIndent._mouseDist/Craft.StructureTableSorter.LEVEL_INDENT),this._updateIndent._targetLevel=this._draggeeLevel+this._updateIndent._indentationDist,this._updateIndent._targetLevel<this._targetLevelBounds.min?(this._updateIndent._indentationDist+=this._targetLevelBounds.min-this._updateIndent._targetLevel,this._updateIndent._targetLevel=this._targetLevelBounds.min):this._updateIndent._targetLevel>this._targetLevelBounds.max&&(this._updateIndent._indentationDist-=this._updateIndent._targetLevel-this._targetLevelBounds.max,this._updateIndent._targetLevel=this._targetLevelBounds.max),this._targetLevel!==(this._targetLevel=this._updateIndent._targetLevel)&&this._updateAncestorsBeforeRepaint(),this._updateIndent._targetLevelMouseDiff=this._updateIndent._mouseDist-this._updateIndent._indentationDist*Craft.StructureTableSorter.LEVEL_INDENT,this._updateIndent._magnetImpact=Math.round(this._updateIndent._targetLevelMouseDiff/15),Math.abs(this._updateIndent._magnetImpact)>Craft.StructureTableSorter.MAX_GIVE&&(this._updateIndent._magnetImpact=(this._updateIndent._magnetImpact>0?1:-1)*Craft.StructureTableSorter.MAX_GIVE),this._updateIndent._closestLevelMagnetIndent=this._getLevelIndent(this._targetLevel)+this._updateIndent._magnetImpact,this.helpers[0].css("margin-"+Craft.left,this._updateIndent._closestLevelMagnetIndent+this._helperMargin),this._$titleHelperCell.css("width",this._titleHelperCellOuterWidth-this._updateIndent._closestLevelMagnetIndent)},_getLevelIndent:function(t){return(t-1)*Craft.StructureTableSorter.LEVEL_INDENT},_getAjaxBaseData:function(t){return{structureId:this.structureId,elementId:t.data("id"),siteId:t.find(".element:first").data("site-id")}},_getAncestors:function(t,e){if(this._getAncestors._ancestors=[],0!=e)for(this._getAncestors._level=e,this._getAncestors._$prevRow=t.prev();this._getAncestors._$prevRow.length&&!(this._getAncestors._$prevRow.data("level")<this._getAncestors._level&&(this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow),this._getAncestors._level=this._getAncestors._$prevRow.data("level"),0==this._getAncestors._level));)this._getAncestors._$prevRow=this._getAncestors._$prevRow.prev();return this._getAncestors._ancestors},_updateAncestorsBeforeRepaint:function(){this._updateAncestorsFrame&&Garnish.cancelAnimationFrame(this._updateAncestorsFrame),this._updateAncestorsFrame=Garnish.requestAnimationFrame(this._updateAncestors.bind(this))},_updateAncestors:function(){for(this._updateAncestorsFrame=null,this._updateAncestors._i=0;this._updateAncestors._i<this._ancestors.length;this._updateAncestors._i++)this._updateAncestors._$ancestor=this._ancestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")-1),0==this._updateAncestors._$ancestor.data("descendants")&&this._updateAncestors._$ancestor.find("> th > .toggle:first").remove();for(this._updateAncestors._newAncestors=this._getAncestors(this.$targetItem,this._targetLevel),this._updateAncestors._i=0;this._updateAncestors._i<this._updateAncestors._newAncestors.length;this._updateAncestors._i++)this._updateAncestors._$ancestor=this._updateAncestors._newAncestors[this._updateAncestors._i],this._updateAncestors._$ancestor.data("descendants",this._updateAncestors._$ancestor.data("descendants")+1),1==this._updateAncestors._$ancestor.data("descendants")&&$('<span class="toggle expanded" title="'+Craft.t("app","Show/hide children")+'"></span>').insertAfter(this._updateAncestors._$ancestor.find("> th .move:first"));this._ancestors=this._updateAncestors._newAncestors,delete this._updateAncestors._i,delete this._updateAncestors._$ancestor,delete this._updateAncestors._newAncestors}},{HELPER_MARGIN:0,LEVEL_INDENT:44,MAX_GIVE:22,defaults:{onPositionChange:$.noop}})},53:function(){Craft.TableElementIndexView=Craft.BaseElementIndexView.extend({$table:null,$selectedSortHeader:null,structureTableSort:null,_totalVisiblePostStructureTableDraggee:null,_morePendingPostStructureTableDraggee:!1,getElementContainer:function(){return this.$table=this.$container.find("table:first"),this.$table.children("tbody:first")},afterInit:function(){this.initTableHeaders(),"index"===this.elementIndex.settings.context&&"structure"===this.elementIndex.getSelectedSortAttribute()&&Garnish.hasAttr(this.$table,"data-structure-id")?this.structureTableSort=new Craft.StructureTableSorter(this,this.getAllElements()):this.structureTableSort=null,"structure"===this.elementIndex.getSelectedSortAttribute()&&this.addListener(this.$elementContainer,"click",(function(t){var e=$(t.target);e.hasClass("toggle")&&!1===this._collapseElement(e)&&this._expandElement(e)}))},initTableHeaders:function(){for(var t=this.elementIndex.getSelectedSortAttribute(),e=this.$table.children("thead").children().children("[data-attribute]"),i=0;i<e.length;i++){var s=e.eq(i),a=s.attr("data-attribute");if(a===t){this.$selectedSortHeader=s;var n=this.elementIndex.getSelectedSortDirection();s.addClass("ordered "+n).on("click",this._handleSelectedSortHeaderClick.bind(this))}else this.elementIndex.getSortAttributeOption(a).length&&s.addClass("orderable").on("click",this._handleUnselectedSortHeaderClick.bind(this))}},isVerticalList:function(){return!0},getTotalVisible:function(){return this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee:this._totalVisible},setTotalVisible:function(t){this._isStructureTableDraggingLastElements()?this._totalVisiblePostStructureTableDraggee=t:this._totalVisible=t},getMorePending:function(){return this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee:this._morePending},setMorePending:function(t){this._isStructureTableDraggingLastElements()?this._morePendingPostStructureTableDraggee=t:this._morePending=this._morePendingPostStructureTableDraggee=t},getLoadMoreParams:function(){var t=this.base();return this._isStructureTableDraggingLastElements()&&(t.criteria.positionedAfter=this.structureTableSort.$targetItem.data("id")),t},appendElements:function(t){this.base(t),this.structureTableSort&&this.structureTableSort.addItems(t),Craft.cp.updateResponsiveTables()},createElementEditor:function(t){var e=this;Craft.createElementEditor(t.data("type"),t,{params:{includeTableAttributesForSource:this.elementIndex.sourceKey},onSaveElement:function(i){i.tableAttributes&&e._updateTableAttributes(t,i.tableAttributes)},elementIndex:this.elementIndex})},_collapseElement:function(t,e){if(!e&&!t.hasClass("expanded"))return!1;t.removeClass("expanded");for(var i=t.parent().parent(),s=i.data("id"),a=i.data("level"),n=i.next();n.length;){if(!Garnish.hasAttr(n,"data-spinnerrow")){if(n.data("level")<=a)break;this.elementSelect&&this.elementSelect.removeItems(n),this.structureTableSort&&this.structureTableSort.removeItems(n),this._totalVisible--}var r=n.next();n.remove(),n=r}this.elementIndex.instanceState.collapsedElementIds||(this.elementIndex.instanceState.collapsedElementIds=[]),this.elementIndex.instanceState.collapsedElementIds.push(s),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds),this.maybeLoadMore()},_expandElement:function(t,e){var i=this;if(!e&&t.hasClass("expanded"))return!1;if(t.addClass("expanded"),this.elementIndex.instanceState.collapsedElementIds){var s=t.parent().parent(),a=s.data("id"),n=$.inArray(a,this.elementIndex.instanceState.collapsedElementIds);if(-1!==n){this.elementIndex.instanceState.collapsedElementIds.splice(n,1),this.elementIndex.setInstanceState("collapsedElementIds",this.elementIndex.instanceState.collapsedElementIds);var r=this._createSpinnerRowAfter(s),o=$.extend(!0,{},this.settings.params);o.criteria.descendantOf=a,Craft.sendActionRequest("POST",this.settings.loadMoreElementsAction,{data:o}).then((function(t){if(r.parent().length){var e=$(t.data.html),s=i._totalVisible+e.length,a=i.settings.batchSize&&e.length===i.settings.batchSize;if(a){var n=r.nextAll();i.elementSelect&&i.elementSelect.removeItems(n),i.structureTableSort&&i.structureTableSort.removeItems(n),n.remove(),s-=n.length}else a=i._morePending;r.replaceWith(e),i.thumbLoader.load(e),(i.elementIndex.actions||i.settings.selectable)&&(i.elementSelect.addItems(e.filter(":not(.disabled)")),i.elementIndex.updateActionTriggers()),i.structureTableSort&&i.structureTableSort.addItems(e),Craft.appendHeadHtml(t.data.headHtml),Craft.appendFootHtml(t.data.footHtml),Craft.cp.updateResponsiveTables(),i.setTotalVisible(s),i.setMorePending(a),i.maybeLoadMore()}})).catch((function(t){Craft.cp.displayError(),r.parent().length}))}}},_createSpinnerRowAfter:function(t){return $('<tr data-spinnerrow><td class="centeralign" colspan="'+t.children().length+'"><div class="spinner"/></td></tr>').insertAfter(t)},_isStructureTableDraggingLastElements:function(){return this.structureTableSort&&this.structureTableSort.dragging&&this.structureTableSort.draggingLastElements},_handleSelectedSortHeaderClick:function(t){var e=$(t.currentTarget);if(!e.hasClass("loading")){var i="asc"===this.elementIndex.getSelectedSortDirection()?"desc":"asc";this.elementIndex.setSortDirection(i),this._handleSortHeaderClick(t,e)}},_handleUnselectedSortHeaderClick:function(t){var e=$(t.currentTarget);if(!e.hasClass("loading")){var i=e.attr("data-attribute");this.elementIndex.setSortAttribute(i),this._handleSortHeaderClick(t,e)}},_handleSortHeaderClick:function(t,e){this.$selectedSortHeader&&this.$selectedSortHeader.removeClass("ordered asc desc"),e.removeClass("orderable").addClass("ordered loading"),this.elementIndex.storeSortAttributeAndDirection(),this.elementIndex.updateElements(),this.elementIndex.setIndexAvailable()},_updateTableAttributes:function(t,e){var i=t.closest("tr");for(var s in e)e.hasOwnProperty(s)&&i.children('[data-attr="'+s+'"]:first').html(e[s])}})},7745:function(){Craft.Tabs=Garnish.Base.extend({$container:null,$ul:null,$menuBtn:null,$tabs:null,$selectedTab:null,$focusableTab:null,menu:null,init:function(t){var e=this;this.$container=$(t),this.$ul=this.$container.find("> ul:first"),this.$tabs=this.$ul.find("> li > a"),this.$selectedTab=this.$tabs.filter(".sel:first"),this.$focusableTab=this.$tabs.filter("[tabindex=0]:first"),this.$menuBtn=this.$container.find("> .menubtn:first").menubtn(),this.menu=this.$menuBtn.data("menubtn").menu,this.$container.data("tabs")&&(console.warn("Double-instantiating a tab manager on an element"),this.$container.data("tabs").destroy()),this.$container.data("tabs",this);for(var i=0;i<this.$tabs.length;i++){var s=this.$tabs.eq(i),a=s.attr("href");a&&"#"===a.charAt(0)&&(this.addListener(s,"keydown",(function(t){[Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)&&(t.preventDefault(),e.selectTab(t.currentTarget))})),this.addListener(s,"click",(function(t){t.preventDefault(),$(t.currentTarget),e.selectTab(t.currentTarget),e.makeTabFocusable(t.currentTarget)})),a.substr(1)===window.LOCATION_HASH&&($initialTab=s)),this.addListener(s,"keydown",(function(t){var i;[Garnish.LEFT_KEY,Garnish.RIGHT_KEY].includes(t.keyCode)&&$.contains(e.$ul[0],t.currentTarget)&&(i=t.keyCode===("ltr"===Craft.orientation?Garnish.LEFT_KEY:Garnish.RIGHT_KEY)?$(t.currentTarget).parent().prev("li").children("a"):$(t.currentTarget).parent().next("li").children("a")).length&&(t.preventDefault(),e.makeTabFocusable(i),i.focus(),e.scrollToTab(i))}))}this.updateMenuBtn(),Garnish.$win.on("resize",(function(){e.updateMenuBtn()})),this.menu.$options.on("click",(function(t){var e=$(t.currentTarget).attr("href");e&&"#"===e.charAt(0)&&t.preventDefault()})),this.menu.on("optionselect",(function(t){e.selectTab($(t.selectedOption).data("id"))}))},selectTab:function(t){var e=this._getTab(t);e[0]!==this.$selectedTab[0]&&(this.deselectTab(),this.$selectedTab=e.addClass("sel"),this.makeTabFocusable(e),this.scrollToTab(e),this.menu.$options.removeClass("sel"),this.menu.$options.filter('[data-id="'.concat(e.data("id"),'"]')).addClass("sel"),this.trigger("selectTab",{$tab:e}),$("#content").trigger("scroll"))},deselectTab:function(){var t=this.$selectedTab.removeClass("sel");this.$selectedTab=null,this.trigger("deselectTab",{$tab:t})},makeTabFocusable:function(t){var e=this._getTab(t);e[0]!==this.$focusableTab[0]&&(this.$focusableTab.attr("tabindex","-1"),this.$focusableTab=e.attr("tabindex","0"))},scrollToTab:function(t){var e=this._getTab(t),i=this.$ul.scrollLeft(),s=e.offset().left-this.$ul.offset().left,a=!1;if(s<0)a=i+s-24;else{var n=e.outerWidth(),r=this.$ul.prop("clientWidth");s+n>r&&(a=i+(s-(r-n))+24)}!1!==a&&this.$ul.scrollLeft(a)},updateMenuBtn:function(){Math.floor(this.$ul.prop("scrollWidth")-48)>this.$container.prop("clientWidth")?(this.$ul.addClass("scrollable"),this.$menuBtn.removeClass("hidden")):(this.$ul.removeClass("scrollable"),this.$menuBtn.addClass("hidden"))},_getTab:function(t){if(t instanceof jQuery)return t;if(t instanceof HTMLElement)return $(t);if("string"!=typeof t)throw"Invalid tab ID";var e=this.$tabs.filter('[data-id="'.concat(t,'"]'));if(!e.length)throw"Invalid tab ID: ".concat(t);return e},destroy:function(){this.$container.removeData("tabs"),this.base()}})},5074:function(){Craft.TagSelectInput=Craft.BaseElementSelectInput.extend({searchTimeout:null,searchMenu:null,$container:null,$elementsContainer:null,$elements:null,$addTagInput:null,$spinner:null,_ignoreBlur:!1,init:function(t){var e=this;if(!$.isPlainObject(t)){for(var i={},s=["id","name","tagGroupId","sourceElementId"],a=0;a<s.length&&void 0!==arguments[a];a++)i[s[a]]=arguments[a];t=i}this.base($.extend({},Craft.TagSelectInput.defaults,t)),this.$addTagInput=this.$container.children(".add").children(".text"),this.$spinner=this.$addTagInput.next(),this.addListener(this.$addTagInput,"input",(function(){e.searchTimeout&&clearTimeout(e.searchTimeout),e.searchTimeout=setTimeout(e.searchForTags.bind(e),500)})),this.addListener(this.$addTagInput,"keydown",(function(t){switch(t.keyCode===Garnish.RETURN_KEY&&t.preventDefault(),t.keyCode){case Garnish.RETURN_KEY:return t.preventDefault(),void(this.searchMenu&&this.selectTag(this.searchMenu.$options.filter(".hover")));case Garnish.DOWN_KEY:if(t.preventDefault(),this.searchMenu){var e=this.searchMenu.$options.filter(".hover");if(e.length){var i=e.parent().nextAll().find("a:not(.disabled)").first();i.length&&this.focusOption(i)}else this.focusOption(this.searchMenu.$options.eq(0))}return;case Garnish.UP_KEY:if(t.preventDefault(),this.searchMenu){var s=this.searchMenu.$options.filter(".hover");if(s.length){var a=s.parent().prevAll().find("a:not(.disabled)").last();a.length&&this.focusOption(a)}else this.focusOption(this.searchMenu.$options.eq(this.searchMenu.$options.length-1))}return}})),this.addListener(this.$addTagInput,"focus",(function(){this.searchMenu&&this.searchMenu.show()})),this.addListener(this.$addTagInput,"blur",(function(){var t=this;this._ignoreBlur?this._ignoreBlur=!1:setTimeout((function(){t.searchMenu&&t.searchMenu.hide()}),1)}))},focusOption:function(t){this.searchMenu.$options.removeClass("hover"),t.addClass("hover"),this.searchMenu.$menuList.attr("aria-activedescendant",t.attr("id"))},getAddElementsBtn:$.noop,getElementSortAxis:function(){return null},searchForTags:function(){var t=this;if(this.searchMenu&&this.killSearchMenu(),this.$addTagInput.val()){this.$spinner.removeClass("hidden");for(var e=[],i=0;i<this.$elements.length;i++){var s=$(this.$elements[i]).data("id");s&&e.push(s)}this.settings.sourceElementId&&e.push(this.settings.sourceElementId);var a={search:this.$addTagInput.val(),tagGroupId:this.settings.tagGroupId,excludeIds:e};Craft.postActionRequest("tags/search-for-tags",a,(function(e,i){if(t.searchMenu&&t.killSearchMenu(),t.$spinner.addClass("hidden"),"success"===i){for(var s,n=$('<div class="menu tagmenu"/>').appendTo(Garnish.$bod),r=$("<ul/>").appendTo(n),o=0;o<e.tags.length;o++)s=$("<li/>").appendTo(r),$('<a data-icon="tag"/>').appendTo(s).text(e.tags[o].title).data("id",e.tags[o].id).addClass(e.tags[o].exclude?"disabled":"");e.exactMatch||(s=$("<li/>").appendTo(r),$('<a data-icon="plus"/>').appendTo(s).text(a.search)),r.find("a:not(.disabled):first").addClass("hover"),t.searchMenu=new Garnish.Menu(n,{attachToElement:t.$addTagInput,onOptionSelect:t.selectTag.bind(t)}),t.addListener(n,"mousedown",(function(){t._ignoreBlur=!0})),t.searchMenu.show()}}))}else this.$spinner.addClass("hidden")},selectTag:function(t){var e=this,i=$(t);if(!i.hasClass("disabled")){var s=i.data("id"),a=i.text(),n=$("<div/>",{class:"element small removable","data-id":s,"data-site-id":this.settings.targetSiteId,"data-label":a,"data-editable":"1"}).appendTo(this.$elementsContainer),r=$("<input/>",{type:"hidden",name:this.settings.name+"[]",value:s}).appendTo(n);$("<a/>",{class:"delete icon",title:Craft.t("app","Remove")}).appendTo(n);var o=$("<div/>",{class:"label"}).appendTo(n);$("<span/>",{class:"title",text:a}).appendTo(o);var l=-(n.outerWidth()+10);this.$addTagInput.css("margin-"+Craft.left,l+"px");var h={};if(h["margin-"+Craft.left]=0,this.$addTagInput.velocity(h,"fast"),this.$elements=this.$elements.add(n),this.addElements(n),this.killSearchMenu(),this.$addTagInput.val(""),this.$addTagInput.trigger("focus"),!s){n.addClass("loading disabled");var d={groupId:this.settings.tagGroupId,title:a};Craft.postActionRequest("tags/create-tag",d,(function(t,i){"success"===i&&t.success?(n.attr("data-id",t.id),r.val(t.id),n.removeClass("loading disabled")):(e.removeElement(n),"success"===i&&Craft.cp.displayError(Craft.t("app","A server error occurred.")))}))}}},killSearchMenu:function(){this.searchMenu.hide(),this.searchMenu.destroy(),this.searchMenu=null}},{defaults:{tagGroupId:null}})},3958:function(){Craft.ThumbsElementIndexView=Craft.BaseElementIndexView.extend({getElementContainer:function(){return this.$container.children("ul")}})},1592:function(){Craft.ui={createTextInput:function(t){t=$.extend({autocomplete:!1},t);var e=$("<input/>",{attr:{class:"text",type:t.type||"text",inputmode:t.inputmode,id:t.id,size:t.size,name:t.name,value:t.value,maxlength:t.maxlength,autofocus:this.getAutofocusValue(t.autofocus),autocomplete:"boolean"==typeof t.autocomplete?t.autocomplete?"on":"off":t.autocomplete,disabled:this.getDisabledValue(t.disabled),readonly:t.readonly,title:t.title,placeholder:t.placeholder,step:t.step,min:t.min,max:t.max}});return t.class&&e.addClass(t.class),t.placeholder&&e.addClass("nicetext"),"password"===t.type&&e.addClass("password"),t.disabled&&e.addClass("disabled"),t.size||e.addClass("fullwidth"),t.showCharsLeft&&t.maxlength&&e.attr("data-show-chars-left").css("padding-"+("ltr"===Craft.orientation?"right":"left"),7.2*t.maxlength.toString().length+14+"px"),(t.placeholder||t.showCharsLeft)&&new Garnish.NiceText(e),"password"===t.type?$('<div class="passwordwrapper"/>').append(e):e},createTextField:function(t){return t.id||(t.id="text"+Math.floor(1e9*Math.random())),this.createField(this.createTextInput(t),t)},createCopyTextInput:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.buttonId||"".concat(e,"-btn"),s=$("<div/>",{class:"copytext"}),a=this.createTextInput($.extend({},t,{readonly:!0})).appendTo(s);return $("<button/>",{type:"button",id:i,class:"btn","data-icon":"clipboard",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard")}).appendTo(s).on("click",(function(){a[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),a[0].setSelectionRange(0,0)})),s},createCopyTextBtn:function(t){var e=t.id||"copytext"+Math.floor(1e9*Math.random()),i=t.value,s=$("<div/>",{id:e,class:"copytextbtn",role:"button",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard"),tabindex:"0"});t.class&&s.addClass(t.class);var a=$("<input/>",{value:i,readonly:!0,size:i.length,tabindex:"-1"}).appendTo(s),n=($("<span/>",{"data-icon":"clipboard","aria-hidden":"true"}).appendTo(s),function(){a[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),s.trigger("copy"),a[0].setSelectionRange(0,0),s.focus()});return s.on("click",(function(){n()})),s.on("keydown",(function(t){t.keyCode===Garnish.SPACE_KEY&&(n(),t.preventDefault())})),s},createCopyTextField:function(t){return t.id||(t.id="copytext"+Math.floor(1e9*Math.random())),this.createField(this.createCopyTextInput(t),t)},createCopyTextPrompt:function(t){var e=$("<div/>",{class:"modal fitted"}),i=$("<div/>",{class:"body"}).appendTo(e);this.createCopyTextField($.extend({size:Math.max(Math.min(t.value.length,50),25)},t)).appendTo(i);var s=new Garnish.Modal(e,{closeOtherModals:!1});return e.on("copy",(function(){s.hide()})),e},createTextarea:function(t){var e=$("<textarea/>",{class:"text",rows:t.rows||2,cols:t.cols||50,id:t.id,name:t.name,maxlength:t.maxlength,autofocus:t.autofocus&&!Garnish.isMobileBrowser(!0),disabled:!!t.disabled,placeholder:t.placeholder,html:t.value});return t.showCharsLeft&&e.attr("data-show-chars-left",""),t.class&&e.addClass(t.class),t.size||e.addClass("fullwidth"),e},createTextareaField:function(t){return t.id||(t.id="textarea"+Math.floor(1e9*Math.random())),this.createField(this.createTextarea(t),t)},createSelect:function(t){var e=$("<div/>",{class:"select"});t.class&&e.addClass(t.class);var i=$("<select/>",{id:t.id,name:t.name,autofocus:t.autofocus&&Garnish.isMobileBrowser(!0),disabled:t.disabled,"data-target-prefix":t.targetPrefix}).appendTo(e);if($.isPlainObject(t.options)){var s=[];for(var a in t.options)if(t.options.hasOwnProperty(a)){var n=t.options[a];$.isPlainObject(n)?void 0!==n.optgroup?s.push(n):s.push({label:n.label,value:void 0!==n.value?n.value:a,disabled:void 0!==n.disabled&&n.disabled}):s.push({label:n,value:a})}t.options=s}for(var r=null,o=0;o<t.options.length;o++){var l=t.options[o];void 0!==l.optgroup?r=$("<optgroup/>",{label:l.label}).appendTo(i):$("<option/>",{value:l.value,selected:l.value==t.value,disabled:void 0!==l.disabled&&l.disabled,html:l.label}).appendTo(r||i)}return t.toggle&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i)),e},createSelectField:function(t){return t.id||(t.id="select"+Math.floor(1e9*Math.random())),this.createField(this.createSelect(t),t)},createCheckbox:function(t){var e=t.id||"checkbox"+Math.floor(1e9*Math.random()),i=$("<input/>",{type:"checkbox",value:void 0!==t.value?t.value:"1",id:e,class:"checkbox",name:t.name,checked:t.checked?"checked":null,autofocus:this.getAutofocusValue(t.autofocus),disabled:this.getDisabledValue(t.disabled),"data-target":t.toggle,"data-reverse-target":t.reverseToggle});t.class&&i.addClass(t.class),(t.toggle||t.reverseToggle)&&(i.addClass("fieldtoggle"),new Craft.FieldToggle(i));var s=$("<label/>",{for:e,html:t.label});return t.name&&(t.name.length<3||"[]"!==t.name.substr(-2))?$([$("<input/>",{type:"hidden",name:t.name,value:""})[0],i[0],s[0]]):$([i[0],s[0]])},createCheckboxField:function(t){t.id||(t.id="checkbox"+Math.floor(1e9*Math.random()));var e=$('<div class="field checkboxfield"/>',{id:"".concat(t.id,"-field")});return t.first&&e.addClass("first"),t.instructions&&e.addClass("has-instructions"),this.createCheckbox(t).appendTo(e),t.instructions&&$('<div class="instructions"/>').text(t.instructions).appendTo(e),e},createCheckboxSelect:function(t){var e,i,s=$('<fieldset class="checkbox-select"/>');t.class&&s.addClass(t.class),t.showAllOption?(e=t.allValue||"*",i=t.values==e,$("<div/>").appendTo(s).append(this.createCheckbox({id:t.id,class:"all",label:"<b>"+(t.allLabel||Craft.t("app","All"))+"</b>",name:t.name,value:e,checked:i,autofocus:t.autofocus}))):i=!1;for(var a=0;a<t.options.length;a++){var n=t.options[a];n.value!=e&&$("<div/>").appendTo(s).append(this.createCheckbox({label:n.label,name:t.name?t.name+"[]":null,value:n.value,checked:i||(t.values||[]).includes(n.value),disabled:i}))}return new Garnish.CheckboxSelect(s),s},createCheckboxSelectField:function(t){return t.fieldset=!0,t.id||(t.id="checkboxselect"+Math.floor(1e9*Math.random())),this.createField(this.createCheckboxSelect(t),t)},createLightswitch:function(t){var e=t.value||"1",i=t.indeterminateValue||"-",s=$("<button/>",{type:"button",class:"lightswitch","data-value":e,"data-indeterminate-value":i,id:t.id,role:"checkbox","aria-checked":t.on?"true":t.indeterminate?"mixed":"false","aria-labelledby":t.labelId,"data-target":t.toggle,"data-reverse-target":t.reverseToggle});return t.on?s.addClass("on"):t.indeterminate&&s.addClass("indeterminate"),t.small&&s.addClass("small"),t.disabled&&s.addClass("disabled"),$('<div class="lightswitch-container"><div class="handle"></div></div>').appendTo(s),t.name&&$("<input/>",{type:"hidden",name:t.name,value:t.on?e:t.indeterminate?i:"",disabled:t.disabled}).appendTo(s),(t.toggle||t.reverseToggle)&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s)),new Craft.LightSwitch(s,{onChange:t.onChange||$.noop}),s},createLightswitchField:function(t){return t.id||(t.id="lightswitch"+Math.floor(1e9*Math.random())),this.createField(this.createLightswitch(t),t).addClass("lightswitch-field")},createColorInput:function(t){var e=t.id||"color"+Math.floor(1e9*Math.random()),i=t.containerId||e+"-container",s=t.name||null,a=t.value||null,n=t.small||!1,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{id:i,class:"flex color-container"}),h=$("<div/>",{class:"color static"+(n?" small":"")}).appendTo(l),d=($("<div/>",{class:"color-preview",style:t.value?{backgroundColor:t.value}:null}).appendTo(h),$("<div/>",{class:"color-input-container"}).append($("<div/>",{class:"color-hex-indicator light code","aria-hidden":"true",text:"#"})).appendTo(l));return this.createTextInput({id:e,name:s,value:Craft.ltrim(a,"#"),size:10,class:"color-input",autofocus:r,disabled:o,"aria-label":Craft.t("app","Color hex value")}).appendTo(d),new Craft.ColorInput(l),l},createColorField:function(t){return t.fieldset=!0,o,t.id||(t.id="color"+Math.floor(1e9*Math.random())),this.createField(this.createColorInput(t),t)},createDateInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"date"+Math.floor(1e9*Math.random()))+"-date",s=t.name||null,a=s?s+"[date]":null,n=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"datewrapper"}),h=this.createTextInput({id:i,type:e?"date":"text",class:!(!e||n)&&"empty-value",name:a,value:n?e?n.toISOString().split("T")[0]:Craft.formatDate(n):"",placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="date"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?h.datetimeinput():h.datepicker($.extend({defaultDate:n||new Date},Craft.datepickerOptions)),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createDateField:function(t){return t.id||(t.id="date"+Math.floor(1e9*Math.random())),this.createField(this.createDateInput(t),t)},createDateRangePicker:function(t){var e=new Date,i=new Date(e.getFullYear(),e.getMonth(),e.getDate());t=$.extend({class:"",options:["today","thisWeek","thisMonth","thisYear","past7Days","past30Days","past90Days","pastYear"],onChange:$.noop,selected:null,startDate:null,endDate:null},t);var s,a,n=$("<div/>",{class:"menu"}),r=$("<ul/>",{class:"padded"}).appendTo(n),o=$("<a/>").addClass("sel").text(Craft.t("app","All")).data("handle","all");$("<li/>").append(o).appendTo(r);for(var l=0;l<t.options.length;l++){var h=t.options[l];switch(h){case"today":s={label:Craft.t("app","Today"),startDate:i,endDate:i};break;case"thisWeek":var d=e.getDay()-Craft.datepickerOptions.firstDay;d<0&&(d+=7),s={label:Craft.t("app","This week"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-d),endDate:i};break;case"thisMonth":s={label:Craft.t("app","This month"),startDate:new Date(e.getFullYear(),e.getMonth()),endDate:i};break;case"thisYear":s={label:Craft.t("app","This year"),startDate:new Date(e.getFullYear(),0),endDate:i};break;case"past7Days":s={label:Craft.t("app","Past {num} days",{num:7}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-7),endDate:i};break;case"past30Days":s={label:Craft.t("app","Past {num} days",{num:30}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-30),endDate:i};break;case"past90Days":s={label:Craft.t("app","Past {num} days",{num:90}),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-90),endDate:i};break;case"pastYear":s={label:Craft.t("app","Past year"),startDate:new Date(e.getFullYear(),e.getMonth(),e.getDate()-365),endDate:i}}var c=$("<li/>"),u=$("<a/>",{text:s.label}).data("handle",h).data("startDate",s.startDate).data("endDate",s.endDate).data("startTime",s.startDate?s.startDate.getTime():null).data("endTime",s.endDate?s.endDate.getTime():null);t.selected&&h==t.selected&&(a=u[0]),c.append(u),c.appendTo(r)}$("<hr/>").appendTo(n);var p=$("<div/>",{class:"flex flex-nowrap padded"}).appendTo(n),g=this.createDateField({label:Craft.t("app","From")}).appendTo(p).find("input"),f=this.createDateField({label:Craft.t("app","To")}).appendTo(p).find("input"),m=g.add(f);m.on("keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&$(this).data("datepicker")&&$(this).data("datepicker").dpDiv.is(":visible")&&t.stopPropagation()})),g.data("datepicker")&&g.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()})),f.data("datepicker")&&f.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()}));var v=new Garnish.Menu(n,{onOptionSelect:function(e){var i=$(e);b.text(i.text()),v.setPositionRelativeToAnchor(),n.find(".sel").removeClass("sel"),i.addClass("sel"),g.datepicker("setDate",i.data("startDate")),f.datepicker("setDate",i.data("endDate")),t.onChange(i.data("startDate")||null,i.data("endDate")||null,i.data("handle"))}});m.on("change",(function(){for(var e,i=g.datepicker("getDate"),s=f.datepicker("getDate"),a=i?i.getTime():null,o=s?s.getTime():null,l=r.find("a"),h=!1,d=0;d<l.length;d++)if(a===((e=l.eq(d)).data("startTime")||null)&&o===(e.data("endTime")||null)){v.selectOption(e[0]),h=!0,t.onChange(null,null,e.data("handle"));break}h||(n.find(".sel").removeClass("sel"),p.addClass("sel"),a||o?a&&o?b.text(g.val()+" - "+f.val()):a?b.text(Craft.t("app","From {date}",{date:g.val()})):b.text(Craft.t("app","To {date}",{date:f.val()})):b.text(Craft.t("app","All")),v.setPositionRelativeToAnchor(),t.onChange(i,s,"custom"))})),v.on("hide",(function(){g.datepicker("hide"),f.datepicker("hide")}));var C="btn menubtn";t.class&&(C=C+" "+t.class);var b=$("<button/>",{type:"button",class:C,"data-icon":"date",text:Craft.t("app","All")});return new Garnish.MenuBtn(b,v),a&&v.selectOption(a),t.startDate&&g.datepicker("setDate",t.startDate),t.endDate&&f.datepicker("setDate",t.endDate),(t.startDate||t.endDate)&&m.trigger("change"),b},createTimeInput:function(t){var e=Garnish.isMobileBrowser(),i=(t.id||"time"+Math.floor(1e9*Math.random()))+"-time",s=t.name||null,a=s?s+"[time]":null,n=t.value&&"function"==typeof t.value.getMonth?t.value:null,r=t.autofocus&&Garnish.isMobileBrowser(!0),o=t.disabled||!1,l=$("<div/>",{class:"timewrapper"}),h=this.createTextInput({id:i,type:e?"time":"text",class:!(!e||n)&&"empty-value",name:a,placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return $('<div data-icon="time"></div>').appendTo(l),s&&$("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),e?(n&&h.val(n.toISOString().split("T")[1]),h.datetimeinput()):(h.timepicker(Craft.timepickerOptions),n&&h.timepicker("setTime",3600*n.getHours()+60*n.getMinutes()+n.getSeconds())),t.hasOuterContainer?l:$('<div class="datetimewrapper"/>').append(l).datetime()},createTimeField:function(t){return t.id||(t.id="time"+Math.floor(1e9*Math.random())),this.createField(this.createTimeInput(t),t)},createField:function(t,e){var i=e.label&&"__blank__"!==e.label?e.label:null,s=(Craft.isMultiSite&&e.siteId&&e.siteId,$(e.fieldset?"<fieldset/>":"<div/>",{class:"field",id:e.fieldId||(e.id?e.id+"-field":null)}));if(e.first&&s.addClass("first"),i){var a=$('<div class="heading"/>').appendTo(s);$(e.fieldset?"<legend/>":"<label/>",{id:e.labelId||(e.id?"".concat(e.id,"-").concat(e.fieldset?"legend":"label"):null),class:e.required?"required":null,for:!e.fieldset&&e.id,text:i}).appendTo(a)}if(e.instructions&&$('<div class="instructions"/>').text(e.instructions).appendTo(s),$('<div class="input"/>').append(t).appendTo(s),e.tip){var n=$('<p class="notice has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(n),$('<span class="visually-hidden"/>').text(Craft.t("app","Tip")+": ").appendTo(n),$("<span/>").text(e.tip).appendTo(n),n.appendTo(s)}if(e.warning){var r=$('<p class="warning has-icon"/>');$('<span class="icon" aria-hidden="true"/>').appendTo(r),$('<span class="visually-hidden"/>').text(Craft.t("app","Warning")+": ").appendTo(r),$("<span/>").text(e.warning).appendTo(r),r.appendTo(s)}return e.errors&&this.addErrorsToField(s,e.errors),s},createErrorList:function(t){var e=$('<ul class="errors"/>');return t&&this.addErrorsToList(e,t),e},addErrorsToList:function(t,e){for(var i=0;i<e.length;i++)$("<li/>").text(e[i]).appendTo(t)},addErrorsToField:function(t,e){if(e){t.addClass("has-errors"),t.children(".input").addClass("errors");var i=t.children("ul.errors");i.length||(i=this.createErrorList().appendTo(t)),this.addErrorsToList(i,e)}},clearErrorsFromField:function(t){t.removeClass("has-errors"),t.children(".input").removeClass("errors"),t.children("ul.errors").remove()},getAutofocusValue:function(t){return t&&!Garnish.isMobileBrowser(!0)?"autofocus":null},getDisabledValue:function(t){return t?"disabled":null}}},1752:function(){Craft.Uploader=Garnish.Base.extend({uploader:null,allowedKinds:null,$element:null,settings:null,_rejectedFiles:{},_extensionList:null,_totalFileCounter:0,_validFileCounter:0,init:function(t,e){this._rejectedFiles={size:[],type:[],limit:[]},this.$element=t,this.allowedKinds=null,this._extensionList=null,this._totalFileCounter=0,this._validFileCounter=0;var i=(e=$.extend({},Craft.Uploader.defaults,e)).events;for(var s in delete e.events,e.allowedKinds&&e.allowedKinds.length&&("string"==typeof e.allowedKinds&&(e.allowedKinds=[e.allowedKinds]),this.allowedKinds=e.allowedKinds,delete e.allowedKinds),e.autoUpload=!1,this.uploader=this.$element.fileupload(e),i)i.hasOwnProperty(s)&&this.uploader.on(s,i[s]);this.settings=e,this.uploader.on("fileuploadadd",this.onFileAdd.bind(this))},setParams:function(t){void 0!==Craft.csrfTokenName&&void 0!==Craft.csrfTokenValue&&(t[Craft.csrfTokenName]=Craft.csrfTokenValue),this.uploader.fileupload("option",{formData:t})},getInProgress:function(){return this.uploader.fileupload("active")},isLastUpload:function(){return this.getInProgress()<2},onFileAdd:function(t,e){var i=this;t.stopPropagation();var s=!1;return this.allowedKinds&&(this._extensionList||this._createExtensionList(),s=!0),e.process().done((function(){var t=e.files[0],a=!0;if(s){var n=t.name.match(/\.([a-z0-4_]+)$/i)[1];-1===$.inArray(n.toLowerCase(),i._extensionList)&&(a=!1,i._rejectedFiles.type.push("“"+t.name+"”"))}t.size>i.settings.maxFileSize&&(i._rejectedFiles.size.push("“"+t.name+"”"),a=!1),a&&"function"==typeof i.settings.canAddMoreFiles&&!i.settings.canAddMoreFiles(i._validFileCounter)&&(i._rejectedFiles.limit.push("“"+t.name+"”"),a=!1),a&&(i._validFileCounter++,e.submit()),++i._totalFileCounter===e.originalFiles.length&&(i._totalFileCounter=0,i._validFileCounter=0,i.processErrorMessages())})),!0},processErrorMessages:function(){var t;this._rejectedFiles.type.length&&(t=1===this._rejectedFiles.type.length?"The file {files} could not be uploaded. The allowed file kinds are: {kinds}.":"The files {files} could not be uploaded. The allowed file kinds are: {kinds}.",t=Craft.t("app",t,{files:this._rejectedFiles.type.join(", "),kinds:this.allowedKinds.join(", ")}),this._rejectedFiles.type=[],alert(t)),this._rejectedFiles.size.length&&(t=1===this._rejectedFiles.size.length?"The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.":"The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.",t=Craft.t("app",t,{files:this._rejectedFiles.size.join(", "),size:this.humanFileSize(Craft.maxUploadSize)}),this._rejectedFiles.size=[],alert(t)),this._rejectedFiles.limit.length&&(t=1===this._rejectedFiles.limit.length?"The file {files} could not be uploaded, because the field limit has been reached.":"The files {files} could not be uploaded, because the field limit has been reached.",t=Craft.t("app",t,{files:this._rejectedFiles.limit.join(", ")}),this._rejectedFiles.limit=[],alert(t))},humanFileSize:function(t){var e=1024;if(t<e)return t+" B";var i=-1;do{t/=e,++i}while(t>=e);return t.toFixed(1)+" "+["kB","MB","GB","TB","PB","EB","ZB","YB"][i]},_createExtensionList:function(){this._extensionList=[];for(var t=0;t<this.allowedKinds.length;t++){var e=this.allowedKinds[t];if(void 0!==Craft.fileKinds[e])for(var i=0;i<Craft.fileKinds[e].extensions.length;i++){var s=Craft.fileKinds[e].extensions[i];this._extensionList.push(s)}}},destroy:function(){this.$element.fileupload("destroy"),this.base()}},{defaults:{dropZone:null,pasteZone:null,fileInput:null,sequentialUploads:!0,maxFileSize:Craft.maxUploadSize,allowedKinds:null,events:{},canAddMoreFiles:null,headers:{Accept:"application/json;q=0.9,*/*;q=0.8"},paramName:"assets-upload"}})},7e3:function(){Craft.UriFormatGenerator=Craft.BaseInputGenerator.extend({generateTargetValue:function(t){t=(t=t.replace("/<(.*?)>/g","")).toLowerCase(),t=(t=(t=Craft.asciiString(t)).replace(/^[^a-z]+/,"")).replace(/[^a-z0-9]+$/,"");var e=Craft.filterArray(t.split(/[^a-z0-9]+/)).join(Craft.slugWordSeparator);return e&&this.settings.suffix&&(e+=this.settings.suffix),e}})},8654:function(){Craft.UserIndex=Craft.BaseElementIndex.extend({init:function(t,e,i){this.on("selectSource",this.updateUrl.bind(this)),this.base(t,e,i)},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultSourceSlug)for(var t=0;t<this.$sources.length;t++){var e=$(this.$sources[t]);if(e.data("slug")===defaultSourceSlug)return e.data("key")}return this.base()},updateUrl:function(){if("index"===this.settings.context&&"undefined"!=typeof history){var t="users",e=this.$source.data("slug");e&&(t+="/".concat(e)),history.replaceState({},"",Craft.getUrl(t))}}}),Craft.registerElementIndexClass("craft\\elements\\User",Craft.UserIndex)},5537:function(){},9383:function(){},6558:function(t,e,i){var s=i(5537);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("3790022a",s,!0,{})},2179:function(t,e,i){var s=i(9383);s.__esModule&&(s=s.default),"string"==typeof s&&(s=[[t.id,s,""]]),s.locals&&(t.exports=s.locals),(0,i(9673).Z)("80058a3c",s,!0,{})},9673:function(t,e,i){"use strict";function s(t,e){for(var i=[],s={},a=0;a<e.length;a++){var n=e[a],r=n[0],o={id:t+":"+a,css:n[1],media:n[2],sourceMap:n[3]};s[r]?s[r].parts.push(o):i.push(s[r]={id:r,parts:[o]})}return i}i.d(e,{Z:function(){return g}});var a="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!a)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var n={},r=a&&(document.head||document.getElementsByTagName("head")[0]),o=null,l=0,h=!1,d=function(){},c=null,u="data-vue-ssr-id",p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function g(t,e,i,a){h=i,c=a||{};var r=s(t,e);return f(r),function(e){for(var i=[],a=0;a<r.length;a++){var o=r[a];(l=n[o.id]).refs--,i.push(l)}for(e?f(r=s(t,e)):r=[],a=0;a<i.length;a++){var l;if(0===(l=i[a]).refs){for(var h=0;h<l.parts.length;h++)l.parts[h]();delete n[l.id]}}}}function f(t){for(var e=0;e<t.length;e++){var i=t[e],s=n[i.id];if(s){s.refs++;for(var a=0;a<s.parts.length;a++)s.parts[a](i.parts[a]);for(;a<i.parts.length;a++)s.parts.push(v(i.parts[a]));s.parts.length>i.parts.length&&(s.parts.length=i.parts.length)}else{var r=[];for(a=0;a<i.parts.length;a++)r.push(v(i.parts[a]));n[i.id]={id:i.id,refs:1,parts:r}}}}function m(){var t=document.createElement("style");return t.type="text/css",r.appendChild(t),t}function v(t){var e,i,s=document.querySelector("style["+u+'~="'+t.id+'"]');if(s){if(h)return d;s.parentNode.removeChild(s)}if(p){var a=l++;s=o||(o=m()),e=b.bind(null,s,a,!1),i=b.bind(null,s,a,!0)}else s=m(),e=_.bind(null,s),i=function(){s.parentNode.removeChild(s)};return e(t),function(s){if(s){if(s.css===t.css&&s.media===t.media&&s.sourceMap===t.sourceMap)return;e(t=s)}else i()}}var $,C=($=[],function(t,e){return $[t]=e,$.filter(Boolean).join("\n")});function b(t,e,i,s){var a=i?"":s.css;if(t.styleSheet)t.styleSheet.cssText=C(e,a);else{var n=document.createTextNode(a),r=t.childNodes;r[e]&&t.removeChild(r[e]),r.length?t.insertBefore(n,r[e]):t.appendChild(n)}}function _(t,e){var i=e.css,s=e.media,a=e.sourceMap;if(s&&t.setAttribute("media",s),c.ssrId&&t.setAttribute(u,e.id),a&&(i+="\n/*# sourceURL="+a.sources[0]+" */",i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"),t.styleSheet)t.styleSheet.cssText=i;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(i))}}}},i={};function s(e){var a=i[e];if(void 0!==a)return a.exports;var n=i[e]={id:e,exports:{}};return t[e](n,n.exports,s),n.exports}s.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return s.d(e,{a:e}),e},s.d=function(t,e){for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},s.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},function(){"use strict";s(2179),s(6558),s(587),s(1504),s(5774),s(8495),s(5970),s(4993),s(8843),s(7745),s(7452),s(76),s(6872),s(2495),s(5077),s(4606),s(9222),s(525),s(3778),s(6617),s(9482),s(3352),s(691),s(1519),s(501),s(1923),s(2318),s(4755),s(8468),s(8895),s(4233),s(9699),s(1402),s(8201),s(3347),s(9478),s(2387),s(7966),s(657),s(4487),s(6966),s(5080),s(7439),s(5328),s(6419),s(872),s(1396),s(5759),s(4070),s(5763),s(5185),s(8030),s(3096),s(3331),s(53),s(5074),s(3958),s(1592),s(1752),s(7e3),s(8654)}()}();
 //# sourceMappingURL=cp.js.map
\ No newline at end of file

programming_language: JavaScript
filename: cp.js.map
change_type: ModificationType.MODIFY
diff: @@ -1 +1 @@
-{"version":3,"file":"cp.js","mappings":"mCAKAA,MAAMC,WAAaC,QAAQC,KAAKC,OAC9B,CACEC,SAAU,KACVC,WAAY,KACZC,OAAQ,KAERC,SAAU,KACVC,OAAQ,KACRC,OAAQ,KACRC,YAAa,KAEbC,KAAM,SAAUP,GACdQ,KAAKC,YAAYT,EAAUL,MAAMC,WAAWc,UAEvCF,KAAKR,SAASW,iBACjBH,KAAKR,SAASY,SAAW,GAG3BJ,KAAKL,SAAWU,EAAEL,KAAKR,SAASc,iBAChCN,KAAKJ,OAASS,EAAEL,KAAKR,SAASe,eAC9BP,KAAKH,OAASG,KAAKJ,OAAOY,SAAS,SACnCR,KAAKP,WAAaO,KAAKH,OAAOW,WAAWC,OAErCT,KAAKR,SAASkB,WAChBV,KAAKN,OAAS,IAAIP,MAAMwB,gBAAgBX,KAAKJ,OAAQ,CACnDgB,aAAcZ,KAAKa,aAAaC,KAAKd,SAIzCA,KAAKF,YAAcE,KAAKJ,OAAOmB,KAAK,0BACpCf,KAAKgB,YAAYhB,KAAKF,YAAa,QAAS,wBAE5CE,KAAKiB,YAGPC,OAAQ,SAAUC,GAChB,KAAInB,KAAKR,SAAS4B,UAAYpB,KAAKP,YAAcO,KAAKR,SAAS4B,UAA/D,CAKA,IAAIC,EAAOhB,EAAEc,GAAKG,SAAStB,KAAKH,QAC9B0B,EAAaF,EAAKN,KAAK,WAErBf,KAAKR,SAASkB,UAChBV,KAAKN,OAAO8B,SAASH,GAGvBrB,KAAKF,YAAcE,KAAKF,YAAY2B,IAAIF,GAExCvB,KAAKgB,YAAYO,EAAY,QAAS,wBACtCvB,KAAKP,aAELO,KAAKiB,aAGPJ,aAAc,W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a,OAAOE,EAAgB,SACpC,WAAa,OAAOA,GAErB,OADAwD,EAAoBxyF,EAAE4yF,EAAQ,CAAE/yF,EAAG+yF,IAC5BA,GCLRJ,EAAoBxyF,EAAI,SAASkvF,EAAS2D,GACzC,IAAI,IAAI1pF,KAAO0pF,EACXL,EAAoB1yC,EAAE+yC,EAAY1pF,KAASqpF,EAAoB1yC,EAAEovC,EAAS/lF,IAC5Ek2B,OAAOyzD,eAAe5D,EAAS/lF,EAAK,CAAE4pF,YAAY,EAAMnlG,IAAKilG,EAAW1pF,MCJ3EqpF,EAAoB1yC,EAAI,SAASnH,EAAKznC,GAAQ,OAAOmuB,OAAO2zD,UAAUp9D,eAAexP,KAAKuyB,EAAKznC,I","sources":["webpack:///./js/AdminTable.js","webpack:///./js/AssetEditor.js","webpack:///./js/AssetImageEditor.js","webpack:///./js/AssetIndex.js","webpack:///./js/AssetSelectInput.js","webpack:///./js/AssetSelectorModal.js","webpack:///./js/AuthManager.js","webpack:///./js/BaseElementEditor.js","webpack:///./js/BaseElementIndex.js","webpack:///./js/BaseElementIndexView.js","webpack:///./js/BaseElementSelectInput.js","webpack:///./js/BaseElementSelectorModal.js","webpack:///./js/BaseInputGenerator.js","webpack:///./js/CP.js","webpack:///./js/CategoryIndex.js","webpack:///./js/CategorySelectInput.js","webpack:///./js/Chart.js","webpack:///./js/ColorInput.js","webpack:///./js/Craft.js","webpack:///./js/CustomizeSourcesModal.js","webpack:///./js/DataTableSorter.js","webpack:///./js/DeleteUserModal.js","webpack:///./js/DraftEditor.js","webpack:///./js/DynamicGenerator.js","webpack:///./js/EditableTable.js","webpack:///./js/ElementActionTrigger.js","webpack:///./js/ElementThumbLoader.js","webpack:///./js/ElevatedSessionForm.js","webpack:///./js/ElevatedSessionManager.js","webpack:///./js/EntryIndex.js","webpack:///./js/FieldLayoutDesigner.js","webpack:///./js/FieldToggle.js","webpack:///./js/Grid.js","webpack:///./js/HandleGenerator.js","webpack:///./js/ImageUpload.js","webpack:///./js/InfoIcon.js","webpack:///./js/LightSwitch.js","webpack:///./js/Listbox.js","webpack:///./js/LivePreview.js","webpack:///./js/PasswordInput.js","webpack:///./js/Preview.js","webpack:///./js/PreviewFileModal.js","webpack:///./js/ProgressBar.js","webpack:///./js/PromptHandler.js","webpack:///./js/SlidePicker.js","webpack:///./js/SlideRuleInput.js","webpack:///./js/Slideout.js","webpack:///./js/SlugGenerator.js","webpack:///./js/Structure.js","webpack:///./js/StructureDrag.js","webpack:///./js/StructureTableSorter.js","webpack:///./js/TableElementIndexView.js","webpack:///./js/Tabs.js","webpack:///./js/TagSelectInput.js","webpack:///./js/ThumbsElementIndexView.js","webpack:///./js/UI.js","webpack:///./js/Uploader.js","webpack:///./js/UriFormatGenerator.js","webpack:///./js/UserIndex.js","webpack:///./css/charts.scss?4afb","webpack:///./css/craft.scss?1b58","webpack:///../../../../../node_modules/vue-style-loader/lib/listToStyles.js","webpack:///../../../../../node_modules/vue-style-loader/lib/addStylesClient.js","webpack:///webpack/bootstrap","webpack:///webpack/runtime/compat get default export","webpack:///webpack/runtime/define property getters","webpack:///webpack/runtime/hasOwnProperty shorthand"],"sourcesContent":["/** global: Craft */\n/** global: Garnish */\n/**\n * Admin table class\n */\nCraft.AdminTable = Garnish.Base.extend(\n  {\n    settings: null,\n    totalItems: null,\n    sorter: null,\n\n    $noItems: null,\n    $table: null,\n    $tbody: null,\n    $deleteBtns: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.AdminTable.defaults);\n\n      if (!this.settings.allowDeleteAll) {\n        this.settings.minItems = 1;\n      }\n\n      this.$noItems = $(this.settings.noItemsSelector);\n      this.$table = $(this.settings.tableSelector);\n      this.$tbody = this.$table.children('tbody');\n      this.totalItems = this.$tbody.children().length;\n\n      if (this.settings.sortable) {\n        this.sorter = new Craft.DataTableSorter(this.$table, {\n          onSortChange: this.reorderItems.bind(this),\n        });\n      }\n\n      this.$deleteBtns = this.$table.find('.delete:not(.disabled)');\n      this.addListener(this.$deleteBtns, 'click', 'handleDeleteBtnClick');\n\n      this.updateUI();\n    },\n\n    addRow: function (row) {\n      if (this.settings.maxItems && this.totalItems >= this.settings.maxItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(row).appendTo(this.$tbody),\n        $deleteBtn = $row.find('.delete');\n\n      if (this.settings.sortable) {\n        this.sorter.addItems($row);\n      }\n\n      this.$deleteBtns = this.$deleteBtns.add($deleteBtn);\n\n      this.addListener($deleteBtn, 'click', 'handleDeleteBtnClick');\n      this.totalItems++;\n\n      this.updateUI();\n    },\n\n    reorderItems: function () {\n      if (!this.settings.sortable) {\n        return;\n      }\n\n      // Get the new field order\n      var ids = [];\n\n      for (var i = 0; i < this.sorter.$items.length; i++) {\n        var id = $(this.sorter.$items[i]).attr(this.settings.idAttribute);\n        ids.push(id);\n      }\n\n      // Send it to the server\n      var data = {\n        ids: JSON.stringify(ids),\n      };\n\n      Craft.postActionRequest(\n        this.settings.reorderAction,\n        data,\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            if (response.success) {\n              this.onReorderItems(ids);\n              Craft.cp.displayNotice(\n                Craft.t('app', this.settings.reorderSuccessMessage)\n              );\n            } else {\n              Craft.cp.displayError(\n                Craft.t('app', this.settings.reorderFailMessage)\n              );\n            }\n          }\n        }\n      );\n    },\n\n    handleDeleteBtnClick: function (event) {\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(event.target).closest('tr');\n\n      if (this.confirmDeleteItem($row)) {\n        this.deleteItem($row);\n      }\n    },\n\n    confirmDeleteItem: function ($row) {\n      var name = this.getItemName($row);\n      return confirm(\n        Craft.t('app', this.settings.confirmDeleteMessage, {name})\n      );\n    },\n\n    deleteItem: function ($row) {\n      var data = {\n        id: this.getItemId($row),\n      };\n\n      Craft.postActionRequest(\n        this.settings.deleteAction,\n        data,\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.handleDeleteItemResponse(response, $row);\n          }\n        }\n      );\n    },\n\n    handleDeleteItemResponse: function (response, $row) {\n      var id = this.getItemId($row),\n        name = this.getItemName($row);\n\n      if (response.success) {\n        if (this.sorter) {\n          this.sorter.removeItems($row);\n        }\n\n        $row.remove();\n        this.totalItems--;\n        this.updateUI();\n        this.onDeleteItem(id);\n\n        Craft.cp.displayNotice(\n          Craft.t('app', this.settings.deleteSuccessMessage, {name})\n        );\n      } else {\n        Craft.cp.displayError(\n          Craft.t('app', this.settings.deleteFailMessage, {name})\n        );\n      }\n    },\n\n    onReorderItems: function (ids) {\n      this.settings.onReorderItems(ids);\n    },\n\n    onDeleteItem: function (id) {\n      this.settings.onDeleteItem(id);\n    },\n\n    getItemId: function ($row) {\n      return $row.attr(this.settings.idAttribute);\n    },\n\n    getItemName: function ($row) {\n      return Craft.escapeHtml($row.attr(this.settings.nameAttribute));\n    },\n\n    updateUI: function () {\n      // Show the \"No Whatever Exists\" message if there aren't any\n      if (this.totalItems === 0) {\n        this.$table.hide();\n        this.$noItems.removeClass('hidden');\n      } else {\n        this.$table.show();\n        this.$noItems.addClass('hidden');\n      }\n\n      // Disable the sort buttons if there's only one row\n      if (this.settings.sortable) {\n        var $moveButtons = this.$table.find('.move');\n\n        if (this.totalItems === 1) {\n          $moveButtons.addClass('disabled');\n        } else {\n          $moveButtons.removeClass('disabled');\n        }\n      }\n\n      // Disable the delete buttons if we've reached the minimum items\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        this.$deleteBtns.addClass('disabled');\n      } else {\n        this.$deleteBtns.removeClass('disabled');\n      }\n\n      // Hide the New Whatever button if we've reached the maximum items\n      if (this.settings.newItemBtnSelector) {\n        if (\n          this.settings.maxItems &&\n          this.totalItems >= this.settings.maxItems\n        ) {\n          $(this.settings.newItemBtnSelector).addClass('hidden');\n        } else {\n          $(this.settings.newItemBtnSelector).removeClass('hidden');\n        }\n      }\n    },\n  },\n  {\n    defaults: {\n      tableSelector: null,\n      noItemsSelector: null,\n      newItemBtnSelector: null,\n      idAttribute: 'data-id',\n      nameAttribute: 'data-name',\n      sortable: false,\n      allowDeleteAll: true,\n      minItems: 0,\n      maxItems: null,\n      reorderAction: null,\n      deleteAction: null,\n      reorderSuccessMessage: Craft.t('app', 'New order saved.'),\n      reorderFailMessage: Craft.t('app', 'Couldn’t save new order.'),\n      confirmDeleteMessage: Craft.t(\n        'app',\n        'Are you sure you want to delete “{name}”?'\n      ),\n      deleteSuccessMessage: Craft.t('app', '“{name}” deleted.'),\n      deleteFailMessage: Craft.t('app', 'Couldn’t delete “{name}”.'),\n      onReorderItems: $.noop,\n      onDeleteItem: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset index class\n */\nCraft.AssetEditor = Craft.BaseElementEditor.extend({\n  $filenameInput: null,\n\n  originalBasename: null,\n  originalExtension: null,\n  reloadIndex: false,\n\n  init: function (element, settings) {\n    this.on('updateForm', () => {\n      this.addListener(\n        this.$sidebar.find('.preview-thumb-container .edit-btn'),\n        'click',\n        'showImageEditor'\n      );\n      this.addListener(\n        this.$sidebar.find('.preview-thumb-container .preview-btn'),\n        'click',\n        'showImagePreview'\n      );\n\n      this.$filenameInput = this.$sidebar.find('.filename');\n      this.addListener(this.$filenameInput, 'focus', 'selectFilename');\n    });\n\n    this.on('closeSlideout', () => {\n      if (this.reloadIndex) {\n        if (this.settings.elementIndex) {\n          this.settings.elementIndex.updateElements();\n        } else if (this.settings.input) {\n          this.settings.input.refreshThumbnail(this.$element.data('id'));\n        }\n      }\n    });\n\n    this.base(element, settings);\n\n    this.settings.validators.push(() => this.validateExtension());\n  },\n\n  showImageEditor: function () {\n    new Craft.AssetImageEditor(this.$element.data('id'), {\n      onSave: () => {\n        this.reloadIndex = true;\n        this.load();\n      },\n    });\n  },\n\n  showImagePreview: function () {\n    var settings = {};\n\n    if (this.$element.data('image-width')) {\n      settings.startingWidth = this.$element.data('image-width');\n      settings.startingHeight = this.$element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(this.$element.data('id'), null, settings);\n  },\n\n  selectFilename: function () {\n    if (typeof this.$filenameInput[0].selectionStart === 'undefined') {\n      return;\n    }\n\n    const {basename, extension} = this._parseFilename();\n\n    if (this.originalBasename === null) {\n      this.originalBasename = basename;\n      this.originalExtension = extension;\n    }\n\n    this.$filenameInput[0].selectionStart = 0;\n    this.$filenameInput[0].selectionEnd = basename.length;\n\n    // Prevent the selection from changing by the mouseup event\n    this.$filenameInput.one('mouseup.keepselection', (ev) => {\n      ev.preventDefault();\n    });\n    setTimeout(() => {\n      this.$filenameInput.off('mouseup.keepselection');\n    }, 500);\n  },\n\n  validateExtension: function () {\n    if (this.originalBasename === null) {\n      return true;\n    }\n\n    const {basename, extension} = this._parseFilename();\n\n    if (extension === this.originalExtension) {\n      return true;\n    }\n\n    // No extension?\n    if (!extension) {\n      // If filename changed as well, assume removal of extension a mistake\n      if (this.originalFilename !== basename) {\n        this.$filenameInput.val(\n          `${Craft.rtrim(basename, '.')}.${this.originalExtension}`\n        );\n        return true;\n      }\n\n      // If filename hasn't changed, make sure they want to remove extension\n      return confirm(\n        Craft.t(\n          'app',\n          'Are you sure you want to remove the extension “.{ext}”?',\n          {\n            ext: this.originalExtension,\n          }\n        )\n      );\n    }\n\n    // If the extension has changed, make sure it's intentional\n    return confirm(\n      Craft.t(\n        'app',\n        'Are you sure you want to change the extension from “.{oldExt}” to “.{newExt}”?',\n        {\n          oldExt: this.originalExtension,\n          newExt: extension,\n        }\n      )\n    );\n  },\n\n  _parseFilename: function () {\n    const parts = this.$filenameInput.val().split('.');\n    const extension = parts.length > 1 ? parts.pop() : null;\n    const basename = parts.join('.');\n    return {basename, extension};\n  },\n});\n\n// Register it!\nCraft.registerElementEditorClass('craft\\\\elements\\\\Asset', Craft.AssetEditor);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Asset image editor class\n */\n\nCraft.AssetImageEditor = Garnish.Modal.extend(\n  {\n    // jQuery objects\n    $body: null,\n    $footer: null,\n    $imageTools: null,\n    $buttons: null,\n    $cancelBtn: null,\n    $replaceBtn: null,\n    $saveBtn: null,\n    $editorContainer: null,\n    $straighten: null,\n    $croppingCanvas: null,\n    $spinnerCanvas: null,\n\n    // FabricJS objects\n    canvas: null,\n    image: null,\n    viewport: null,\n    focalPoint: null,\n    grid: null,\n    croppingCanvas: null,\n    clipper: null,\n    croppingRectangle: null,\n    cropperHandles: null,\n    cropperGrid: null,\n    croppingShade: null,\n\n    // Image state attributes\n    imageStraightenAngle: 0,\n    viewportRotation: 0,\n    originalWidth: 0,\n    originalHeight: 0,\n    imageVerticeCoords: null,\n    zoomRatio: 1,\n\n    // Editor state attributes\n    animationInProgress: false,\n    currentView: '',\n    assetId: null,\n    cacheBust: null,\n    draggingCropper: false,\n    scalingCropper: false,\n    draggingFocal: false,\n    previousMouseX: 0,\n    previousMouseY: 0,\n    shiftKeyHeld: false,\n    editorHeight: 0,\n    editorWidth: 0,\n    cropperState: false,\n    scaleFactor: 1,\n    flipData: {},\n    focalPointState: false,\n    spinnerInterval: null,\n    maxImageSize: null,\n    lastLoadedDimensions: null,\n    imageIsLoading: false,\n    mouseMoveEvent: null,\n    croppingConstraint: false,\n    constraintOrientation: 'landscape',\n    showingCustomConstraint: false,\n\n    // Rendering proxy functions\n    renderImage: null,\n    renderCropper: null,\n\n    init: function (assetId, settings) {\n      this.cacheBust = Date.now();\n\n      this.setSettings(settings, Craft.AssetImageEditor.defaults);\n\n      if (this.settings.allowDegreeFractions === null) {\n        this.settings.allowDegreeFractions = Craft.isImagick;\n      }\n\n      this.assetId = assetId;\n      this.flipData = {x: 0, y: 0};\n\n      // Build the modal\n      this.$container = $(\n        '<form class=\"modal fitted imageeditor\"></form>'\n      ).appendTo(Garnish.$bod);\n      this.$body = $('<div class=\"body\"></div>').appendTo(this.$container);\n      this.$footer = $('<div class=\"footer\"/>').appendTo(this.$container);\n\n      this.base(this.$container, this.settings);\n\n      this.$buttons = $('<div class=\"buttons right\"/>').appendTo(this.$footer);\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn cancel',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$buttons);\n      this.$replaceBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn submit save replace',\n        text: Craft.t('app', 'Save'),\n      }).appendTo(this.$buttons);\n\n      if (this.settings.allowSavingAsNew) {\n        this.$saveBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit save copy',\n          text: Craft.t('app', 'Save as a new asset'),\n        }).appendTo(this.$buttons);\n        this.addListener(this.$saveBtn, 'activate', this.saveImage);\n      }\n\n      this.addListener(this.$replaceBtn, 'activate', this.saveImage);\n      this.addListener(this.$cancelBtn, 'activate', this.hide);\n      this.removeListener(this.$shade, 'click');\n\n      this.maxImageSize = this.getMaxImageSize();\n      Craft.postActionRequest(\n        'assets/image-editor',\n        {assetId},\n        this.loadEditor.bind(this)\n      );\n    },\n\n    /**\n     * Get the max image size that is viewable in the editor currently\n     */\n    getMaxImageSize: function () {\n      var browserViewportWidth =\n        Garnish.$doc.get(0).documentElement.clientWidth;\n      var browserViewportHeight =\n        Garnish.$doc.get(0).documentElement.clientHeight;\n\n      return (\n        Math.max(browserViewportHeight, browserViewportWidth) *\n        (window.devicePixelRatio > 1 ? 2 : 1)\n      );\n    },\n\n    /**\n     * Load the editor markup and start loading components and the image.\n     *\n     * @param data\n     */\n    loadEditor: function (data) {\n      if (!data.html) {\n        alert(Craft.t('app', 'Could not load the image editor.'));\n      }\n\n      this.$body.html(data.html);\n      this.$tabs = $('.tabs li', this.$body);\n      this.$viewsContainer = $('.views', this.$body);\n      this.$views = $('> div', this.$viewsContainer);\n      this.$imageTools = $('.image-container .image-tools', this.$body);\n      this.$editorContainer = $('.image-container .image', this.$body);\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this._showSpinner();\n\n      this.updateSizeAndPosition();\n\n      // Load the canvas on which we'll host our image and set up the proxy render function\n      this.canvas = new fabric.StaticCanvas('image-canvas');\n\n      // Set up the cropping canvas jquery element for tracking all the nice events\n      this.$croppingCanvas = $('#cropping-canvas', this.$editorContainer);\n      this.$croppingCanvas.width(this.editorWidth);\n      this.$croppingCanvas.height(this.editorHeight);\n\n      this.canvas.enableRetinaScaling = true;\n      this.renderImage = () => {\n        Garnish.requestAnimationFrame(this.canvas.renderAll.bind(this.canvas));\n      };\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      // Load image and set up the initial properties\n      fabric.Image.fromURL(imageUrl, (imageObject) => {\n        this.image = imageObject;\n        this.image.set({\n          originX: 'center',\n          originY: 'center',\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        });\n        this.canvas.add(this.image);\n\n        this.originalHeight = this.image.getHeight();\n        this.originalWidth = this.image.getWidth();\n        this.zoomRatio = 1;\n\n        this.lastLoadedDimensions = this.getScaledImageDimensions();\n\n        // Set up the image bounding box, viewport and position everything\n        this._setFittedImageVerticeCoordinates();\n        this._repositionEditorElements();\n\n        // Set up the focal point\n        var focalState = {\n          imageDimensions: this.getScaledImageDimensions(),\n          offsetX: 0,\n          offsetY: 0,\n        };\n\n        var focal = false;\n        if (data.focalPoint) {\n          // Transform the focal point coordinates from relative to absolute\n          var focalData = data.focalPoint;\n\n          // Resolve for the current image dimensions.\n          var adjustedX = focalState.imageDimensions.width * focalData.x;\n          var adjustedY = focalState.imageDimensions.height * focalData.y;\n\n          focalState.offsetX = adjustedX - focalState.imageDimensions.width / 2;\n          focalState.offsetY =\n            adjustedY - focalState.imageDimensions.height / 2;\n\n          focal = true;\n        }\n\n        this.storeFocalPointState(focalState);\n\n        if (focal) {\n          this._createFocalPoint();\n        }\n\n        this._createViewport();\n        this.storeCropperState();\n\n        // Add listeners to buttons\n        this._addControlListeners();\n\n        // Add mouse event listeners\n        this.addListener(\n          this.$croppingCanvas,\n          'mousemove,touchmove',\n          this._handleMouseMove\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mousedown,touchstart',\n          this._handleMouseDown\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseup,touchend',\n          this._handleMouseUp\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseout,touchcancel',\n          this._handleMouseOut\n        );\n\n        this._hideSpinner();\n\n        // Render it, finally\n        this.renderImage();\n\n        // Make sure verything gets fired for the first tab\n        this.$tabs.first().trigger('click');\n      });\n    },\n\n    /**\n     * Reload the image to better fit the current available image editor viewport.\n     */\n    _reloadImage: function () {\n      if (this.imageIsLoading) {\n        return;\n      }\n\n      this.imageIsLoading = true;\n      this.maxImageSize = this.getMaxImageSize();\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      this.image.setSrc(imageUrl, (imageObject) => {\n        this.originalHeight = imageObject.getHeight();\n        this.originalWidth = imageObject.getWidth();\n        this.lastLoadedDimensions = {\n          width: this.originalHeight,\n          height: this.originalWidth,\n        };\n        this.updateSizeAndPosition();\n        this.renderImage();\n        this.imageIsLoading = false;\n      });\n    },\n\n    /**\n     * Update the modal size and position on browser resize\n     */\n    updateSizeAndPosition: function () {\n      if (!this.$container) {\n        return;\n      }\n\n      // Fullscreen modal\n      var innerWidth = window.innerWidth;\n      var innerHeight = window.innerHeight;\n\n      this.$container.css({\n        width: innerWidth,\n        'min-width': innerWidth,\n        left: 0,\n\n        height: innerHeight,\n        'min-height': innerHeight,\n        top: 0,\n      });\n\n      this.$body.css({\n        height: innerHeight - 62,\n      });\n\n      if (innerWidth < innerHeight) {\n        this.$container.addClass('vertical');\n      } else {\n        this.$container.removeClass('vertical');\n      }\n\n      if (this.$spinnerCanvas) {\n        this.$spinnerCanvas.css({\n          left:\n            this.$spinnerCanvas.parent().width() / 2 -\n            this.$spinnerCanvas.width() / 2 +\n            'px',\n          top:\n            this.$spinnerCanvas.parent().height() / 2 -\n            this.$spinnerCanvas.height() / 2 +\n            'px',\n        });\n      }\n\n      // If image is already loaded, make sure it looks pretty.\n      if (this.$editorContainer && this.image) {\n        this._repositionEditorElements();\n      }\n    },\n\n    /**\n     * Reposition the editor elements to accurately reflect the editor state with current dimensions\n     */\n    _repositionEditorElements: function () {\n      // Remember what the dimensions were before the resize took place\n      var previousEditorDimensions = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this.canvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      var currentScaledDimensions = this.getScaledImageDimensions();\n\n      // If we're cropping now, we have to reposition the cropper correctly in case\n      // the area for image changes, forcing the image size to change as well.\n      if (this.currentView === 'crop') {\n        this.zoomRatio = this.getZoomToFitRatio(\n          this.getScaledImageDimensions()\n        );\n        var previouslyOccupiedArea = this._getBoundingRectangle(\n          this.imageVerticeCoords\n        );\n        this._setFittedImageVerticeCoordinates();\n        this._repositionCropper(previouslyOccupiedArea);\n      } else {\n        // Otherwise just recalculate the image zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n      }\n\n      // Reposition the image relatively to the previous editor dimensions.\n      this._repositionImage(previousEditorDimensions);\n      this._repositionViewport();\n      this._repositionFocalPoint(previousEditorDimensions);\n      this._zoomImage();\n\n      this.renderImage();\n\n      if (\n        currentScaledDimensions.width / this.lastLoadedDimensions.width > 1.5 ||\n        currentScaledDimensions.height / this.lastLoadedDimensions.height > 1.5\n      ) {\n        this._reloadImage();\n      }\n    },\n\n    /**\n     * Reposition image based on how the editor dimensions have changed.\n     * This ensures keeping the image center offset, if there is any.\n     *\n     * @param previousEditorDimensions\n     */\n    _repositionImage: function (previousEditorDimensions) {\n      this.image.set({\n        left:\n          this.image.left -\n          (previousEditorDimensions.width - this.editorWidth) / 2,\n        top:\n          this.image.top -\n          (previousEditorDimensions.height - this.editorHeight) / 2,\n      });\n    },\n\n    /**\n     * Create the viewport for image editor.\n     */\n    _createViewport: function () {\n      this.viewport = new fabric.Rect({\n        width: this.image.width,\n        height: this.image.height,\n        fill: 'rgba(127,0,0,1)',\n        originX: 'center',\n        originY: 'center',\n        globalCompositeOperation: 'destination-in', // This clips everything outside of the viewport\n        left: this.image.left,\n        top: this.image.top,\n      });\n      this.canvas.add(this.viewport);\n      this.renderImage();\n    },\n\n    /**\n     * Create the focal point.\n     */\n    _createFocalPoint: function () {\n      var focalPointState = this.focalPointState;\n      var sizeFactor =\n        this.getScaledImageDimensions().width /\n        focalPointState.imageDimensions.width;\n\n      var focalX =\n        focalPointState.offsetX *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n      var focalY =\n        focalPointState.offsetY *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n\n      // Adjust by image margins\n      focalX += this.image.left;\n      focalY += this.image.top;\n\n      var deltaX = 0;\n      var deltaY = 0;\n\n      // When creating a fresh focal point, drop it dead in the center of the viewport, not the image.\n      if (\n        this.viewport &&\n        focalPointState.offsetX === 0 &&\n        focalPointState.offsetY === 0\n      ) {\n        if (this.currentView !== 'crop') {\n          deltaX = this.viewport.left - this.image.left;\n          deltaY = this.viewport.top - this.image.top;\n        } else {\n          // Unless we have a cropper showing, in which case drop it in the middle of the cropper\n          deltaX = this.clipper.left - this.image.left;\n          deltaY = this.clipper.top - this.image.top;\n        }\n\n        // Bump focal to middle of viewport\n        focalX += deltaX;\n        focalY += deltaY;\n\n        // Reflect changes in saved state\n        focalPointState.offsetX +=\n          deltaX / (sizeFactor * this.zoomRatio * this.scaleFactor);\n        focalPointState.offsetY +=\n          deltaY / (sizeFactor * this.zoomRatio * this.scaleFactor);\n      }\n\n      this.focalPoint = new fabric.Group(\n        [\n          new fabric.Circle({\n            radius: 8,\n            fill: 'rgba(0,0,0,0.5)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n          new fabric.Circle({\n            radius: 1,\n            fill: 'rgba(255,255,255,0)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n        ],\n        {\n          originX: 'center',\n          originY: 'center',\n          left: focalX,\n          top: focalY,\n        }\n      );\n\n      this.storeFocalPointState(focalPointState);\n      this.canvas.add(this.focalPoint);\n    },\n\n    /**\n     * Toggle focal point\n     */\n    toggleFocalPoint: function () {\n      if (!this.focalPoint) {\n        this._createFocalPoint();\n      } else {\n        this.canvas.remove(this.focalPoint);\n        this.focalPoint = null;\n      }\n\n      this.renderImage();\n    },\n\n    /**\n     * Reposition the viewport to handle editor resizing.\n     */\n    _repositionViewport: function () {\n      if (this.viewport) {\n        var dimensions = {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        };\n\n        // If we're cropping, nothing exciting happens for the viewport\n        if (this.currentView === 'crop') {\n          dimensions.width = this.editorWidth;\n          dimensions.height = this.editorHeight;\n        } else {\n          // If this is the first initial reposition, no cropper state yet\n          if (this.cropperState) {\n            // Recall the state\n            var state = this.cropperState;\n\n            var scaledImageDimensions = this.getScaledImageDimensions();\n            // Make sure we have the correct current image size\n            var sizeFactor =\n              scaledImageDimensions.width / state.imageDimensions.width;\n\n            // Set the viewport dimensions\n            dimensions.width = state.width * sizeFactor * this.zoomRatio;\n            dimensions.height = state.height * sizeFactor * this.zoomRatio;\n\n            // Adjust the image position to show the correct part of the image in the viewport\n            this.image.set({\n              left: this.editorWidth / 2 - state.offsetX * sizeFactor,\n              top: this.editorHeight / 2 - state.offsetY * sizeFactor,\n            });\n          } else {\n            $.extend(dimensions, this.getScaledImageDimensions());\n          }\n        }\n        this.viewport.set(dimensions);\n      }\n    },\n\n    _repositionFocalPoint: function (previousEditorDimensions) {\n      if (this.focalPoint) {\n        var offsetX = this.focalPoint.left - this.editorWidth / 2;\n        var offsetY = this.focalPoint.top - this.editorHeight / 2;\n\n        var currentWidth = this.image.width;\n        var newWidth = this.getScaledImageDimensions().width * this.zoomRatio;\n        var ratio = newWidth / currentWidth / this.scaleFactor;\n\n        offsetX -= (previousEditorDimensions.width - this.editorWidth) / 2;\n        offsetY -= (previousEditorDimensions.height - this.editorHeight) / 2;\n\n        offsetX *= ratio;\n        offsetY *= ratio;\n\n        this.focalPoint.set({\n          left: this.editorWidth / 2 + offsetX,\n          top: this.editorHeight / 2 + offsetY,\n        });\n      }\n    },\n\n    /**\n     * Return true if the image orientation has changed\n     */\n    hasOrientationChanged: function () {\n      return this.viewportRotation % 180 !== 0;\n    },\n\n    /**\n     * Return the current image dimensions that would be used in the current image area with no straightening or rotation applied.\n     */\n    getScaledImageDimensions: function () {\n      if (typeof this.getScaledImageDimensions._ === 'undefined') {\n        this.getScaledImageDimensions._ = {};\n      }\n\n      this.getScaledImageDimensions._.imageRatio =\n        this.originalHeight / this.originalWidth;\n      this.getScaledImageDimensions._.editorRatio =\n        this.editorHeight / this.editorWidth;\n\n      this.getScaledImageDimensions._.dimensions = {};\n      if (\n        this.getScaledImageDimensions._.imageRatio >\n        this.getScaledImageDimensions._.editorRatio\n      ) {\n        this.getScaledImageDimensions._.dimensions.height = Math.min(\n          this.editorHeight,\n          this.originalHeight\n        );\n        this.getScaledImageDimensions._.dimensions.width = Math.round(\n          this.originalWidth /\n            (this.originalHeight /\n              this.getScaledImageDimensions._.dimensions.height)\n        );\n      } else {\n        this.getScaledImageDimensions._.dimensions.width = Math.min(\n          this.editorWidth,\n          this.originalWidth\n        );\n        this.getScaledImageDimensions._.dimensions.height = Math.round(\n          this.originalHeight *\n            (this.getScaledImageDimensions._.dimensions.width /\n              this.originalWidth)\n        );\n      }\n\n      return this.getScaledImageDimensions._.dimensions;\n    },\n\n    /**\n     * Set the image dimensions to reflect the current zoom ratio.\n     */\n    _zoomImage: function () {\n      if (typeof this._zoomImage._ === 'undefined') {\n        this._zoomImage._ = {};\n      }\n\n      this._zoomImage._.imageDimensions = this.getScaledImageDimensions();\n      this.image.set({\n        width: this._zoomImage._.imageDimensions.width * this.zoomRatio,\n        height: this._zoomImage._.imageDimensions.height * this.zoomRatio,\n      });\n    },\n\n    /**\n     * Set up listeners for the controls.\n     */\n    _addControlListeners: function () {\n      // Tabs\n      this.addListener(this.$tabs, 'click', this._handleTabClick);\n\n      // Focal point\n      this.addListener($('.focal-point'), 'click', this.toggleFocalPoint);\n\n      // Rotate controls\n      this.addListener($('.rotate-left'), 'click', function () {\n        this.rotateImage(-90);\n      });\n      this.addListener($('.rotate-right'), 'click', function () {\n        this.rotateImage(90);\n      });\n      this.addListener($('.flip-vertical'), 'click', function () {\n        this.flipImage('y');\n      });\n      this.addListener($('.flip-horizontal'), 'click', function () {\n        this.flipImage('x');\n      });\n\n      // Straighten slider\n      this.straighteningInput = new Craft.SlideRuleInput('slide-rule', {\n        onStart: () => {\n          this._showGrid();\n        },\n        onChange: (slider) => {\n          this.straighten(slider);\n        },\n        onEnd: () => {\n          this._hideGrid();\n          this._cleanupFocalPointAfterStraighten();\n        },\n      });\n\n      // Cropper scale modifier key\n      this.addListener(Garnish.$doc, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = true;\n        }\n      });\n      this.addListener(Garnish.$doc, 'keyup', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = false;\n        }\n      });\n\n      this.addListener(\n        $('.constraint-buttons .constraint', this.$container),\n        'click',\n        this._handleConstraintClick\n      );\n      this.addListener(\n        $('.orientation input', this.$container),\n        'click',\n        this._handleOrientationClick\n      );\n      this.addListener(\n        $('.constraint-buttons .custom-input input', this.$container),\n        'keyup',\n        this._applyCustomConstraint\n      );\n    },\n\n    /**\n     * Handle a constraint button click.\n     *\n     * @param ev\n     */\n    _handleConstraintClick: function (ev) {\n      var constraint = $(ev.currentTarget).data('constraint');\n      var $target = $(ev.currentTarget);\n      $target.siblings().removeClass('active');\n      $target.addClass('active');\n\n      if (constraint == 'custom') {\n        this._showCustomConstraint();\n        this._applyCustomConstraint();\n        return;\n      }\n\n      this._hideCustomConstraint();\n\n      this.setCroppingConstraint(constraint);\n      this.enforceCroppingConstraint();\n    },\n\n    /**\n     * Handle an orientation switch click.\n     *\n     * @param ev\n     */\n    _handleOrientationClick: function (ev) {\n      if (ev.currentTarget.value === this.constraintOrientation) {\n        return;\n      }\n      this.constraintOrientation = ev.currentTarget.value;\n\n      var $constraints = $('.constraint.flip', this.$container);\n\n      for (var i = 0; i < $constraints.length; i++) {\n        var $constraint = $($constraints[i]);\n        $constraint.data('constraint', 1 / $constraint.data('constraint'));\n        $constraint.html($constraint.html().split(':').reverse().join(':'));\n      }\n\n      $constraints.filter('.active').click();\n    },\n\n    /**\n     * Apply the custom ratio set in the inputs\n     */\n    _applyCustomConstraint: function () {\n      var constraint = this._getCustomConstraint();\n\n      if (constraint.w > 0 && constraint.h > 0) {\n        this.setCroppingConstraint(constraint.w / constraint.h);\n        this.enforceCroppingConstraint();\n      }\n    },\n\n    /**\n     * Get the custom constraint.\n     *\n     * @returns {{w: *, h: *}}\n     */\n    _getCustomConstraint: function () {\n      var w = parseFloat($('.custom-constraint-w').val());\n      var h = parseFloat($('.custom-constraint-h').val());\n      return {\n        w: isNaN(w) ? 0 : w,\n        h: isNaN(h) ? 0 : h,\n      };\n    },\n\n    /**\n     * Set the custom constraint.\n     *\n     * @param w\n     * @param h\n     */\n    _setCustomConstraint: function (w, h) {\n      $('.custom-constraint-w').val(parseFloat(w));\n      $('.custom-constraint-h').val(parseFloat(h));\n    },\n\n    /**\n     * Hide the custom constraint inputs.\n     */\n    _hideCustomConstraint: function () {\n      this.showingCustomConstraint = false;\n      $('.constraint.custom .custom-input', this.$container).addClass('hidden');\n      $('.constraint.custom .custom-label', this.$container).removeClass(\n        'hidden'\n      );\n      $('.orientation', this.$container).removeClass('hidden');\n    },\n\n    /**\n     * Show the custom constraint inputs.\n     */\n    _showCustomConstraint: function () {\n      if (this.showingCustomConstraint) {\n        return;\n      }\n\n      this.showingCustomConstraint = true;\n      $('.constraint.custom .custom-input', this.$container).removeClass(\n        'hidden'\n      );\n      $('.constraint.custom .custom-label', this.$container).addClass('hidden');\n      $('.orientation', this.$container).addClass('hidden');\n    },\n\n    /**\n     * Handle tab click.\n     *\n     * @param ev\n     */\n    _handleTabClick: function (ev) {\n      if (!this.animationInProgress) {\n        var $tab = $(ev.currentTarget);\n        var view = $tab.data('view');\n        this.$tabs.removeClass('selected');\n        $tab.addClass('selected');\n        this.showView(view);\n      }\n    },\n\n    /**\n     * Show a view.\n     *\n     * @param view\n     */\n    showView: function (view) {\n      if (this.currentView === view) {\n        return;\n      }\n\n      this.$views.addClass('hidden');\n      var $view = this.$views.filter('[data-view=\"' + view + '\"]');\n      $view.removeClass('hidden');\n\n      if (view === 'rotate') {\n        this.enableSlider();\n      } else {\n        this.disableSlider();\n      }\n\n      // Now that most likely our editor dimensions have changed, time to reposition stuff\n      this.updateSizeAndPosition();\n\n      // See if we have to enable or disable crop mode as we transition between tabs\n      if (this.currentView === 'crop' && view !== 'crop') {\n        this.disableCropMode();\n      } else if (this.currentView !== 'crop' && view === 'crop') {\n        this.enableCropMode();\n      }\n\n      // Mark the current view\n      this.currentView = view;\n    },\n\n    /**\n     * Store the current cropper state.\n     *\n     * Cropper state is always assumed to be saved at a zoom ratio of 1 to be used\n     * as the basis for recalculating the cropper position and dimensions.\n     *\n     * @param [state]\n     */\n    storeCropperState: function (state) {\n      if (typeof this.storeCropperState._ === 'undefined') {\n        this.storeCropperState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.cropperState = state;\n      } else if (this.clipper) {\n        this.storeCropperState._.zoomFactor = 1 / this.zoomRatio;\n\n        this.cropperState = {\n          offsetX:\n            (this.clipper.left - this.image.left) *\n            this.storeCropperState._.zoomFactor,\n          offsetY:\n            (this.clipper.top - this.image.top) *\n            this.storeCropperState._.zoomFactor,\n          height: this.clipper.height * this.storeCropperState._.zoomFactor,\n          width: this.clipper.width * this.storeCropperState._.zoomFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      } else {\n        this.storeCropperState._.dimensions = this.getScaledImageDimensions();\n        this.cropperState = {\n          offsetX: 0,\n          offsetY: 0,\n          height: this.storeCropperState._.dimensions.height,\n          width: this.storeCropperState._.dimensions.width,\n          imageDimensions: this.storeCropperState._.dimensions,\n        };\n      }\n    },\n\n    /**\n     * Store focal point coordinates in a manner that is not tied to zoom ratio and rotation.\n     */\n    storeFocalPointState: function (state) {\n      if (typeof this.storeFocalPointState._ === 'undefined') {\n        this.storeFocalPointState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.focalPointState = state;\n      } else if (this.focalPoint) {\n        this.storeFocalPointState._.zoomFactor = 1 / this.zoomRatio;\n        this.focalPointState = {\n          offsetX:\n            ((this.focalPoint.left - this.image.left) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          offsetY:\n            ((this.focalPoint.top - this.image.top) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      }\n    },\n\n    /**\n     * Rotate the image along with the viewport.\n     *\n     * @param degrees\n     */\n    rotateImage: function (degrees) {\n      if (!this.animationInProgress) {\n        // We're not that kind of an establishment, sir.\n        if (degrees !== 90 && degrees !== -90) {\n          return false;\n        }\n\n        this.animationInProgress = true;\n        this.viewportRotation += degrees;\n\n        // Normalize the viewport rotation angle so it's between 0 and 359\n        this.viewportRotation = parseInt(\n          (this.viewportRotation + 360) % 360,\n          10\n        );\n\n        var newAngle = this.image.angle + degrees;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var imageZoomRatio;\n\n        if (this.hasOrientationChanged()) {\n          imageZoomRatio = this.getZoomToCoverRatio({\n            height: scaledImageDimensions.width,\n            width: scaledImageDimensions.height,\n          });\n        } else {\n          imageZoomRatio = this.getZoomToCoverRatio(scaledImageDimensions);\n        }\n\n        // In cases when for some reason we've already zoomed in on the image,\n        // use existing zoom.\n        if (this.zoomRatio > imageZoomRatio) {\n          imageZoomRatio = this.zoomRatio;\n        }\n\n        var viewportProperties = {\n          angle: degrees === 90 ? '+=90' : '-=90',\n        };\n\n        var imageProperties = {\n          angle: newAngle,\n          width: scaledImageDimensions.width * imageZoomRatio,\n          height: scaledImageDimensions.height * imageZoomRatio,\n        };\n\n        var scaleFactor = 1;\n        if (this.scaleFactor < 1) {\n          scaleFactor = 1 / this.scaleFactor;\n          this.scaleFactor = 1;\n        } else {\n          if (this.viewport.width > this.editorHeight) {\n            scaleFactor = this.editorHeight / this.viewport.width;\n          } else if (this.viewport.height > this.editorWidth) {\n            scaleFactor = this.editorWidth / this.viewport.height;\n          }\n          this.scaleFactor = scaleFactor;\n        }\n\n        if (scaleFactor < 1) {\n          imageProperties.width *= scaleFactor;\n          imageProperties.height *= scaleFactor;\n        }\n\n        var state = this.cropperState;\n\n        // Make sure we reposition the image as well to focus on the same image area\n        var deltaX = state.offsetX;\n        var deltaY = state.offsetY;\n        var angleInRadians = degrees * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        var newDeltaX =\n          deltaX * Math.cos(angleInRadians) - deltaY * Math.sin(angleInRadians);\n        var newDeltaY =\n          deltaX * Math.sin(angleInRadians) + deltaY * Math.cos(angleInRadians);\n\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        var modifiedDeltaX =\n          newDeltaX * sizeFactor * this.zoomRatio * this.scaleFactor;\n        var modifiedDeltaY =\n          newDeltaY * sizeFactor * this.zoomRatio * this.scaleFactor;\n\n        imageProperties.left = this.editorWidth / 2 - modifiedDeltaX;\n        imageProperties.top = this.editorHeight / 2 - modifiedDeltaY;\n\n        state.offsetX = newDeltaX;\n        state.offsetY = newDeltaY;\n\n        var temp = state.width;\n        state.width = state.height;\n        state.height = temp;\n\n        this.storeCropperState(state);\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        }\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            // If we're zooming the image in or out, better do the same to viewport\n            var temp = this.viewport.height * scaleFactor;\n            this.viewport.height = this.viewport.width * scaleFactor;\n            this.viewport.width = temp;\n            this.viewport.set({angle: 0});\n          },\n        });\n\n        // Animate the rotation and dimension change\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            var cleanAngle = parseFloat((this.image.angle + 360) % 360);\n            this.image.set({angle: cleanAngle});\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              this._adjustFocalPointByAngle(degrees);\n              this.straighten(this.straighteningInput);\n              this.canvas.add(this.focalPoint);\n            } else {\n              this._resetFocalPointPosition();\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Flip an image along an axis.\n     *\n     * @param axis\n     */\n    flipImage: function (axis) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        if (this.hasOrientationChanged()) {\n          axis = axis === 'y' ? 'x' : 'y';\n        }\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        } else {\n          this._resetFocalPointPosition();\n        }\n\n        var editorCenter = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n        this.straighteningInput.setValue(-this.imageStraightenAngle);\n        this.imageStraightenAngle = -this.imageStraightenAngle;\n        var properties = {\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        };\n\n        var deltaY, deltaX;\n        var cropperState = this.cropperState;\n        var focalPointState = this.focalPointState;\n\n        // Reposition the image, viewport, and stored cropper and focal point states.\n        if (\n          (axis === 'y' && this.hasOrientationChanged()) ||\n          (axis !== 'y' && !this.hasOrientationChanged())\n        ) {\n          cropperState.offsetX = -cropperState.offsetX;\n          focalPointState.offsetX = -focalPointState.offsetX;\n          deltaX = this.image.left - editorCenter.x;\n          properties.left = editorCenter.x - deltaX;\n        } else {\n          cropperState.offsetY = -cropperState.offsetY;\n          focalPointState.offsetY = -focalPointState.offsetY;\n          deltaY = this.image.top - editorCenter.y;\n          properties.top = editorCenter.y - deltaY;\n        }\n\n        if (axis === 'y') {\n          properties.scaleY = this.image.scaleY * -1;\n          this.flipData.y = 1 - this.flipData.y;\n        } else {\n          properties.scaleX = this.image.scaleX * -1;\n          this.flipData.x = 1 - this.flipData.x;\n        }\n\n        this.storeCropperState(cropperState);\n        this.storeFocalPointState(focalPointState);\n\n        this.image.animate(properties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              // Well this is handy\n              this._adjustFocalPointByAngle(0);\n              this.canvas.add(this.focalPoint);\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Perform the straightening with input slider.\n     *\n     * @param {Craft.SlideRuleInput} slider\n     */\n    straighten: function (slider) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        var previousAngle = this.image.angle;\n\n        this.imageStraightenAngle =\n          (this.settings.allowDegreeFractions\n            ? parseFloat(slider.value)\n            : Math.round(parseFloat(slider.value))) % 360;\n\n        // Straighten the image\n        this.image.set({\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        });\n\n        // Set the new zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n        this._zoomImage();\n\n        if (this.cropperState) {\n          this._adjustEditorElementsOnStraighten(previousAngle);\n        }\n\n        this.renderImage();\n\n        this.animationInProgress = false;\n      }\n    },\n\n    /**\n     * Adjust the cropped viewport when straightening the image to correct for\n     * bumping into edges, keeping focus on the cropped area center and to\n     * maintain the illusion that the image is being straightened relative to the viewport center.\n     *\n     * @param {integer} previousAngle integer the previous image angle before straightening\n     */\n    _adjustEditorElementsOnStraighten: function (previousAngle) {\n      var scaledImageDimensions = this.getScaledImageDimensions();\n      var angleDelta = this.image.angle - previousAngle;\n      var state = this.cropperState;\n\n      var currentZoomRatio = this.zoomRatio;\n      var adjustmentRatio = 1;\n\n      var deltaX, deltaY, newCenterX, newCenterY, sizeFactor;\n\n      do {\n        // Get the cropper center coordinates\n        var cropperCenterX = state.offsetX;\n        var cropperCenterY = state.offsetY;\n        var angleInRadians = angleDelta * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        newCenterX =\n          cropperCenterX * Math.cos(angleInRadians) -\n          cropperCenterY * Math.sin(angleInRadians);\n        newCenterY =\n          cropperCenterX * Math.sin(angleInRadians) +\n          cropperCenterY * Math.cos(angleInRadians);\n\n        sizeFactor = scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Figure out the final image offset to keep the viewport focused where we need it\n        deltaX = newCenterX * currentZoomRatio * sizeFactor;\n        deltaY = newCenterY * currentZoomRatio * sizeFactor;\n\n        // If the image would creep in the viewport, figure out how to math around it.\n        var imageVertices = this.getImageVerticeCoords(currentZoomRatio);\n        var rectangle = {\n          width: this.viewport.width,\n          height: this.viewport.height,\n          left: this.editorWidth / 2 - this.viewport.width / 2 + deltaX,\n          top: this.editorHeight / 2 - this.viewport.height / 2 + deltaY,\n        };\n        adjustmentRatio = this._getZoomRatioToFitRectangle(\n          rectangle,\n          imageVertices\n        );\n        currentZoomRatio = currentZoomRatio * adjustmentRatio;\n\n        // If we had to make adjustments, do the calculations again\n      } while (adjustmentRatio !== 1);\n\n      // Reposition the image correctly\n      this.image.set({\n        left: this.editorWidth / 2 - deltaX,\n        top: this.editorHeight / 2 - deltaY,\n      });\n\n      // Finally, store the new cropper state to reflect the rotation change.\n      state.offsetX = newCenterX;\n      state.offsetY = newCenterY;\n      state.width = this.viewport.width / currentZoomRatio / sizeFactor;\n      state.height = this.viewport.height / currentZoomRatio / sizeFactor;\n\n      this.storeCropperState(state);\n\n      // Zoom the image in and we're done.\n      this.zoomRatio = currentZoomRatio;\n\n      if (this.focalPoint) {\n        this._adjustFocalPointByAngle(angleDelta);\n\n        if (!this._isCenterInside(this.focalPoint, this.viewport)) {\n          this.focalPoint.set({opacity: 0});\n        } else {\n          this.focalPoint.set({opacity: 1});\n        }\n      } else if (angleDelta !== 0) {\n        this._resetFocalPointPosition();\n      }\n\n      this._zoomImage();\n    },\n\n    /**\n     * If focal point is active and outside of viewport after straightening, reset it.\n     */\n    _cleanupFocalPointAfterStraighten: function () {\n      if (\n        this.focalPoint &&\n        !this._isCenterInside(this.focalPoint, this.viewport)\n      ) {\n        this.focalPoint.set({opacity: 1});\n        var state = this.focalPointState;\n        state.offsetX = 0;\n        state.offsetY = 0;\n        this.storeFocalPointState(state);\n        this.toggleFocalPoint();\n      }\n    },\n\n    /**\n     * Reset focal point to the middle of image.\n     */\n    _resetFocalPointPosition: function () {\n      var state = this.focalPointState;\n      state.offsetX = 0;\n      state.offsetY = 0;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Returns true if a center of an object is inside another rectangle shaped object that is not rotated.\n     *\n     * @param object\n     * @param containingObject\n     *\n     * @returns {boolean}\n     */\n    _isCenterInside: function (object, containingObject) {\n      return (\n        object.left > containingObject.left - containingObject.width / 2 &&\n        object.top > containingObject.top - containingObject.height / 2 &&\n        object.left < containingObject.left + containingObject.width / 2 &&\n        object.top < containingObject.top + containingObject.height / 2\n      );\n    },\n\n    /**\n     * Adjust the focal point by an angle in degrees.\n     * @param angle\n     */\n    _adjustFocalPointByAngle: function (angle) {\n      var angleInRadians = angle * (Math.PI / 180);\n      var state = this.focalPointState;\n\n      var focalX = state.offsetX;\n      var focalY = state.offsetY;\n\n      // Calculate how the focal point would need to move in a circle to keep on the same spot\n      // on the image if it was rotated with zoom intact.\n      var newFocalX =\n        focalX * Math.cos(angleInRadians) - focalY * Math.sin(angleInRadians);\n      var newFocalY =\n        focalX * Math.sin(angleInRadians) + focalY * Math.cos(angleInRadians);\n      var sizeFactor =\n        this.getScaledImageDimensions().width / state.imageDimensions.width;\n\n      var adjustedFocalX = newFocalX * sizeFactor * this.zoomRatio;\n      var adjustedFocalY = newFocalY * sizeFactor * this.zoomRatio;\n\n      this.focalPoint.left = this.image.left + adjustedFocalX;\n      this.focalPoint.top = this.image.top + adjustedFocalY;\n\n      state.offsetX = newFocalX;\n      state.offsetY = newFocalY;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Get the zoom ratio required to fit a rectangle within another rectangle, that is defined by vertices.\n     * If the rectangle fits, 1 will be returned.\n     *\n     * @param rectangle\n     * @param containingVertices\n     */\n    _getZoomRatioToFitRectangle: function (rectangle, containingVertices) {\n      var rectangleVertices = this._getRectangleVertices(rectangle);\n      var vertex;\n\n      // Check if any of the viewport vertices end up out of bounds\n      for (\n        var verticeIndex = 0;\n        verticeIndex < rectangleVertices.length;\n        verticeIndex++\n      ) {\n        vertex = rectangleVertices[verticeIndex];\n\n        if (!this.arePointsInsideRectangle([vertex], containingVertices)) {\n          break;\n        }\n\n        vertex = false;\n      }\n\n      // If there's no vertex set after loop, it means that all of them are inside the image rectangle\n      var adjustmentRatio;\n\n      if (!vertex) {\n        adjustmentRatio = 1;\n      } else {\n        // Find out which edge got crossed by the vertex\n        var edge = this._getEdgeCrossed(containingVertices, vertex);\n\n        var rectangleCenter = {\n          x: rectangle.left + rectangle.width / 2,\n          y: rectangle.top + rectangle.height / 2,\n        };\n\n        // Calculate how much further that edge needs to be.\n        // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points\n        var distanceFromVertexToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * vertex.x -\n              (edge[1].x - edge[0].x) * vertex.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n        var distanceFromCenterToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * rectangleCenter.x -\n              (edge[1].x - edge[0].x) * rectangleCenter.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n\n        // Adjust the zoom ratio\n        adjustmentRatio =\n          (distanceFromVertexToEdge + distanceFromCenterToEdge) /\n          distanceFromCenterToEdge;\n      }\n\n      return adjustmentRatio;\n    },\n\n    /**\n     * Save the image.\n     *\n     * @param ev\n     */\n    saveImage: function (ev) {\n      var $button = $(ev.currentTarget);\n      if ($button.hasClass('disabled')) {\n        return false;\n      }\n\n      $('.btn', this.$buttons).addClass('disabled');\n      this.$buttons.append('<div class=\"spinner\"></div>');\n\n      var postData = {\n        assetId: this.assetId,\n        viewportRotation: this.viewportRotation,\n        imageRotation: this.imageStraightenAngle,\n        replace: $button.hasClass('replace') ? 1 : 0,\n      };\n\n      if (this.cropperState) {\n        var cropData = {};\n\n        cropData.height = this.cropperState.height;\n        cropData.width = this.cropperState.width;\n        cropData.offsetX = this.cropperState.offsetX;\n        cropData.offsetY = this.cropperState.offsetY;\n\n        postData.imageDimensions = this.cropperState.imageDimensions;\n\n        postData.cropData = cropData;\n      } else {\n        postData.imageDimensions = this.getScaledImageDimensions();\n      }\n\n      if (this.focalPoint) {\n        postData.focalPoint = this.focalPointState;\n      }\n\n      postData.flipData = this.flipData;\n      postData.zoom = this.zoomRatio;\n\n      Craft.postActionRequest('assets/save-image', postData, (data) => {\n        this.$buttons\n          .find('.btn')\n          .removeClass('disabled')\n          .end()\n          .find('.spinner')\n          .remove();\n\n        if (data.error) {\n          alert(data.error);\n          return;\n        }\n\n        this.onSave();\n        this.hide();\n        Craft.cp.runQueue();\n      });\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to cover a viewport by given dimensions.\n     *\n     * @param dimensions\n     */\n    getZoomToCoverRatio: function (dimensions) {\n      // Convert the angle to radians\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      // Calculate the dimensions of the scaled image using the magic of math\n      var scaledWidth =\n        Math.sin(angleInRadians) * dimensions.height +\n        Math.cos(angleInRadians) * dimensions.width;\n      var scaledHeight =\n        Math.sin(angleInRadians) * dimensions.width +\n        Math.cos(angleInRadians) * dimensions.height;\n\n      // Calculate the ratio\n      return Math.max(\n        scaledWidth / dimensions.width,\n        scaledHeight / dimensions.height\n      );\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to fit inside a viewport by given dimensions.\n     *\n     * @param dimensions\n     */\n    getZoomToFitRatio: function (dimensions) {\n      // Get the bounding box for a rotated image\n      var boundingBox = this._getImageBoundingBox(dimensions);\n\n      // Scale the bounding box to fit\n      var scale = 1;\n      if (\n        boundingBox.height > this.editorHeight ||\n        boundingBox.width > this.editorWidth\n      ) {\n        var vertScale = this.editorHeight / boundingBox.height;\n        var horiScale = this.editorWidth / boundingBox.width;\n        scale = Math.min(horiScale, vertScale);\n      }\n\n      return scale;\n    },\n\n    /**\n     * Return the combined zoom ratio to fit a rectangle inside image that's been zoomed to fit.\n     */\n    getCombinedZoomRatio: function (dimensions) {\n      return (\n        this.getZoomToCoverRatio(dimensions) /\n        this.getZoomToFitRatio(dimensions)\n      );\n    },\n\n    /**\n     * Draw the grid.\n     *\n     * @private\n     */\n    _showGrid: function () {\n      if (!this.grid) {\n        var strokeOptions = {\n          strokeWidth: 1,\n          stroke: 'rgba(255,255,255,0.5)',\n        };\n\n        var lineCount = 8;\n        var gridWidth = this.viewport.width;\n        var gridHeight = this.viewport.height;\n        var xStep = gridWidth / (lineCount + 1);\n        var yStep = gridHeight / (lineCount + 1);\n\n        var grid = [\n          new fabric.Rect({\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,1)',\n            originX: 'center',\n            originY: 'center',\n            width: gridWidth,\n            height: gridHeight,\n            left: gridWidth / 2,\n            top: gridHeight / 2,\n            fill: 'rgba(255,255,255,0)',\n          }),\n        ];\n\n        var i;\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line(\n              [i * xStep, 0, i * xStep, gridHeight],\n              strokeOptions\n            )\n          );\n        }\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line([0, i * yStep, gridWidth, i * yStep], strokeOptions)\n          );\n        }\n\n        this.grid = new fabric.Group(grid, {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n          originX: 'center',\n          originY: 'center',\n          angle: this.viewport.angle,\n        });\n\n        this.canvas.add(this.grid);\n        this.renderImage();\n      }\n    },\n\n    /**\n     * Hide the grid\n     */\n    _hideGrid: function () {\n      this.canvas.remove(this.grid);\n      this.grid = null;\n      this.renderImage();\n    },\n\n    /**\n     * Remove all the events when hiding the editor.\n     */\n    onFadeOut: function () {\n      this.destroy();\n    },\n\n    /**\n     * Make sure underlying content is not scrolled by accident.\n     */\n    show: function () {\n      this.base();\n      Garnish.$bod.addClass('no-scroll');\n    },\n\n    /**\n     * Allow the content to scroll.\n     */\n    hide: function () {\n      this.removeAllListeners();\n      this.straighteningInput.removeAllListeners();\n      Garnish.$bod.removeClass('no-scroll');\n      this.base();\n    },\n\n    /**\n     * onSave callback.\n     */\n    onSave: function () {\n      this.settings.onSave();\n      this.trigger('save');\n    },\n\n    /**\n     * Enable the rotation slider.\n     */\n    enableSlider: function () {\n      this.$imageTools.removeClass('hidden');\n    },\n\n    /**\n     * Disable the rotation slider.\n     */\n    disableSlider: function () {\n      this.$imageTools.addClass('hidden');\n    },\n\n    /**\n     * Switch to crop mode.\n     */\n    enableCropMode: function () {\n      var imageDimensions = this.getScaledImageDimensions();\n      this.zoomRatio = this.getZoomToFitRatio(imageDimensions);\n\n      var viewportProperties = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var callback = () => {\n        this._setFittedImageVerticeCoordinates();\n\n        // Restore cropper\n        var state = this.cropperState;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Restore based on the stored information\n        var cropperData = {\n          left: this.image.left + state.offsetX * sizeFactor * this.zoomRatio,\n          top: this.image.top + state.offsetY * sizeFactor * this.zoomRatio,\n          width: state.width * sizeFactor * this.zoomRatio,\n          height: state.height * sizeFactor * this.zoomRatio,\n        };\n\n        this._showCropper(cropperData);\n\n        if (this.focalPoint) {\n          sizeFactor =\n            scaledImageDimensions.width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * Switch out of crop mode.\n     */\n    disableCropMode: function () {\n      var viewportProperties = {};\n\n      this._hideCropper();\n      var imageDimensions = this.getScaledImageDimensions();\n      var targetZoom =\n        this.getZoomToCoverRatio(imageDimensions) * this.scaleFactor;\n      var inverseZoomFactor = targetZoom / this.zoomRatio;\n      this.zoomRatio = targetZoom;\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var offsetX = this.clipper.left - this.image.left;\n      var offsetY = this.clipper.top - this.image.top;\n\n      var imageOffsetX = offsetX * inverseZoomFactor;\n      var imageOffsetY = offsetY * inverseZoomFactor;\n      imageProperties.left = this.editorWidth / 2 - imageOffsetX;\n      imageProperties.top = this.editorHeight / 2 - imageOffsetY;\n\n      // Calculate the cropper dimensions after all the zooming\n      viewportProperties.height = this.clipper.height * inverseZoomFactor;\n      viewportProperties.width = this.clipper.width * inverseZoomFactor;\n\n      if (\n        !this.focalPoint ||\n        (this.focalPoint &&\n          !this._isCenterInside(this.focalPoint, this.clipper))\n      ) {\n        if (this.focalPoint) {\n          this.toggleFocalPoint();\n        }\n\n        this._resetFocalPointPosition();\n      }\n\n      var callback = () => {\n        // Reposition focal point correctly\n        if (this.focalPoint) {\n          var sizeFactor =\n            this.getScaledImageDimensions().width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * Transition between cropping end editor modes\n     *\n     * @param callback\n     * @param imageProperties\n     * @param viewportProperties\n     * @private\n     */\n    _editorModeTransition: function (\n      callback,\n      imageProperties,\n      viewportProperties\n    ) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        // Without this it looks semi-broken during animation\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n          this.renderImage();\n        }\n\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            callback();\n            this.animationInProgress = false;\n            this.renderImage();\n          },\n        });\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n        });\n      }\n    },\n\n    _showSpinner: function () {\n      this.$spinnerCanvas = $('<canvas id=\"spinner-canvas\"></canvas>').appendTo(\n        $('.image', this.$container)\n      );\n      var canvas = document.getElementById('spinner-canvas');\n      var context = canvas.getContext('2d');\n      var start = new Date();\n      var lines = 16,\n        cW = context.canvas.width,\n        cH = context.canvas.height;\n\n      var draw = function () {\n        var rotation = parseInt(((new Date() - start) / 1000) * lines) / lines;\n        context.save();\n        context.clearRect(0, 0, cW, cH);\n        context.translate(cW / 2, cH / 2);\n        context.rotate(Math.PI * 2 * rotation);\n        for (var i = 0; i < lines; i++) {\n          context.beginPath();\n          context.rotate((Math.PI * 2) / lines);\n          context.moveTo(cW / 10, 0);\n          context.lineTo(cW / 4, 0);\n          context.lineWidth = cW / 30;\n          context.strokeStyle = 'rgba(255,255,255,' + i / lines + ')';\n          context.stroke();\n        }\n        context.restore();\n      };\n      this.spinnerInterval = window.setInterval(draw, 1000 / 30);\n    },\n\n    _hideSpinner: function () {\n      window.clearInterval(this.spinnerInterval);\n      this.$spinnerCanvas.remove();\n      this.$spinnerCanvas = null;\n    },\n\n    /**\n     * Show the cropper.\n     *\n     * @param clipperData\n     */\n    _showCropper: function (clipperData) {\n      this._setupCropperLayer(clipperData);\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Hide the cropper.\n     */\n    _hideCropper: function () {\n      if (this.clipper) {\n        this.croppingCanvas.remove(this.clipper);\n        this.croppingCanvas.remove(this.croppingShade);\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n\n        this.croppingCanvas = null;\n        this.renderCropper = null;\n      }\n    },\n\n    /**\n     * Draw the cropper.\n     *\n     * @param clipperData\n     */\n    _setupCropperLayer: function (clipperData) {\n      // Set up the canvas for cropper\n      this.croppingCanvas = new fabric.StaticCanvas('cropping-canvas', {\n        backgroundColor: 'rgba(0,0,0,0)',\n        hoverCursor: 'default',\n        selection: false,\n      });\n\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      this.renderCropper = () =>\n        Garnish.requestAnimationFrame(\n          this.croppingCanvas.renderAll.bind(this.croppingCanvas)\n        );\n\n      $('#cropping-canvas', this.$editorContainer).css({\n        position: 'absolute',\n        top: 0,\n        left: 0,\n      });\n\n      this.croppingShade = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: this.editorWidth,\n        height: this.editorHeight,\n        fill: 'rgba(0,0,0,0.7)',\n      });\n\n      // Calculate the cropping rectangle size\n      var imageDimensions = this.getScaledImageDimensions();\n      var rectangleRatio =\n        this.imageStraightenAngle === 0\n          ? 1\n          : this.getCombinedZoomRatio(imageDimensions) * 1.2;\n      var rectWidth = imageDimensions.width / rectangleRatio;\n      var rectHeight = imageDimensions.height / rectangleRatio;\n\n      if (this.hasOrientationChanged()) {\n        var temp = rectHeight;\n        rectHeight = rectWidth;\n        rectWidth = temp;\n      }\n\n      // Set up the cropping viewport rectangle\n      this.clipper = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: rectWidth,\n        height: rectHeight,\n        stroke: 'black',\n        fill: 'rgba(128,0,0,1)',\n        strokeWidth: 0,\n      });\n\n      // Set from clipper data\n      if (clipperData) {\n        this.clipper.set(clipperData);\n      }\n\n      this.clipper.globalCompositeOperation = 'destination-out';\n      this.croppingCanvas.add(this.croppingShade);\n      this.croppingCanvas.add(this.clipper);\n    },\n\n    /**\n     * Redraw the cropper boundaries\n     */\n    _redrawCropperElements: function () {\n      if (typeof this._redrawCropperElements._ === 'undefined') {\n        this._redrawCropperElements._ = {};\n      }\n\n      if (this.cropperHandles) {\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n      }\n      this._redrawCropperElements._.lineOptions = {\n        strokeWidth: 4,\n        stroke: 'rgb(255,255,255)',\n        fill: false,\n      };\n\n      this._redrawCropperElements._.gridOptions = {\n        strokeWidth: 2,\n        stroke: 'rgba(255,255,255,0.5)',\n      };\n\n      // Draw the handles\n      this._redrawCropperElements._.pathGroup = [\n        new fabric.Path(\n          'M 0,10 L 0,0 L 10,0',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width - 8) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',10',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height - 8) +\n            ' L' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height + 4) +\n            ' L ' +\n            (this.clipper.width - 8) +\n            ',' +\n            (this.clipper.height + 4),\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M 10,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height - 8),\n          this._redrawCropperElements._.lineOptions\n        ),\n      ];\n\n      this.cropperHandles = new fabric.Group(\n        this._redrawCropperElements._.pathGroup,\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      // Don't forget the rectangle\n      this.croppingRectangle = new fabric.Rect({\n        left: this.clipper.left,\n        top: this.clipper.top,\n        width: this.clipper.width,\n        height: this.clipper.height,\n        fill: 'rgba(0,0,0,0)',\n        stroke: 'rgba(255,255,255,0.8)',\n        strokeWidth: 2,\n        originX: 'center',\n        originY: 'center',\n      });\n\n      this.cropperGrid = new fabric.Group(\n        [\n          new fabric.Line(\n            [\n              this.clipper.width * 0.33,\n              0,\n              this.clipper.width * 0.33,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              this.clipper.width * 0.66,\n              0,\n              this.clipper.width * 0.66,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.33,\n              this.clipper.width,\n              this.clipper.height * 0.33,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.66,\n              this.clipper.width,\n              this.clipper.height * 0.66,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n        ],\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      this._redrawCropperElements._.cropTextTop =\n        this.croppingRectangle.top + this.clipper.height / 2 + 12;\n      this._redrawCropperElements._.cropTextBackgroundColor = 'rgba(0,0,0,0)';\n\n      if (\n        this._redrawCropperElements._.cropTextTop + 12 >\n        this.editorHeight - 2\n      ) {\n        this._redrawCropperElements._.cropTextTop -= 24;\n        this._redrawCropperElements._.cropTextBackgroundColor =\n          'rgba(0,0,0,0.5)';\n      }\n\n      this.croppingCanvas.add(this.cropperHandles);\n      this.croppingCanvas.add(this.cropperGrid);\n      this.croppingCanvas.add(this.croppingRectangle);\n    },\n\n    /**\n     * Reposition the cropper when the image editor dimensions change.\n     *\n     * @param previousImageArea\n     */\n    _repositionCropper: function (previousImageArea) {\n      if (!this.croppingCanvas) {\n        return;\n      }\n\n      // Get the current clipper offset relative to center\n      var currentOffset = {\n        x: this.clipper.left - this.croppingCanvas.width / 2,\n        y: this.clipper.top - this.croppingCanvas.height / 2,\n      };\n\n      // Resize the cropping canvas\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      // Check by what factor will the new final bounding box be different\n      var currentArea = this._getBoundingRectangle(this.imageVerticeCoords);\n      var areaFactor = currentArea.width / previousImageArea.width;\n\n      // Adjust the cropper size to scale along with the bounding box\n      this.clipper.width = Math.round(this.clipper.width * areaFactor);\n      this.clipper.height = Math.round(this.clipper.height * areaFactor);\n\n      // Adjust the coordinates: re-position clipper in relation to the new center to adjust\n      // for editor size changes and then multiply by the size factor to adjust for image size changes\n      this.clipper.left = this.editorWidth / 2 + currentOffset.x * areaFactor;\n      this.clipper.top = this.editorHeight / 2 + currentOffset.y * areaFactor;\n\n      // Resize the cropping shade\n      this.croppingShade.set({\n        width: this.editorWidth,\n        height: this.editorHeight,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      });\n\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Get the dimensions of a bounding rectangle by a set of four coordinates.\n     *\n     * @param coordinateSet\n     */\n    _getBoundingRectangle: function (coordinateSet) {\n      return {\n        width:\n          Math.max(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ) -\n          Math.min(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ),\n        height:\n          Math.max(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ) -\n          Math.min(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ),\n      };\n    },\n\n    /**\n     * Handle the mouse being clicked.\n     *\n     * @param ev\n     */\n    _handleMouseDown: function (ev) {\n      // Focal before resize before dragging\n      var focal = this.focalPoint && this._isMouseOver(ev, this.focalPoint);\n      var move = this.croppingCanvas && this._isMouseOver(ev, this.clipper);\n      var handle = this.croppingCanvas && this._cropperHandleHitTest(ev);\n\n      if (handle || move || focal) {\n        this.previousMouseX = ev.pageX;\n        this.previousMouseY = ev.pageY;\n\n        if (focal) {\n          this.draggingFocal = true;\n        } else if (handle) {\n          this.scalingCropper = handle;\n        } else if (move) {\n          this.draggingCropper = true;\n        }\n      }\n    },\n\n    /**\n     * Handle the mouse being moved.\n     *\n     * @param ev\n     */\n    _handleMouseMove: function (ev) {\n      if (this.mouseMoveEvent !== null) {\n        Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this));\n      }\n      this.mouseMoveEvent = ev;\n    },\n\n    _handleMouseMoveInternal: function () {\n      if (this.mouseMoveEvent === null) {\n        return;\n      }\n\n      if (this.focalPoint && this.draggingFocal) {\n        this._handleFocalDrag(this.mouseMoveEvent);\n        this.storeFocalPointState();\n        this.renderImage();\n      } else if (this.draggingCropper || this.scalingCropper) {\n        if (this.draggingCropper) {\n          this._handleCropperDrag(this.mouseMoveEvent);\n        } else {\n          this._handleCropperResize(this.mouseMoveEvent);\n        }\n\n        this._redrawCropperElements();\n\n        this.storeCropperState();\n        this.renderCropper();\n      } else {\n        this._setMouseCursor(this.mouseMoveEvent);\n      }\n\n      this.previousMouseX = this.mouseMoveEvent.pageX;\n      this.previousMouseY = this.mouseMoveEvent.pageY;\n\n      this.mouseMoveEvent = null;\n    },\n\n    /**\n     * Handle mouse being released.\n     *\n     * @param ev\n     */\n    _handleMouseUp: function (ev) {\n      this.draggingCropper = false;\n      this.scalingCropper = false;\n      this.draggingFocal = false;\n    },\n\n    /**\n     * Handle mouse out\n     *\n     * @param ev\n     */\n    _handleMouseOut: function (ev) {\n      this._handleMouseUp(ev);\n      this.mouseMoveEvent = ev;\n      this._handleMouseMoveInternal();\n    },\n\n    /**\n     * Handle cropper being dragged.\n     *\n     * @param ev\n     */\n    _handleCropperDrag: function (ev) {\n      if (typeof this._handleCropperDrag._ === 'undefined') {\n        this._handleCropperDrag._ = {};\n      }\n\n      this._handleCropperDrag._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (\n        this._handleCropperDrag._.deltaX === 0 &&\n        this._handleCropperDrag._.deltaY === 0\n      ) {\n        return false;\n      }\n\n      this._handleCropperDrag._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperDrag._.vertices = this._getRectangleVertices(\n        this._handleCropperDrag._.rectangle,\n        this._handleCropperDrag._.deltaX,\n        this._handleCropperDrag._.deltaY\n      );\n\n      // If this would drag it outside of the image\n      if (\n        !this.arePointsInsideRectangle(\n          this._handleCropperDrag._.vertices,\n          this.imageVerticeCoords\n        )\n      ) {\n        // Try to find the furthest point in the same general direction where we can drag it\n\n        // Delta iterator setup\n        this._handleCropperDrag._.dxi = 0;\n        this._handleCropperDrag._.dyi = 0;\n        this._handleCropperDrag._.xStep =\n          this._handleCropperDrag._.deltaX > 0 ? -1 : 1;\n        this._handleCropperDrag._.yStep =\n          this._handleCropperDrag._.deltaY > 0 ? -1 : 1;\n\n        // The furthest we can move\n        this._handleCropperDrag._.furthest = 0;\n        this._handleCropperDrag._.furthestDeltas = {};\n\n        // Loop through every combination of dragging it not so far\n        for (\n          this._handleCropperDrag._.dxi = Math.min(\n            Math.abs(this._handleCropperDrag._.deltaX),\n            10\n          );\n          this._handleCropperDrag._.dxi >= 0;\n          this._handleCropperDrag._.dxi--\n        ) {\n          for (\n            this._handleCropperDrag._.dyi = Math.min(\n              Math.abs(this._handleCropperDrag._.deltaY),\n              10\n            );\n            this._handleCropperDrag._.dyi >= 0;\n            this._handleCropperDrag._.dyi--\n          ) {\n            this._handleCropperDrag._.vertices = this._getRectangleVertices(\n              this._handleCropperDrag._.rectangle,\n              this._handleCropperDrag._.dxi *\n                (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n              this._handleCropperDrag._.dyi *\n                (this._handleCropperDrag._.deltaY > 0 ? 1 : -1)\n            );\n\n            if (\n              this.arePointsInsideRectangle(\n                this._handleCropperDrag._.vertices,\n                this.imageVerticeCoords\n              )\n            ) {\n              if (\n                this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi >\n                this._handleCropperDrag._.furthest\n              ) {\n                this._handleCropperDrag._.furthest =\n                  this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi;\n                this._handleCropperDrag._.furthestDeltas = {\n                  x:\n                    this._handleCropperDrag._.dxi *\n                    (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n                  y:\n                    this._handleCropperDrag._.dyi *\n                    (this._handleCropperDrag._.deltaY > 0 ? 1 : -1),\n                };\n              }\n            }\n          }\n        }\n\n        // REALLY can't drag along the cursor movement\n        if (this._handleCropperDrag._.furthest == 0) {\n          return;\n        } else {\n          this._handleCropperDrag._.deltaX =\n            this._handleCropperDrag._.furthestDeltas.x;\n          this._handleCropperDrag._.deltaY =\n            this._handleCropperDrag._.furthestDeltas.y;\n        }\n      }\n\n      this.clipper.set({\n        left: this.clipper.left + this._handleCropperDrag._.deltaX,\n        top: this.clipper.top + this._handleCropperDrag._.deltaY,\n      });\n    },\n\n    /**\n     * Handle focal point being dragged.\n     *\n     * @param ev\n     */\n    _handleFocalDrag: function (ev) {\n      if (typeof this._handleFocalDrag._ === 'undefined') {\n        this._handleFocalDrag._ = {};\n      }\n\n      if (this.focalPoint) {\n        this._handleFocalDrag._.deltaX = ev.pageX - this.previousMouseX;\n        this._handleFocalDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n        if (\n          this._handleFocalDrag._.deltaX === 0 &&\n          this._handleFocalDrag._.deltaY === 0\n        ) {\n          return;\n        }\n\n        this._handleFocalDrag._.newX =\n          this.focalPoint.left + this._handleFocalDrag._.deltaX;\n        this._handleFocalDrag._.newY =\n          this.focalPoint.top + this._handleFocalDrag._.deltaY;\n\n        // Just make sure that the focal point stays inside the image\n        if (this.currentView === 'crop') {\n          if (\n            !this.arePointsInsideRectangle(\n              [\n                {\n                  x: this._handleFocalDrag._.newX,\n                  y: this._handleFocalDrag._.newY,\n                },\n              ],\n              this.imageVerticeCoords\n            )\n          ) {\n            return;\n          }\n        } else {\n          if (\n            !(\n              this.viewport.left -\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX <\n                0 &&\n              this.viewport.left +\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX >\n                0 &&\n              this.viewport.top -\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY <\n                0 &&\n              this.viewport.top +\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY >\n                0\n            )\n          ) {\n            return;\n          }\n        }\n\n        this.focalPoint.set({\n          left: this.focalPoint.left + this._handleFocalDrag._.deltaX,\n          top: this.focalPoint.top + this._handleFocalDrag._.deltaY,\n        });\n      }\n    },\n\n    /**\n     * Set the cropping constraint\n     * @param constraint\n     */\n    setCroppingConstraint: function (constraint) {\n      // In case this caused the sidebar width to change.\n      this.updateSizeAndPosition();\n\n      switch (constraint) {\n        case 'none':\n          this.croppingConstraint = false;\n          break;\n\n        case 'original':\n          this.croppingConstraint = this.originalWidth / this.originalHeight;\n          break;\n\n        case 'current':\n          this.croppingConstraint = this.clipper.width / this.clipper.height;\n          break;\n\n        case 'custom':\n          break;\n        default:\n          this.croppingConstraint = parseFloat(constraint);\n\n          break;\n      }\n    },\n\n    /**\n     * Enforce the cropping constraint\n     */\n    enforceCroppingConstraint: function () {\n      if (typeof this.enforceCroppingConstraint._ === 'undefined') {\n        this.enforceCroppingConstraint._ = {};\n      }\n\n      if (this.animationInProgress || !this.croppingConstraint) {\n        return;\n      }\n\n      this.animationInProgress = true;\n\n      // Mock the clipping rectangle for collision tests\n      this.enforceCroppingConstraint._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      // If wider than it should be\n      if (this.clipper.width > this.clipper.height * this.croppingConstraint) {\n        this.enforceCroppingConstraint._.previousHeight =\n          this.enforceCroppingConstraint._.rectangle.height;\n\n        // Make it taller!\n        this.enforceCroppingConstraint._.rectangle.height =\n          this.clipper.width / this.croppingConstraint;\n\n        // Getting really awkward having to convert between 0;0 being center or top-left corner.\n        this.enforceCroppingConstraint._.rectangle.top -=\n          (this.enforceCroppingConstraint._.rectangle.height -\n            this.enforceCroppingConstraint._.previousHeight) /\n          2;\n\n        // If the clipper would end up out of bounds, make it narrower instead.\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.clipper.height * this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.enforceCroppingConstraint._.rectangle.width /\n            this.croppingConstraint;\n        }\n      } else {\n        // Follow the same pattern, if taller than it should be.\n        this.enforceCroppingConstraint._.previousWidth =\n          this.enforceCroppingConstraint._.rectangle.width;\n        this.enforceCroppingConstraint._.rectangle.width =\n          this.clipper.height * this.croppingConstraint;\n        this.enforceCroppingConstraint._.rectangle.left -=\n          (this.enforceCroppingConstraint._.rectangle.width -\n            this.enforceCroppingConstraint._.previousWidth) /\n          2;\n\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.clipper.width / this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.enforceCroppingConstraint._.rectangle.height *\n            this.croppingConstraint;\n        }\n      }\n\n      this.enforceCroppingConstraint._.properties = {\n        height: this.enforceCroppingConstraint._.rectangle.height,\n        width: this.enforceCroppingConstraint._.rectangle.width,\n      };\n\n      // Make sure to redraw cropper handles and gridlines when resizing\n      this.clipper.animate(this.enforceCroppingConstraint._.properties, {\n        onChange: () => {\n          this._redrawCropperElements();\n          this.croppingCanvas.renderAll();\n        },\n        duration: this.settings.animationDuration,\n        onComplete: () => {\n          this._redrawCropperElements();\n          this.animationInProgress = false;\n          this.renderCropper();\n          this.storeCropperState();\n        },\n      });\n    },\n\n    /**\n     * Handle cropper being resized.\n     *\n     * @param ev\n     */\n    _handleCropperResize: function (ev) {\n      if (typeof this._handleCropperResize._ === 'undefined') {\n        this._handleCropperResize._ = {};\n      }\n\n      // Size deltas\n      this._handleCropperResize._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperResize._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (this.scalingCropper === 'b' || this.scalingCropper === 't') {\n        this._handleCropperResize._.deltaX = 0;\n      }\n\n      if (this.scalingCropper === 'l' || this.scalingCropper === 'r') {\n        this._handleCropperResize._.deltaY = 0;\n      }\n\n      if (\n        this._handleCropperResize._.deltaX === 0 &&\n        this._handleCropperResize._.deltaY === 0\n      ) {\n        return;\n      }\n\n      // Translate from center-center origin to absolute coords\n      this._handleCropperResize._.startingRectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperResize._.rectangle =\n        this._calculateNewCropperSizeByDeltas(\n          this._handleCropperResize._.startingRectangle,\n          this._handleCropperResize._.deltaX,\n          this._handleCropperResize._.deltaY,\n          this.scalingCropper\n        );\n\n      if (\n        this._handleCropperResize._.rectangle.height < 30 ||\n        this._handleCropperResize._.rectangle.width < 30\n      ) {\n        return;\n      }\n\n      if (\n        !this.arePointsInsideRectangle(\n          this._getRectangleVertices(this._handleCropperResize._.rectangle),\n          this.imageVerticeCoords\n        )\n      ) {\n        return;\n      }\n\n      // Translate back to center-center origin.\n      this.clipper.set({\n        top:\n          this._handleCropperResize._.rectangle.top +\n          this._handleCropperResize._.rectangle.height / 2,\n        left:\n          this._handleCropperResize._.rectangle.left +\n          this._handleCropperResize._.rectangle.width / 2,\n        width: this._handleCropperResize._.rectangle.width,\n        height: this._handleCropperResize._.rectangle.height,\n      });\n\n      this._redrawCropperElements();\n    },\n\n    _calculateNewCropperSizeByDeltas: function (\n      startingRectangle,\n      deltaX,\n      deltaY,\n      cropperDirection\n    ) {\n      if (typeof this._calculateNewCropperSizeByDeltas._ === 'undefined') {\n        this._calculateNewCropperSizeByDeltas._ = {};\n      }\n\n      // Center deltas\n      this._calculateNewCropperSizeByDeltas._.topDelta = 0;\n      this._calculateNewCropperSizeByDeltas._.leftDelta = 0;\n\n      this._calculateNewCropperSizeByDeltas._.rectangle = startingRectangle;\n      this._calculateNewCropperSizeByDeltas._.deltaX = deltaX;\n      this._calculateNewCropperSizeByDeltas._.deltaY = deltaY;\n\n      // Lock the aspect ratio if needed\n      if (this.croppingConstraint) {\n        this._calculateNewCropperSizeByDeltas._.change = 0;\n\n        // Take into account the mouse direction and figure out the \"real\" change in cropper size\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'br':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n\n        if (this.croppingConstraint > 1) {\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.deltaX /\n            this.croppingConstraint;\n        } else {\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.deltaY *\n            this.croppingConstraint;\n        }\n\n        this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n          this._calculateNewCropperSizeByDeltas._.deltaY;\n        this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n          this._calculateNewCropperSizeByDeltas._.deltaX;\n\n        // Make the cropper compress/expand relative to the correct edge to make it feel \"right\"\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n              -this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n              -this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n      } else {\n        // Lock the aspect ratio\n        if (\n          this.shiftKeyHeld &&\n          (cropperDirection === 'tl' ||\n            cropperDirection === 'tr' ||\n            cropperDirection === 'bl' ||\n            cropperDirection === 'br')\n        ) {\n          this._calculateNewCropperSizeByDeltas._.ratio;\n          if (Math.abs(deltaX) > Math.abs(deltaY)) {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaY =\n              this._calculateNewCropperSizeByDeltas._.deltaX /\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaY *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          } else {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaX =\n              this._calculateNewCropperSizeByDeltas._.deltaY *\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaX *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          }\n        }\n\n        if (cropperDirection.match(/t/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n          this._calculateNewCropperSizeByDeltas._.rectangle.height -=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/b/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/r/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n        if (cropperDirection.match(/l/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n          this._calculateNewCropperSizeByDeltas._.rectangle.width -=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n      }\n\n      this._calculateNewCropperSizeByDeltas._.rectangle.top =\n        this._calculateNewCropperSizeByDeltas._.rectangle.top;\n      this._calculateNewCropperSizeByDeltas._.rectangle.left =\n        this._calculateNewCropperSizeByDeltas._.rectangle.left;\n      this._calculateNewCropperSizeByDeltas._.rectangle.width =\n        this._calculateNewCropperSizeByDeltas._.rectangle.width;\n      this._calculateNewCropperSizeByDeltas._.rectangle.height =\n        this._calculateNewCropperSizeByDeltas._.rectangle.height;\n\n      return this._calculateNewCropperSizeByDeltas._.rectangle;\n    },\n\n    /**\n     * Set mouse cursor by it's position over cropper.\n     *\n     * @param ev\n     */\n    _setMouseCursor: function (ev) {\n      if (typeof this._setMouseCursor._ === 'undefined') {\n        this._setMouseCursor._ = {};\n      }\n\n      if (Garnish.isMobileBrowser(true)) {\n        return;\n      }\n      this._setMouseCursor._.cursor = 'default';\n      this._setMouseCursor._.handle =\n        this.croppingCanvas && this._cropperHandleHitTest(ev);\n      if (this.focalPoint && this._isMouseOver(ev, this.focalPoint)) {\n        this._setMouseCursor._.cursor = 'pointer';\n      } else if (this._setMouseCursor._.handle) {\n        if (\n          this._setMouseCursor._.handle === 't' ||\n          this._setMouseCursor._.handle === 'b'\n        ) {\n          this._setMouseCursor._.cursor = 'ns-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'l' ||\n          this._setMouseCursor._.handle === 'r'\n        ) {\n          this._setMouseCursor._.cursor = 'ew-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'tl' ||\n          this._setMouseCursor._.handle === 'br'\n        ) {\n          this._setMouseCursor._.cursor = 'nwse-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'bl' ||\n          this._setMouseCursor._.handle === 'tr'\n        ) {\n          this._setMouseCursor._.cursor = 'nesw-resize';\n        }\n      } else if (this.croppingCanvas && this._isMouseOver(ev, this.clipper)) {\n        this._setMouseCursor._.cursor = 'move';\n      }\n\n      $('.body').css('cursor', this._setMouseCursor._.cursor);\n    },\n\n    /**\n     * Test whether the mouse cursor is on any cropper handles.\n     *\n     * @param ev\n     */\n    _cropperHandleHitTest: function (ev) {\n      if (typeof this._cropperHandleHitTest._ === 'undefined') {\n        this._cropperHandleHitTest._ = {};\n      }\n\n      this._cropperHandleHitTest._.parentOffset = this.$croppingCanvas.offset();\n      this._cropperHandleHitTest._.mouseX =\n        ev.pageX - this._cropperHandleHitTest._.parentOffset.left;\n      this._cropperHandleHitTest._.mouseY =\n        ev.pageY - this._cropperHandleHitTest._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._cropperHandleHitTest._.lb =\n        this.clipper.left - this.clipper.width / 2;\n      this._cropperHandleHitTest._.rb =\n        this._cropperHandleHitTest._.lb + this.clipper.width;\n      this._cropperHandleHitTest._.tb =\n        this.clipper.top - this.clipper.height / 2;\n      this._cropperHandleHitTest._.bb =\n        this._cropperHandleHitTest._.tb + this.clipper.height;\n\n      // Left side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tl';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 3 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'bl';\n        }\n      }\n      // Right side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 13 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tr';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 2 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'br';\n        }\n      }\n\n      // Left or right\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 3 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'l';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 1 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 5 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'r';\n      }\n\n      // Top or bottom\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.tb + 4 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb - 2 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 't';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb + 2 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.bb - 4 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 'b';\n      }\n\n      return false;\n    },\n\n    /**\n     * Test whether the mouse cursor is on a fabricJS object.\n     *\n     * @param object\n     * @param event\n     *\n     * @return boolean\n     */\n\n    _isMouseOver: function (event, object) {\n      if (typeof this._isMouseOver._ === 'undefined') {\n        this._isMouseOver._ = {};\n      }\n\n      this._isMouseOver._.parentOffset = this.$croppingCanvas.offset();\n      this._isMouseOver._.mouseX =\n        event.pageX - this._isMouseOver._.parentOffset.left;\n      this._isMouseOver._.mouseY =\n        event.pageY - this._isMouseOver._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._isMouseOver._.lb = object.left - object.width / 2;\n      this._isMouseOver._.rb = this._isMouseOver._.lb + object.width;\n      this._isMouseOver._.tb = object.top - object.height / 2;\n      this._isMouseOver._.bb = this._isMouseOver._.tb + object.height;\n\n      return (\n        this._isMouseOver._.mouseX >= this._isMouseOver._.lb &&\n        this._isMouseOver._.mouseX <= this._isMouseOver._.rb &&\n        this._isMouseOver._.mouseY >= this._isMouseOver._.tb &&\n        this._isMouseOver._.mouseY <= this._isMouseOver._.bb\n      );\n    },\n\n    /**\n     * Get vertices of a rectangle defined by left,top,height and width properties.\n     * Optionally it's possible to provide offsetX and offsetY values.\n     * Left and top properties of rectangle reference the top-left corner.\n     *\n     * @param rectangle\n     * @param [offsetX]\n     * @param [offsetY]\n     */\n    _getRectangleVertices: function (rectangle, offsetX, offsetY) {\n      if (typeof this._getRectangleVertices._ === 'undefined') {\n        this._getRectangleVertices._ = {};\n      }\n\n      if (typeof offsetX === 'undefined') {\n        offsetX = 0;\n      }\n      if (typeof offsetY === 'undefined') {\n        offsetY = 0;\n      }\n\n      this._getRectangleVertices._.topLeft = {\n        x: rectangle.left + offsetX,\n        y: rectangle.top + offsetY,\n      };\n\n      this._getRectangleVertices._.topRight = {\n        x: this._getRectangleVertices._.topLeft.x + rectangle.width,\n        y: this._getRectangleVertices._.topLeft.y,\n      };\n      this._getRectangleVertices._.bottomRight = {\n        x: this._getRectangleVertices._.topRight.x,\n        y: this._getRectangleVertices._.topRight.y + rectangle.height,\n      };\n      this._getRectangleVertices._.bottomLeft = {\n        x: this._getRectangleVertices._.topLeft.x,\n        y: this._getRectangleVertices._.bottomRight.y,\n      };\n\n      return [\n        this._getRectangleVertices._.topLeft,\n        this._getRectangleVertices._.topRight,\n        this._getRectangleVertices._.bottomRight,\n        this._getRectangleVertices._.bottomLeft,\n      ];\n    },\n\n    /**\n     * Set image vertice coordinates for an image that's been zoomed to fit.\n     */\n    _setFittedImageVerticeCoordinates: function () {\n      this.imageVerticeCoords = this.getImageVerticeCoords('fit');\n    },\n\n    /**\n     * Get image vertice coords by a zoom mode and taking into account the straightening angle.\n     * The zoomMode can be either \"cover\", \"fit\" or a discrete float value.\n     *\n     * @param zoomMode\n     */\n    getImageVerticeCoords: function (zoomMode) {\n      var angleInRadians =\n        -1 *\n        ((this.hasOrientationChanged() ? 90 : 0) + this.imageStraightenAngle) *\n        (Math.PI / 180);\n\n      var imageDimensions = this.getScaledImageDimensions();\n\n      var ratio;\n\n      if (typeof zoomMode === 'number') {\n        ratio = zoomMode;\n      } else if (zoomMode === 'cover') {\n        ratio = this.getZoomToCoverRatio(imageDimensions);\n      } else {\n        ratio = this.getZoomToFitRatio(imageDimensions);\n      }\n\n      // Get the dimensions of the scaled image\n      var scaledHeight = imageDimensions.height * ratio;\n      var scaledWidth = imageDimensions.width * ratio;\n\n      // Calculate the segments of the containing box for the image.\n      // When referring to top/bottom or right/left segments, these are on the\n      // right-side and bottom projection of the containing box for the zoomed out image.\n      var topVerticalSegment = Math.cos(angleInRadians) * scaledHeight;\n      var bottomVerticalSegment = Math.sin(angleInRadians) * scaledWidth;\n      var rightHorizontalSegment = Math.cos(angleInRadians) * scaledWidth;\n      var leftHorizontalSegment = Math.sin(angleInRadians) * scaledHeight;\n\n      // Calculate the offsets from editor box for the image-containing box\n      var verticalOffset =\n        (this.editorHeight - (topVerticalSegment + bottomVerticalSegment)) / 2;\n      var horizontalOffset =\n        (this.editorWidth - (leftHorizontalSegment + rightHorizontalSegment)) /\n        2;\n\n      // Finally, calculate the image vertice coordinates\n      return {\n        a: {\n          x: horizontalOffset + rightHorizontalSegment,\n          y: verticalOffset,\n        },\n        b: {\n          x: this.editorWidth - horizontalOffset,\n          y: verticalOffset + topVerticalSegment,\n        },\n        c: {\n          x: horizontalOffset + leftHorizontalSegment,\n          y: this.editorHeight - verticalOffset,\n        },\n        d: {\n          x: horizontalOffset,\n          y: verticalOffset + bottomVerticalSegment,\n        },\n      };\n    },\n\n    /**\n     * Debug stuff by continuously rendering a fabric object on canvas.\n     *\n     * @param fabricObj\n     */\n    _debug: function (fabricObj) {\n      this.canvas.remove(this.debugger);\n      this.debugger = fabricObj;\n      this.canvas.add(this.debugger);\n    },\n\n    /**\n     * Given an array of points in the form of {x: int, y:int} and a rectangle in the form of\n     * {a:{x:int, y:int}, b:{x:int, y:int}, c:{x:int, y:int}} (the fourth vertice is unnecessary)\n     * return true if the point is in the rectangle.\n     *\n     * Adapted from: http://stackoverflow.com/a/2763387/2040791\n     *\n     * @param points\n     * @param rectangle\n     */\n    arePointsInsideRectangle: function (points, rectangle) {\n      if (typeof this.arePointsInsideRectangle._ === 'undefined') {\n        this.arePointsInsideRectangle._ = {};\n      }\n\n      // Pre-calculate the vectors and scalar products for two rectangle edges\n      this.arePointsInsideRectangle._.ab = this._getVector(\n        rectangle.a,\n        rectangle.b\n      );\n      this.arePointsInsideRectangle._.bc = this._getVector(\n        rectangle.b,\n        rectangle.c\n      );\n      this.arePointsInsideRectangle._.scalarAbAb = this._getScalarProduct(\n        this.arePointsInsideRectangle._.ab,\n        this.arePointsInsideRectangle._.ab\n      );\n      this.arePointsInsideRectangle._.scalarBcBc = this._getScalarProduct(\n        this.arePointsInsideRectangle._.bc,\n        this.arePointsInsideRectangle._.bc\n      );\n\n      for (\n        this.arePointsInsideRectangle._.i = 0;\n        this.arePointsInsideRectangle._.i < points.length;\n        this.arePointsInsideRectangle._.i++\n      ) {\n        this.arePointsInsideRectangle._.point =\n          points[this.arePointsInsideRectangle._.i];\n\n        // Calculate the vectors for two rectangle sides and for\n        // the vector from vertices a and b to the point P\n        this.arePointsInsideRectangle._.ap = this._getVector(\n          rectangle.a,\n          this.arePointsInsideRectangle._.point\n        );\n        this.arePointsInsideRectangle._.bp = this._getVector(\n          rectangle.b,\n          this.arePointsInsideRectangle._.point\n        );\n\n        // Calculate scalar or dot products for some vector combinations\n        this.arePointsInsideRectangle._.scalarAbAp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.ab,\n          this.arePointsInsideRectangle._.ap\n        );\n        this.arePointsInsideRectangle._.scalarBcBp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.bc,\n          this.arePointsInsideRectangle._.bp\n        );\n\n        this.arePointsInsideRectangle._.projectsOnAB =\n          0 <= this.arePointsInsideRectangle._.scalarAbAp &&\n          this.arePointsInsideRectangle._.scalarAbAp <=\n            this.arePointsInsideRectangle._.scalarAbAb;\n        this.arePointsInsideRectangle._.projectsOnBC =\n          0 <= this.arePointsInsideRectangle._.scalarBcBp &&\n          this.arePointsInsideRectangle._.scalarBcBp <=\n            this.arePointsInsideRectangle._.scalarBcBc;\n\n        if (\n          !(\n            this.arePointsInsideRectangle._.projectsOnAB &&\n            this.arePointsInsideRectangle._.projectsOnBC\n          )\n        ) {\n          return false;\n        }\n      }\n\n      return true;\n    },\n\n    /**\n     * Returns an object representing the vector between points a and b.\n     *\n     * @param a\n     * @param b\n     */\n    _getVector: function (a, b) {\n      return {x: b.x - a.x, y: b.y - a.y};\n    },\n\n    /**\n     * Returns the scalar product of two vectors\n     *\n     * @param a\n     * @param b\n     */\n    _getScalarProduct: function (a, b) {\n      return a.x * b.x + a.y * b.y;\n    },\n\n    /**\n     * Returns the magnitude of a vector_redrawCropperElements\n     * .\n     *\n     * @param vector\n     */\n    _getVectorMagnitude: function (vector) {\n      return Math.sqrt(vector.x * vector.x + vector.y * vector.y);\n    },\n\n    /**\n     * Returns the angle between two vectors in degrees with two decimal points\n     *\n     * @param a\n     * @param b\n     */\n    _getAngleBetweenVectors: function (a, b) {\n      return (\n        Math.round(\n          ((Math.acos(\n            Math.min(\n              1,\n              this._getScalarProduct(a, b) /\n                (this._getVectorMagnitude(a) * this._getVectorMagnitude(b))\n            )\n          ) *\n            180) /\n            Math.PI) *\n            100\n        ) / 100\n      );\n    },\n\n    /**\n     * Return the rectangle edge crossed by an imaginary line drawn from editor center to a vertex\n     *\n     * @param rectangle\n     * @param vertex\n     *\n     * @returns {*}\n     */\n    _getEdgeCrossed: function (rectangle, vertex) {\n      // Determine over which edge the vertex is\n      var edgePoints = [\n        [rectangle.a, rectangle.b],\n        [rectangle.b, rectangle.c],\n        [rectangle.c, rectangle.d],\n        [rectangle.d, rectangle.a],\n      ];\n\n      var centerPoint = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n      var smallestDiff = 180;\n      var edgeCrossed = null;\n\n      // Test each edge\n      for (var edgeIndex = 0; edgeIndex < edgePoints.length; edgeIndex++) {\n        var edge = edgePoints[edgeIndex];\n        var toCenter = this._getVector(edge[0], centerPoint);\n        var edgeVector = this._getVector(edge[0], edge[1]);\n        var toVertex = this._getVector(edge[0], vertex);\n\n        // If the angle between toCenter/toVertex is the sum of\n        // angles between edgeVector/toCenter and edgeVector/toVertex, it means that\n        // the edgeVector is between the other two meaning that this is the offending vertex.\n        // To avoid the rounding errors, we'll take the closest match\n        var diff = Math.abs(\n          this._getAngleBetweenVectors(toCenter, toVertex) -\n            (this._getAngleBetweenVectors(toCenter, edgeVector) +\n              this._getAngleBetweenVectors(edgeVector, toVertex))\n        );\n\n        if (diff < smallestDiff) {\n          smallestDiff = diff;\n          edgeCrossed = edge;\n        }\n      }\n\n      return edgeCrossed;\n    },\n\n    /**\n     * Get the image bounding box by image scaled dimensions, taking ingo account the straightening angle.\n     *\n     * @param dimensions\n     */\n    _getImageBoundingBox: function (dimensions) {\n      var box = {};\n\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      var proportion = dimensions.height / dimensions.width;\n      box.height =\n        dimensions.width *\n        (Math.sin(angleInRadians) + Math.cos(angleInRadians) * proportion);\n      box.width =\n        dimensions.width *\n        (Math.cos(angleInRadians) + Math.sin(angleInRadians) * proportion);\n\n      if (this.hasOrientationChanged()) {\n        var temp = box.width;\n        box.width = box.height;\n        box.height = temp;\n      }\n\n      return box;\n    },\n  },\n  {\n    defaults: {\n      animationDuration: 100,\n      allowSavingAsNew: true,\n      onSave: $.noop,\n      allowDegreeFractions: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset index class\n */\nCraft.AssetIndex = Craft.BaseElementIndex.extend({\n  $includeSubfoldersContainer: null,\n  $includeSubfoldersCheckbox: null,\n  showingIncludeSubfoldersCheckbox: false,\n\n  $uploadButton: null,\n  $uploadInput: null,\n  $progressBar: null,\n  $folders: null,\n\n  uploader: null,\n  promptHandler: null,\n  progressBar: null,\n\n  _uploadTotalFiles: 0,\n  _uploadFileProgress: {},\n  _currentUploaderSettings: {},\n\n  _assetDrag: null,\n  _folderDrag: null,\n  _expandDropTargetFolderTimeout: null,\n  _tempExpandedFolders: [],\n\n  _fileConflictTemplate: {\n    choices: [\n      {value: 'keepBoth', title: Craft.t('app', 'Keep both')},\n      {value: 'replace', title: Craft.t('app', 'Replace it')},\n    ],\n  },\n  _folderConflictTemplate: {\n    choices: [\n      {\n        value: 'replace',\n        title: Craft.t(\n          'app',\n          'Replace the folder (all existing files will be deleted)'\n        ),\n      },\n      {\n        value: 'merge',\n        title: Craft.t(\n          'app',\n          'Merge the folder (any conflicting files will be replaced)'\n        ),\n      },\n    ],\n  },\n\n  init: function (elementType, $container, settings) {\n    this.base(elementType, $container, settings);\n\n    if (this.settings.context === 'index') {\n      if (!this._folderDrag) {\n        this._initIndexPageMode();\n      }\n\n      this.addListener(Garnish.$win, 'resize,scroll', '_positionProgressBar');\n    } else {\n      this.addListener(this.$main, 'scroll', '_positionProgressBar');\n\n      if (this.settings.modal) {\n        this.settings.modal.on(\n          'updateSizeAndPosition',\n          this._positionProgressBar.bind(this)\n        );\n      }\n    }\n  },\n\n  initSources: function () {\n    if (this.settings.context === 'index' && !this._folderDrag) {\n      this._initIndexPageMode();\n    }\n\n    return this.base();\n  },\n\n  initSource: function ($source) {\n    this.base($source);\n\n    this._createFolderContextMenu($source);\n\n    if (this.settings.context === 'index') {\n      if (this._folderDrag && this._getSourceLevel($source) > 1) {\n        if ($source.data('folder-id')) {\n          this._folderDrag.addItems($source.parent());\n        }\n      }\n\n      if (this._assetDrag) {\n        this._assetDrag.updateDropTargets();\n      }\n    }\n  },\n\n  deinitSource: function ($source) {\n    this.base($source);\n\n    // Does this source have a context menu?\n    var contextMenu = $source.data('contextmenu');\n\n    if (contextMenu) {\n      contextMenu.destroy();\n    }\n\n    if (this.settings.context === 'index') {\n      if (this._folderDrag && this._getSourceLevel($source) > 1) {\n        this._folderDrag.removeItems($source.parent());\n      }\n\n      if (this._assetDrag) {\n        this._assetDrag.updateDropTargets();\n      }\n    }\n  },\n\n  _getSourceLevel: function ($source) {\n    return $source.parentsUntil('nav', 'ul').length;\n  },\n\n  /**\n   * Initialize the index page-specific features\n   */\n  _initIndexPageMode: function () {\n    if (this._folderDrag) {\n      return;\n    }\n\n    // Make the elements selectable\n    this.settings.selectable = true;\n    this.settings.multiSelect = true;\n\n    // Asset dragging\n    // ---------------------------------------------------------------------\n\n    this._assetDrag = new Garnish.DragDrop({\n      activeDropTargetClass: 'sel',\n      helperOpacity: 0.75,\n      filter: () =>\n        this.view.getSelectedElements().has('div.element[data-movable]'),\n      helper: ($file) => this._getFileDragHelper($file),\n      dropTargets: () => {\n        // Which data attribute should we be checking?\n        var attr;\n        if (\n          this._assetDrag.$draggee &&\n          this._assetDrag.$draggee.has('.element[data-peer-file]').length\n        ) {\n          attr = 'data-can-move-peer-files-to';\n        } else {\n          attr = 'data-can-move-to';\n        }\n\n        var targets = [];\n\n        for (var i = 0; i < this.$sources.length; i++) {\n          // Make sure it's a volume folder\n          var $source = this.$sources.eq(i);\n          if (Garnish.hasAttr($source, attr)) {\n            targets.push($source);\n          }\n        }\n\n        return targets;\n      },\n\n      onDragStart: this._onDragStart.bind(this),\n      onDropTargetChange: this._onDropTargetChange.bind(this),\n      onDragStop: this._onFileDragStop.bind(this),\n      helperBaseZindex: 800,\n    });\n\n    // Folder dragging\n    // ---------------------------------------------------------------------\n\n    this._folderDrag = new Garnish.DragDrop({\n      activeDropTargetClass: 'sel',\n      helperOpacity: 0.75,\n\n      helper: ($draggeeHelper) => {\n        var $helperSidebar = $('<div class=\"sidebar drag-helper\"/>'),\n          $helperNav = $('<nav/>').appendTo($helperSidebar),\n          $helperUl = $('<ul/>').appendTo($helperNav);\n\n        $draggeeHelper.appendTo($helperUl).removeClass('expanded');\n        $draggeeHelper.children('a').addClass('sel');\n\n        // Match the style\n        $draggeeHelper.css({\n          'padding-top': this._folderDrag.$draggee.css('padding-top'),\n          'padding-right': this._folderDrag.$draggee.css('padding-right'),\n          'padding-bottom': this._folderDrag.$draggee.css('padding-bottom'),\n          'padding-left': this._folderDrag.$draggee.css('padding-left'),\n        });\n\n        return $helperSidebar;\n      },\n\n      dropTargets: () => {\n        var targets = [];\n\n        // Tag the dragged folder and it's subfolders\n        var draggedSourceIds = [];\n        this._folderDrag.$draggee.find('a[data-key]').each(function () {\n          draggedSourceIds.push($(this).data('key'));\n        });\n\n        for (var i = 0; i < this.$sources.length; i++) {\n          // Make sure it's a volume folder and not one of the dragged folders\n          var $source = this.$sources.eq(i),\n            key = $source.data('key');\n\n          if (!this._getFolderUidFromSourceKey(key)) {\n            continue;\n          }\n\n          if (!Craft.inArray(key, draggedSourceIds)) {\n            targets.push($source);\n          }\n        }\n\n        return targets;\n      },\n\n      onDragStart: this._onDragStart.bind(this),\n      onDropTargetChange: this._onDropTargetChange.bind(this),\n      onDragStop: this._onFolderDragStop.bind(this),\n    });\n  },\n\n  /**\n   * On file drag stop\n   */\n  _onFileDragStop: function () {\n    if (\n      this._assetDrag.$activeDropTarget &&\n      this._assetDrag.$activeDropTarget[0] !== this.$source[0]\n    ) {\n      // Keep it selected\n      var originatingSource = this.$source;\n\n      var targetFolderId = this._assetDrag.$activeDropTarget.data('folder-id'),\n        originalAssetIds = [];\n\n      // For each file, prepare array data.\n      for (var i = 0; i < this._assetDrag.$draggee.length; i++) {\n        var originalAssetId = Craft.getElementInfo(\n          this._assetDrag.$draggee[i]\n        ).id;\n\n        originalAssetIds.push(originalAssetId);\n      }\n\n      // Are any files actually getting moved?\n      if (originalAssetIds.length) {\n        this.setIndexBusy();\n\n        this._positionProgressBar();\n        this.progressBar.resetProgressBar();\n        this.progressBar.setItemCount(originalAssetIds.length);\n        this.progressBar.showProgressBar();\n\n        // For each file to move a separate request\n        var parameterArray = [];\n        for (i = 0; i < originalAssetIds.length; i++) {\n          parameterArray.push({\n            action: 'assets/move-asset',\n            params: {\n              assetId: originalAssetIds[i],\n              folderId: targetFolderId,\n            },\n          });\n        }\n\n        // Define the callback for when all file moves are complete\n        var onMoveFinish = (responseArray) => {\n          this.promptHandler.resetPrompts();\n\n          // Loop trough all the responses\n          for (var i = 0; i < responseArray.length; i++) {\n            var response = responseArray[i];\n\n            // Push prompt into prompt array\n            if (response.conflict) {\n              this.promptHandler.addPrompt({\n                assetId: response.assetId,\n                suggestedFilename: response.suggestedFilename,\n                prompt: {\n                  message: response.conflict,\n                  choices: this._fileConflictTemplate.choices,\n                },\n              });\n            }\n\n            if (response.error) {\n              alert(response.error);\n            }\n          }\n\n          this.setIndexAvailable();\n          this.progressBar.hideProgressBar();\n          var reloadIndex = false;\n\n          var performAfterMoveActions = function () {\n            // Select original source\n            this.sourceSelect.selectItem(originatingSource);\n\n            // Make sure we use the correct offset when fetching the next page\n            this._totalVisible -= this._assetDrag.$draggee.length;\n\n            // And remove the elements that have been moved away\n            for (var i = 0; i < originalAssetIds.length; i++) {\n              $('[data-id=' + originalAssetIds[i] + ']').remove();\n            }\n\n            this.view.deselectAllElements();\n            this._collapseExtraExpandedFolders(targetFolderId);\n\n            if (reloadIndex) {\n              this.updateElements();\n            }\n          };\n\n          if (this.promptHandler.getPromptCount()) {\n            // Define callback for completing all prompts\n            var promptCallback = (returnData) => {\n              var newParameterArray = [];\n\n              // Loop trough all returned data and prepare a new request array\n              for (var i = 0; i < returnData.length; i++) {\n                if (returnData[i].choice === 'cancel') {\n                  reloadIndex = true;\n                  continue;\n                }\n\n                if (returnData[i].choice === 'keepBoth') {\n                  newParameterArray.push({\n                    action: 'assets/move-asset',\n                    params: {\n                      folderId: targetFolderId,\n                      assetId: returnData[i].assetId,\n                      filename: returnData[i].suggestedFilename,\n                    },\n                  });\n                }\n\n                if (returnData[i].choice === 'replace') {\n                  newParameterArray.push({\n                    action: 'assets/move-asset',\n                    params: {\n                      folderId: targetFolderId,\n                      assetId: returnData[i].assetId,\n                      force: true,\n                    },\n                  });\n                }\n              }\n\n              // Nothing to do, carry on\n              if (newParameterArray.length === 0) {\n                performAfterMoveActions.apply(this);\n              } else {\n                // Start working\n                this.setIndexBusy();\n                this.progressBar.resetProgressBar();\n                this.progressBar.setItemCount(\n                  this.promptHandler.getPromptCount()\n                );\n                this.progressBar.showProgressBar();\n\n                // Move conflicting files again with resolutions now\n                this._performBatchRequests(newParameterArray, onMoveFinish);\n              }\n            };\n\n            this._assetDrag.fadeOutHelpers();\n            this.promptHandler.showBatchPrompts(promptCallback);\n          } else {\n            performAfterMoveActions.apply(this);\n            this._assetDrag.fadeOutHelpers();\n          }\n        };\n\n        // Initiate the file move with the built array, index of 0 and callback to use when done\n        this._performBatchRequests(parameterArray, onMoveFinish);\n\n        // Skip returning dragees\n        return;\n      }\n    } else {\n      // Add the .sel class back on the selected source\n      this.$source.addClass('sel');\n\n      this._collapseExtraExpandedFolders();\n    }\n\n    this._assetDrag.returnHelpersToDraggees();\n  },\n\n  /**\n   * On folder drag stop\n   */\n  _onFolderDragStop: function () {\n    // Only move if we have a valid target and we're not trying to move into our direct parent\n    if (\n      this._folderDrag.$activeDropTarget &&\n      this._folderDrag.$activeDropTarget\n        .siblings('ul')\n        .children('li')\n        .filter(this._folderDrag.$draggee).length === 0\n    ) {\n      var targetFolderId = this._folderDrag.$activeDropTarget.data('folder-id');\n\n      this._collapseExtraExpandedFolders(targetFolderId);\n\n      // Get the old folder IDs, and sort them so that we're moving the most-nested folders first\n      var folderIds = [];\n\n      for (var i = 0; i < this._folderDrag.$draggee.length; i++) {\n        var $a = this._folderDrag.$draggee.eq(i).children('a'),\n          folderId = $a.data('folder-id');\n\n        // Make sure it's not already in the target folder and use this single folder Id.\n        if (folderId != targetFolderId) {\n          folderIds.push(folderId);\n          break;\n        }\n      }\n\n      if (folderIds.length) {\n        folderIds.sort();\n        folderIds.reverse();\n\n        this.setIndexBusy();\n        this._positionProgressBar();\n        this.progressBar.resetProgressBar();\n        this.progressBar.setItemCount(folderIds.length);\n        this.progressBar.showProgressBar();\n\n        var parameterArray = [];\n\n        for (i = 0; i < folderIds.length; i++) {\n          parameterArray.push({\n            action: 'assets/move-folder',\n            params: {\n              folderId: folderIds[i],\n              parentId: targetFolderId,\n            },\n          });\n        }\n\n        // Increment, so to avoid displaying folder files that are being moved\n        this.requestId++;\n\n        /*\n                 Here's the rundown:\n                 1) Send all the folders being moved\n                 2) Get results:\n                 a) For all conflicting, receive prompts and resolve them to get:\n                 b) For all valid move operations: by now server has created the needed folders\n                 in target destination. Server returns an array of file move operations\n                 c) server also returns a list of all the folder id changes\n                 d) and the data-id of node to be removed, in case of conflict\n                 e) and a list of folders to delete after the move\n                 3) From data in 2) build a large file move operation array\n                 4) Create a request loop based on this, so we can display progress bar\n                 5) when done, delete all the folders and perform other maintenance\n                 6) Champagne\n                 */\n\n        // This will hold the final list of files to move\n        var fileMoveList = [];\n\n        var newSourceKey = '';\n\n        var onMoveFinish = (responseArray) => {\n          this.promptHandler.resetPrompts();\n\n          // Loop trough all the responses\n          for (var i = 0; i < responseArray.length; i++) {\n            var data = responseArray[i];\n\n            // If successful and have data, then update\n            if (data.success) {\n              if (data.transferList) {\n                fileMoveList = data.transferList;\n              }\n\n              if (data.newFolderId) {\n                newSourceKey =\n                  this._folderDrag.$activeDropTarget.data('key') +\n                  '/folder:' +\n                  data.newFolderUid;\n              }\n            }\n\n            // Push prompt into prompt array\n            if (data.conflict) {\n              data.prompt = {\n                message: data.conflict,\n                choices: this._folderConflictTemplate.choices,\n              };\n\n              this.promptHandler.addPrompt(data);\n            }\n\n            if (data.error) {\n              alert(data.error);\n            }\n          }\n\n          if (this.promptHandler.getPromptCount()) {\n            // Define callback for completing all prompts\n            var promptCallback = (returnData) => {\n              this.promptHandler.resetPrompts();\n\n              var newParameterArray = [];\n\n              var params = {};\n              // Loop trough all returned data and prepare a new request array\n              for (var i = 0; i < returnData.length; i++) {\n                if (returnData[i].choice === 'cancel') {\n                  continue;\n                }\n\n                if (returnData[i].choice === 'replace') {\n                  params.force = true;\n                }\n\n                if (returnData[i].choice === 'merge') {\n                  params.merge = true;\n                }\n\n                params.folderId = data.folderId;\n                params.parentId = data.parentId;\n\n                newParameterArray.push({\n                  action: 'assets/move-folder',\n                  params: params,\n                });\n              }\n\n              // Start working on them lists, baby\n              if (newParameterArray.length === 0) {\n                this._performActualFolderMove(\n                  fileMoveList,\n                  folderIds,\n                  newSourceKey\n                );\n              } else {\n                // Start working\n                this.setIndexBusy();\n                this.progressBar.resetProgressBar();\n                this.progressBar.setItemCount(\n                  this.promptHandler.getPromptCount()\n                );\n                this.progressBar.showProgressBar();\n\n                this._performBatchRequests(newParameterArray, onMoveFinish);\n              }\n            };\n\n            this.promptHandler.showBatchPrompts(promptCallback);\n\n            this.setIndexAvailable();\n            this.progressBar.hideProgressBar();\n          } else {\n            this._performActualFolderMove(\n              fileMoveList,\n              folderIds,\n              newSourceKey\n            );\n          }\n        };\n\n        // Initiate the folder move with the built array, index of 0 and callback to use when done\n        this._performBatchRequests(parameterArray, onMoveFinish);\n\n        // Skip returning dragees until we get the Ajax response\n        return;\n      }\n    } else {\n      // Add the .sel class back on the selected source\n      this.$source.addClass('sel');\n\n      this._collapseExtraExpandedFolders();\n    }\n\n    this._folderDrag.returnHelpersToDraggees();\n  },\n\n  /**\n   * Really move the folder. Like really. For real.\n   */\n  _performActualFolderMove: function (\n    fileMoveList,\n    folderDeleteList,\n    newSourceKey\n  ) {\n    this.setIndexBusy();\n    this.progressBar.resetProgressBar();\n    this.progressBar.setItemCount(1);\n    this.progressBar.showProgressBar();\n\n    var moveCallback = (folderDeleteList) => {\n      // Delete the old folders\n      var counter = 0;\n      var limit = folderDeleteList.length;\n      for (var i = 0; i < folderDeleteList.length; i++) {\n        // When all folders are deleted, reload the sources.\n        Craft.postActionRequest(\n          'assets/delete-folder',\n          {folderId: folderDeleteList[i]},\n          () => {\n            if (++counter === limit) {\n              this.setIndexAvailable();\n              this.progressBar.hideProgressBar();\n              this._folderDrag.returnHelpersToDraggees();\n              this.setInstanceState('selectedSource', newSourceKey);\n              this.refreshSources();\n            }\n          }\n        );\n      }\n    };\n\n    if (fileMoveList.length > 0) {\n      var parameterArray = [];\n\n      for (var i = 0; i < fileMoveList.length; i++) {\n        parameterArray.push({\n          action: 'assets/move-asset',\n          params: fileMoveList[i],\n        });\n      }\n      this._performBatchRequests(parameterArray, function () {\n        moveCallback(folderDeleteList);\n      });\n    } else {\n      moveCallback(folderDeleteList);\n    }\n  },\n\n  /**\n   * Returns the root level source for a source.\n   *\n   * @param $source\n   * @returns {*}\n   * @private\n   */\n  _getRootSource: function ($source) {\n    var $parent;\n    while (($parent = this._getParentSource($source)) && $parent.length) {\n      $source = $parent;\n    }\n    return $source;\n  },\n\n  /**\n   * Get parent source for a source.\n   *\n   * @param $source\n   * @returns {*}\n   * @private\n   */\n  _getParentSource: function ($source) {\n    if (this._getSourceLevel($source) > 1) {\n      return $source.parent().parent().siblings('a');\n    }\n  },\n\n  _selectSourceByFolderId: function (targetFolderId) {\n    var $targetSource = this._getSourceByKey(targetFolderId);\n\n    // Make sure that all the parent sources are expanded and this source is visible.\n    var $parentSources = $targetSource.parent().parents('li');\n\n    for (var i = 0; i < $parentSources.length; i++) {\n      var $parentSource = $($parentSources[i]);\n\n      if (!$parentSource.hasClass('expanded')) {\n        $parentSource.children('.toggle').trigger('click');\n      }\n    }\n\n    this.selectSource($targetSource);\n    this.updateElements();\n  },\n\n  /**\n   * Initialize the uploader.\n   *\n   * @private\n   */\n  afterInit: function () {\n    if (!this.$uploadButton) {\n      this.$uploadButton = $('<button/>', {\n        type: 'button',\n        class: 'btn submit',\n        'data-icon': 'upload',\n        style: 'position: relative; overflow: hidden;',\n        text: Craft.t('app', 'Upload files'),\n      });\n      this.addButton(this.$uploadButton);\n\n      this.$uploadInput = $(\n        '<input type=\"file\" multiple=\"multiple\" name=\"assets-upload\" />'\n      )\n        .hide()\n        .insertBefore(this.$uploadButton);\n    }\n\n    this.promptHandler = new Craft.PromptHandler();\n    this.progressBar = new Craft.ProgressBar(this.$main, true);\n\n    var options = {\n      url: Craft.getActionUrl('assets/upload'),\n      fileInput: this.$uploadInput,\n      dropZone: this.$container,\n    };\n\n    options.events = {\n      fileuploadstart: this._onUploadStart.bind(this),\n      fileuploadprogressall: this._onUploadProgress.bind(this),\n      fileuploaddone: this._onUploadComplete.bind(this),\n      fileuploadfail: this._onUploadFailure.bind(this),\n    };\n\n    if (\n      this.settings.criteria &&\n      typeof this.settings.criteria.kind !== 'undefined'\n    ) {\n      options.allowedKinds = this.settings.criteria.kind;\n    }\n\n    this._currentUploaderSettings = options;\n\n    this.uploader = new Craft.Uploader(this.$uploadButton, options);\n\n    this.$uploadButton.on('click', () => {\n      if (this.$uploadButton.hasClass('disabled')) {\n        return;\n      }\n      if (!this.isIndexBusy) {\n        this.$uploadButton\n          .parent()\n          .find('input[name=assets-upload]')\n          .trigger('click');\n      }\n    });\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific volume in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof window.defaultSource !== 'undefined'\n    ) {\n      let defaultSourceParts = window.defaultSource.split('/');\n      let volumeSource = this.$sources.toArray().find((s) => {\n        return $(s).data('volume-handle') === defaultSourceParts[0];\n      });\n      if (volumeSource) {\n        let $source = $(volumeSource);\n\n        for (let i = 1; i < defaultSourceParts.length; i++) {\n          // does $source have a subfolder with this path name?\n          let subfolderSource = this._getChildSources($source)\n            .toArray()\n            .find((s) => {\n              return $('> .label', s).text() === defaultSourceParts[i];\n            });\n          if (!subfolderSource) {\n            break;\n          }\n          this._expandSource($source);\n          $source = $(subfolderSource);\n        }\n\n        return $source.data('key');\n      }\n    }\n\n    return this.base();\n  },\n\n  onSelectSource: function () {\n    var $source = this._getSourceByKey(this.sourceKey);\n    var folderId = $source.data('folder-id');\n\n    if (folderId && Garnish.hasAttr(this.$source, 'data-can-upload')) {\n      this.uploader.setParams({\n        folderId: this.$source.attr('data-folder-id'),\n      });\n      this.$uploadButton.removeClass('disabled');\n    } else {\n      this.$uploadButton.addClass('disabled');\n    }\n\n    // Update the URL if we're on the Assets index\n    if ($source.length && this.settings.context === 'index') {\n      this._updateUrl($source);\n    }\n\n    this.base();\n  },\n\n  _updateUrl: function ($source) {\n    if (typeof history === 'undefined') {\n      return;\n    }\n\n    // Find all the subfolder sources. At the end, $thisSource will be the root volume source\n    let nestedSources = [];\n    let $thisSource = $source;\n    let $parent;\n    while (($parent = this._getParentSource($thisSource)) && $parent.length) {\n      nestedSources.unshift($thisSource);\n      $thisSource = $parent;\n    }\n\n    let uri = 'assets';\n    if ($thisSource.data('volume-handle')) {\n      uri += '/' + $thisSource.data('volume-handle');\n      nestedSources.forEach(($s) => {\n        uri += '/' + $s.children('.label').text();\n      });\n    }\n\n    history.replaceState({}, '', Craft.getUrl(uri));\n  },\n\n  _getFolderUidFromSourceKey: function (sourceKey) {\n    var m = sourceKey.match(/\\bfolder:([0-9a-f\\-]+)$/);\n\n    return m ? m[1] : null;\n  },\n\n  startSearching: function () {\n    // Does this source have subfolders?\n    if (!this.settings.hideSidebar && this.$source.siblings('ul').length) {\n      if (this.$includeSubfoldersContainer === null) {\n        var id = 'includeSubfolders-' + Math.floor(Math.random() * 1000000000);\n\n        this.$includeSubfoldersContainer = $(\n          '<div style=\"margin-bottom: -25px; opacity: 0;\"/>'\n        ).insertAfter(this.$search);\n        var $subContainer = $('<div style=\"padding-top: 5px;\"/>').appendTo(\n          this.$includeSubfoldersContainer\n        );\n        this.$includeSubfoldersCheckbox = $(\n          '<input type=\"checkbox\" id=\"' + id + '\" class=\"checkbox\"/>'\n        ).appendTo($subContainer);\n        $('<label class=\"light smalltext\" for=\"' + id + '\"/>')\n          .text(' ' + Craft.t('app', 'Search in subfolders'))\n          .appendTo($subContainer);\n\n        this.addListener(\n          this.$includeSubfoldersCheckbox,\n          'change',\n          function () {\n            this.setSelecetedSourceState(\n              'includeSubfolders',\n              this.$includeSubfoldersCheckbox.prop('checked')\n            );\n            this.updateElements();\n          }\n        );\n      } else {\n        this.$includeSubfoldersContainer.velocity('stop');\n      }\n\n      var checked = this.getSelectedSourceState('includeSubfolders', false);\n      this.$includeSubfoldersCheckbox.prop('checked', checked);\n\n      this.$includeSubfoldersContainer.velocity(\n        {\n          marginBottom: 0,\n          opacity: 1,\n        },\n        'fast'\n      );\n\n      this.showingIncludeSubfoldersCheckbox = true;\n    }\n\n    this.base();\n  },\n\n  stopSearching: function () {\n    if (this.showingIncludeSubfoldersCheckbox) {\n      this.$includeSubfoldersContainer.velocity('stop');\n\n      this.$includeSubfoldersContainer.velocity(\n        {\n          marginBottom: -25,\n          opacity: 0,\n        },\n        'fast'\n      );\n\n      this.showingIncludeSubfoldersCheckbox = false;\n    }\n\n    this.base();\n  },\n\n  getViewParams: function () {\n    var data = this.base();\n\n    if (\n      this.showingIncludeSubfoldersCheckbox &&\n      this.$includeSubfoldersCheckbox.prop('checked')\n    ) {\n      data.criteria.includeSubfolders = true;\n    }\n\n    return data;\n  },\n\n  /**\n   * React on upload submit.\n   *\n   * @private\n   */\n  _onUploadStart: function () {\n    this.setIndexBusy();\n\n    // Initial values\n    this._positionProgressBar();\n    this.progressBar.resetProgressBar();\n    this.progressBar.showProgressBar();\n\n    this.promptHandler.resetPrompts();\n  },\n\n  /**\n   * Update uploaded byte count.\n   */\n  _onUploadProgress: function (event, data) {\n    var progress = parseInt((data.loaded / data.total) * 100, 10);\n    this.progressBar.setProgressPercentage(progress);\n  },\n\n  /**\n   * On Upload Complete.\n   */\n  _onUploadComplete: function (event, data) {\n    var response = data.result;\n    var filename = data.files[0].name;\n\n    var doReload = true;\n\n    if (response.success || response.conflict) {\n      // Add the uploaded file to the selected ones, if appropriate\n      this.selectElementAfterUpdate(response.assetId);\n\n      // If there is a prompt, add it to the queue\n      if (response.conflict) {\n        response.prompt = {\n          message: Craft.t('app', response.conflict, {file: response.filename}),\n          choices: this._fileConflictTemplate.choices,\n        };\n\n        this.promptHandler.addPrompt(response);\n      }\n\n      Craft.cp.runQueue();\n    } else {\n      if (response.error) {\n        alert(\n          Craft.t('app', 'Upload failed. The error message was: “{error}”', {\n            error: response.error,\n          })\n        );\n      } else {\n        alert(Craft.t('app', 'Upload failed for {filename}.', {filename}));\n      }\n\n      doReload = false;\n    }\n\n    // For the last file, display prompts, if any. If not - just update the element view.\n    if (this.uploader.isLastUpload()) {\n      this.progressBar.hideProgressBar();\n      this.setIndexAvailable();\n\n      if (this.promptHandler.getPromptCount()) {\n        this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this));\n      } else {\n        if (doReload) {\n          this._updateAfterUpload();\n        }\n      }\n    }\n  },\n\n  /**\n   * On Upload Failure.\n   */\n  _onUploadFailure: function (event, data) {\n    if (data.jqXHR.responseJSON.error) {\n      alert(data.jqXHR.responseJSON.error);\n      this.progressBar.hideProgressBar();\n      this.setIndexAvailable();\n    }\n  },\n\n  /**\n   * Update the elements after an upload, setting sort to dateModified descending, if not using index.\n   *\n   * @private\n   */\n  _updateAfterUpload: function () {\n    if (this.settings.context !== 'index') {\n      this.clearSearch();\n      this.setSortAttribute('dateCreated');\n      this.setSortDirection('desc');\n    }\n    this.updateElements();\n  },\n\n  /**\n   * Follow up to an upload that triggered at least one conflict resolution prompt.\n   *\n   * @param returnData\n   * @private\n   */\n  _uploadFollowup: function (returnData) {\n    this.setIndexBusy();\n    this.progressBar.resetProgressBar();\n\n    this.promptHandler.resetPrompts();\n\n    var finalCallback = () => {\n      this.progressBar.hideProgressBar();\n      this.setIndexAvailable();\n      this._updateAfterUpload();\n    };\n\n    this.progressBar.setItemCount(returnData.length);\n\n    var doFollowup = (parameterArray, parameterIndex, callback) => {\n      var postData = {};\n      var action = null;\n\n      var followupCallback = (data, textStatus) => {\n        if (textStatus === 'success' && data.assetId) {\n          this.selectElementAfterUpdate(data.assetId);\n        } else if (data.error) {\n          alert(data.error);\n        }\n        parameterIndex++;\n        this.progressBar.incrementProcessedItemCount(1);\n        this.progressBar.updateProgressBar();\n\n        if (parameterIndex === parameterArray.length) {\n          callback();\n        } else {\n          doFollowup(parameterArray, parameterIndex, callback);\n        }\n      };\n\n      if (parameterArray[parameterIndex].choice === 'replace') {\n        action = 'assets/replace-file';\n        postData.sourceAssetId = parameterArray[parameterIndex].assetId;\n\n        if (parameterArray[parameterIndex].conflictingAssetId) {\n          postData.assetId = parameterArray[parameterIndex].conflictingAssetId;\n        } else {\n          postData.targetFilename = parameterArray[parameterIndex].filename;\n        }\n      } else if (parameterArray[parameterIndex].choice === 'cancel') {\n        action = 'assets/delete-asset';\n        postData.assetId = parameterArray[parameterIndex].assetId;\n      }\n\n      if (!action) {\n        // We don't really need to do another request, so let's pretend that already happened\n        followupCallback(\n          {assetId: parameterArray[parameterIndex].assetId},\n          'success'\n        );\n      } else {\n        Craft.postActionRequest(action, postData, followupCallback);\n      }\n    };\n\n    this.progressBar.showProgressBar();\n    doFollowup(returnData, 0, finalCallback);\n  },\n\n  /**\n   * Perform actions after updating elements\n   * @private\n   */\n  onUpdateElements: function () {\n    this._onUpdateElements(false, this.view.getAllElements());\n    this.view.on('appendElements', (ev) => {\n      this._onUpdateElements(true, ev.newElements);\n    });\n\n    this.base();\n  },\n\n  /**\n   * Do the after-update initializations\n   * @private\n   */\n  _onUpdateElements: function (append, $newElements) {\n    if (this.settings.context === 'index') {\n      if (!append) {\n        this._assetDrag.removeAllItems();\n      }\n\n      this._assetDrag.addItems($newElements.has('div.element[data-movable]'));\n    }\n\n    this.base(append, $newElements);\n\n    this.removeListener(this.$elements, 'keydown');\n    this.addListener(this.$elements, 'keydown', this._onKeyDown.bind(this));\n    this.view.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n  },\n\n  /**\n   * Handle a keypress\n   * @private\n   */\n  _onKeyDown: function (ev) {\n    if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n      if (Craft.PreviewFileModal.openInstance) {\n        Craft.PreviewFileModal.openInstance.selfDestruct();\n      } else {\n        var $element = this.view.elementSelect.$focusedItem.find('.element');\n\n        if ($element.length) {\n          this._loadPreview($element);\n        }\n      }\n\n      ev.stopPropagation();\n      return false;\n    }\n  },\n\n  /**\n   * Handle element being focused\n   * @private\n   */\n  _onElementFocus: function (ev) {\n    var $element = $(ev.item).find('.element');\n\n    if (Craft.PreviewFileModal.openInstance && $element.length) {\n      this._loadPreview($element);\n    }\n  },\n\n  /**\n   * Load the preview for an Asset element\n   * @private\n   */\n  _loadPreview: function ($element) {\n    var settings = {};\n\n    if ($element.data('image-width')) {\n      settings.startingWidth = $element.data('image-width');\n      settings.startingHeight = $element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(\n      $element.data('id'),\n      this.view.elementSelect,\n      settings\n    );\n  },\n\n  /**\n   * On Drag Start\n   */\n  _onDragStart: function () {\n    this._tempExpandedFolders = [];\n  },\n\n  /**\n   * Get File Drag Helper\n   */\n  _getFileDragHelper: function ($element) {\n    var currentView = this.getSelectedSourceState('mode');\n    var $outerContainer;\n    var $innerContainer;\n\n    switch (currentView) {\n      case 'table': {\n        $outerContainer = $(\n          '<div class=\"elements datatablesorthelper\"/>'\n        ).appendTo(Garnish.$bod);\n        $innerContainer = $('<div class=\"tableview\"/>').appendTo(\n          $outerContainer\n        );\n        var $table = $('<table class=\"data\"/>').appendTo($innerContainer);\n        var $tbody = $('<tbody/>').appendTo($table);\n\n        $element.appendTo($tbody);\n\n        // Copy the column widths\n        this._$firstRowCells = this.view.$table\n          .children('tbody')\n          .children('tr:first')\n          .children();\n        var $helperCells = $element.children();\n\n        for (var i = 0; i < $helperCells.length; i++) {\n          // Hard-set the cell widths\n          var $helperCell = $($helperCells[i]);\n\n          // Skip the checkbox cell\n          if ($helperCell.hasClass('checkbox-cell')) {\n            $helperCell.remove();\n            $outerContainer.css('margin-' + Craft.left, 19); // 26 - 7\n            continue;\n          }\n\n          var $firstRowCell = $(this._$firstRowCells[i]),\n            width = $firstRowCell.width();\n\n          $firstRowCell.width(width);\n          $helperCell.width(width);\n        }\n\n        return $outerContainer;\n      }\n      case 'thumbs': {\n        $outerContainer = $('<div class=\"elements thumbviewhelper\"/>').appendTo(\n          Garnish.$bod\n        );\n        $innerContainer = $('<ul class=\"thumbsview\"/>').appendTo(\n          $outerContainer\n        );\n\n        $element.appendTo($innerContainer);\n\n        return $outerContainer;\n      }\n    }\n\n    return $();\n  },\n\n  /**\n   * On Drop Target Change\n   */\n  _onDropTargetChange: function ($dropTarget) {\n    clearTimeout(this._expandDropTargetFolderTimeout);\n\n    if ($dropTarget) {\n      var folderId = $dropTarget.data('folder-id');\n\n      if (folderId) {\n        this.dropTargetFolder = this._getSourceByKey(folderId);\n\n        if (\n          this._hasSubfolders(this.dropTargetFolder) &&\n          !this._isExpanded(this.dropTargetFolder)\n        ) {\n          this._expandDropTargetFolderTimeout = setTimeout(\n            this._expandFolder.bind(this),\n            500\n          );\n        }\n      } else {\n        this.dropTargetFolder = null;\n      }\n    }\n\n    if ($dropTarget && $dropTarget[0] !== this.$source[0]) {\n      // Temporarily remove the .sel class on the active source\n      this.$source.removeClass('sel');\n    } else {\n      this.$source.addClass('sel');\n    }\n  },\n\n  /**\n   * Collapse Extra Expanded Folders\n   */\n  _collapseExtraExpandedFolders: function (dropTargetFolderId) {\n    clearTimeout(this._expandDropTargetFolderTimeout);\n\n    // If a source ID is passed in, exclude its parents\n    var $excludedSources;\n\n    if (dropTargetFolderId) {\n      $excludedSources = this._getSourceByKey(dropTargetFolderId)\n        .parents('li')\n        .children('a');\n    }\n\n    for (var i = this._tempExpandedFolders.length - 1; i >= 0; i--) {\n      var $source = this._tempExpandedFolders[i];\n\n      // Check the parent list, if a source id is passed in\n      if (\n        typeof $excludedSources === 'undefined' ||\n        $excludedSources.filter('[data-key=\"' + $source.data('key') + '\"]')\n          .length === 0\n      ) {\n        this._collapseFolder($source);\n        this._tempExpandedFolders.splice(i, 1);\n      }\n    }\n  },\n\n  _getSourceByKey: function (key) {\n    return this.$sources.filter('[data-key$=\"' + key + '\"]');\n  },\n\n  _hasSubfolders: function ($source) {\n    return $source.siblings('ul').find('li').length;\n  },\n\n  _isExpanded: function ($source) {\n    return $source.parent('li').hasClass('expanded');\n  },\n\n  _expandFolder: function () {\n    // Collapse any temp-expanded drop targets that aren't parents of this one\n    this._collapseExtraExpandedFolders(this.dropTargetFolder.data('folder-id'));\n\n    this.dropTargetFolder.siblings('.toggle').trigger('click');\n\n    // Keep a record of that\n    this._tempExpandedFolders.push(this.dropTargetFolder);\n  },\n\n  _collapseFolder: function ($source) {\n    if ($source.parent().hasClass('expanded')) {\n      $source.siblings('.toggle').trigger('click');\n    }\n  },\n\n  _createFolderContextMenu: function ($source) {\n    // Make sure it's a volume folder\n    if (!this._getFolderUidFromSourceKey($source.data('key'))) {\n      return;\n    }\n\n    var menuOptions = [\n      {\n        label: Craft.t('app', 'New subfolder'),\n        onClick: () => {\n          this._createSubfolder($source);\n        },\n      },\n    ];\n\n    // For all folders that are not top folders\n    if (\n      this.settings.context === 'index' &&\n      this._getSourceLevel($source) > 1\n    ) {\n      menuOptions.push({\n        label: Craft.t('app', 'Rename folder'),\n        onClick: () => {\n          this._renameFolder($source);\n        },\n      });\n      menuOptions.push({\n        label: Craft.t('app', 'Delete folder'),\n        onClick: () => {\n          this._deleteFolder($source);\n        },\n      });\n    }\n\n    new Garnish.ContextMenu($source, menuOptions, {menuClass: 'menu'});\n  },\n\n  _createSubfolder: function ($parentFolder) {\n    var subfolderName = prompt(Craft.t('app', 'Enter the name of the folder'));\n\n    if (subfolderName) {\n      var params = {\n        parentId: $parentFolder.data('folder-id'),\n        folderName: subfolderName,\n      };\n\n      this.setIndexBusy();\n\n      Craft.postActionRequest(\n        'assets/create-folder',\n        params,\n        (data, textStatus) => {\n          this.setIndexAvailable();\n\n          if (textStatus === 'success' && data.success) {\n            this._prepareParentForChildren($parentFolder);\n\n            var $subfolder = $(\n              '<li>' +\n                '<a data-key=\"' +\n                $parentFolder.data('key') +\n                '/folder:' +\n                data.folderUid +\n                '\"' +\n                (Garnish.hasAttr($parentFolder, 'data-has-thumbs')\n                  ? ' data-has-thumbs'\n                  : '') +\n                ' data-folder-id=\"' +\n                data.folderId +\n                '\"' +\n                (Garnish.hasAttr($parentFolder, 'data-can-upload')\n                  ? ' data-can-upload'\n                  : '') +\n                (Garnish.hasAttr($parentFolder, 'data-can-move-to')\n                  ? ' data-can-move-to'\n                  : '') +\n                (Garnish.hasAttr($parentFolder, 'data-can-move-peer-files-to')\n                  ? ' data-can-move-peer-files-to'\n                  : '') +\n                '>' +\n                data.folderName +\n                '</a>' +\n                '</li>'\n            );\n\n            var $a = $subfolder.children('a:first');\n            this._appendSubfolder($parentFolder, $subfolder);\n            this.initSource($a);\n          }\n\n          if (textStatus === 'success' && data.error) {\n            alert(data.error);\n          }\n        }\n      );\n    }\n  },\n\n  _deleteFolder: function ($targetFolder) {\n    if (\n      confirm(\n        Craft.t('app', 'Really delete folder “{folder}”?', {\n          folder: $.trim($targetFolder.text()),\n        })\n      )\n    ) {\n      var params = {\n        folderId: $targetFolder.data('folder-id'),\n      };\n\n      this.setIndexBusy();\n\n      Craft.postActionRequest(\n        'assets/delete-folder',\n        params,\n        (data, textStatus) => {\n          this.setIndexAvailable();\n\n          if (textStatus === 'success' && data.success) {\n            var $parentFolder = this._getParentSource($targetFolder);\n\n            // Remove folder and any trace from its parent, if needed\n            this.deinitSource($targetFolder);\n\n            $targetFolder.parent().remove();\n            this._cleanUpTree($parentFolder);\n          }\n\n          if (textStatus === 'success' && data.error) {\n            alert(data.error);\n          }\n        }\n      );\n    }\n  },\n\n  /**\n   * Rename\n   */\n  _renameFolder: function ($source) {\n    const $label = $source.children('.label');\n    const oldName = Craft.trim($label.text());\n    const newName = prompt(Craft.t('app', 'Rename folder'), oldName);\n\n    if (!newName || newName === oldName) {\n      return;\n    }\n\n    this.setIndexBusy();\n\n    Craft.sendActionRequest('POST', 'assets/rename-folder', {\n      data: {\n        folderId: $source.data('folder-id'),\n        newName: newName,\n      },\n    })\n      .then((response) => {\n        if (response.data.success) {\n          $label.text(response.data.newName);\n\n          // Is this the selected source?\n          if ($source.data('key') === this.$source.data('key')) {\n            this.updateElements();\n\n            // Update the URL if we're on the Assets index\n            if (this.settings.context === 'index') {\n              this._updateUrl($source);\n            }\n          }\n        } else if (response.data.error) {\n          alert(response.data.error);\n        }\n      })\n      .finally(() => {\n        this.setIndexAvailable();\n      });\n  },\n\n  /**\n   * Prepare a source folder for children folder.\n   *\n   * @param $parentFolder\n   * @private\n   */\n  _prepareParentForChildren: function ($parentFolder) {\n    if (!this._hasSubfolders($parentFolder)) {\n      $parentFolder\n        .parent()\n        .addClass('expanded')\n        .append('<div class=\"toggle\"></div><ul></ul>');\n      this.initSourceToggle($parentFolder);\n    }\n  },\n\n  /**\n   * Appends a subfolder to the parent folder at the correct spot.\n   *\n   * @param $parentFolder\n   * @param $subfolder\n   * @private\n   */\n  _appendSubfolder: function ($parentFolder, $subfolder) {\n    var $subfolderList = $parentFolder.siblings('ul'),\n      $existingChildren = $subfolderList.children('li'),\n      subfolderLabel = $.trim($subfolder.children('a:first').text()),\n      folderInserted = false;\n\n    for (var i = 0; i < $existingChildren.length; i++) {\n      var $existingChild = $($existingChildren[i]);\n\n      if ($.trim($existingChild.children('a:first').text()) > subfolderLabel) {\n        $existingChild.before($subfolder);\n        folderInserted = true;\n        break;\n      }\n    }\n\n    if (!folderInserted) {\n      $parentFolder.siblings('ul').append($subfolder);\n    }\n  },\n\n  _cleanUpTree: function ($parentFolder) {\n    if (\n      $parentFolder !== null &&\n      $parentFolder.siblings('ul').children('li').length === 0\n    ) {\n      this.deinitSourceToggle($parentFolder);\n      $parentFolder.siblings('ul').remove();\n      $parentFolder.siblings('.toggle').remove();\n      $parentFolder.parent().removeClass('expanded');\n    }\n  },\n\n  _positionProgressBar: function () {\n    if (!this.progressBar) {\n      this.progressBar = new Craft.ProgressBar(this.$main, true);\n    }\n\n    var $container = $(),\n      scrollTop = 0,\n      offset = 0;\n\n    if (this.settings.context === 'index') {\n      $container = this.progressBar.$progressBar.closest('#content');\n      scrollTop = Garnish.$win.scrollTop();\n    } else {\n      $container = this.progressBar.$progressBar.closest('.main');\n      scrollTop = this.$main.scrollTop();\n    }\n\n    var containerTop = $container.offset().top;\n    var diff = scrollTop - containerTop;\n    var windowHeight = Garnish.$win.height();\n\n    if ($container.height() > windowHeight) {\n      offset = windowHeight / 2 - 6 + diff;\n    } else {\n      offset = $container.height() / 2 - 6;\n    }\n\n    if (this.settings.context !== 'index') {\n      offset = scrollTop + ($container.height() / 2 - 6);\n    }\n\n    this.progressBar.$progressBar.css({\n      top: offset,\n    });\n  },\n\n  _performBatchRequests: function (parameterArray, finalCallback) {\n    const responseArray = [];\n    let activeRequests = parameterArray.length;\n\n    while (parameterArray.length) {\n      const parameters = parameterArray.shift();\n      Craft.sendActionRequest('POST', parameters.action, {\n        data: parameters.params,\n      })\n        .then((response) => {\n          responseArray.push(response.data);\n        })\n        .finally(() => {\n          this.progressBar.incrementProcessedItemCount(1);\n          this.progressBar.updateProgressBar();\n\n          // Was that the last one?\n          if (--activeRequests === 0) {\n            // If assets were just merged we should get the reference tags updated right away\n            Craft.cp.runQueue();\n            finalCallback(responseArray);\n          }\n        });\n    }\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Asset', Craft.AssetIndex);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset Select input\n */\nCraft.AssetSelectInput = Craft.BaseElementSelectInput.extend({\n  requestId: 0,\n  hud: null,\n  $uploadBtn: null,\n  uploader: null,\n  progressBar: null,\n\n  init: function () {\n    this.base.apply(this, arguments);\n\n    if (this.settings.canUpload) {\n      this._attachUploader();\n    }\n\n    this.addListener(\n      this.$elementsContainer,\n      'keydown',\n      this._onKeyDown.bind(this)\n    );\n    this.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n  },\n\n  /**\n   * Handle a keypress\n   * @private\n   */\n  _onKeyDown: function (ev) {\n    if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n      if (Craft.PreviewFileModal.openInstance) {\n        Craft.PreviewFileModal.openInstance.selfDestruct();\n      } else {\n        var $element = this.elementSelect.$focusedItem;\n\n        if ($element.length) {\n          this._loadPreview($element);\n        }\n      }\n\n      ev.stopPropagation();\n\n      return false;\n    }\n  },\n\n  /**\n   * Handle element being focused\n   * @private\n   */\n  _onElementFocus: function (ev) {\n    var $element = $(ev.item);\n\n    if (Craft.PreviewFileModal.openInstance && $element.length) {\n      this._loadPreview($element);\n    }\n  },\n\n  /**\n   * Load the preview for an Asset element\n   * @private\n   */\n  _loadPreview: function ($element) {\n    var settings = {};\n\n    if ($element.data('image-width')) {\n      settings.startingWidth = $element.data('image-width');\n      settings.startingHeight = $element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(\n      $element.data('id'),\n      this.elementSelect,\n      settings\n    );\n  },\n\n  /**\n   * Create the element editor\n   */\n  createElementEditor: function ($element) {\n    return this.base($element, {\n      params: {\n        defaultFieldLayoutId: this.settings.defaultFieldLayoutId,\n      },\n      input: this,\n    });\n  },\n\n  /**\n   * Attach the uploader with drag event handler\n   */\n  _attachUploader: function () {\n    this.progressBar = new Craft.ProgressBar(\n      $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n    );\n\n    var options = {\n      url: Craft.getActionUrl('assets/upload'),\n      dropZone: this.$container,\n      formData: {\n        fieldId: this.settings.fieldId,\n      },\n    };\n\n    if (this.settings.sourceElementId) {\n      options.formData.elementId = this.settings.sourceElementId;\n    }\n\n    if (this.settings.criteria.siteId) {\n      options.formData.siteId = this.settings.criteria.siteId;\n    }\n\n    if (this.$addElementBtn) {\n      this.$uploadBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn dashed',\n        'data-icon': 'upload',\n        'aria-label':\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n        'aria-describedby': this.settings.describedBy,\n        text:\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n      }).insertAfter(this.$addElementBtn);\n      options.fileInput = $('<input/>', {\n        type: 'file',\n        class: 'hidden',\n        multiple: this.settings.limit != 1,\n      }).insertAfter(this.$uploadBtn);\n\n      // Trigger a window resize in case the field is inside an element editor HUD\n      Garnish.$win.trigger('resize');\n    }\n\n    // If CSRF protection isn't enabled, these won't be defined.\n    if (\n      typeof Craft.csrfTokenName !== 'undefined' &&\n      typeof Craft.csrfTokenValue !== 'undefined'\n    ) {\n      // Add the CSRF token\n      options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n    }\n\n    if (typeof this.settings.criteria.kind !== 'undefined') {\n      options.allowedKinds = this.settings.criteria.kind;\n    }\n\n    options.canAddMoreFiles = this.canAddMoreFiles.bind(this);\n\n    options.events = {};\n    options.events.fileuploadstart = this._onUploadStart.bind(this);\n    options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n    options.events.fileuploaddone = this._onUploadComplete.bind(this);\n    options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n    this.uploader = new Craft.Uploader(this.$container, options);\n\n    if (this.$uploadBtn) {\n      this.$uploadBtn.on('click', (ev) => {\n        // We can't store a reference to the file input, because it gets replaced with a new input\n        // each time a new file is uploaded - see https://stackoverflow.com/a/25034721/1688568\n        this.$uploadBtn.next('input[type=file]').trigger('click');\n      });\n    }\n  },\n\n  refreshThumbnail: function (elementId) {\n    var parameters = {\n      elementId: elementId,\n      siteId: this.settings.criteria.siteId,\n      size: this.settings.viewMode,\n    };\n\n    Craft.postActionRequest('elements/get-element-html', parameters, (data) => {\n      if (data.error) {\n        alert(data.error);\n      } else {\n        var $existing = this.$elements.filter('[data-id=\"' + elementId + '\"]');\n        $existing\n          .find('.elementthumb')\n          .replaceWith($(data.html).find('.elementthumb'));\n        this.thumbLoader.load($existing);\n      }\n    });\n  },\n\n  /**\n   * Add the freshly uploaded file to the input field.\n   */\n  selectUploadedFile: function (element) {\n    // Check if we're able to add new elements\n    if (!this.canAddMoreElements()) {\n      return;\n    }\n\n    var $newElement = element.$element;\n\n    // Make a couple tweaks\n    $newElement.addClass('removable');\n    $newElement.prepend(\n      '<input type=\"hidden\" name=\"' +\n        this.settings.name +\n        '[]\" value=\"' +\n        element.id +\n        '\">' +\n        '<a class=\"delete icon\" title=\"' +\n        Craft.t('app', 'Remove') +\n        '\"></a>'\n    );\n\n    $newElement.appendTo(this.$elementsContainer);\n\n    var margin = -($newElement.outerWidth() + 10);\n\n    this.$addElementBtn.css('margin-' + Craft.left, margin + 'px');\n\n    var animateCss = {};\n    animateCss['margin-' + Craft.left] = 0;\n    this.$addElementBtn.velocity(animateCss, 'fast');\n\n    this.addElements($newElement);\n\n    delete this.modal;\n  },\n\n  /**\n   * On upload start.\n   */\n  _onUploadStart: function () {\n    this.progressBar.$progressBar.css({\n      top: Math.round(this.$container.outerHeight() / 2) - 6,\n    });\n\n    this.$container.addClass('uploading');\n    this.progressBar.resetProgressBar();\n    this.progressBar.showProgressBar();\n  },\n\n  /**\n   * On upload progress.\n   */\n  _onUploadProgress: function (event, data) {\n    var progress = parseInt((data.loaded / data.total) * 100, 10);\n    this.progressBar.setProgressPercentage(progress);\n  },\n\n  /**\n   * On a file being uploaded.\n   */\n  _onUploadComplete: function (event, data) {\n    if (data.result.error) {\n      alert(data.result.error);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    } else {\n      var parameters = {\n        elementId: data.result.assetId,\n        siteId: this.settings.criteria.siteId,\n        size: this.settings.viewMode,\n      };\n\n      Craft.postActionRequest(\n        'elements/get-element-html',\n        parameters,\n        (data) => {\n          if (data.error) {\n            alert(data.error);\n          } else {\n            var html = $(data.html);\n            Craft.appendHeadHtml(data.headHtml);\n            this.selectUploadedFile(Craft.getElementInfo(html));\n          }\n\n          // Last file\n          if (this.uploader.isLastUpload()) {\n            this.progressBar.hideProgressBar();\n            this.$container.removeClass('uploading');\n\n            if (window.draftEditor) {\n              window.draftEditor.checkForm();\n            }\n          }\n        }\n      );\n\n      Craft.cp.runQueue();\n    }\n  },\n\n  /**\n   * On Upload Failure.\n   */\n  _onUploadFailure: function (event, data) {\n    if (data.jqXHR.responseJSON.error) {\n      alert(data.jqXHR.responseJSON.error);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    }\n  },\n\n  /**\n   * We have to take into account files about to be added as well\n   */\n  canAddMoreFiles: function (slotsTaken) {\n    return (\n      !this.settings.limit ||\n      this.$elements.length + slotsTaken < this.settings.limit\n    );\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset selector modal class\n */\nCraft.AssetSelectorModal = Craft.BaseElementSelectorModal.extend(\n  {\n    $selectTransformBtn: null,\n    _selectedTransform: null,\n\n    init: function (elementType, settings) {\n      settings = $.extend({}, Craft.AssetSelectorModal.defaults, settings);\n\n      this.base(elementType, settings);\n\n      if (settings.transforms.length) {\n        this.createSelectTransformButton(settings.transforms);\n      }\n    },\n\n    createSelectTransformButton: function (transforms) {\n      if (!transforms || !transforms.length) {\n        return;\n      }\n\n      var $btnGroup = $('<div class=\"btngroup\"/>').appendTo(\n        this.$primaryButtons\n      );\n      this.$selectBtn.appendTo($btnGroup);\n\n      this.$selectTransformBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn menubtn disabled',\n        text: Craft.t('app', 'Select transform'),\n      }).appendTo($btnGroup);\n\n      var $menu = $('<div class=\"menu\" data-align=\"right\"></div>').insertAfter(\n          this.$selectTransformBtn\n        ),\n        $menuList = $('<ul></ul>').appendTo($menu);\n\n      for (var i = 0; i < transforms.length; i++) {\n        $(\n          '<li><a data-transform=\"' +\n            transforms[i].handle +\n            '\">' +\n            transforms[i].name +\n            '</a></li>'\n        ).appendTo($menuList);\n      }\n\n      var MenuButton = new Garnish.MenuBtn(this.$selectTransformBtn, {\n        onOptionSelect: this.onSelectTransform.bind(this),\n      });\n      MenuButton.disable();\n\n      this.$selectTransformBtn.data('menuButton', MenuButton);\n    },\n\n    onSelectionChange: function (ev) {\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        allowTransforms = false;\n\n      if ($selectedElements.length && this.settings.transforms.length) {\n        allowTransforms = true;\n\n        for (var i = 0; i < $selectedElements.length; i++) {\n          if (!$('.element.hasthumb:first', $selectedElements[i]).length) {\n            break;\n          }\n        }\n      }\n\n      var MenuBtn = null;\n\n      if (this.$selectTransformBtn) {\n        MenuBtn = this.$selectTransformBtn.data('menuButton');\n      }\n\n      if (allowTransforms) {\n        if (MenuBtn) {\n          MenuBtn.enable();\n        }\n\n        this.$selectTransformBtn.removeClass('disabled');\n      } else if (this.$selectTransformBtn) {\n        if (MenuBtn) {\n          MenuBtn.disable();\n        }\n\n        this.$selectTransformBtn.addClass('disabled');\n      }\n\n      this.base();\n    },\n\n    onSelectTransform: function (option) {\n      var transform = $(option).data('transform');\n      this.selectImagesWithTransform(transform);\n    },\n\n    selectImagesWithTransform: function (transform) {\n      // First we must get any missing transform URLs\n      if (\n        typeof Craft.AssetSelectorModal.transformUrls[transform] === 'undefined'\n      ) {\n        Craft.AssetSelectorModal.transformUrls[transform] = {};\n      }\n\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        imageIdsWithMissingUrls = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $item = $($selectedElements[i]),\n          elementId = Craft.getElementInfo($item).id;\n\n        if (\n          typeof Craft.AssetSelectorModal.transformUrls[transform][\n            elementId\n          ] === 'undefined'\n        ) {\n          imageIdsWithMissingUrls.push(elementId);\n        }\n      }\n\n      if (imageIdsWithMissingUrls.length) {\n        this.showFooterSpinner();\n\n        this.fetchMissingTransformUrls(\n          imageIdsWithMissingUrls,\n          transform,\n          () => {\n            this.hideFooterSpinner();\n            this.selectImagesWithTransform(transform);\n          }\n        );\n      } else {\n        this._selectedTransform = transform;\n        this.selectElements();\n        this._selectedTransform = null;\n      }\n    },\n\n    fetchMissingTransformUrls: function (\n      imageIdsWithMissingUrls,\n      transform,\n      callback\n    ) {\n      var elementId = imageIdsWithMissingUrls.pop();\n\n      var data = {\n        assetId: elementId,\n        handle: transform,\n      };\n\n      Craft.postActionRequest(\n        'assets/generate-transform',\n        data,\n        (response, textStatus) => {\n          Craft.AssetSelectorModal.transformUrls[transform][elementId] = false;\n\n          if (textStatus === 'success') {\n            if (response.url) {\n              Craft.AssetSelectorModal.transformUrls[transform][elementId] =\n                response.url;\n            }\n          }\n\n          // More to load?\n          if (imageIdsWithMissingUrls.length) {\n            this.fetchMissingTransformUrls(\n              imageIdsWithMissingUrls,\n              transform,\n              callback\n            );\n          } else {\n            callback();\n          }\n        }\n      );\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = this.base($selectedElements);\n\n      if (this._selectedTransform) {\n        for (var i = 0; i < info.length; i++) {\n          var elementId = info[i].id;\n\n          if (\n            typeof Craft.AssetSelectorModal.transformUrls[\n              this._selectedTransform\n            ][elementId] !== 'undefined' &&\n            Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n              elementId\n            ] !== false\n          ) {\n            info[i].url =\n              Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n                elementId\n              ];\n          }\n        }\n      }\n\n      return info;\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo, this._selectedTransform);\n    },\n  },\n  {\n    defaults: {\n      canSelectImageTransforms: false,\n      transforms: [],\n    },\n\n    transformUrls: {},\n  }\n);\n\n// Register it!\nCraft.registerElementSelectorModalClass(\n  'craft\\\\elements\\\\Asset',\n  Craft.AssetSelectorModal\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * AuthManager class\n */\nCraft.AuthManager = Garnish.Base.extend(\n  {\n    remainingSessionTime: null,\n    checkRemainingSessionTimer: null,\n    showLoginModalTimer: null,\n    decrementLogoutWarningInterval: null,\n\n    showingLogoutWarningModal: false,\n    showingLoginModal: false,\n\n    logoutWarningModal: null,\n    loginModal: null,\n\n    $logoutWarningPara: null,\n    $passwordInput: null,\n    $passwordSpinner: null,\n    $loginBtn: null,\n    $loginErrorPara: null,\n\n    submitLoginIfLoggedOut: false,\n\n    /**\n     * Init\n     */\n    init: function () {\n      this.updateRemainingSessionTime(Craft.remainingSessionTime);\n    },\n\n    /**\n     * Sets a timer for the next time to check the auth timeout.\n     */\n    setCheckRemainingSessionTimer: function (seconds) {\n      if (this.checkRemainingSessionTimer) {\n        clearTimeout(this.checkRemainingSessionTimer);\n      }\n\n      this.checkRemainingSessionTimer = setTimeout(\n        this.checkRemainingSessionTime.bind(this),\n        seconds * 1000\n      );\n    },\n\n    /**\n     * Pings the server to see how many seconds are left on the current user session, and handles the response.\n     */\n    checkRemainingSessionTime: function (extendSession) {\n      $.ajax({\n        url: Craft.getActionUrl(\n          'users/session-info',\n          extendSession ? null : 'dontExtendSession=1'\n        ),\n        type: 'GET',\n        dataType: 'json',\n        complete: (jqXHR, textStatus) => {\n          if (textStatus === 'success') {\n            if (\n              typeof jqXHR.responseJSON.csrfTokenValue !== 'undefined' &&\n              typeof Craft.csrfTokenValue !== 'undefined'\n            ) {\n              Craft.csrfTokenValue = jqXHR.responseJSON.csrfTokenValue;\n            }\n\n            this.updateRemainingSessionTime(jqXHR.responseJSON.timeout);\n            this.submitLoginIfLoggedOut = false;\n          } else {\n            this.updateRemainingSessionTime(-1);\n          }\n        },\n      });\n    },\n\n    /**\n     * Updates our record of the auth timeout, and handles it.\n     */\n    updateRemainingSessionTime: function (remainingSessionTime) {\n      this.remainingSessionTime = parseInt(remainingSessionTime);\n\n      // Are we within the warning window?\n      if (\n        this.remainingSessionTime !== -1 &&\n        this.remainingSessionTime < Craft.AuthManager.minSafeSessionTime\n      ) {\n        // Is there still time to renew the session?\n        if (this.remainingSessionTime) {\n          if (!this.showingLogoutWarningModal) {\n            // Show the warning modal\n            this.showLogoutWarningModal();\n          }\n\n          // Will the session expire before the next checkup?\n          if (this.remainingSessionTime < Craft.AuthManager.checkInterval) {\n            if (this.showLoginModalTimer) {\n              clearTimeout(this.showLoginModalTimer);\n            }\n\n            this.showLoginModalTimer = setTimeout(\n              this.showLoginModal.bind(this),\n              this.remainingSessionTime * 1000\n            );\n          }\n        } else {\n          if (this.showingLoginModal) {\n            if (this.submitLoginIfLoggedOut) {\n              this.submitLogin();\n            }\n          } else {\n            // Show the login modal\n            this.showLoginModal();\n          }\n        }\n\n        this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n      } else {\n        // Everything's good!\n        this.hideLogoutWarningModal();\n        this.hideLoginModal();\n\n        // Will be be within the minSafeSessionTime before the next update?\n        if (\n          this.remainingSessionTime !== -1 &&\n          this.remainingSessionTime <\n            Craft.AuthManager.minSafeSessionTime +\n              Craft.AuthManager.checkInterval\n        ) {\n          this.setCheckRemainingSessionTimer(\n            this.remainingSessionTime - Craft.AuthManager.minSafeSessionTime + 1\n          );\n        } else {\n          this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the logout warning modal.\n     */\n    showLogoutWarningModal: function () {\n      var quickShow;\n\n      if (this.showingLoginModal) {\n        this.hideLoginModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLogoutWarningModal = true;\n\n      if (!this.logoutWarningModal) {\n        let $form = $(\n          '<form id=\"logoutwarningmodal\" class=\"modal alert fitted\"/>'\n        );\n        let $body = $('<div class=\"body\"/>').appendTo($form);\n        let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n        let $logoutBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Log out now'),\n        }).appendTo($buttons);\n        let $renewSessionBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit',\n          text: Craft.t('app', 'Keep me logged in'),\n        }).appendTo($buttons);\n\n        this.$logoutWarningPara = $('<p/>').prependTo($body);\n\n        this.logoutWarningModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark logoutwarningmodalshade',\n          onFadeIn: function () {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the renew button\n              setTimeout(function () {\n                $renewSessionBtn.trigger('focus');\n              }, 100);\n            }\n          },\n        });\n\n        this.addListener($logoutBtn, 'activate', 'logout');\n        this.addListener($form, 'submit', 'renewSession');\n      }\n\n      if (quickShow) {\n        this.logoutWarningModal.quickShow();\n      } else {\n        this.logoutWarningModal.show();\n      }\n\n      this.updateLogoutWarningMessage();\n\n      this.decrementLogoutWarningInterval = setInterval(\n        this.decrementLogoutWarning.bind(this),\n        1000\n      );\n    },\n\n    /**\n     * Updates the logout warning message indicating that the session is about to expire.\n     */\n    updateLogoutWarningMessage: function () {\n      this.$logoutWarningPara.text(\n        Craft.t('app', 'Your session will expire in {time}.', {\n          time: Craft.secondsToHumanTimeDuration(this.remainingSessionTime),\n        })\n      );\n\n      this.logoutWarningModal.updateSizeAndPosition();\n    },\n\n    decrementLogoutWarning: function () {\n      if (this.remainingSessionTime > 0) {\n        this.remainingSessionTime--;\n        this.updateLogoutWarningMessage();\n      }\n\n      if (this.remainingSessionTime === 0) {\n        clearInterval(this.decrementLogoutWarningInterval);\n      }\n    },\n\n    /**\n     * Hides the logout warning modal.\n     */\n    hideLogoutWarningModal: function (quick) {\n      this.showingLogoutWarningModal = false;\n\n      if (this.logoutWarningModal) {\n        if (quick) {\n          this.logoutWarningModal.quickHide();\n        } else {\n          this.logoutWarningModal.hide();\n        }\n\n        if (this.decrementLogoutWarningInterval) {\n          clearInterval(this.decrementLogoutWarningInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the login modal.\n     */\n    showLoginModal: function () {\n      var quickShow;\n\n      if (this.showingLogoutWarningModal) {\n        this.hideLogoutWarningModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLoginModal = true;\n\n      if (!this.loginModal) {\n        var $form = $('<form id=\"loginmodal\" class=\"modal alert fitted\"/>'),\n          $body = $(\n            '<div class=\"body\"><h2>' +\n              Craft.t('app', 'Your session has ended.') +\n              '</h2><p>' +\n              Craft.t('app', 'Enter your password to log back in.') +\n              '</p></div>'\n          ).appendTo($form),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<div/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\"/>'\n        ).appendTo($passwordWrapper);\n        this.$passwordSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n          $inputContainer\n        );\n        this.$loginBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit disabled',\n          text: Craft.t('app', 'Login'),\n        }).appendTo($buttonContainer);\n        this.$loginErrorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.loginModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark loginmodalshade',\n          onFadeIn: () => {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the password input\n              setTimeout(() => {\n                this.$passwordInput.trigger('focus');\n              }, 100);\n            }\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($form, 'submit', 'login');\n      }\n\n      if (quickShow) {\n        this.loginModal.quickShow();\n      } else {\n        this.loginModal.show();\n      }\n    },\n\n    /**\n     * Hides the login modal.\n     */\n    hideLoginModal: function (quick) {\n      this.showingLoginModal = false;\n\n      if (this.loginModal) {\n        if (quick) {\n          this.loginModal.quickHide();\n        } else {\n          this.loginModal.hide();\n        }\n      }\n    },\n\n    logout: function () {\n      $.get({\n        url: Craft.getActionUrl('users/logout'),\n        dataType: 'json',\n        success: () => {\n          Craft.redirectTo('');\n        },\n      });\n    },\n\n    renewSession: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      this.hideLogoutWarningModal();\n      this.checkRemainingSessionTime(true);\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$loginBtn.removeClass('disabled');\n        return true;\n      } else {\n        this.$loginBtn.addClass('disabled');\n        return false;\n      }\n    },\n\n    login: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (this.validatePassword()) {\n        this.$passwordSpinner.removeClass('hidden');\n        this.clearLoginError();\n\n        if (typeof Craft.csrfTokenValue !== 'undefined') {\n          // Check the auth status one last time before sending this off,\n          // in case the user has already logged back in from another window/tab\n          this.submitLoginIfLoggedOut = true;\n          this.checkRemainingSessionTime();\n        } else {\n          this.submitLogin();\n        }\n      }\n    },\n\n    submitLogin: function () {\n      var data = {\n        loginName: Craft.username,\n        password: this.$passwordInput.val(),\n      };\n\n      Craft.postActionRequest('users/login', data, (response, textStatus) => {\n        this.$passwordSpinner.addClass('hidden');\n\n        if (textStatus === 'success') {\n          if (response.success) {\n            this.hideLoginModal();\n            this.checkRemainingSessionTime();\n          } else {\n            this.showLoginError(response.error);\n            Garnish.shake(this.loginModal.$container);\n\n            if (!Garnish.isMobileBrowser(true)) {\n              this.$passwordInput.trigger('focus');\n            }\n          }\n        } else {\n          this.showLoginError();\n        }\n      });\n    },\n\n    showLoginError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$loginErrorPara.text(error);\n      this.loginModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showLoginError('');\n    },\n  },\n  {\n    checkInterval: 60,\n    minSafeSessionTime: 120,\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element editor\n */\nCraft.BaseElementEditor = Garnish.Base.extend(\n  {\n    $element: null,\n    elementId: null,\n    siteId: null,\n    deltaNames: null,\n    initialData: null,\n\n    $header: null,\n    $toolbar: null,\n    $tabContainer: null,\n    $editLink: null,\n    $sidebarBtn: null,\n    $loadSpinner: null,\n\n    $body: null,\n    $fieldsContainer: null,\n\n    $sidebar: null,\n\n    $footer: null,\n    $siteSelectContainer: null,\n    $siteSelect: null,\n    $siteSpinner: null,\n    $cancelBtn: null,\n    $saveBtn: null,\n    $saveSpinner: null,\n\n    slideout: null,\n    tabManager: null,\n    showingSidebar: false,\n\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    initialDeltaValues: null,\n\n    init: function (element, settings) {\n      // Param mapping\n      if (typeof settings === 'undefined' && $.isPlainObject(element)) {\n        // (settings)\n        settings = element;\n        element = null;\n      }\n\n      this.$element = $(element);\n      this.setSettings(settings, Craft.BaseElementEditor.defaults);\n\n      // Header\n      this.$header = $('<header/>', {class: 'pane-header'});\n      this.$toolbar = $('<div/>', {class: 'ee-toolbar'}).appendTo(this.$header);\n      this.$tabContainer = $('<div/>', {class: 'pane-tabs'}).appendTo(\n        this.$toolbar\n      );\n      this.$loadSpinner = $('<div/>', {\n        class: 'spinner',\n        title: Craft.t('app', 'Loading'),\n        'aria-label': Craft.t('app', 'Loading'),\n      }).appendTo(this.$toolbar);\n      this.$editLink = $('<a/>', {\n        target: '_blank',\n        class: 'btn hidden',\n        title: Craft.t('app', 'Open the full edit page in a new tab'),\n        'aria-label': Craft.t('app', 'Open the full edit page in a new tab'),\n        'data-icon': 'external',\n      }).appendTo(this.$toolbar);\n      this.$sidebarBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn hidden sidebar-btn',\n        title: Craft.t('app', 'Show sidebar'),\n        'aria-label': Craft.t('app', 'Show sidebar'),\n        'data-icon': `sidebar-${Garnish.ltr ? 'right' : 'left'}`,\n      }).appendTo(this.$toolbar);\n\n      this.addListener(this.$sidebarBtn, 'click', (ev) => {\n        ev.preventDefault();\n        if (!this.showingSidebar) {\n          this.showSidebar();\n        } else {\n          this.hideSidebar();\n        }\n      });\n\n      // Body\n      this.$body = $('<div/>', {class: 'ee-body'});\n\n      // Fields\n      this.$fieldsContainer = $('<div/>', {class: 'fields'}).appendTo(\n        this.$body\n      );\n\n      // Sidebar\n      this.$sidebar = $('<div/>', {class: 'ee-sidebar hidden'}).appendTo(\n        this.$body\n      );\n      Craft.trapFocusWithin(this.$sidebar);\n\n      // Footer\n      this.$footer = $('<div/>', {class: 'ee-footer hidden'});\n      const $siteSelectOuterContainer = $('<div/>', {\n        class: 'ee-site-select',\n      }).appendTo(this.$footer);\n      this.$siteSelectContainer = $('<div/>', {\n        class: 'select hidden',\n      }).appendTo($siteSelectOuterContainer);\n      this.$siteSelect = $('<select/>').appendTo(this.$siteSelectContainer);\n      this.$siteSpinner = $('<div/>', {class: 'spinner hidden'}).appendTo(\n        $siteSelectOuterContainer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$footer);\n      this.$saveBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit',\n        text: Craft.t('app', 'Save'),\n      }).appendTo(this.$footer);\n      this.$saveSpinner = $('<div/>', {class: 'spinner hidden'}).appendTo(\n        this.$footer\n      );\n\n      let $contents = this.$header.add(this.$body).add(this.$footer);\n\n      // Create the slideout\n      this.slideout = new Craft.Slideout($contents, {\n        containerElement: 'form',\n        containerAttributes: {\n          action: '',\n          method: 'post',\n          novalidate: '',\n          class: 'element-editor',\n        },\n        closeOnEsc: false,\n        closeOnShadeClick: false,\n      });\n      this.slideout.$container.data('elementEditor', this);\n      this.slideout.on('beforeClose', () => {\n        this.hideSidebar();\n      });\n      this.slideout.on('close', () => {\n        this.trigger('closeSlideout');\n        this.destroy();\n      });\n\n      // Register shortcuts & events\n      Garnish.uiLayerManager.registerShortcut(\n        {\n          keyCode: Garnish.S_KEY,\n          ctrl: true,\n        },\n        () => {\n          this.saveElement();\n        }\n      );\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.maybeCloseSlideout();\n      });\n      this.addListener(this.$cancelBtn, 'click', () => {\n        this.maybeCloseSlideout();\n      });\n      this.addListener(this.slideout.$shade, 'click', () => {\n        this.maybeCloseSlideout();\n      });\n      this.addListener(this.slideout.$container, 'click', (ev) => {\n        const $target = $(event.target);\n\n        if (\n          this.showingSidebar &&\n          !$target.closest(this.$sidebarBtn).length &&\n          !$target.closest(this.$sidebar).length\n        ) {\n          this.hideSidebar();\n        }\n      });\n      this.addListener(this.slideout.$container, 'submit', (ev) => {\n        ev.preventDefault();\n        this.saveElement();\n      });\n      this.addListener(this.$siteSelect, 'change', 'switchSite');\n\n      this.load().then(() => {\n        this.onShowHud();\n        this.onCreateForm(this.$body);\n      });\n    },\n\n    setElementAttribute: function (name, value) {\n      if (!this.settings.attributes) {\n        this.settings.attributes = {};\n      }\n\n      if (value === null) {\n        delete this.settings.attributes[name];\n      } else {\n        this.settings.attributes[name] = value;\n      }\n    },\n\n    getBaseData: function () {\n      const data = $.extend({}, this.settings.params);\n\n      if (this.settings.siteId) {\n        data.siteId = this.settings.siteId;\n      } else if (this.$element && this.$element.data('site-id')) {\n        data.siteId = this.$element.data('site-id');\n      }\n\n      if (this.settings.elementId) {\n        data.elementId = this.settings.elementId;\n      } else if (this.$element && this.$element.data('id')) {\n        data.elementId = this.$element.data('id');\n      }\n\n      if (this.settings.elementType) {\n        data.elementType = this.settings.elementType;\n      }\n\n      if (this.settings.attributes) {\n        data.attributes = this.settings.attributes;\n      }\n\n      if (this.settings.prevalidate) {\n        data.prevalidate = 1;\n      }\n\n      return data;\n    },\n\n    /**\n     * @param {object} [data={}]\n     * @param {boolean} [refreshInitialData=true]\n     * @returns {Promise}\n     */\n    load: function (data, refreshInitialData) {\n      return new Promise((resolve, reject) => {\n        this.trigger('beforeLoad');\n        // todo: remove this in Craft 4\n        this.trigger('beginLoading');\n        this.showLoadSpinner();\n        this.onBeginLoading();\n\n        if (this.cancelToken) {\n          this.ignoreFailedRequest = true;\n          this.cancelToken.cancel();\n        }\n\n        this.cancelToken = axios.CancelToken.source();\n\n        Craft.sendActionRequest('POST', 'elements/get-editor-html', {\n          cancelToken: this.cancelToken.token,\n          data: $.extend(this.getBaseData(), data || {}, {\n            includeSites: Craft.isMultiSite && this.settings.showSiteSwitcher,\n          }),\n        })\n          .then((response) => {\n            this.hideLoadSpinner();\n            this.trigger('load');\n            // todo: remove this in Craft 4\n            this.trigger('endLoading');\n            this.onEndLoading();\n            this.cancelToken = null;\n            if (this.initialDeltaValues === null) {\n              this.initialDeltaValues = response.data.initialDeltaValues;\n            }\n            this.updateForm(response.data, refreshInitialData);\n            this.cancelToken = null;\n            resolve();\n          })\n          .catch((e) => {\n            this.hideLoadSpinner();\n            this.onEndLoading();\n            this.cancelToken = null;\n            if (!this.ignoreFailedRequest) {\n              Craft.cp.displayError();\n              reject(e);\n            }\n            this.ignoreFailedRequest = false;\n          });\n      });\n    },\n\n    showHeader: function () {\n      this.$header.removeClass('hidden');\n    },\n\n    hideHeader: function () {\n      this.$header.addClass('hidden');\n    },\n\n    showLoadSpinner: function () {\n      this.showHeader();\n      this.$loadSpinner.removeClass('hidden');\n    },\n\n    hideLoadSpinner: function () {\n      this.$loadSpinner.addClass('hidden');\n    },\n\n    switchSite: function () {\n      if (\n        this.isDirty() &&\n        !confirm(\n          Craft.t(\n            'app',\n            'Switching sites will lose unsaved changes. Are you sure you want to switch sites?'\n          )\n        )\n      ) {\n        this.$siteSelect.val(this.siteId);\n        return;\n      }\n\n      const newSiteId = this.$siteSelect.val();\n\n      if (newSiteId == this.siteId) {\n        return;\n      }\n\n      this.$siteSpinner.removeClass('hidden');\n\n      this.load({siteId: newSiteId})\n        .then(() => {\n          this.$siteSpinner.addClass('hidden');\n        })\n        .catch(() => {\n          this.$siteSpinner.addClass('hidden');\n          // Reset the site select\n          this.$siteSelect.val(this.siteId);\n        });\n    },\n\n    /**\n     * @param {object} data\n     * @param {boolean} [refreshInitialData=true]\n     */\n    updateForm: function (data, refreshInitialData) {\n      // Cleanup\n      if (this.tabManager) {\n        this.$tabContainer.html('');\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n      refreshInitialData = refreshInitialData !== false;\n\n      this.siteId = data.siteId;\n      this.$fieldsContainer.html(data.fieldHtml);\n\n      let showHeader = false;\n\n      if (data.sites && data.sites.length > 1) {\n        showHeader = true;\n        this.$siteSelectContainer.removeClass('hidden');\n        this.$siteSelect.html('');\n\n        for (let i = 0; i < data.sites.length; i++) {\n          const siteInfo = data.sites[i];\n          const $option = $('<option/>', {\n            value: siteInfo.id,\n            text: siteInfo.name,\n          }).appendTo(this.$siteSelect);\n          if (siteInfo.id == data.siteId) {\n            $option.attr('selected', 'selected');\n          }\n        }\n      } else {\n        this.$siteSelectContainer.addClass('hidden');\n      }\n\n      if (data.tabHtml) {\n        showHeader = true;\n        this.$tabContainer.replaceWith((this.$tabContainer = $(data.tabHtml)));\n        this.tabManager = new Craft.Tabs(this.$tabContainer);\n        this.tabManager.on('deselectTab', (ev) => {\n          $(ev.$tab.attr('href')).addClass('hidden');\n        });\n        this.tabManager.on('selectTab', (ev) => {\n          $(ev.$tab.attr('href')).removeClass('hidden');\n          Garnish.$win.trigger('resize');\n          this.$body.trigger('scroll');\n        });\n      }\n\n      if (data.editUrl) {\n        showHeader = true;\n        this.$editLink.removeClass('hidden').attr('href', data.editUrl);\n      } else if (this.$editLink) {\n        this.$editLink.addClass('hidden');\n      }\n\n      if (data.sidebarHtml) {\n        showHeader = true;\n        this.$sidebarBtn.removeClass('hidden');\n        this.$sidebar.html(data.sidebarHtml);\n        Craft.initUiElements(this.$sidebar);\n        new Craft.ElementThumbLoader().load($(this.$sidebar));\n\n        // Open outbound links in new windows\n        this.$sidebar.find('a').each(function () {\n          if (\n            this.hostname.length &&\n            typeof $(this).attr('target') === 'undefined'\n          ) {\n            $(this).attr('target', '_blank');\n          }\n        });\n      } else if (this.$sidebarBtn) {\n        this.$sidebarBtn.addClass('hidden');\n        this.$sidebar.addClass('hidden');\n      }\n\n      if (showHeader) {\n        this.showHeader();\n      } else {\n        this.hideHeader();\n      }\n\n      this.$footer.removeClass('hidden');\n\n      if (refreshInitialData) {\n        this.deltaNames = data.deltaNames;\n      }\n\n      Garnish.requestAnimationFrame(() => {\n        Craft.appendHeadHtml(data.headHtml);\n        Craft.appendFootHtml(data.footHtml);\n        Craft.initUiElements(this.$fieldsContainer);\n\n        if (refreshInitialData) {\n          this.initialData = this.slideout.$container.serialize();\n        }\n\n        if (!Garnish.isMobileBrowser()) {\n          Craft.setFocusWithin(this.$fieldsContainer);\n        }\n\n        this.trigger('updateForm');\n      });\n    },\n\n    showSidebar: function () {\n      if (this.showingSidebar) {\n        return;\n      }\n\n      this.$body.scrollTop(0).addClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.element-editor')\n        .css(this._closedSidebarStyles())\n        .removeClass('hidden');\n\n      // Hack to force CSS animations\n      this.$sidebar[0].offsetWidth;\n\n      this.$sidebar.css(this._openedSidebarStyles());\n\n      if (!Garnish.isMobileBrowser()) {\n        this.$sidebar.one('transitionend.element-editor', () => {\n          Craft.setFocusWithin(this.$sidebar);\n        });\n      }\n\n      this.$sidebarBtn.addClass('active').attr({\n        title: Craft.t('app', 'Hide sidebar'),\n        'aria-label': Craft.t('app', 'Hide sidebar'),\n      });\n\n      Garnish.$win.trigger('resize');\n      this.$sidebar.trigger('scroll');\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.hideSidebar();\n      });\n\n      this.showingSidebar = true;\n    },\n\n    hideSidebar: function () {\n      if (!this.showingSidebar) {\n        return;\n      }\n\n      this.$body.removeClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.element-editor')\n        .css(this._closedSidebarStyles())\n        .one('transitionend.element-editor', () => {\n          this.$sidebar.addClass('hidden');\n        });\n\n      this.$sidebarBtn.removeClass('active').attr({\n        title: Craft.t('app', 'Show sidebar'),\n        'aria-label': Craft.t('app', 'Show sidebar'),\n      });\n\n      Garnish.uiLayerManager.removeLayer();\n\n      this.showingSidebar = false;\n    },\n\n    _openedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '0',\n      };\n    },\n\n    _closedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '-350px',\n      };\n    },\n\n    saveElement: function () {\n      const validators = this.settings.validators;\n\n      if ($.isArray(validators)) {\n        for (let i = 0; i < validators.length; i++) {\n          if ($.isFunction(validators[i]) && !validators[i].call()) {\n            return false;\n          }\n        }\n      }\n\n      this.$saveSpinner.removeClass('hidden');\n\n      let data =\n        $.param(this.getBaseData()) +\n        '&' +\n        this.slideout.$container.serialize();\n      data = Craft.findDeltaData(\n        this.initialData,\n        data,\n        this.deltaNames,\n        null,\n        this.initialDeltaValues\n      );\n\n      Craft.postActionRequest(\n        'elements/save-element',\n        data,\n        (response, textStatus) => {\n          this.$saveSpinner.addClass('hidden');\n\n          if (textStatus === 'success') {\n            if (response.success) {\n              if (\n                this.$element &&\n                this.siteId == this.$element.data('site-id')\n              ) {\n                // Update the label\n                const $title = this.$element.find('.title');\n                const $a = $title.find('a');\n\n                if ($a.length && response.cpEditUrl) {\n                  $a.attr('href', response.cpEditUrl);\n                  $a.text(response.newTitle);\n                } else {\n                  $title.text(response.newTitle);\n                }\n              }\n\n              if (\n                this.settings.elementType &&\n                Craft.elementTypeNames[this.settings.elementType]\n              ) {\n                Craft.cp.displayNotice(\n                  Craft.t('app', '{type} saved.', {\n                    type: Craft.elementTypeNames[this.settings.elementType][0],\n                  })\n                );\n              }\n\n              this.closeSlideout();\n              this.trigger('saveElement', {\n                response: response,\n              });\n              this.onSaveElement(response);\n              this.settings.onSaveElement(response);\n\n              // There may be a new background job that needs to be run\n              Craft.cp.runQueue();\n            } else {\n              this.updateForm(response, false);\n              Garnish.shake(this.slideout.$container);\n            }\n          }\n        }\n      );\n    },\n\n    isDirty: function () {\n      return (\n        this.initialData !== null &&\n        this.slideout.$container.serialize() !== this.initialData\n      );\n    },\n\n    maybeCloseSlideout: function () {\n      if (!this.slideout.isOpen) {\n        return;\n      }\n\n      if (\n        !this.isDirty() ||\n        confirm(\n          Craft.t(\n            'app',\n            'Are you sure you want to close the editor? Any changes will be lost.'\n          )\n        )\n      ) {\n        this.closeSlideout();\n      }\n    },\n\n    closeSlideout: function () {\n      this.slideout.close();\n      this.onHideHud();\n\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n    },\n\n    destroy: function () {\n      this.slideout.destroy();\n      delete this.slideout;\n      this.base();\n    },\n\n    // Deprecated Methods\n    // -------------------------------------------------------------------------\n\n    /** @deprecated in 3.7.0 */\n    loadHud: function () {\n      this.load();\n    },\n    /** @deprecated in 3.7.0 */\n    maybeCloseHud: function () {\n      this.maybeCloseSlideout();\n    },\n    /** @deprecated in 3.7.0 */\n    closeHud: function () {\n      this.closeSlideout();\n    },\n    /** @deprecated */\n    reloadForm: function (data, callback) {\n      this.load(data)\n        .then(() => {\n          callback('success');\n        })\n        .catch(() => {\n          callback('error');\n        });\n    },\n    /** @deprecated in 3.7.0 */\n    onBeginLoading: function () {\n      this.settings.onBeginLoading();\n    },\n    /** @deprecated in 3.7.0 */\n    onEndLoading: function () {\n      this.settings.onEndLoading();\n    },\n    /** @deprecated in 3.7.0 */\n    onSaveElement: function (response) {},\n    /** @deprecated in 3.7.0 */\n    onCreateForm: function ($form) {\n      this.settings.onCreateForm($form);\n    },\n    /** @deprecated in 3.7.0 */\n    onShowHud: function () {\n      this.trigger('showHud');\n      this.settings.onShowHud();\n    },\n    /** @deprecated in 3.7.0 */\n    onHideHud: function () {\n      this.trigger('hideHud');\n      this.settings.onHideHud();\n    },\n  },\n  {\n    defaults: {\n      showSiteSwitcher: true,\n      elementId: null,\n      elementType: null,\n      siteId: null,\n      attributes: null,\n      params: null,\n      prevalidate: false,\n      elementIndex: null,\n      onSaveElement: $.noop,\n      validators: [],\n\n      /** @deprecated in 3.7.0 */\n      onShowHud: $.noop,\n      /** @deprecated in 3.7.0 */\n      onHideHud: $.noop,\n      /** @deprecated in 3.7.0 */\n      onBeginLoading: $.noop,\n      /** @deprecated in 3.7.0 */\n      onEndLoading: $.noop,\n      /** @deprecated in 3.7.0 */\n      onCreateForm: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element index class\n */\nCraft.BaseElementIndex = Garnish.Base.extend(\n  {\n    initialized: false,\n    elementType: null,\n\n    instanceState: null,\n    sourceStates: null,\n    sourceStatesStorageKey: null,\n\n    searchTimeout: null,\n    sourceSelect: null,\n\n    $container: null,\n    $main: null,\n    isIndexBusy: false,\n\n    $sidebar: null,\n    showingSidebar: null,\n    sourceKey: null,\n    sourceViewModes: null,\n    $source: null,\n    sourcesByKey: null,\n    $visibleSources: null,\n\n    $customizeSourcesBtn: null,\n    customizeSourcesModal: null,\n\n    $toolbar: null,\n    toolbarOffset: null,\n\n    $search: null,\n    searching: false,\n    searchText: null,\n    trashed: false,\n    drafts: false,\n    $clearSearchBtn: null,\n\n    $statusMenuBtn: null,\n    $statusMenuContainer: null,\n    statusMenu: null,\n    status: null,\n\n    $siteMenuBtn: null,\n    siteMenu: null,\n    siteId: null,\n\n    $sortMenuBtn: null,\n    sortMenu: null,\n    $sortAttributesList: null,\n    $sortDirectionsList: null,\n    $scoreSortAttribute: null,\n    $structureSortAttribute: null,\n\n    $elements: null,\n    $viewModeBtnContainer: null,\n    viewModeBtns: null,\n    viewMode: null,\n    view: null,\n    _autoSelectElements: null,\n    $countSpinner: null,\n    $countContainer: null,\n    page: 1,\n    resultSet: null,\n    totalResults: null,\n    $exportBtn: null,\n\n    actions: null,\n    actionsHeadHtml: null,\n    actionsFootHtml: null,\n    $selectAllContainer: null,\n    $selectAllCheckbox: null,\n    showingActionTriggers: false,\n    exporters: null,\n    exportersByType: null,\n    _$detachedToolbarItems: null,\n    _$triggers: null,\n\n    _ignoreFailedRequest: false,\n    _cancelToken: null,\n\n    /**\n     * Constructor\n     */\n    init: function (elementType, $container, settings) {\n      this.elementType = elementType;\n      this.$container = $container;\n      this.setSettings(settings, Craft.BaseElementIndex.defaults);\n\n      // Set the state objects\n      // ---------------------------------------------------------------------\n\n      this.instanceState = this.getDefaultInstanceState();\n\n      this.sourceStates = {};\n\n      // Instance states (selected source) are stored by a custom storage key defined in the settings\n      if (this.settings.storageKey) {\n        $.extend(\n          this.instanceState,\n          Craft.getLocalStorage(this.settings.storageKey),\n          {}\n        );\n      }\n\n      // Source states (view mode, etc.) are stored by the element type and context\n      this.sourceStatesStorageKey =\n        'BaseElementIndex.' + this.elementType + '.' + this.settings.context;\n      $.extend(\n        this.sourceStates,\n        Craft.getLocalStorage(this.sourceStatesStorageKey, {})\n      );\n\n      // Find the DOM elements\n      // ---------------------------------------------------------------------\n\n      this.$main = this.$container.find('.main');\n      this.$toolbar = this.$container.find(this.settings.toolbarSelector);\n      this.$statusMenuBtn = this.$toolbar.find('.statusmenubtn:first');\n      this.$statusMenuContainer = this.$statusMenuBtn.parent();\n      this.$siteMenuBtn = this.$container.find('.sitemenubtn:first');\n      this.$sortMenuBtn = this.$toolbar.find('.sortmenubtn:first');\n      this.$search = this.$toolbar.find('.search:first input:first');\n      this.$clearSearchBtn = this.$toolbar.find('.search:first > .clear');\n      this.$sidebar = this.$container.find('.sidebar:first');\n      this.$customizeSourcesBtn = this.$sidebar.find('.customize-sources');\n      this.$elements = this.$container.find('.elements:first');\n      this.$countSpinner = this.$container.find('#count-spinner');\n      this.$countContainer = this.$container.find('#count-container');\n      this.$exportBtn = this.$container.find('#export-btn');\n\n      // Hide sidebar if needed\n      if (this.settings.hideSidebar) {\n        this.$sidebar.hide();\n        $('.body, .content', this.$container).removeClass('has-sidebar');\n      }\n\n      // Initialize the sources\n      // ---------------------------------------------------------------------\n\n      if (!this.initSources()) {\n        return;\n      }\n\n      // Customize button\n      if (this.$customizeSourcesBtn.length) {\n        this.addListener(\n          this.$customizeSourcesBtn,\n          'click',\n          'createCustomizeSourcesModal'\n        );\n      }\n\n      // Initialize the status menu\n      // ---------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        this.statusMenu = this.$statusMenuBtn.menubtn().data('menubtn').menu;\n        this.statusMenu.on('optionselect', this._handleStatusChange.bind(this));\n      }\n\n      // Initialize the site menu\n      // ---------------------------------------------------------------------\n\n      // Is there a site menu?\n      if (this.$siteMenuBtn.length) {\n        this.siteMenu = this.$siteMenuBtn.menubtn().data('menubtn').menu;\n\n        // Figure out the initial site\n        var $option = this.siteMenu.$options.filter('.sel:first');\n\n        if (!$option.length) {\n          $option = this.siteMenu.$options.first();\n        }\n\n        if ($option.length) {\n          this._setSite($option.data('site-id'));\n        } else {\n          // No site options -- they must not have any site permissions\n          this.settings.criteria = {id: '0'};\n        }\n\n        this.siteMenu.on('optionselect', this._handleSiteChange.bind(this));\n\n        if (this.siteId) {\n          // Should we be using a different default site?\n          var defaultSiteId =\n            this.settings.defaultSiteId || Craft.cp.getSiteId();\n\n          if (defaultSiteId && defaultSiteId != this.siteId) {\n            // Is that one available here?\n            var $storedSiteOption = this.siteMenu.$options.filter(\n              '[data-site-id=\"' + defaultSiteId + '\"]:first'\n            );\n\n            if ($storedSiteOption.length) {\n              // Todo: switch this to siteMenu.selectOption($storedSiteOption) once Menu is updated to support that\n              $storedSiteOption.trigger('click');\n            }\n          }\n        }\n      } else if (\n        this.settings.criteria &&\n        this.settings.criteria.siteId &&\n        this.settings.criteria.siteId !== '*'\n      ) {\n        this._setSite(this.settings.criteria.siteId);\n      } else {\n        this._setSite(Craft.siteId);\n      }\n\n      // Don't let the criteria override the selected site\n      if (this.settings.criteria && this.settings.criteria.siteId) {\n        delete this.settings.criteria.siteId;\n      }\n\n      // Initialize the search input\n      // ---------------------------------------------------------------------\n\n      // Automatically update the elements after new search text has been sitting for a 1/2 second\n      this.addListener(this.$search, 'input', () => {\n        if (!this.searching && this.$search.val()) {\n          this.startSearching();\n        } else if (this.searching && !this.$search.val()) {\n          this.stopSearching();\n        }\n\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(\n          this.updateElementsIfSearchTextChanged.bind(this),\n          500\n        );\n      });\n\n      // Update the elements when the Return key is pressed\n      this.addListener(this.$search, 'keypress', (ev) => {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n\n          if (this.searchTimeout) {\n            clearTimeout(this.searchTimeout);\n          }\n\n          this.updateElementsIfSearchTextChanged();\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearSearchBtn, 'click', () => {\n        this.clearSearch(true);\n\n        if (!Garnish.isMobileBrowser(true)) {\n          this.$search.trigger('focus');\n        }\n      });\n\n      // Auto-focus the Search box\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$search.trigger('focus');\n      }\n\n      // Initialize the sort menu\n      // ---------------------------------------------------------------------\n\n      // Is there a sort menu?\n      if (this.$sortMenuBtn.length) {\n        this.sortMenu = this.$sortMenuBtn.menubtn().data('menubtn').menu;\n        this.$sortAttributesList =\n          this.sortMenu.$container.children('.sort-attributes');\n        this.$sortDirectionsList =\n          this.sortMenu.$container.children('.sort-directions');\n\n        this.sortMenu.on('optionselect', this._handleSortChange.bind(this));\n      }\n\n      // Initialize the Export button\n      // ---------------------------------------------------------------------\n\n      this.addListener(this.$exportBtn, 'click', '_showExportHud');\n\n      // Let everyone know that the UI is initialized\n      // ---------------------------------------------------------------------\n\n      this.initialized = true;\n      this.afterInit();\n\n      // Select the initial source\n      // ---------------------------------------------------------------------\n\n      this.selectDefaultSource();\n\n      // Load the first batch of elements!\n      // ---------------------------------------------------------------------\n\n      // Default to whatever page is in the URL\n      this.setPage(Craft.pageNum);\n\n      this.updateElements(true);\n    },\n\n    afterInit: function () {\n      this.onAfterInit();\n    },\n\n    _createCancelToken: function () {\n      this._cancelToken = axios.CancelToken.source();\n      return this._cancelToken.token;\n    },\n\n    _cancelRequests: function () {\n      if (this._cancelToken) {\n        this._ignoreFailedRequest = true;\n        this._cancelToken.cancel();\n        Garnish.requestAnimationFrame(() => {\n          this._ignoreFailedRequest = false;\n        });\n      }\n    },\n\n    getSourceContainer: function () {\n      return this.$sidebar.find('nav > ul');\n    },\n\n    get $sources() {\n      if (!this.sourceSelect) {\n        return undefined;\n      }\n\n      return this.sourceSelect.$items;\n    },\n\n    getSite: function () {\n      if (!this.siteId) {\n        return undefined;\n      }\n      return Craft.sites.find((s) => s.id == this.siteId);\n    },\n\n    initSources: function () {\n      var $sources = this._getSourcesInList(this.getSourceContainer());\n\n      // No source, no party.\n      if ($sources.length === 0) {\n        return false;\n      }\n\n      // The source selector\n      if (!this.sourceSelect) {\n        this.sourceSelect = new Garnish.Select(this.$sidebar.find('nav'), {\n          multi: false,\n          allowEmpty: false,\n          vertical: true,\n          onSelectionChange: this._handleSourceSelectionChange.bind(this),\n        });\n      }\n\n      this.sourcesByKey = {};\n\n      for (let i = 0; i < $sources.length; i++) {\n        this.initSource($($sources[i]));\n      }\n\n      return true;\n    },\n\n    selectDefaultSource: function () {\n      var sourceKey = this.getDefaultSourceKey(),\n        $source;\n\n      if (sourceKey) {\n        $source = this.getSourceByKey(sourceKey);\n\n        // Make sure it's visible\n        if (this.$visibleSources.index($source) === -1) {\n          $source = null;\n        }\n      }\n\n      if (!sourceKey || !$source) {\n        // Select the first source by default\n        $source = this.$visibleSources.first();\n      }\n\n      return this.selectSource($source);\n    },\n\n    refreshSources: function () {\n      this.sourceSelect.removeAllItems();\n\n      this.setIndexBusy();\n\n      Craft.sendActionRequest('POST', this.settings.refreshSourcesAction, {\n        data: {\n          context: this.settings.context,\n          elementType: this.elementType,\n        },\n      })\n        .then((response) => {\n          this.setIndexAvailable();\n          this.getSourceContainer().replaceWith(response.data.html);\n          this.initSources();\n          this.selectDefaultSource();\n        })\n        .catch(() => {\n          this.setIndexAvailable();\n          if (!this._ignoreFailedRequest) {\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          }\n        });\n    },\n\n    initSource: function ($source) {\n      this.sourceSelect.addItems($source);\n      this.initSourceToggle($source);\n      this.sourcesByKey[$source.data('key')] = $source;\n\n      if (\n        $source.data('hasNestedSources') &&\n        this.instanceState.expandedSources.indexOf($source.data('key')) !== -1\n      ) {\n        this._expandSource($source);\n      }\n    },\n\n    initSourceToggle: function ($source) {\n      // Remove handlers for the same thing. Just in case.\n      this.deinitSourceToggle($source);\n\n      var $toggle = this._getSourceToggle($source);\n\n      if ($toggle.length) {\n        this.addListener($source, 'dblclick', '_handleSourceDblClick');\n        this.addListener($toggle, 'click', '_handleSourceToggleClick');\n        $source.data('hasNestedSources', true);\n      } else {\n        $source.data('hasNestedSources', false);\n      }\n    },\n\n    deinitSource: function ($source) {\n      this.sourceSelect.removeItems($source);\n      this.deinitSourceToggle($source);\n      delete this.sourcesByKey[$source.data('key')];\n    },\n\n    deinitSourceToggle: function ($source) {\n      if ($source.data('hasNestedSources')) {\n        this.removeListener($source, 'dblclick');\n        this.removeListener(this._getSourceToggle($source), 'click');\n      }\n\n      $source.removeData('hasNestedSources');\n    },\n\n    getDefaultInstanceState: function () {\n      return {\n        selectedSource: null,\n        expandedSources: [],\n      };\n    },\n\n    getDefaultSourceKey: function () {\n      if (this.settings.defaultSource) {\n        var paths = this.settings.defaultSource.split('/'),\n          path = '';\n\n        // Expand the tree\n        for (var i = 0; i < paths.length; i++) {\n          path += paths[i];\n          var $source = this.getSourceByKey(path);\n\n          // If the folder can't be found, then just go to the stored instance source.\n          if (!$source) {\n            return this.instanceState.selectedSource;\n          }\n\n          this._expandSource($source);\n          path += '/';\n        }\n\n        // Just make sure that the modal is aware of the newly expanded sources, too.\n        this._setSite(this.siteId);\n\n        return this.settings.defaultSource;\n      }\n\n      return this.instanceState.selectedSource;\n    },\n\n    getDefaultExpandedSources: function () {\n      return this.instanceState.expandedSources;\n    },\n\n    startSearching: function () {\n      // Show the clear button and add/select the Score sort option\n      this.$clearSearchBtn.removeClass('hidden');\n\n      if (!this.$scoreSortAttribute) {\n        this.$scoreSortAttribute = $(\n          '<li><a data-attr=\"score\">' + Craft.t('app', 'Score') + '</a></li>'\n        );\n        this.sortMenu.addOptions(this.$scoreSortAttribute.children());\n      }\n\n      this.$scoreSortAttribute.prependTo(this.$sortAttributesList);\n\n      this.searching = true;\n\n      this._updateStructureSortOption();\n      this.setSortAttribute('score');\n    },\n\n    clearSearch: function (updateElements) {\n      if (!this.searching) {\n        return;\n      }\n\n      this.$search.val('');\n\n      if (this.searchTimeout) {\n        clearTimeout(this.searchTimeout);\n      }\n\n      this.stopSearching();\n\n      if (updateElements) {\n        this.updateElementsIfSearchTextChanged();\n      } else {\n        this.searchText = null;\n      }\n    },\n\n    stopSearching: function () {\n      // Hide the clear button and Score sort option\n      this.$clearSearchBtn.addClass('hidden');\n\n      this.$scoreSortAttribute.detach();\n\n      this.searching = false;\n\n      this._updateStructureSortOption();\n    },\n\n    setInstanceState: function (key, value) {\n      if (typeof key === 'object') {\n        $.extend(this.instanceState, key);\n      } else {\n        this.instanceState[key] = value;\n      }\n\n      this.storeInstanceState();\n    },\n\n    storeInstanceState: function () {\n      if (this.settings.storageKey) {\n        Craft.setLocalStorage(this.settings.storageKey, this.instanceState);\n      }\n    },\n\n    getSourceState: function (source, key, defaultValue) {\n      if (typeof this.sourceStates[source] === 'undefined') {\n        // Set it now so any modifications to it by whoever's calling this will be stored.\n        this.sourceStates[source] = {};\n      }\n\n      if (typeof key === 'undefined') {\n        return this.sourceStates[source];\n      } else if (typeof this.sourceStates[source][key] !== 'undefined') {\n        return this.sourceStates[source][key];\n      } else {\n        return typeof defaultValue !== 'undefined' ? defaultValue : null;\n      }\n    },\n\n    getSelectedSourceState: function (key, defaultValue) {\n      return this.getSourceState(\n        this.instanceState.selectedSource,\n        key,\n        defaultValue\n      );\n    },\n\n    setSelecetedSourceState: function (key, value) {\n      var viewState = this.getSelectedSourceState();\n\n      if (typeof key === 'object') {\n        $.extend(viewState, key);\n      } else {\n        viewState[key] = value;\n      }\n\n      this.sourceStates[this.instanceState.selectedSource] = viewState;\n\n      // Store it in localStorage too\n      Craft.setLocalStorage(this.sourceStatesStorageKey, this.sourceStates);\n    },\n\n    storeSortAttributeAndDirection: function () {\n      const attr = this.getSelectedSortAttribute();\n\n      if (attr !== 'score') {\n        const history = [];\n\n        if (attr) {\n          // Remember the previous choices\n          const attributes = [attr];\n\n          // Only include the most last attribute if it changed\n          const lastAttr = this.getSelectedSourceState('order');\n          if (lastAttr && lastAttr !== attr) {\n            history.push([lastAttr, this.getSelectedSourceState('sort')]);\n            attributes.push(lastAttr);\n          }\n\n          const oldHistory = this.getSelectedSourceState('orderHistory', []);\n          for (let i = 0; i < oldHistory.length; i++) {\n            const [a] = oldHistory[i];\n            if (a && !attributes.includes(a)) {\n              history.push(oldHistory[i]);\n              attributes.push(a);\n            } else {\n              break;\n            }\n          }\n        }\n\n        this.setSelecetedSourceState({\n          order: attr,\n          sort: this.getSelectedSortDirection(),\n          orderHistory: history,\n        });\n      }\n    },\n\n    /**\n     * Sets the page number.\n     */\n    setPage: function (page) {\n      if (this.settings.context !== 'index') {\n        return;\n      }\n\n      page = Math.max(page, 1);\n      this.page = page;\n\n      // Update the URL\n      var url = document.location.href\n        .replace(/\\?.*$/, '')\n        .replace(\n          new RegExp(\n            '/' +\n              Craft.pageTrigger.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') +\n              '\\\\d+$'\n          ),\n          ''\n        )\n        .replace(/\\/+$/, '');\n\n      if (this.page !== 1) {\n        if (Craft.pageTrigger[0] !== '?') {\n          url += '/';\n        }\n        url += Craft.pageTrigger + this.page;\n      }\n\n      history.replaceState({}, '', url);\n    },\n\n    _resetCount: function () {\n      this.resultSet = null;\n      this.totalResults = null;\n    },\n\n    /**\n     * Returns the data that should be passed to the elementIndex/getElements controller action\n     * when loading elements.\n     */\n    getViewParams: function () {\n      var criteria = {\n        siteId: this.siteId,\n        search: this.searchText,\n        offset: this.settings.batchSize * (this.page - 1),\n        limit: this.settings.batchSize,\n      };\n\n      // Only set drafts/draftOf/trashed params when needed, so we don't potentially override a source's criteria\n      if (\n        this.settings.canHaveDrafts &&\n        (this.drafts || (this.settings.context === 'index' && !this.status))\n      ) {\n        criteria.drafts = this.drafts || null;\n        criteria.savedDraftsOnly = true;\n        if (!this.drafts) {\n          criteria.draftOf = false;\n        }\n      }\n      if (this.trashed) {\n        criteria.trashed = true;\n      }\n\n      if (!Garnish.hasAttr(this.$source, 'data-override-status')) {\n        criteria.status = this.status;\n      }\n\n      $.extend(criteria, this.settings.criteria);\n\n      var params = {\n        context: this.settings.context,\n        elementType: this.elementType,\n        source: this.instanceState.selectedSource,\n        criteria: criteria,\n        disabledElementIds: this.settings.disabledElementIds,\n        viewState: $.extend({}, this.getSelectedSourceState()),\n        paginated: this._isViewPaginated() ? 1 : 0,\n      };\n\n      // Possible that the order/sort isn't entirely accurate if we're sorting by Score\n      params.viewState.order = this.getSelectedSortAttribute();\n      params.viewState.sort = this.getSelectedSortDirection();\n\n      if (this.getSelectedSortAttribute() === 'structure') {\n        if (typeof this.instanceState.collapsedElementIds === 'undefined') {\n          this.instanceState.collapsedElementIds = [];\n        }\n        params.collapsedElementIds = this.instanceState.collapsedElementIds;\n      }\n\n      // Give plugins a chance to hook in here\n      this.trigger('registerViewParams', {\n        params: params,\n      });\n\n      return params;\n    },\n\n    updateElements: function (preservePagination) {\n      // Ignore if we're not fully initialized yet\n      if (!this.initialized) {\n        return;\n      }\n\n      // Cancel any ongoing requests\n      this._cancelRequests();\n\n      this.setIndexBusy();\n\n      // Kill the old view class\n      if (this.view) {\n        this.view.destroy();\n        delete this.view;\n      }\n\n      if (preservePagination !== true) {\n        this.setPage(1);\n        this._resetCount();\n      }\n\n      var params = this.getViewParams();\n\n      Craft.sendActionRequest('POST', this.settings.updateElementsAction, {\n        data: params,\n        cancelToken: this._createCancelToken(),\n      })\n        .then((response) => {\n          this.setIndexAvailable();\n          (this.settings.context === 'index'\n            ? Garnish.$scrollContainer\n            : this.$main\n          ).scrollTop(0);\n          this._updateView(params, response.data);\n        })\n        .catch((e) => {\n          this.setIndexAvailable();\n          if (!this._ignoreFailedRequest) {\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          }\n        });\n    },\n\n    updateElementsIfSearchTextChanged: function () {\n      if (\n        this.searchText !==\n        (this.searchText = this.searching ? this.$search.val() : null)\n      ) {\n        this.updateElements();\n      }\n    },\n\n    showActionTriggers: function () {\n      // Ignore if they're already shown\n      if (this.showingActionTriggers) {\n        return;\n      }\n\n      // Hard-code the min toolbar height in case it was taller than the actions toolbar\n      // (prevents the elements from jumping if this ends up being a double-click)\n      this.$toolbar.css('min-height', this.$toolbar.height());\n\n      // Hide any toolbar inputs\n      this._$detachedToolbarItems = this.$toolbar.children();\n      this._$detachedToolbarItems.detach();\n\n      if (!this._$triggers) {\n        this._createTriggers();\n      } else {\n        this._$triggers.appendTo(this.$toolbar);\n      }\n\n      this.showingActionTriggers = true;\n    },\n\n    submitAction: function (action, actionParams) {\n      // Make sure something's selected\n      var selectedElementIds = this.view.getSelectedElementIds(),\n        totalSelected = selectedElementIds.length;\n\n      if (totalSelected === 0) {\n        return;\n      }\n\n      if (typeof action === 'string') {\n        action = this._findAction(action);\n      }\n\n      if (action.confirm && !confirm(action.confirm)) {\n        return;\n      }\n\n      // Cancel any ongoing requests\n      this._cancelRequests();\n\n      // Get ready to submit\n      var viewParams = this.getViewParams();\n\n      actionParams = actionParams ? Craft.expandPostArray(actionParams) : {};\n      var params = $.extend(viewParams, action.settings || {}, actionParams, {\n        elementAction: action.type,\n        elementIds: selectedElementIds,\n      });\n\n      // Do it\n      this.setIndexBusy();\n      this._autoSelectElements = selectedElementIds;\n\n      if (action.download) {\n        if (Craft.csrfTokenName) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl(this.settings.submitActionsAction),\n          params\n        )\n          .then((response) => {\n            this.setIndexAvailable();\n          })\n          .catch((e) => {\n            this.setIndexAvailable();\n          });\n      } else {\n        Craft.sendActionRequest('POST', this.settings.submitActionsAction, {\n          data: params,\n          cancelToken: this._createCancelToken(),\n        })\n          .then((response) => {\n            this.setIndexAvailable();\n            if (response.data.success) {\n              // Update the count text too\n              this._resetCount();\n              this._updateView(viewParams, response.data);\n\n              if (typeof response.data.badgeCounts !== 'undefined') {\n                this._updateBadgeCounts(response.data.badgeCounts);\n              }\n\n              if (response.data.message) {\n                Craft.cp.displayNotice(response.data.message);\n              }\n\n              this.afterAction(action, params);\n            } else {\n              Craft.cp.displayError(response.data.message);\n            }\n          })\n          .catch(() => {\n            this.setIndexAvailable();\n          });\n      }\n    },\n\n    _findAction: function (actionClass) {\n      for (var i = 0; i < this.actions.length; i++) {\n        if (this.actions[i].type === actionClass) {\n          return this.actions[i];\n        }\n      }\n      throw `Invalid element action: ${actionClass}`;\n    },\n\n    afterAction: function (action, params) {\n      // There may be a new background job that needs to be run\n      Craft.cp.runQueue();\n\n      this.onAfterAction(action, params);\n    },\n\n    hideActionTriggers: function () {\n      // Ignore if there aren't any\n      if (!this.showingActionTriggers) {\n        return;\n      }\n\n      this._$detachedToolbarItems.appendTo(this.$toolbar);\n      this._$triggers.detach();\n      // this._$detachedToolbarItems.removeClass('hidden');\n\n      // Unset the min toolbar height\n      this.$toolbar.css('min-height', '');\n\n      this.showingActionTriggers = false;\n    },\n\n    updateActionTriggers: function () {\n      // Do we have an action UI to update?\n      if (this.actions) {\n        var totalSelected = this.view.getSelectedElements().length;\n\n        if (totalSelected !== 0) {\n          if (totalSelected === this.view.getEnabledElements().length) {\n            this.$selectAllCheckbox.removeClass('indeterminate');\n            this.$selectAllCheckbox.addClass('checked');\n            this.$selectAllContainer.attr('aria-checked', 'true');\n          } else {\n            this.$selectAllCheckbox.addClass('indeterminate');\n            this.$selectAllCheckbox.removeClass('checked');\n            this.$selectAllContainer.attr('aria-checked', 'mixed');\n          }\n\n          this.showActionTriggers();\n        } else {\n          this.$selectAllCheckbox.removeClass('indeterminate checked');\n          this.$selectAllContainer.attr('aria-checked', 'false');\n          this.hideActionTriggers();\n        }\n      }\n    },\n\n    getSelectedElements: function () {\n      return this.view ? this.view.getSelectedElements() : $();\n    },\n\n    getSelectedElementIds: function () {\n      return this.view ? this.view.getSelectedElementIds() : [];\n    },\n\n    setStatus: function (status) {\n      // Find the option (and make sure it actually exists)\n      var $option = this.statusMenu.$options.filter(\n        'a[data-status=\"' + status + '\"]:first'\n      );\n\n      if ($option.length) {\n        this.statusMenu.selectOption($option[0]);\n      }\n    },\n\n    getSortAttributeOption: function (attr) {\n      return this.$sortAttributesList.find('a[data-attr=\"' + attr + '\"]:first');\n    },\n\n    getSelectedSortAttribute: function () {\n      return this.$sortAttributesList.find('a.sel:first').data('attr');\n    },\n\n    setSortAttribute: function (attr) {\n      // Find the option (and make sure it actually exists)\n      var $option = this.getSortAttributeOption(attr);\n\n      if ($option.length) {\n        this.$sortAttributesList.find('a.sel').removeClass('sel');\n        $option.addClass('sel');\n\n        var label = $option.text();\n        this.$sortMenuBtn.attr(\n          'title',\n          Craft.t('app', 'Sort by {attribute}', {attribute: label})\n        );\n        this.$sortMenuBtn.text(label);\n\n        if (attr === 'score') {\n          this.setSortDirection('desc');\n        } else {\n          this.setSortDirection($option.data('default-dir') || 'asc');\n        }\n\n        if (attr === 'structure') {\n          this.$sortDirectionsList.find('a').addClass('disabled');\n        } else {\n          this.$sortDirectionsList.find('a').removeClass('disabled');\n        }\n      }\n    },\n\n    getSortDirectionOption: function (dir) {\n      return this.$sortDirectionsList.find('a[data-dir=' + dir + ']:first');\n    },\n\n    getSelectedSortDirection: function () {\n      return this.$sortDirectionsList.find('a.sel:first').data('dir');\n    },\n\n    getSelectedViewMode: function () {\n      return this.getSelectedSourceState('mode') || 'table';\n    },\n\n    setSortDirection: function (dir) {\n      if (dir !== 'desc') {\n        dir = 'asc';\n      }\n\n      this.$sortMenuBtn.attr('data-icon', dir);\n      this.$sortDirectionsList.find('a.sel').removeClass('sel');\n      this.getSortDirectionOption(dir).addClass('sel');\n    },\n\n    getSourceByKey: function (key) {\n      if (typeof this.sourcesByKey[key] === 'undefined') {\n        return null;\n      }\n\n      return this.sourcesByKey[key];\n    },\n\n    selectSource: function ($source) {\n      if (!$source || !$source.length) {\n        return false;\n      }\n\n      if (\n        this.$source &&\n        this.$source[0] &&\n        this.$source[0] === $source[0] &&\n        $source.data('key') === this.sourceKey\n      ) {\n        return false;\n      }\n\n      // Hide action triggers if they're currently being shown\n      this.hideActionTriggers();\n\n      this.$source = $source;\n      this.sourceKey = $source.data('key');\n      this.setInstanceState('selectedSource', this.sourceKey);\n      this.sourceSelect.selectItem($source);\n\n      Craft.cp.updateSidebarMenuLabel();\n\n      if (this.searching) {\n        // Clear the search value without causing it to update elements\n        this.searchText = null;\n        this.$search.val('');\n        this.stopSearching();\n      }\n\n      // Sort menu\n      // ----------------------------------------------------------------------\n\n      // Remove any existing custom sort options from the menu\n      this.$sortAttributesList.children('li[data-extra]').remove();\n\n      // Does this source have any custom sort options?\n      let $topSource = this.$source.closest('nav > ul > li').children('a');\n      let sortOptions = $topSource.data('sort-options');\n      if (sortOptions) {\n        for (let i = 0; i < sortOptions.length; i++) {\n          let $option = $('<li/>', {\n            'data-extra': true,\n          })\n            .append(\n              $('<a/>', {\n                text: sortOptions[i][0],\n                'data-attr': sortOptions[i][1],\n              })\n            )\n            .appendTo(this.$sortAttributesList);\n          this.sortMenu.addOptions($option.children());\n        }\n      }\n\n      // Does this source have a structure?\n      if (Garnish.hasAttr(this.$source, 'data-has-structure')) {\n        if (!this.$structureSortAttribute) {\n          this.$structureSortAttribute = $(\n            '<li><a data-attr=\"structure\">' +\n              Craft.t('app', 'Structure') +\n              '</a></li>'\n          );\n          this.sortMenu.addOptions(this.$structureSortAttribute.children());\n        }\n\n        this.$structureSortAttribute.prependTo(this.$sortAttributesList);\n      } else if (this.$structureSortAttribute) {\n        this.$structureSortAttribute.removeClass('sel').detach();\n      }\n\n      this.setStoredSortOptionsForSource();\n\n      // Status menu\n      // ----------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        if (Garnish.hasAttr(this.$source, 'data-override-status')) {\n          this.$statusMenuContainer.addClass('hidden');\n        } else {\n          this.$statusMenuContainer.removeClass('hidden');\n        }\n\n        if (this.trashed) {\n          // Swap to the initial status\n          var $firstOption = this.statusMenu.$options.first();\n          this.setStatus($firstOption.data('status'));\n        }\n      }\n\n      // View mode buttons\n      // ----------------------------------------------------------------------\n\n      // Clear out any previous view mode data\n      if (this.$viewModeBtnContainer) {\n        this.$viewModeBtnContainer.remove();\n      }\n\n      this.viewModeBtns = {};\n      this.viewMode = null;\n\n      // Get the new list of view modes\n      this.sourceViewModes = this.getViewModesForSource();\n\n      // Create the buttons if there's more than one mode available to this source\n      if (this.sourceViewModes.length > 1) {\n        this.$viewModeBtnContainer = $('<div class=\"btngroup\"/>').appendTo(\n          this.$toolbar\n        );\n\n        for (var i = 0; i < this.sourceViewModes.length; i++) {\n          let sourceViewMode = this.sourceViewModes[i];\n\n          let $viewModeBtn = $('<button/>', {\n            type: 'button',\n            class:\n              'btn' +\n              (typeof sourceViewMode.className !== 'undefined'\n                ? ` ${sourceViewMode.className}`\n                : ''),\n            'data-view': sourceViewMode.mode,\n            'data-icon': sourceViewMode.icon,\n            'aria-label': sourceViewMode.title,\n            title: sourceViewMode.title,\n          }).appendTo(this.$viewModeBtnContainer);\n\n          this.viewModeBtns[sourceViewMode.mode] = $viewModeBtn;\n\n          this.addListener(\n            $viewModeBtn,\n            'click',\n            {mode: sourceViewMode.mode},\n            function (ev) {\n              this.selectViewMode(ev.data.mode);\n              this.updateElements();\n            }\n          );\n        }\n      }\n\n      // Figure out which mode we should start with\n      var viewMode = this.getSelectedViewMode();\n\n      if (!viewMode || !this.doesSourceHaveViewMode(viewMode)) {\n        // Try to keep using the current view mode\n        if (this.viewMode && this.doesSourceHaveViewMode(this.viewMode)) {\n          viewMode = this.viewMode;\n        }\n        // Just use the first one\n        else {\n          viewMode = this.sourceViewModes[0].mode;\n        }\n      }\n\n      this.selectViewMode(viewMode);\n\n      this.onSelectSource();\n\n      return true;\n    },\n\n    selectSourceByKey: function (key) {\n      var $source = this.getSourceByKey(key);\n\n      if ($source) {\n        return this.selectSource($source);\n      } else {\n        return false;\n      }\n    },\n\n    setStoredSortOptionsForSource: function () {\n      var sortAttr = this.getSelectedSourceState('order'),\n        sortDir = this.getSelectedSourceState('sort');\n\n      if (!sortAttr || !sortDir) {\n        // Get the default\n        sortAttr = this.getDefaultSort();\n\n        if (Garnish.isArray(sortAttr)) {\n          sortDir = sortAttr[1];\n          sortAttr = sortAttr[0];\n        }\n      }\n\n      if (sortDir !== 'asc' && sortDir !== 'desc') {\n        sortDir = 'asc';\n      }\n\n      this.setSortAttribute(sortAttr);\n      this.setSortDirection(sortDir);\n    },\n\n    getDefaultSort: function () {\n      // Does the source specify what to do?\n      if (this.$source && Garnish.hasAttr(this.$source, 'data-default-sort')) {\n        return this.$source.attr('data-default-sort').split(':');\n      } else {\n        // Default to whatever's first\n        return [this.$sortAttributesList.find('a:first').data('attr'), 'asc'];\n      }\n    },\n\n    getViewModesForSource: function () {\n      var viewModes = [\n        {\n          mode: 'table',\n          title: Craft.t('app', 'Display in a table'),\n          icon: 'list',\n        },\n      ];\n\n      if (this.$source && Garnish.hasAttr(this.$source, 'data-has-thumbs')) {\n        viewModes.push({\n          mode: 'thumbs',\n          title: Craft.t('app', 'Display as thumbnails'),\n          icon: 'grid',\n        });\n      }\n\n      return viewModes;\n    },\n\n    doesSourceHaveViewMode: function (viewMode) {\n      for (var i = 0; i < this.sourceViewModes.length; i++) {\n        if (this.sourceViewModes[i].mode === viewMode) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    selectViewMode: function (viewMode, force) {\n      // Make sure that the current source supports it\n      if (!force && !this.doesSourceHaveViewMode(viewMode)) {\n        viewMode = this.sourceViewModes[0].mode;\n      }\n\n      // Has anything changed?\n      if (viewMode === this.viewMode) {\n        return;\n      }\n\n      // Deselect the previous view mode\n      if (\n        this.viewMode &&\n        typeof this.viewModeBtns[this.viewMode] !== 'undefined'\n      ) {\n        this.viewModeBtns[this.viewMode].removeClass('active');\n      }\n\n      this.viewMode = viewMode;\n      this.setSelecetedSourceState('mode', this.viewMode);\n\n      if (typeof this.viewModeBtns[this.viewMode] !== 'undefined') {\n        this.viewModeBtns[this.viewMode].addClass('active');\n      }\n    },\n\n    createView: function (mode, settings) {\n      var viewClass = this.getViewClass(mode);\n      return new viewClass(this, this.$elements, settings);\n    },\n\n    getViewClass: function (mode) {\n      switch (mode) {\n        case 'table':\n          return Craft.TableElementIndexView;\n        case 'thumbs':\n          return Craft.ThumbsElementIndexView;\n        default:\n          throw `View mode \"${mode}\" not supported.`;\n      }\n    },\n\n    rememberDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index === -1) {\n        this.settings.disabledElementIds.push(id);\n      }\n    },\n\n    forgetDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index !== -1) {\n        this.settings.disabledElementIds.splice(index, 1);\n      }\n    },\n\n    enableElements: function ($elements) {\n      $elements\n        .removeClass('disabled')\n        .parents('.disabled')\n        .removeClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.forgetDisabledElementId(id);\n      }\n\n      this.onEnableElements($elements);\n    },\n\n    disableElements: function ($elements) {\n      $elements.removeClass('sel').addClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.rememberDisabledElementId(id);\n      }\n\n      this.onDisableElements($elements);\n    },\n\n    getElementById: function (id) {\n      return this.view.getElementById(id);\n    },\n\n    enableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.enableElements($element);\n        } else {\n          this.forgetDisabledElementId(id);\n        }\n      }\n    },\n\n    disableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.disableElements($element);\n        } else {\n          this.rememberDisabledElementId(id);\n        }\n      }\n    },\n\n    selectElementAfterUpdate: function (id) {\n      if (this._autoSelectElements === null) {\n        this._autoSelectElements = [];\n      }\n\n      this._autoSelectElements.push(id);\n    },\n\n    addButton: function ($button) {\n      this.getButtonContainer().append($button);\n    },\n\n    isShowingSidebar: function () {\n      if (this.showingSidebar === null) {\n        this.showingSidebar =\n          this.$sidebar.length && !this.$sidebar.hasClass('hidden');\n      }\n\n      return this.showingSidebar;\n    },\n\n    getButtonContainer: function () {\n      // Is there a predesignated place where buttons should go?\n      if (this.settings.buttonContainer) {\n        return $(this.settings.buttonContainer);\n      } else {\n        var $container = $('#action-button');\n\n        if (!$container.length) {\n          $container = $('<div id=\"action-button\"/>').appendTo($('#header'));\n        }\n\n        return $container;\n      }\n    },\n\n    setIndexBusy: function () {\n      this.$elements.addClass('busy');\n      this.isIndexBusy = true;\n    },\n\n    setIndexAvailable: function () {\n      this.$elements.removeClass('busy');\n      this.isIndexBusy = false;\n    },\n\n    createCustomizeSourcesModal: function () {\n      // Recreate it each time\n      var modal = new Craft.CustomizeSourcesModal(this, {\n        onHide: function () {\n          modal.destroy();\n        },\n      });\n\n      return modal;\n    },\n\n    disable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.disable();\n      }\n\n      if (this.view) {\n        this.view.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.enable();\n      }\n\n      if (this.view) {\n        this.view.enable();\n      }\n\n      this.base();\n    },\n\n    onAfterInit: function () {\n      this.settings.onAfterInit();\n      this.trigger('afterInit');\n    },\n\n    onSelectSource: function () {\n      this.settings.onSelectSource(this.sourceKey);\n      this.trigger('selectSource', {sourceKey: this.sourceKey});\n    },\n\n    onSelectSite: function () {\n      this.settings.onSelectSite(this.siteId);\n      this.trigger('selectSite', {siteId: this.siteId});\n    },\n\n    onUpdateElements: function () {\n      this.settings.onUpdateElements();\n      this.trigger('updateElements');\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n    },\n\n    onEnableElements: function ($elements) {\n      this.settings.onEnableElements($elements);\n      this.trigger('enableElements', {elements: $elements});\n    },\n\n    onDisableElements: function ($elements) {\n      this.settings.onDisableElements($elements);\n      this.trigger('disableElements', {elements: $elements});\n    },\n\n    onAfterAction: function (action, params) {\n      this.settings.onAfterAction(action, params);\n      this.trigger('afterAction', {action: action, params: params});\n    },\n\n    // UI state handlers\n    // -------------------------------------------------------------------------\n\n    _handleSourceSelectionChange: function () {\n      // If the selected source was just removed (maybe because its parent was collapsed),\n      // there won't be a selected source\n      if (!this.sourceSelect.totalSelected) {\n        this.sourceSelect.selectItem(this.$visibleSources.first());\n        return;\n      }\n\n      if (this.selectSource(this.sourceSelect.$selectedItems)) {\n        this.updateElements();\n      }\n    },\n\n    _handleActionTriggerSubmit: function (ev) {\n      ev.preventDefault();\n\n      var $form = $(ev.currentTarget);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($form.hasClass('disabled') || $form.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($form.data('action'), Garnish.getPostData($form));\n    },\n\n    _handleMenuActionTriggerSubmit: function (ev) {\n      var $option = $(ev.option);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($option.hasClass('disabled') || $option.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($option.data('action'));\n    },\n\n    _handleStatusChange: function (ev) {\n      this.statusMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$statusMenuBtn.html($option.html());\n\n      this.trashed = false;\n      this.drafts = false;\n      this.status = null;\n\n      if (Garnish.hasAttr($option, 'data-trashed')) {\n        this.trashed = true;\n      } else if (Garnish.hasAttr($option, 'data-drafts')) {\n        this.drafts = true;\n      } else {\n        this.status = $option.data('status');\n      }\n\n      this._updateStructureSortOption();\n      this.updateElements();\n    },\n\n    _handleSiteChange: function (ev) {\n      this.siteMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$siteMenuBtn.html($option.html());\n      this._setSite($option.data('site-id'));\n      this.onSelectSite();\n    },\n\n    _setSite: function (siteId) {\n      let firstSite = this.siteId === null;\n      this.siteId = siteId;\n      this.$visibleSources = $();\n\n      // Hide any sources that aren't available for this site\n      var $firstVisibleSource;\n      var $source;\n      // Select a new source automatically if a site is already selected, but we don't have a selected source\n      // (or if the currently selected source ends up not supporting the new site)\n      var selectNewSource =\n        !firstSite && (!this.$source || !this.$source.length);\n\n      for (var i = 0; i < this.$sources.length; i++) {\n        $source = this.$sources.eq(i);\n        if (\n          typeof $source.data('sites') === 'undefined' ||\n          $source\n            .data('sites')\n            .toString()\n            .split(',')\n            .indexOf(siteId.toString()) !== -1\n        ) {\n          $source.parent().removeClass('hidden');\n          this.$visibleSources = this.$visibleSources.add($source);\n          if (!$firstVisibleSource) {\n            $firstVisibleSource = $source;\n          }\n        } else {\n          $source.parent().addClass('hidden');\n\n          // Is this the currently selected source?\n          if (this.$source && this.$source.get(0) == $source.get(0)) {\n            selectNewSource = true;\n          }\n        }\n      }\n\n      if (this.initialized && selectNewSource) {\n        this.selectSource($firstVisibleSource);\n      }\n\n      // Hide any empty-nester headings\n      var $headings = this.getSourceContainer().children('.heading');\n      var $heading;\n\n      for (i = 0; i < $headings.length; i++) {\n        $heading = $headings.eq(i);\n        if ($heading.nextUntil('.heading', ':not(.hidden)').length !== 0) {\n          $heading.removeClass('hidden');\n        } else {\n          $heading.addClass('hidden');\n        }\n      }\n\n      if (this.initialized) {\n        if (this.settings.context === 'index') {\n          // Remember this site for later\n          Craft.cp.setSiteId(siteId);\n        }\n\n        // Update the elements\n        this.updateElements();\n      }\n    },\n\n    _handleSortChange: function (ev) {\n      var $option = $(ev.selectedOption);\n\n      if ($option.hasClass('disabled') || $option.hasClass('sel')) {\n        return;\n      }\n\n      // Is this an attribute or a direction?\n      if ($option.parent().parent().is(this.$sortAttributesList)) {\n        this.setSortAttribute($option.data('attr'));\n      } else {\n        this.setSortDirection($option.data('dir'));\n      }\n\n      this.storeSortAttributeAndDirection();\n      this.updateElements();\n    },\n\n    _handleSelectionChange: function () {\n      this.updateActionTriggers();\n      this.onSelectionChange();\n    },\n\n    _handleSourceDblClick: function (ev) {\n      this._toggleSource($(ev.currentTarget));\n      ev.stopPropagation();\n    },\n\n    _handleSourceToggleClick: function (ev) {\n      this._toggleSource($(ev.currentTarget).prev('a'));\n      ev.stopPropagation();\n    },\n\n    _updateStructureSortOption: function () {\n      var $option = this.getSortAttributeOption('structure');\n\n      if (!$option.length) {\n        return;\n      }\n\n      if (this.trashed || this.drafts || this.searching) {\n        $option.addClass('disabled');\n        if (this.getSelectedSortAttribute() === 'structure') {\n          // Temporarily set the sort to the first option\n          var $firstOption = this.$sortAttributesList.find(\n            'a:not(.disabled):first'\n          );\n          this.setSortAttribute($firstOption.data('attr'));\n          this.setSortDirection('asc');\n        }\n      } else {\n        $option.removeClass('disabled');\n        this.setStoredSortOptionsForSource();\n      }\n    },\n\n    // Source managemnet\n    // -------------------------------------------------------------------------\n\n    _getSourcesInList: function ($list) {\n      return $list.children('li').children('a');\n    },\n\n    _getChildSources: function ($source) {\n      var $list = $source.siblings('ul');\n      return this._getSourcesInList($list);\n    },\n\n    _getSourceToggle: function ($source) {\n      return $source.siblings('.toggle');\n    },\n\n    _toggleSource: function ($source) {\n      if ($source.parent('li').hasClass('expanded')) {\n        this._collapseSource($source);\n      } else {\n        this._expandSource($source);\n      }\n    },\n\n    _expandSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'true',\n        'aria-label': Craft.t('app', 'Hide nested sources'),\n      });\n      $source.parent('li').addClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.initSource($($childSources[i]));\n        if (this.$visibleSources) {\n          this.$visibleSources = this.$visibleSources.add($childSources[i]);\n        }\n      }\n\n      var key = $source.data('key');\n      if (this.instanceState.expandedSources.indexOf(key) === -1) {\n        this.instanceState.expandedSources.push(key);\n        this.storeInstanceState();\n      }\n    },\n\n    _collapseSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'false',\n        'aria-label': Craft.t('app', 'Show nested sources'),\n      });\n      $source.parent('li').removeClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.deinitSource($($childSources[i]));\n        this.$visibleSources = this.$visibleSources.not($childSources[i]);\n      }\n\n      var i = this.instanceState.expandedSources.indexOf($source.data('key'));\n      if (i !== -1) {\n        this.instanceState.expandedSources.splice(i, 1);\n        this.storeInstanceState();\n      }\n    },\n\n    // View\n    // -------------------------------------------------------------------------\n\n    _isViewPaginated: function () {\n      return (\n        this.settings.context === 'index' &&\n        this.getSelectedSortAttribute() !== 'structure'\n      );\n    },\n\n    _updateView: function (params, response) {\n      // Cleanup\n      // -------------------------------------------------------------\n\n      // Get rid of the old action triggers regardless of whether the new batch has actions or not\n      if (this.actions) {\n        this.hideActionTriggers();\n        this.actions =\n          this.actionsHeadHtml =\n          this.actionsFootHtml =\n          this._$triggers =\n            null;\n      }\n\n      // Update the count text\n      // -------------------------------------------------------------\n\n      if (this.$countContainer.length) {\n        this.$countSpinner.removeClass('hidden');\n        this.$countContainer.html('');\n\n        this._countResults()\n          .then((total) => {\n            this.$countSpinner.addClass('hidden');\n\n            let itemLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][2]\n              : 'element';\n            let itemsLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][3]\n              : 'elements';\n\n            if (!this._isViewPaginated()) {\n              let countLabel = Craft.t(\n                'app',\n                '{total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n              this.$countContainer.text(countLabel);\n            } else {\n              let first = Math.min(\n                this.settings.batchSize * (this.page - 1) + 1,\n                total\n              );\n              let last = Math.min(first + (this.settings.batchSize - 1), total);\n              let countLabel = Craft.t(\n                'app',\n                '{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  first: first,\n                  last: last,\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n\n              let $paginationContainer = $(\n                '<div class=\"flex pagination\"/>'\n              ).appendTo(this.$countContainer);\n              let totalPages = Math.max(\n                Math.ceil(total / this.settings.batchSize),\n                1\n              );\n\n              let $prevBtn = $('<div/>', {\n                class:\n                  'page-link prev-page' + (this.page > 1 ? '' : ' disabled'),\n                title: Craft.t('app', 'Previous Page'),\n              }).appendTo($paginationContainer);\n              let $nextBtn = $('<div/>', {\n                class:\n                  'page-link next-page' +\n                  (this.page < totalPages ? '' : ' disabled'),\n                title: Craft.t('app', 'Next Page'),\n              }).appendTo($paginationContainer);\n\n              $('<div/>', {\n                class: 'page-info',\n                text: countLabel,\n              }).appendTo($paginationContainer);\n\n              if (this.page > 1) {\n                this.addListener($prevBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page - 1);\n                  this.updateElements(true);\n                });\n              }\n\n              if (this.page < totalPages) {\n                this.addListener($nextBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page + 1);\n                  this.updateElements(true);\n                });\n              }\n            }\n          })\n          .catch(() => {\n            this.$countSpinner.addClass('hidden');\n          });\n      }\n\n      // Update the view with the new container + elements HTML\n      // -------------------------------------------------------------\n\n      this.$elements.html(response.html);\n      Craft.appendHeadHtml(response.headHtml);\n      Craft.appendFootHtml(response.footHtml);\n\n      // Batch actions setup\n      // -------------------------------------------------------------\n\n      this.$selectAllContainer = this.$elements.find(\n        '.selectallcontainer:first'\n      );\n\n      if (response.actions && response.actions.length) {\n        if (this.$selectAllContainer.length) {\n          this.actions = response.actions;\n          this.actionsHeadHtml = response.actionsHeadHtml;\n          this.actionsFootHtml = response.actionsFootHtml;\n\n          // Create the select all checkbox\n          this.$selectAllCheckbox = $('<div class=\"checkbox\"/>').prependTo(\n            this.$selectAllContainer\n          );\n\n          this.$selectAllContainer.attr({\n            role: 'checkbox',\n            tabindex: '0',\n            'aria-checked': 'false',\n            'aria-label': Craft.t('app', 'Select all'),\n          });\n\n          this.addListener(this.$selectAllContainer, 'click', function () {\n            if (this.view.getSelectedElements().length === 0) {\n              this.view.selectAllElements();\n            } else {\n              this.view.deselectAllElements();\n            }\n          });\n\n          this.addListener(this.$selectAllContainer, 'keydown', function (ev) {\n            if (ev.keyCode === Garnish.SPACE_KEY) {\n              ev.preventDefault();\n\n              $(ev.currentTarget).trigger('click');\n            }\n          });\n        }\n      } else {\n        if (!this.$selectAllContainer.siblings().length) {\n          this.$selectAllContainer.parent('.header').remove();\n        }\n        this.$selectAllContainer.remove();\n      }\n\n      // Exporters setup\n      // -------------------------------------------------------------\n\n      this.exporters = response.exporters;\n      this.exportersByType = Craft.index(this.exporters || [], (e) => e.type);\n\n      if (this.exporters && this.exporters.length) {\n        this.$exportBtn.removeClass('hidden');\n      } else {\n        this.$exportBtn.addClass('hidden');\n      }\n\n      // Create the view\n      // -------------------------------------------------------------\n\n      // Should we make the view selectable?\n      var selectable = this.actions || this.settings.selectable;\n\n      this.view = this.createView(this.getSelectedViewMode(), {\n        context: this.settings.context,\n        batchSize:\n          this.settings.context !== 'index' ||\n          this.getSelectedSortAttribute() === 'structure'\n            ? this.settings.batchSize\n            : null,\n        params: params,\n        selectable: selectable,\n        multiSelect: this.actions || this.settings.multiSelect,\n        checkboxMode: !!this.actions,\n        onSelectionChange: this._handleSelectionChange.bind(this),\n      });\n\n      // Auto-select elements\n      // -------------------------------------------------------------\n\n      if (this._autoSelectElements) {\n        if (selectable) {\n          for (var i = 0; i < this._autoSelectElements.length; i++) {\n            this.view.selectElementById(this._autoSelectElements[i]);\n          }\n        }\n\n        this._autoSelectElements = null;\n      }\n\n      // Trigger the event\n      // -------------------------------------------------------------\n\n      this.onUpdateElements();\n    },\n\n    _updateBadgeCounts: function (badgeCounts) {\n      for (let sourceKey in badgeCounts) {\n        if (badgeCounts.hasOwnProperty(sourceKey)) {\n          const $source = this.getSourceByKey(sourceKey);\n          if ($source) {\n            let $badge = $source.children('.badge');\n            if (badgeCounts[sourceKey] !== null) {\n              if (!$badge.length) {\n                $badge = $('<span class=\"badge\"/>').appendTo($source);\n              }\n              $badge.text(badgeCounts[sourceKey]);\n            } else if ($badge) {\n              $badge.remove();\n            }\n          }\n        }\n      }\n    },\n\n    _countResults: function () {\n      return new Promise((resolve, reject) => {\n        if (this.totalResults !== null) {\n          resolve(this.totalResults);\n        } else {\n          var params = this.getViewParams();\n          delete params.criteria.offset;\n          delete params.criteria.limit;\n\n          // Make sure we've got an active result set ID\n          if (this.resultSet === null) {\n            this.resultSet = Math.floor(Math.random() * 100000000);\n          }\n          params.resultSet = this.resultSet;\n\n          Craft.sendActionRequest('POST', this.settings.countElementsAction, {\n            data: params,\n            cancelToken: this._createCancelToken(),\n          })\n            .then((response) => {\n              if (response.data.resultSet == this.resultSet) {\n                this.totalResults = response.data.count;\n                resolve(response.data.count);\n              } else {\n                reject();\n              }\n            })\n            .catch(reject);\n        }\n      });\n    },\n\n    _createTriggers: function () {\n      var triggers = [],\n        safeMenuActions = [],\n        destructiveMenuActions = [];\n\n      var i;\n\n      for (i = 0; i < this.actions.length; i++) {\n        var action = this.actions[i];\n\n        if (action.trigger) {\n          var $form = $(\n            '<form id=\"' +\n              Craft.formatInputId(action.type) +\n              '-actiontrigger\"/>'\n          )\n            .data('action', action)\n            .append(action.trigger);\n\n          this.addListener($form, 'submit', '_handleActionTriggerSubmit');\n          triggers.push($form);\n        } else {\n          if (!action.destructive) {\n            safeMenuActions.push(action);\n          } else {\n            destructiveMenuActions.push(action);\n          }\n        }\n      }\n\n      var $btn;\n\n      if (safeMenuActions.length || destructiveMenuActions.length) {\n        var $menuTrigger = $('<form/>');\n\n        $btn = $('<button/>', {\n          type: 'button',\n          class: 'btn menubtn',\n          'data-icon': 'settings',\n          title: Craft.t('app', 'Actions'),\n        }).appendTo($menuTrigger);\n\n        var $menu = $('<ul class=\"menu\"/>').appendTo($menuTrigger),\n          $safeList = this._createMenuTriggerList(safeMenuActions, false),\n          $destructiveList = this._createMenuTriggerList(\n            destructiveMenuActions,\n            true\n          );\n\n        if ($safeList) {\n          $safeList.appendTo($menu);\n        }\n\n        if ($safeList && $destructiveList) {\n          $('<hr/>').appendTo($menu);\n        }\n\n        if ($destructiveList) {\n          $destructiveList.appendTo($menu);\n        }\n\n        triggers.push($menuTrigger);\n      }\n\n      this._$triggers = $();\n\n      for (i = 0; i < triggers.length; i++) {\n        var $div = $('<div/>').append(triggers[i]);\n        this._$triggers = this._$triggers.add($div);\n      }\n\n      this._$triggers.appendTo(this.$toolbar);\n      Craft.appendHeadHtml(this.actionsHeadHtml);\n      Craft.appendFootHtml(this.actionsFootHtml);\n\n      Craft.initUiElements(this._$triggers);\n\n      if ($btn) {\n        $btn\n          .data('menubtn')\n          .on('optionSelect', this._handleMenuActionTriggerSubmit.bind(this));\n      }\n    },\n\n    _showExportHud: function () {\n      this.$exportBtn.addClass('active');\n\n      var $form = $('<form/>', {\n        class: 'export-form',\n      });\n\n      var typeOptions = [];\n      for (var i = 0; i < this.exporters.length; i++) {\n        typeOptions.push({\n          label: this.exporters[i].name,\n          value: this.exporters[i].type,\n        });\n      }\n      var $typeField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Export Type'),\n          options: typeOptions,\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      var $formatField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Format'),\n          options: [\n            {label: 'CSV', value: 'csv'},\n            {label: 'JSON', value: 'json'},\n            {label: 'XML', value: 'xml'},\n          ],\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      let $typeSelect = $typeField.find('select');\n      this.addListener($typeSelect, 'change', () => {\n        let type = $typeSelect.val();\n        if (this.exportersByType[type].formattable) {\n          $formatField.removeClass('hidden');\n        } else {\n          $formatField.addClass('hidden');\n        }\n      });\n      $typeSelect.trigger('change');\n\n      // Only show the Limit field if there aren't any selected elements\n      var selectedElementIds = this.view.getSelectedElementIds();\n\n      if (!selectedElementIds.length) {\n        var $limitField = Craft.ui\n          .createTextField({\n            label: Craft.t('app', 'Limit'),\n            placeholder: Craft.t('app', 'No limit'),\n            type: 'number',\n            min: 1,\n          })\n          .appendTo($form);\n      }\n\n      $('<button/>', {\n        type: 'submit',\n        class: 'btn submit fullwidth',\n        text: Craft.t('app', 'Export'),\n      }).appendTo($form);\n\n      var $spinner = $('<div/>', {\n        class: 'spinner hidden',\n      }).appendTo($form);\n\n      var hud = new Garnish.HUD(this.$exportBtn, $form);\n\n      hud.on('hide', () => {\n        this.$exportBtn.removeClass('active');\n      });\n\n      var submitting = false;\n\n      this.addListener($form, 'submit', function (ev) {\n        ev.preventDefault();\n        if (submitting) {\n          return;\n        }\n\n        submitting = true;\n        $spinner.removeClass('hidden');\n\n        var params = this.getViewParams();\n        delete params.criteria.offset;\n        delete params.criteria.limit;\n        delete params.collapsedElementIds;\n\n        params.type = $typeField.find('select').val();\n        params.format = $formatField.find('select').val();\n\n        if (selectedElementIds.length) {\n          params.criteria.id = selectedElementIds;\n        } else {\n          var limit = parseInt($limitField.find('input').val());\n          if (limit && !isNaN(limit)) {\n            params.criteria.limit = limit;\n          }\n        }\n\n        if (Craft.csrfTokenValue) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl('element-indexes/export'),\n          params\n        )\n          .then(function () {\n            submitting = false;\n            $spinner.addClass('hidden');\n          })\n          .catch(function () {\n            submitting = false;\n            $spinner.addClass('hidden');\n            if (!this._ignoreFailedRequest) {\n              Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            }\n          });\n      });\n    },\n\n    _createMenuTriggerList: function (actions, destructive) {\n      if (actions && actions.length) {\n        var $ul = $('<ul/>');\n\n        for (var i = 0; i < actions.length; i++) {\n          $('<li/>')\n            .append(\n              $('<a/>', {\n                id: Craft.formatInputId(actions[i].type) + '-actiontrigger',\n                class: destructive ? 'error' : null,\n                data: {\n                  action: actions[i],\n                },\n                text: actions[i].name,\n              })\n            )\n            .appendTo($ul);\n        }\n\n        return $ul;\n      }\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      modal: null,\n      storageKey: null,\n      criteria: null,\n      batchSize: 100,\n      disabledElementIds: [],\n      selectable: false,\n      multiSelect: false,\n      buttonContainer: null,\n      hideSidebar: false,\n      toolbarSelector: '.toolbar:first',\n      refreshSourcesAction: 'element-indexes/get-source-tree-html',\n      updateElementsAction: 'element-indexes/get-elements',\n      countElementsAction: 'element-indexes/count-elements',\n      submitActionsAction: 'element-indexes/perform-action',\n      defaultSiteId: null,\n      defaultSource: null,\n      canHaveDrafts: false,\n\n      onAfterInit: $.noop,\n      onSelectSource: $.noop,\n      onSelectSite: $.noop,\n      onUpdateElements: $.noop,\n      onSelectionChange: $.noop,\n      onEnableElements: $.noop,\n      onDisableElements: $.noop,\n      onAfterAction: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.BaseElementIndexView = Garnish.Base.extend(\n  {\n    $container: null,\n    $loadingMoreSpinner: null,\n    $elementContainer: null,\n    $scroller: null,\n\n    elementIndex: null,\n    thumbLoader: null,\n    elementSelect: null,\n\n    loadingMore: false,\n\n    _totalVisible: null,\n    _morePending: null,\n    _handleEnableElements: null,\n    _handleDisableElements: null,\n\n    init: function (elementIndex, container, settings) {\n      this.elementIndex = elementIndex;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.BaseElementIndexView.defaults);\n\n      // Create a \"loading-more\" spinner\n      this.$loadingMoreSpinner = $(\n        '<div class=\"centeralign hidden\">' +\n          '<div class=\"spinner loadingmore\"></div>' +\n          '</div>'\n      ).insertAfter(this.$container);\n\n      // Get the actual elements container and its child elements\n      this.$elementContainer = this.getElementContainer();\n      var $elements = this.$elementContainer.children();\n\n      this.setTotalVisible($elements.length);\n      this.setMorePending(\n        this.settings.batchSize && $elements.length == this.settings.batchSize\n      );\n\n      // Instantiate the thumb loader\n      this.thumbLoader = new Craft.ElementThumbLoader();\n      this.thumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select(\n          this.$elementContainer,\n          $elements.filter(':not(.disabled)'),\n          {\n            multi: this.settings.multiSelect,\n            vertical: this.isVerticalList(),\n            handle:\n              this.settings.context === 'index'\n                ? '.checkbox, .element:first'\n                : null,\n            filter: ':not(a):not(.toggle)',\n            checkboxMode: this.settings.checkboxMode,\n            onSelectionChange: this.onSelectionChange.bind(this),\n          }\n        );\n\n        this._handleEnableElements = (ev) => {\n          this.elementSelect.addItems(ev.elements);\n        };\n\n        this._handleDisableElements = (ev) => {\n          this.elementSelect.removeItems(ev.elements);\n        };\n\n        this.elementIndex.on('enableElements', this._handleEnableElements);\n        this.elementIndex.on('disableElements', this._handleDisableElements);\n      }\n\n      // Enable inline element editing if this is an index page\n      if (this.settings.context === 'index') {\n        this._handleElementEditing = (ev) => {\n          var $target = $(ev.target);\n\n          if ($target.prop('nodeName') === 'A') {\n            // Let the link do its thing\n            return;\n          }\n\n          var $element;\n\n          if ($target.hasClass('element')) {\n            $element = $target;\n          } else {\n            $element = $target.closest('.element');\n\n            if (!$element.length) {\n              return;\n            }\n          }\n\n          if (Garnish.hasAttr($element, 'data-editable')) {\n            this.createElementEditor($element);\n          }\n        };\n\n        if (!this.elementIndex.trashed) {\n          this.addListener(\n            this.$elementContainer,\n            'dblclick',\n            this._handleElementEditing\n          );\n          if ($.isTouchCapable()) {\n            this.addListener(\n              this.$elementContainer,\n              'taphold',\n              this._handleElementEditing\n            );\n          }\n        }\n      }\n\n      // Give sub-classes a chance to do post-initialization stuff here\n      this.afterInit();\n\n      // Set up lazy-loading\n      if (this.settings.batchSize) {\n        if (this.settings.context === 'index') {\n          this.$scroller = Garnish.$scrollContainer;\n        } else {\n          this.$scroller = this.elementIndex.$main;\n        }\n\n        this.$scroller.scrollTop(0);\n        this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n        this.maybeLoadMore();\n      }\n    },\n\n    getElementContainer: function () {\n      throw 'Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method.';\n    },\n\n    afterInit: function () {},\n\n    getAllElements: function () {\n      return this.$elementContainer.children();\n    },\n\n    getEnabledElements: function () {\n      return this.$elementContainer.children(':not(.disabled)');\n    },\n\n    getElementById: function (id) {\n      var $element = this.$elementContainer.children(\n        '[data-id=\"' + id + '\"]:first'\n      );\n\n      if ($element.length) {\n        return $element;\n      } else {\n        return null;\n      }\n    },\n\n    getSelectedElements: function () {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      return this.elementSelect.$selectedItems;\n    },\n\n    getSelectedElementIds: function () {\n      let $selectedElements;\n      try {\n        $selectedElements = this.getSelectedElements();\n      } catch (e) {}\n\n      let ids = [];\n      if ($selectedElements) {\n        for (var i = 0; i < $selectedElements.length; i++) {\n          ids.push($selectedElements.eq(i).data('id'));\n        }\n      }\n      return ids;\n    },\n\n    selectElement: function ($element) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      this.elementSelect.selectItem($element, true);\n      return true;\n    },\n\n    selectElementById: function (id) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      var $element = this.getElementById(id);\n\n      if ($element) {\n        this.elementSelect.selectItem($element, true);\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    selectAllElements: function () {\n      this.elementSelect.selectAll();\n    },\n\n    deselectAllElements: function () {\n      this.elementSelect.deselectAll();\n    },\n\n    isVerticalList: function () {\n      return false;\n    },\n\n    getTotalVisible: function () {\n      return this._totalVisible;\n    },\n\n    setTotalVisible: function (totalVisible) {\n      this._totalVisible = totalVisible;\n    },\n\n    getMorePending: function () {\n      return this._morePending;\n    },\n\n    setMorePending: function (morePending) {\n      this._morePending = morePending;\n    },\n\n    /**\n     * Checks if the user has reached the bottom of the scroll area, and if so, loads the next batch of elemets.\n     */\n    maybeLoadMore: function () {\n      if (this.canLoadMore()) {\n        this.loadMore();\n      }\n    },\n\n    /**\n     * Returns whether the user has reached the bottom of the scroll area.\n     */\n    canLoadMore: function () {\n      if (!this.getMorePending() || !this.settings.batchSize) {\n        return false;\n      }\n\n      // Check if the user has reached the bottom of the scroll area\n      var containerHeight;\n\n      if (this.$scroller[0] === Garnish.$win[0]) {\n        var winHeight = Garnish.$win.innerHeight(),\n          winScrollTop = Garnish.$win.scrollTop(),\n          containerOffset = this.$container.offset().top;\n        containerHeight = this.$container.height();\n\n        return winHeight + winScrollTop >= containerOffset + containerHeight;\n      } else {\n        var containerScrollHeight = this.$scroller.prop('scrollHeight'),\n          containerScrollTop = this.$scroller.scrollTop();\n        containerHeight = this.$scroller.outerHeight();\n\n        return (\n          containerScrollHeight - containerScrollTop <= containerHeight + 15\n        );\n      }\n    },\n\n    /**\n     * Loads the next batch of elements.\n     */\n    loadMore: function () {\n      if (\n        !this.getMorePending() ||\n        this.loadingMore ||\n        !this.settings.batchSize\n      ) {\n        return;\n      }\n\n      this.loadingMore = true;\n      this.$loadingMoreSpinner.removeClass('hidden');\n      this.removeListener(this.$scroller, 'scroll');\n\n      Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n        data: this.getLoadMoreParams(),\n      })\n        .then((response) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n\n          let $newElements = $(response.data.html);\n\n          this.appendElements($newElements);\n          Craft.appendHeadHtml(response.data.headHtml);\n          Craft.appendFootHtml(response.data.footHtml);\n\n          if (this.elementSelect) {\n            this.elementSelect.addItems($newElements.filter(':not(.disabled)'));\n            this.elementIndex.updateActionTriggers();\n          }\n\n          this.setTotalVisible(this.getTotalVisible() + $newElements.length);\n          this.setMorePending($newElements.length == this.settings.batchSize);\n\n          // Is there room to load more right now?\n          this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n          this.maybeLoadMore();\n        })\n        .catch((e) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n        });\n    },\n\n    getLoadMoreParams: function () {\n      // Use the same params that were passed when initializing this view\n      var params = $.extend(true, {}, this.settings.params);\n      params.criteria.offset = this.getTotalVisible();\n      return params;\n    },\n\n    appendElements: function ($newElements) {\n      $newElements.appendTo(this.$elementContainer);\n      this.thumbLoader.load($newElements);\n      this.onAppendElements($newElements);\n    },\n\n    onAppendElements: function ($newElements) {\n      this.settings.onAppendElements($newElements);\n      this.trigger('appendElements', {\n        newElements: $newElements,\n      });\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n    },\n\n    createElementEditor: function ($element) {\n      Craft.createElementEditor($element.data('type'), $element, {\n        elementIndex: this.elementIndex,\n      });\n    },\n\n    disable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.disable();\n      }\n    },\n\n    enable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.enable();\n      }\n    },\n\n    destroy: function () {\n      // Remove the \"loading-more\" spinner, since we added that outside of the view container\n      this.$loadingMoreSpinner.remove();\n\n      // Kill the thumb loader\n      this.thumbLoader.destroy();\n      delete this.thumbLoader;\n\n      // Delete the element select\n      if (this.elementSelect) {\n        this.elementIndex.off('enableElements', this._handleEnableElements);\n        this.elementIndex.off('disableElements', this._handleDisableElements);\n\n        this.elementSelect.destroy();\n        delete this.elementSelect;\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      batchSize: null,\n      params: null,\n      selectable: false,\n      multiSelect: false,\n      checkboxMode: false,\n      loadMoreElementsAction: 'element-indexes/get-more-elements',\n      onAppendElements: $.noop,\n      onSelectionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Select input\n */\nCraft.BaseElementSelectInput = Garnish.Base.extend(\n  {\n    thumbLoader: null,\n    elementSelect: null,\n    elementSort: null,\n    modal: null,\n    elementEditor: null,\n\n    fieldLabel: null,\n\n    $container: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addElementBtn: null,\n    $addElementBtnContainer: null,\n\n    _initialized: false,\n\n    init: function (settings) {\n      // Normalize the settings and set them\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = [\n            'id',\n            'name',\n            'elementType',\n            'sources',\n            'criteria',\n            'sourceElementId',\n            'limit',\n            'modalStorageKey',\n            'fieldId',\n          ];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.setSettings(settings, Craft.BaseElementSelectInput.defaults);\n\n      // Apply the storage key prefix\n      if (this.settings.modalStorageKey) {\n        this.modalStorageKey =\n          'BaseElementSelectInput.' + this.settings.modalStorageKey;\n      }\n\n      // No reason for this to be sortable if we're only allowing 1 selection\n      if (this.settings.limit == 1) {\n        this.settings.sortable = false;\n      }\n\n      this.$container = this.getContainer();\n      this.fieldLabel = this.getFieldLabel();\n\n      // Store a reference to this class\n      this.$container.data('elementSelect', this);\n\n      this.$elementsContainer = this.getElementsContainer();\n\n      this.$addElementBtn = this.getAddElementsBtn();\n      if (this.$addElementBtn) {\n        this.$addElementBtnContainer = this.$addElementBtn.parent('.flex');\n        if (!this.$addElementBtnContainer.length) {\n          this.$addElementBtnContainer = null;\n        }\n      }\n\n      this.thumbLoader = new Craft.ElementThumbLoader();\n\n      this.initElementSelect();\n      this.initElementSort();\n      this.resetElements();\n\n      if (this.$addElementBtn) {\n        this.addListener(this.$addElementBtn, 'activate', 'showModal');\n      }\n\n      Garnish.requestAnimationFrame(() => {\n        this._initialized = true;\n      });\n    },\n\n    get totalSelected() {\n      return this.$elements.length;\n    },\n\n    getContainer: function () {\n      return $('#' + this.settings.id);\n    },\n\n    getFieldLabel: function () {\n      if (!this.$container) return;\n\n      const $fieldset = this.$container.closest('fieldset');\n      return $fieldset.find('legend').first().data('label');\n    },\n\n    getElementsContainer: function () {\n      return this.$container.children('.elements');\n    },\n\n    getElements: function () {\n      return this.$elementsContainer.children();\n    },\n\n    getAddElementsBtn: function () {\n      return this.$container.find('.btn.add:first');\n    },\n\n    initElementSelect: function () {\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select({\n          multi: this.settings.sortable,\n          filter: ':not(.delete)',\n        });\n      }\n    },\n\n    initElementSort: function () {\n      if (this.settings.sortable) {\n        this.elementSort = new Garnish.DragSort({\n          container: this.$elementsContainer,\n          filter: this.settings.selectable\n            ? () => {\n                // Only return all the selected items if the target item is selected\n                if (this.elementSort.$targetItem.hasClass('sel')) {\n                  return this.elementSelect.getSelectedItems();\n                } else {\n                  return this.elementSort.$targetItem;\n                }\n              }\n            : null,\n          ignoreHandleSelector: '.delete',\n          axis: this.getElementSortAxis(),\n          collapseDraggees: true,\n          magnetStrength: 4,\n          helperLagBase: 1.5,\n          onSortChange: this.settings.selectable\n            ? () => {\n                this.elementSelect.resetItemOrder();\n              }\n            : null,\n        });\n      }\n    },\n\n    getElementSortAxis: function () {\n      return this.settings.viewMode === 'list' ? 'y' : null;\n    },\n\n    canAddMoreElements: function () {\n      return (\n        !this.settings.limit || this.$elements.length < this.settings.limit\n      );\n    },\n\n    updateAddElementsBtn: function () {\n      if (this.canAddMoreElements()) {\n        this.enableAddElementsBtn();\n      } else {\n        this.disableAddElementsBtn();\n      }\n    },\n\n    disableAddElementsBtn: function () {\n      let $btn = this.$addElementBtnContainer || this.$addElementBtn;\n      if ($btn) {\n        $btn.addClass('hidden');\n      }\n    },\n\n    enableAddElementsBtn: function () {\n      let $btn = this.$addElementBtnContainer || this.$addElementBtn;\n      if ($btn) {\n        $btn.removeClass('hidden');\n      }\n    },\n\n    focusNextLogicalElement: function () {\n      if (this.canAddMoreElements()) {\n        // If can add more elements, focus ADD button\n        let $btn = this.$addElementBtn;\n\n        if ($btn) {\n          $btn.get(0).focus();\n        }\n      } else {\n        // If can't add more elements, focus on the final remove\n        this.focusLastRemoveBtn();\n      }\n    },\n\n    focusLastRemoveBtn: function () {\n      const $removeBtns = this.$container.find('.delete');\n\n      if (!$removeBtns.length) return;\n\n      $removeBtns.last()[0].focus();\n    },\n\n    resetElements: function () {\n      if (this.$elements !== null) {\n        this.removeElements(this.$elements);\n      } else {\n        this.$elements = $();\n      }\n\n      this.addElements(this.getElements());\n    },\n\n    addElements: function ($elements) {\n      this.thumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect.addItems($elements);\n      }\n\n      if (this.settings.sortable) {\n        this.elementSort.addItems($elements);\n      }\n\n      if (this.settings.editable) {\n        this._handleShowElementEditor = (ev) => {\n          var $element = $(ev.currentTarget);\n          if (\n            Garnish.hasAttr($element, 'data-editable') &&\n            !$element.hasClass('disabled') &&\n            !$element.hasClass('loading')\n          ) {\n            this.elementEditor = this.createElementEditor($element);\n          }\n        };\n\n        this.addListener($elements, 'dblclick', this._handleShowElementEditor);\n\n        if ($.isTouchCapable()) {\n          this.addListener($elements, 'taphold', this._handleShowElementEditor);\n        }\n      }\n\n      $elements.find('.delete').on('click dblclick', (ev) => {\n        this.removeElement($(ev.currentTarget).closest('.element'));\n        // Prevent this from acting as one of a double-click\n        ev.stopPropagation();\n      });\n\n      this.$elements = this.$elements.add($elements);\n      this.updateAddElementsBtn();\n    },\n\n    createElementEditor: function ($element, settings) {\n      if (!settings) {\n        settings = {};\n      }\n      settings.prevalidate = this.settings.prevalidate;\n      return Craft.createElementEditor(\n        this.settings.elementType,\n        $element,\n        settings\n      );\n    },\n\n    removeElements: function ($elements) {\n      if (this.settings.selectable) {\n        this.elementSelect.removeItems($elements);\n      }\n\n      if (this.modal) {\n        var ids = [];\n\n        for (var i = 0; i < $elements.length; i++) {\n          var id = $elements.eq(i).data('id');\n\n          if (id) {\n            ids.push(id);\n          }\n        }\n\n        if (ids.length) {\n          this.modal.elementIndex.enableElementsById(ids);\n        }\n      }\n\n      // Disable the hidden input in case the form is submitted before this element gets removed from the DOM\n      $elements.children('input').prop('disabled', true);\n\n      // Move the focus to the next element in the list, if there is one\n      let $nextDeleteBtn;\n      if (this.settings.selectable) {\n        const lastElementIndex = this.$elements.index($elements.last());\n        $nextDeleteBtn = this.$elements\n          .eq(lastElementIndex + 1)\n          .find('.delete');\n      }\n      if ($nextDeleteBtn.length) {\n        $nextDeleteBtn.focus();\n      } else {\n        this.focusNextLogicalElement();\n      }\n\n      this.$elements = this.$elements.not($elements);\n      this.updateAddElementsBtn();\n\n      this.onRemoveElements();\n    },\n\n    removeElement: function ($element) {\n      this.removeElements($element);\n      this.animateElementAway($element, () => {\n        $element.remove();\n      });\n    },\n\n    animateElementAway: function ($element, callback) {\n      $element.css('z-index', 0);\n\n      var animateCss = {\n        opacity: -1,\n      };\n      animateCss['margin-' + Craft.left] = -(\n        $element.outerWidth() + parseInt($element.css('margin-' + Craft.right))\n      );\n\n      if (this.settings.viewMode === 'list' || this.$elements.length === 0) {\n        animateCss['margin-bottom'] = -(\n          $element.outerHeight() + parseInt($element.css('margin-bottom'))\n        );\n      }\n\n      // Pause the draft editor\n      if (window.draftEditor) {\n        window.draftEditor.pause();\n      }\n\n      $element.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.REMOVE_FX_DURATION,\n        () => {\n          if (callback) {\n            callback();\n          }\n\n          // Resume the draft editor\n          if (window.draftEditor) {\n            window.draftEditor.resume();\n          }\n        }\n      );\n    },\n\n    showModal: function () {\n      // Make sure we haven't reached the limit\n      if (!this.canAddMoreElements()) {\n        return;\n      }\n\n      if (!this.modal) {\n        this.modal = this.createModal();\n      } else {\n        this.modal.show();\n      }\n    },\n\n    createModal: function () {\n      return Craft.createElementSelectorModal(\n        this.settings.elementType,\n        this.getModalSettings()\n      );\n    },\n\n    getModalSettings: function () {\n      return $.extend(\n        {\n          closeOtherModals: false,\n          storageKey: this.modalStorageKey,\n          sources: this.settings.sources,\n          criteria: this.settings.criteria,\n          multiSelect: this.settings.limit != 1,\n          showSiteMenu: this.settings.showSiteMenu,\n          disabledElementIds: this.getDisabledElementIds(),\n          onSelect: this.onModalSelect.bind(this),\n          onHide: this.onModalHide.bind(this),\n          triggerElement: this.$addElementBtn,\n          modalTitle: Craft.t('app', 'Select {element}', {\n            element: this.fieldLabel,\n          }),\n        },\n        this.settings.modalSettings\n      );\n    },\n\n    getSelectedElementIds: function () {\n      var ids = [];\n\n      for (var i = 0; i < this.$elements.length; i++) {\n        ids.push(this.$elements.eq(i).data('id'));\n      }\n\n      return ids;\n    },\n\n    getDisabledElementIds: function () {\n      var ids = this.getSelectedElementIds();\n\n      if (!this.settings.allowSelfRelations && this.settings.sourceElementId) {\n        ids.push(this.settings.sourceElementId);\n      }\n\n      if (this.settings.disabledElementIds) {\n        ids.push(...this.settings.disabledElementIds);\n      }\n\n      return ids;\n    },\n\n    onModalSelect: function (elements) {\n      if (this.settings.limit) {\n        // Cut off any excess elements\n        var slotsLeft = this.settings.limit - this.$elements.length;\n\n        if (elements.length > slotsLeft) {\n          elements = elements.slice(0, slotsLeft);\n        }\n      }\n\n      this.selectElements(elements);\n      this.updateDisabledElementsInModal();\n    },\n\n    onModalHide: function () {\n      // If can add more elements, do default behavior of focus on \"Add\" button\n      if (this.canAddMoreElements()) return;\n\n      setTimeout(() => {\n        this.focusNextLogicalElement();\n      }, 200);\n    },\n\n    selectElements: function (elements) {\n      for (let i = 0; i < elements.length; i++) {\n        let elementInfo = elements[i],\n          $element = this.createNewElement(elementInfo);\n\n        this.appendElement($element);\n        this.addElements($element);\n        this.animateElementIntoPlace(elementInfo.$element, $element);\n\n        // Override the element reference with the new one\n        elementInfo.$element = $element;\n      }\n\n      this.onSelectElements(elements);\n    },\n\n    createNewElement: function (elementInfo) {\n      var $element = elementInfo.$element.clone();\n      var removeText = Craft.t('app', 'Remove {label}', {\n        label: elementInfo.label,\n      });\n      // Make a couple tweaks\n      Craft.setElementSize(\n        $element,\n        this.settings.viewMode === 'large' ? 'large' : 'small'\n      );\n      $element.addClass('removable');\n      $element.prepend(\n        `<input type=\"hidden\" name=\"${this.settings.name}${\n          this.settings.single ? '' : '[]'\n        }\" value=\"${elementInfo.id}\">` +\n          '<button type=\"button\" class=\"delete icon\" title=\"' +\n          Craft.t('app', 'Remove') +\n          '\" aria-label=\"' +\n          removeText +\n          '\"></button>'\n      );\n\n      return $element;\n    },\n\n    appendElement: function ($element) {\n      $element.appendTo(this.$elementsContainer);\n    },\n\n    animateElementIntoPlace: function ($modalElement, $inputElement) {\n      var origOffset = $modalElement.offset(),\n        destOffset = $inputElement.offset(),\n        $helper = $inputElement.clone().appendTo(Garnish.$bod);\n\n      $inputElement.css('visibility', 'hidden');\n\n      $helper.css({\n        position: 'absolute',\n        zIndex: 10000,\n        top: origOffset.top,\n        left: origOffset.left,\n      });\n\n      var animateCss = {\n        top: destOffset.top,\n        left: destOffset.left,\n      };\n\n      $helper.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.ADD_FX_DURATION,\n        function () {\n          $helper.remove();\n          $inputElement.css('visibility', 'visible');\n        }\n      );\n    },\n\n    updateDisabledElementsInModal: function () {\n      if (this.modal.elementIndex) {\n        this.modal.elementIndex.disableElementsById(\n          this.getDisabledElementIds()\n        );\n      }\n    },\n\n    getElementById: function (id) {\n      for (var i = 0; i < this.$elements.length; i++) {\n        var $element = this.$elements.eq(i);\n\n        if ($element.data('id') == id) {\n          return $element;\n        }\n      }\n    },\n\n    onSelectElements: function (elements) {\n      this.trigger('selectElements', {elements});\n      this.settings.onSelectElements(elements);\n\n      if (window.draftEditor) {\n        window.draftEditor.checkForm();\n      }\n    },\n\n    onRemoveElements: function () {\n      this.trigger('removeElements');\n      this.settings.onRemoveElements();\n    },\n  },\n  {\n    ADD_FX_DURATION: 200,\n    REMOVE_FX_DURATION: 200,\n\n    defaults: {\n      id: null,\n      name: null,\n      fieldId: null,\n      elementType: null,\n      sources: null,\n      criteria: {},\n      allowSelfRelations: false,\n      sourceElementId: null,\n      disabledElementIds: null,\n      viewMode: 'list',\n      single: false,\n      limit: null,\n      showSiteMenu: false,\n      modalStorageKey: null,\n      modalSettings: {},\n      onSelectElements: $.noop,\n      onRemoveElements: $.noop,\n      sortable: true,\n      selectable: true,\n      editable: true,\n      prevalidate: false,\n      editorSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element selector modal class\n */\nCraft.BaseElementSelectorModal = Garnish.Modal.extend(\n  {\n    elementType: null,\n    elementIndex: null,\n\n    $body: null,\n    $selectBtn: null,\n    $sidebar: null,\n    $sources: null,\n    $sourceToggles: null,\n    $main: null,\n    $search: null,\n    $elements: null,\n    $tbody: null,\n    $primaryButtons: null,\n    $secondaryButtons: null,\n    $cancelBtn: null,\n    $footerSpinner: null,\n\n    init: function (elementType, settings) {\n      this.elementType = elementType;\n      this.setSettings(settings, Craft.BaseElementSelectorModal.defaults);\n      var $headingId = 'elementSelectorModalHeading-' + Date.now();\n\n      // Build the modal\n      var $container = $(\n          '<div class=\"modal elementselectormodal\" aria-labelledby=\"' +\n            $headingId +\n            '\"></div>'\n        ).appendTo(Garnish.$bod),\n        $heading = $(\n          '<h2 id=\"' +\n            $headingId +\n            '\" class=\"visually-hidden\">' +\n            this.settings.modalTitle +\n            '</h2>'\n        ).appendTo($container),\n        $body = $(\n          '<div class=\"body\"><div class=\"spinner big\"></div></div>'\n        ).appendTo($container),\n        $footer = $('<div class=\"footer\"/>').appendTo($container);\n\n      if (this.settings.fullscreen) {\n        $container.addClass('fullscreen');\n        this.settings.minGutter = 0;\n      }\n\n      this.base($container, this.settings);\n\n      this.$footerSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n        $footer\n      );\n      this.$secondaryButtons = $(\n        '<div class=\"buttons left secondary-buttons\"/>'\n      ).appendTo($footer);\n      this.$primaryButtons = $('<div class=\"buttons right\"/>').appendTo(\n        $footer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$primaryButtons);\n      this.$selectBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn disabled submit',\n        text: Craft.t('app', 'Select'),\n      }).appendTo(this.$primaryButtons);\n\n      this.$body = $body;\n\n      this.addListener(this.$cancelBtn, 'activate', 'cancel');\n      this.addListener(this.$selectBtn, 'activate', 'selectElements');\n    },\n\n    onFadeIn: function () {\n      if (!this.elementIndex) {\n        this._createElementIndex();\n      } else {\n        // Auto-focus the Search box\n        if (!Garnish.isMobileBrowser(true)) {\n          this.elementIndex.$search.trigger('focus');\n        }\n      }\n\n      this.base();\n    },\n\n    onSelectionChange: function () {\n      this.updateSelectBtnState();\n    },\n\n    updateSelectBtnState: function () {\n      if (this.$selectBtn) {\n        if (this.elementIndex.getSelectedElements().length) {\n          this.enableSelectBtn();\n        } else {\n          this.disableSelectBtn();\n        }\n      }\n    },\n\n    enableSelectBtn: function () {\n      this.$selectBtn.removeClass('disabled');\n    },\n\n    disableSelectBtn: function () {\n      this.$selectBtn.addClass('disabled');\n    },\n\n    enableCancelBtn: function () {\n      this.$cancelBtn.removeClass('disabled');\n    },\n\n    disableCancelBtn: function () {\n      this.$cancelBtn.addClass('disabled');\n    },\n\n    showFooterSpinner: function () {\n      this.$footerSpinner.removeClass('hidden');\n    },\n\n    hideFooterSpinner: function () {\n      this.$footerSpinner.addClass('hidden');\n    },\n\n    cancel: function () {\n      if (!this.$cancelBtn.hasClass('disabled')) {\n        this.hide();\n      }\n    },\n\n    selectElements: function () {\n      if (this.elementIndex && this.elementIndex.getSelectedElements().length) {\n        // TODO: This code shouldn't know about views' elementSelect objects\n        this.elementIndex.view.elementSelect.clearMouseUpTimeout();\n\n        var $selectedElements = this.elementIndex.getSelectedElements(),\n          elementInfo = this.getElementInfo($selectedElements);\n\n        this.onSelect(elementInfo);\n\n        if (this.settings.disableElementsOnSelect) {\n          this.elementIndex.disableElements(\n            this.elementIndex.getSelectedElements()\n          );\n        }\n\n        if (this.settings.hideOnSelect) {\n          this.hide();\n        }\n      }\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $element = $($selectedElements[i]);\n        var elementInfo = Craft.getElementInfo($element);\n\n        info.push(elementInfo);\n      }\n\n      return info;\n    },\n\n    show: function () {\n      this.updateSelectBtnState();\n      this.base();\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo);\n    },\n\n    disable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.enable();\n      }\n\n      this.base();\n    },\n\n    _createElementIndex: function () {\n      // Get the modal body HTML based on the settings\n      var data = {\n        context: 'modal',\n        elementType: this.elementType,\n        sources: this.settings.sources,\n      };\n\n      if (\n        this.settings.showSiteMenu !== null &&\n        this.settings.showSiteMenu !== 'auto'\n      ) {\n        data.showSiteMenu = this.settings.showSiteMenu ? '1' : '0';\n      }\n\n      Craft.postActionRequest(\n        this.settings.bodyAction,\n        data,\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.$body.html(response.html);\n\n            if (this.$body.has('.sidebar:not(.hidden)').length) {\n              this.$body.addClass('has-sidebar');\n            }\n\n            // Initialize the element index\n            this.elementIndex = Craft.createElementIndex(\n              this.elementType,\n              this.$body,\n              Object.assign(\n                {\n                  context: 'modal',\n                  modal: this,\n                  storageKey: this.settings.storageKey,\n                  criteria: this.settings.criteria,\n                  disabledElementIds: this.settings.disabledElementIds,\n                  selectable: true,\n                  multiSelect: this.settings.multiSelect,\n                  buttonContainer: this.$secondaryButtons,\n                  onSelectionChange: this.onSelectionChange.bind(this),\n                  hideSidebar: this.settings.hideSidebar,\n                  defaultSiteId: this.settings.defaultSiteId,\n                  defaultSource: this.settings.defaultSource,\n                },\n                this.settings.indexSettings\n              )\n            );\n\n            // Double-clicking or double-tapping should select the elements\n            this.addListener(\n              this.elementIndex.$elements,\n              'doubletap',\n              function (ev, touchData) {\n                // Make sure the touch targets are the same\n                // (they may be different if Command/Ctrl/Shift-clicking on multiple elements quickly)\n                if (touchData.firstTap.target === touchData.secondTap.target) {\n                  this.selectElements();\n                }\n              }\n            );\n          }\n        }\n      );\n    },\n  },\n  {\n    defaults: {\n      fullscreen: false,\n      resizable: true,\n      storageKey: null,\n      sources: null,\n      criteria: null,\n      multiSelect: false,\n      showSiteMenu: null,\n      disabledElementIds: [],\n      disableElementsOnSelect: false,\n      hideOnSelect: true,\n      modalTitle: Craft.t('app', 'Select element'),\n      onCancel: $.noop,\n      onSelect: $.noop,\n      hideSidebar: false,\n      defaultSiteId: null,\n      defaultSource: null,\n      bodyAction: 'elements/get-modal-body',\n      indexSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Input Generator\n */\nCraft.BaseInputGenerator = Garnish.Base.extend({\n  $source: null,\n  $target: null,\n  $form: null,\n  settings: null,\n\n  listening: null,\n  timeout: null,\n\n  init: function (source, target, settings) {\n    this.$source = $(source);\n    this.$target = $(target);\n    this.$form = this.$source.closest('form');\n\n    this.setSettings(settings);\n\n    this.startListening();\n  },\n\n  setNewSource: function (source) {\n    var listening = this.listening;\n    this.stopListening();\n\n    this.$source = $(source);\n\n    if (listening) {\n      this.startListening();\n    }\n  },\n\n  startListening: function () {\n    if (this.listening) {\n      return;\n    }\n\n    this.listening = true;\n\n    this.addListener(this.$source, 'input', 'onSourceTextChange');\n    this.addListener(this.$target, 'input', 'onTargetTextChange');\n    this.addListener(this.$form, 'submit', 'onFormSubmit');\n  },\n\n  stopListening: function () {\n    if (!this.listening) {\n      return;\n    }\n\n    this.listening = false;\n\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.removeAllListeners(this.$source);\n    this.removeAllListeners(this.$target);\n    this.removeAllListeners(this.$form);\n  },\n\n  onSourceTextChange: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.timeout = setTimeout(this.updateTarget.bind(this), 250);\n  },\n\n  onTargetTextChange: function () {\n    if (this.$target.get(0) === document.activeElement) {\n      this.stopListening();\n    }\n  },\n\n  onFormSubmit: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.updateTarget();\n  },\n\n  updateTarget: function () {\n    if (!this.$target.is(':visible')) {\n      return;\n    }\n\n    var sourceVal = this.$source.val();\n\n    if (typeof sourceVal === 'undefined') {\n      // The source input may not exist anymore\n      return;\n    }\n\n    var targetVal = this.generateTargetValue(sourceVal);\n\n    this.$target.val(targetVal);\n\n    for (let i = 0; i < this.$target.length; i++) {\n      this.$target[i].dispatchEvent(\n        new InputEvent('input', {\n          inputType: 'insertText',\n        })\n      );\n      this.$target[i].dispatchEvent(new Event('input'));\n    }\n\n    // If the target already has focus, select its whole value to mimic\n    // the behavior if the value had already been generated and they just tabbed in\n    if (this.$target.is(':focus')) {\n      Craft.selectFullValue(this.$target);\n    }\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return sourceVal;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * CP class\n */\nCraft.CP = Garnish.Base.extend(\n  {\n    authManager: null,\n\n    $nav: null,\n    $navToggle: null,\n    $globalSidebar: null,\n    $globalContainer: null,\n    $mainContainer: null,\n    $alerts: null,\n    $crumbs: null,\n    $breadcrumbList: null,\n    $breadcrumbItems: null,\n    $notificationContainer: null,\n    $main: null,\n    $primaryForm: null,\n    $headerContainer: null,\n    $header: null,\n    $mainContent: null,\n    $details: null,\n    $sidebarContainer: null,\n    $sidebar: null,\n    $contentContainer: null,\n    $edition: null,\n\n    $confirmUnloadForms: null,\n    $deltaForms: null,\n    $collapsibleTables: null,\n\n    isMobile: null,\n    fixedHeader: false,\n\n    breadcrumbListWidth: 0,\n    breadcrumbDisclosureItem: `<li class=\"breadcrumb-toggle-wrapper\" data-disclosure-item><button data-disclosure-trigger aria-controls=\"breadcrumb-disclosure\" aria-haspopup=\"true\">${Craft.t(\n      'app',\n      'More…'\n    )}</button><div id=\"breadcrumb-disclosure\" class=\"menu menu--disclosure\" data-disclosure-menu><ul></ul></div></li>`,\n\n    tabManager: null,\n\n    enableQueue: true,\n    totalJobs: 0,\n    jobInfo: null,\n    displayedJobInfo: null,\n    displayedJobInfoUnchanged: 1,\n    trackJobProgressTimeout: null,\n    jobProgressIcon: null,\n\n    checkingForUpdates: false,\n    forcingRefreshOnUpdatesCheck: false,\n    includingDetailsOnUpdatesCheck: false,\n    checkForUpdatesCallbacks: null,\n\n    resizeTimeout: null,\n\n    init: function () {\n      // Is this session going to expire?\n      if (Craft.remainingSessionTime !== 0) {\n        this.authManager = new Craft.AuthManager();\n      }\n\n      // Find all the key elements\n      this.$nav = $('#nav');\n      this.$navToggle = $('#nav-toggle');\n      this.$globalSidebar = $('#global-sidebar');\n      this.$globalContainer = $('#global-container');\n      this.$mainContainer = $('#main-container');\n      this.$alerts = $('#alerts');\n      this.$crumbs = $('#crumbs');\n      this.$breadcrumbList = $('.breadcrumb-list');\n      this.$breadcrumbItems = $('.breadcrumb-list li');\n      this.$notificationContainer = $('#notifications');\n      this.$main = $('#main');\n      this.$primaryForm = $('#main-form');\n      this.$headerContainer = $('#header-container');\n      this.$header = $('#header');\n      this.$mainContent = $('#main-content');\n      this.$details = $('#details');\n      this.$sidebarContainer = $('#sidebar-container');\n      this.$sidebar = $('#sidebar');\n      this.$contentContainer = $('#content-container');\n      this.$collapsibleTables = $('table.collapsible');\n\n      this.isMobile = Garnish.isMobileBrowser();\n\n      this.updateSidebarMenuLabel();\n\n      // Swap any instruction text with info icons\n      let $allInstructions = this.$details.find(\n        '.meta > .field > .instructions'\n      );\n\n      for (let i = 0; i < $allInstructions.length; i++) {\n        let $instructions = $allInstructions.eq(i);\n        let $label = $instructions.siblings('.heading').children('label');\n        $('<span/>', {\n          class: 'info',\n          html: $instructions.children().html(),\n        }).appendTo($label);\n        $instructions.remove();\n      }\n\n      if (!this.isMobile && this.$header.length) {\n        this.addListener(Garnish.$win, 'scroll', 'updateFixedHeader');\n        this.updateFixedHeader();\n      }\n\n      Garnish.$doc.ready(() => {\n        // Update responsive tables on window resize\n        this.addListener(Garnish.$win, 'resize', (ev) => {\n          // Ignore element resizes\n          if (ev.target === window) {\n            this.handleWindowResize();\n\n            clearTimeout(this.resizeTimeout);\n            var cp = this;\n            this.resizeTimeout = setTimeout(function () {\n              cp.setSidebarNavAttributes();\n            }, 100);\n          }\n        });\n        this.handleWindowResize();\n        this.setSidebarNavAttributes();\n\n        // Fade the notification out two seconds after page load\n        var $errorNotifications =\n            this.$notificationContainer.children('.error'),\n          $otherNotifications =\n            this.$notificationContainer.children(':not(.error)');\n\n        $errorNotifications\n          .delay(Craft.CP.notificationDuration * 2)\n          .velocity('fadeOut');\n        $otherNotifications\n          .delay(Craft.CP.notificationDuration)\n          .velocity('fadeOut');\n\n        // Wait a frame before initializing any confirm-unload forms,\n        // so other JS that runs on ready() has a chance to initialize\n        Garnish.requestAnimationFrame(this.initSpecialForms.bind(this));\n      });\n\n      // Alerts\n      if (this.$alerts.length) {\n        this.initAlerts();\n      }\n\n      // Toggles\n      this.addListener(this.$navToggle, 'click', 'toggleNav');\n      this.addListener($('#sidebar-toggle'), 'click', 'toggleSidebar');\n\n      // Does this page have a primary form?\n      if (!this.$primaryForm.length) {\n        this.$primaryForm = $('form[data-saveshortcut]:first');\n      }\n\n      // Does the primary form support the save shortcut?\n      if (\n        this.$primaryForm.length &&\n        Garnish.hasAttr(this.$primaryForm, 'data-saveshortcut')\n      ) {\n        let shortcuts = [];\n        let actions = this.$primaryForm.data('actions');\n        if (typeof actions === 'undefined') {\n          shortcuts.push([\n            {\n              keyCode: Garnish.S_KEY,\n              ctrl: true,\n            },\n            {\n              redirect: this.$primaryForm.data('saveshortcut-redirect'),\n              retainScroll: Garnish.hasAttr(\n                this.$primaryForm,\n                'saveshortcut-scroll'\n              ),\n            },\n          ]);\n        } else {\n          for (let i = 0; i < actions.length; i++) {\n            let action = actions[i];\n            if (!action.shortcut) {\n              continue;\n            }\n            shortcuts.push([\n              {\n                keyCode: Garnish.S_KEY,\n                ctrl: true,\n                shift: !!action.shift,\n              },\n              {\n                action: action.action,\n                redirect: action.redirect,\n                confirm: action.confirm,\n                params: action.params,\n                data: action.data,\n                retainScroll: action.retainScroll,\n              },\n            ]);\n          }\n        }\n        for (let i = 0; i < shortcuts.length; i++) {\n          Garnish.uiLayerManager.registerShortcut(shortcuts[i][0], () => {\n            this.submitPrimaryForm(shortcuts[i][1]);\n          });\n        }\n      }\n\n      this.initTabs();\n\n      // Should we match the previous scroll position?\n      let scrollY = Craft.getLocalStorage('scrollY');\n      if (typeof scrollY !== 'undefined') {\n        Craft.removeLocalStorage('scrollY');\n        Garnish.$doc.ready(() => {\n          Garnish.requestAnimationFrame(() => {\n            window.scrollTo(0, scrollY);\n          });\n        });\n      }\n\n      if ($.isTouchCapable()) {\n        this.$mainContainer.on(\n          'focus',\n          'input, textarea, .focusable-input',\n          this._handleInputFocus.bind(this)\n        );\n        this.$mainContainer.on(\n          'blur',\n          'input, textarea, .focusable-input',\n          this._handleInputBlur.bind(this)\n        );\n      }\n\n      // Announcements HUD\n      if (Craft.announcements.length) {\n        let $btn = $('#announcements-btn').removeClass('hidden');\n        const hasUnreads = Craft.announcements.some((a) => a.unread);\n        if (hasUnreads) {\n          $btn.addClass('unread');\n        }\n        let hud;\n        this.addListener($btn, 'click', () => {\n          if (!hud) {\n            let contents = '';\n            Craft.group(Craft.announcements, 'timestamp').forEach(\n              ([announcements, timestamp]) => {\n                announcements.forEach((a, i) => {\n                  contents +=\n                    `<div class=\"announcement ${a.unread ? 'unread' : ''}\">` +\n                    (i === 0\n                      ? `<div class=\"timestamp\">${a.timestamp}</div>`\n                      : '') +\n                    `<h2>${a.heading}</h2>` +\n                    `<p>${a.body}</p>` +\n                    '</div>';\n                });\n              }\n            );\n            hud = new Garnish.HUD(\n              $btn,\n              `<div id=\"announcements\">${contents}</div>`,\n              {\n                onShow: () => {\n                  $btn.addClass('active');\n                },\n                onHide: () => {\n                  $btn.removeClass('active');\n                },\n              }\n            );\n\n            // Open outbound links in new windows\n            $('a', hud.$main).each(function () {\n              if (\n                this.hostname.length &&\n                this.hostname !== location.hostname &&\n                typeof $(this).attr('target') === 'undefined'\n              ) {\n                $(this).attr('rel', 'noopener').attr('target', '_blank');\n              }\n            });\n\n            if (hasUnreads) {\n              $btn.removeClass('unread');\n              Craft.sendActionRequest(\n                'POST',\n                'users/mark-announcements-as-read',\n                {\n                  data: {\n                    ids: Craft.announcements.map((a) => a.id),\n                  },\n                }\n              );\n            }\n          } else {\n            hud.show();\n          }\n        });\n      }\n    },\n\n    initSpecialForms: function () {\n      // Look for forms that we should watch for changes on\n      this.$confirmUnloadForms = $('form[data-confirm-unload]');\n      this.$deltaForms = $('form[data-delta]');\n\n      if (!this.$confirmUnloadForms.length) {\n        return;\n      }\n\n      var $forms = this.$confirmUnloadForms.add(this.$deltaForms);\n      var $form, serialized;\n\n      for (var i = 0; i < $forms.length; i++) {\n        $form = $forms.eq(i);\n        if (!$form.data('initialSerializedValue')) {\n          if (typeof $form.data('serializer') === 'function') {\n            serialized = $form.data('serializer')();\n          } else {\n            serialized = $form.serialize();\n          }\n          $form.data('initialSerializedValue', serialized);\n        }\n        this.addListener($form, 'submit', function (ev) {\n          if (Garnish.hasAttr($form, 'data-confirm-unload')) {\n            this.removeListener(Garnish.$win, 'beforeunload');\n          }\n          if (Garnish.hasAttr($form, 'data-delta')) {\n            ev.preventDefault();\n            var serialized;\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            var data = Craft.findDeltaData(\n              $form.data('initialSerializedValue'),\n              serialized,\n              Craft.deltaNames\n            );\n            Craft.createForm(data).appendTo(Garnish.$bod).submit();\n          }\n        });\n      }\n\n      this.addListener(Garnish.$win, 'beforeunload', function (ev) {\n        var confirmUnload = false;\n        var $form, serialized;\n        if (\n          typeof Craft.livePreview !== 'undefined' &&\n          Craft.livePreview.inPreviewMode\n        ) {\n          confirmUnload = true;\n        } else {\n          for (var i = 0; i < this.$confirmUnloadForms.length; i++) {\n            $form = this.$confirmUnloadForms.eq(i);\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            if ($form.data('initialSerializedValue') !== serialized) {\n              confirmUnload = true;\n              break;\n            }\n          }\n        }\n\n        if (confirmUnload) {\n          var message = Craft.t(\n            'app',\n            'Any changes will be lost if you leave this page.'\n          );\n\n          if (ev) {\n            ev.originalEvent.returnValue = message;\n          } else {\n            window.event.returnValue = message;\n          }\n\n          return message;\n        }\n      });\n    },\n\n    _handleInputFocus: function () {\n      this.updateFixedHeader();\n    },\n\n    _handleInputBlur: function () {\n      this.updateFixedHeader();\n    },\n\n    /**\n     * Submits a form.\n     * @param {Object} [options]\n     * @param {string} [options.action] The `action` param value override\n     * @param {string} [options.redirect] The `redirect` param value override\n     * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n     * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n     * @param {Object} [options.data] Additional data to be passed to the submit event\n     * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n     */\n    submitPrimaryForm: function (options) {\n      // Give other stuff on the page a chance to prepare\n      this.trigger('beforeSaveShortcut');\n\n      if (typeof options !== 'object' || !$.isPlainObject(options)) {\n        options = {};\n      }\n\n      if (!options.redirect) {\n        options.redirect = this.$primaryForm.data('saveshortcut-redirect');\n      }\n\n      if (!options.data) {\n        options.data = {};\n      }\n      options.data.saveShortcut = true;\n\n      Craft.submitForm(this.$primaryForm, options);\n    },\n\n    updateSidebarMenuLabel: function () {\n      var $item = this.$sidebar.find('a.sel:first');\n      var $label = $item.children('.label');\n      $('#selected-sidebar-item-label').text(\n        $label.length ? $label.text() : $item.text()\n      );\n      Garnish.$bod.removeClass('showing-sidebar');\n    },\n\n    toggleNav: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (isExpanded) {\n        this.disableGlobalSidebarLinks();\n        this.$navToggle.focus();\n        this.$navToggle.attr('aria-expanded', 'false');\n        Garnish.$bod.removeClass('showing-nav');\n      } else {\n        this.enableGlobalSidebarLinks();\n        this.$globalSidebar.find(':focusable')[0].focus();\n        this.$navToggle.attr('aria-expanded', 'true');\n        Garnish.$bod.addClass('showing-nav');\n      }\n    },\n\n    enableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '0');\n      });\n    },\n\n    disableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '-1');\n      });\n    },\n\n    setSidebarNavAttributes: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (!isExpanded) {\n        this.disableGlobalSidebarLinks();\n      } else {\n        this.enableGlobalSidebarLinks();\n      }\n    },\n\n    navIsExpanded: function () {\n      if (!this.$globalSidebar[0]) return null;\n\n      const isAlwaysVisible = getComputedStyle(this.$globalSidebar[0])\n        .getPropertyValue('--is-always-visible')\n        .trim();\n\n      return (\n        this.$navToggle.attr('aria-expanded') === 'true' ||\n        isAlwaysVisible === 'true'\n      );\n    },\n\n    toggleSidebar: function () {\n      Garnish.$bod.toggleClass('showing-sidebar');\n    },\n\n    initTabs: function () {\n      if (this.tabManager) {\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n\n      const $tabs = $('#tabs');\n      if (!$tabs.length) {\n        return;\n      }\n\n      this.tabManager = new Craft.Tabs($tabs);\n\n      this.tabManager.on('selectTab', (ev) => {\n        const href = ev.$tab.attr('href');\n\n        // Show its content area\n        if (href.charAt(0) === '#') {\n          $(href).removeClass('hidden');\n        }\n\n        // Trigger a resize event to update any UI components that are listening for it\n        Garnish.$win.trigger('resize');\n\n        // Fixes Redactor fixed toolbars on previously hidden panes\n        Garnish.$doc.trigger('scroll');\n\n        // If there is a revision menu, set its links to this tab ID\n        if (href && href.charAt(0) === '#') {\n          const menuBtn = $('#context-btn').menubtn().data('menubtn');\n          if (menuBtn) {\n            for (let i = 0; i < menuBtn.menu.$options.length; i++) {\n              let a = menuBtn.menu.$options[i];\n              if (a.href) {\n                a.href = a.href.match(/^[^#]*/)[0] + href;\n              }\n            }\n          }\n        }\n\n        if (typeof history !== 'undefined') {\n          // Delay changing the hash so it doesn't cause the browser to jump on page load\n          Garnish.requestAnimationFrame(() => {\n            history.replaceState(undefined, undefined, href);\n          });\n        }\n      });\n\n      this.tabManager.on('deselectTab', (ev) => {\n        if (ev.$tab.attr('href').charAt(0) === '#') {\n          // Hide its content area\n          $(ev.$tab.attr('href')).addClass('hidden');\n        }\n      });\n\n      if (window.LOCATION_HASH) {\n        const $tab = this.tabManager.$tabs.filter(\n          `[href=\"#${window.LOCATION_HASH}\"]`\n        );\n        if ($tab.length) {\n          this.tabManager.selectTab($tab);\n        }\n      }\n    },\n\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsContainer() {\n      return this.tabManager ? this.tabManager.$container : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsList() {\n      return this.tabManager ? this.tabManager.$ul : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabs() {\n      return this.tabManager ? this.tabManager.$ul.find('> li') : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $selectedTab() {\n      return this.tabManager ? this.tabManager.$selectedTab : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get selectedTabIndex() {\n      return this.tabManager\n        ? this.tabManager.$tabs.index(this.tabManager.$selectedTab)\n        : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $focusableTab() {\n      return this.tabManager ? this.tabManager.$focusableTab : undefined;\n    },\n    /**\n     * @param {object} tab\n     * @deprecated in 3.7.0\n     */\n    selectTab: function (tab) {\n      if (this.tabManager) {\n        this.tabManager.selectTab(tab);\n      }\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    deselectTab: function () {\n      if (this.tabManager) {\n        this.tabManager.deselectTab();\n      }\n    },\n\n    handleWindowResize: function () {\n      this.updateResponsiveTables();\n      this.handleBreadcrumbVisibility();\n    },\n\n    breadcrumbItemsWrap: function () {\n      if (!this.$breadcrumbItems[0]) return;\n\n      this.$breadcrumbList.css(\n        Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n        ''\n      );\n      const listWidth = this.$breadcrumbList[0].getBoundingClientRect().width;\n      let totalItemWidth = 0;\n\n      // Iterate through all list items (inclusive of more button)\n      const $items = this.$breadcrumbList.find('li');\n      for (let i = 0; i < $items.length; i++) {\n        totalItemWidth += $items.get(i).getBoundingClientRect().width;\n      }\n\n      this.breadcrumbListWidth = listWidth;\n\n      if (totalItemWidth <= listWidth) {\n        return false;\n      }\n\n      // If it's less than a pixel off, it's probably just a rounding error.\n      // Give the container an extra pixel to be safe, though\n      if (totalItemWidth < listWidth + 1) {\n        this.$breadcrumbList.css(\n          Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n          '-1px'\n        );\n        return false;\n      }\n\n      return true;\n    },\n\n    handleBreadcrumbVisibility: function () {\n      if (!this.breadcrumbItemsWrap()) return;\n\n      if (this.$breadcrumbList.find('[data-disclosure-item]').length === 0) {\n        this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n      }\n\n      const triggerWidth = this.$breadcrumbList.find(\n        '[data-disclosure-item]'\n      )[0].offsetWidth;\n      let visibleItemWidth = triggerWidth;\n      let finalIndex;\n      let newWidth;\n      const listWidth = this.breadcrumbListWidth;\n\n      // Find breadcrumbs that should remain visible without overflowing\n      this.$breadcrumbItems.each(function (index) {\n        newWidth = visibleItemWidth + this.offsetWidth;\n\n        if (newWidth < listWidth) {\n          finalIndex = index;\n          visibleItemWidth += this.offsetWidth;\n        } else {\n          return false;\n        }\n      });\n\n      // Separate breadcrums that should remain visible vs. hidden\n      const shownItems = this.$breadcrumbItems.slice(0, finalIndex + 1);\n      const hiddenItems = this.$breadcrumbItems.slice(finalIndex + 1);\n\n      // Empty list DOM and add shown items and trigger item\n      this.$breadcrumbList.html('');\n      this.$breadcrumbList.append(shownItems);\n      this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n\n      // Add hidden items to disclosure menu and initialize\n      this.$breadcrumbList\n        .find('[data-disclosure-menu] ul')\n        .append(hiddenItems);\n      this.$breadcrumbList.find('[data-disclosure-trigger]').disclosureMenu();\n    },\n\n    updateResponsiveTables: function () {\n      for (\n        this.updateResponsiveTables._i = 0;\n        this.updateResponsiveTables._i < this.$collapsibleTables.length;\n        this.updateResponsiveTables._i++\n      ) {\n        this.updateResponsiveTables._$table = this.$collapsibleTables.eq(\n          this.updateResponsiveTables._i\n        );\n        this.updateResponsiveTables._containerWidth =\n          this.updateResponsiveTables._$table.parent().width();\n        this.updateResponsiveTables._check = false;\n\n        if (this.updateResponsiveTables._containerWidth > 0) {\n          // Is this the first time we've checked this table?\n          if (\n            typeof this.updateResponsiveTables._$table.data(\n              'lastContainerWidth'\n            ) === 'undefined'\n          ) {\n            this.updateResponsiveTables._check = true;\n          } else {\n            this.updateResponsiveTables._isCollapsed =\n              this.updateResponsiveTables._$table.hasClass('collapsed');\n\n            // Getting wider?\n            if (\n              this.updateResponsiveTables._containerWidth >\n              this.updateResponsiveTables._$table.data('lastContainerWidth')\n            ) {\n              if (this.updateResponsiveTables._isCollapsed) {\n                this.updateResponsiveTables._$table.removeClass('collapsed');\n                this.updateResponsiveTables._check = true;\n              }\n            } else if (!this.updateResponsiveTables._isCollapsed) {\n              this.updateResponsiveTables._check = true;\n            }\n          }\n\n          // Are we checking the table width?\n          if (this.updateResponsiveTables._check) {\n            if (\n              this.updateResponsiveTables._$table.width() - 30 >\n              this.updateResponsiveTables._containerWidth\n            ) {\n              this.updateResponsiveTables._$table.addClass('collapsed');\n            }\n          }\n\n          // Remember the container width for next time\n          this.updateResponsiveTables._$table.data(\n            'lastContainerWidth',\n            this.updateResponsiveTables._containerWidth\n          );\n        }\n      }\n    },\n\n    updateFixedHeader: function () {\n      if (this.isMobile) {\n        return;\n      }\n\n      // Have we scrolled passed the top of #main?\n      if (\n        this.$main.length &&\n        this.$headerContainer[0].getBoundingClientRect().top < 0\n      ) {\n        if (!this.fixedHeader) {\n          var headerHeight = this.$headerContainer.height();\n\n          // Hard-set the minimum content container height\n          this.$contentContainer.css(\n            'min-height',\n            'calc(100vh - ' + (headerHeight + 14 + 48 - 1) + 'px)'\n          );\n\n          // Hard-set the header container height\n          this.$headerContainer.height(headerHeight);\n          Garnish.$bod.addClass('fixed-header');\n\n          // Fix the sidebar and details pane positions if they are taller than #content-container\n          var contentHeight = this.$contentContainer.outerHeight();\n          var $detailsHeight = this.$details.outerHeight();\n          var css = {\n            top: headerHeight + 'px',\n            'max-height': 'calc(100vh - ' + headerHeight + 'px)',\n          };\n          this.$sidebar.addClass('fixed').css(css);\n          this.$details.addClass('fixed').css(css);\n          this.fixedHeader = true;\n        }\n      } else if (this.fixedHeader) {\n        this.$headerContainer.height('auto');\n        Garnish.$bod.removeClass('fixed-header');\n        this.$contentContainer.css('min-height', '');\n        this.$sidebar.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.$details.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.fixedHeader = false;\n      }\n    },\n\n    /**\n     * Dispays a notification.\n     *\n     * @param {string} type\n     * @param {string} message\n     */\n    displayNotification: function (type, message) {\n      var notificationDuration = Craft.CP.notificationDuration;\n\n      if (['cp-error', 'error'].includes(type)) {\n        notificationDuration *= 2;\n        icon = 'alert';\n        label = Craft.t('app', 'Error');\n      } else {\n        icon = 'info';\n        label = Craft.t('app', 'Notice');\n      }\n\n      var $notification = $(`\n            <div class=\"notification ${type.replace('cp-', '')}\">\n                <span data-icon=\"${icon}\" aria-label=\"${label}\"></span>\n                ${message}\n            </div>\n            `).appendTo(this.$notificationContainer);\n\n      var fadedMargin = -($notification.outerWidth() / 2) + 'px';\n\n      $notification\n        .hide()\n        .css({\n          opacity: 0,\n          'margin-left': fadedMargin,\n          'margin-right': fadedMargin,\n        })\n        .velocity(\n          {opacity: 1, 'margin-left': '2px', 'margin-right': '2px'},\n          {display: 'inline-block', duration: 'fast'}\n        )\n        .delay(notificationDuration)\n        .velocity(\n          {opacity: 0, 'margin-left': fadedMargin, 'margin-right': fadedMargin},\n          {\n            complete: function () {\n              $notification.remove();\n            },\n          }\n        );\n\n      this.trigger('displayNotification', {\n        notificationType: type,\n        message: message,\n      });\n    },\n\n    /**\n     * Displays a notice.\n     *\n     * @param {string} message\n     */\n    displayNotice: function (message) {\n      this.displayNotification('notice', message);\n    },\n\n    /**\n     * Displays an error.\n     *\n     * @param {string} message\n     */\n    displayError: function (message) {\n      if (!message) {\n        message = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.displayNotification('error', message);\n    },\n\n    fetchAlerts: function () {\n      var data = {\n        path: Craft.path,\n      };\n\n      Craft.queueActionRequest(\n        'app/get-cp-alerts',\n        data,\n        this.displayAlerts.bind(this)\n      );\n    },\n\n    displayAlerts: function (alerts) {\n      this.$alerts.remove();\n\n      if (Garnish.isArray(alerts) && alerts.length) {\n        this.$alerts = $('<ul id=\"alerts\"/>').prependTo($('#page-container'));\n\n        for (var i = 0; i < alerts.length; i++) {\n          $(\n            `<li><span data-icon=\"alert\" aria-label=\"${Craft.t(\n              'app',\n              'Error'\n            )}\"></span> ${alerts[i]}</li>`\n          ).appendTo(this.$alerts);\n        }\n\n        var height = this.$alerts.outerHeight();\n        this.$alerts\n          .css('margin-top', -height)\n          .velocity({'margin-top': 0}, 'fast');\n\n        this.initAlerts();\n      }\n    },\n\n    initAlerts: function () {\n      // Are there any shunnable alerts?\n      var $shunnableAlerts = this.$alerts.find('a[class^=\"shun:\"]');\n\n      for (var i = 0; i < $shunnableAlerts.length; i++) {\n        this.addListener($shunnableAlerts[i], 'click', (ev) => {\n          ev.preventDefault();\n\n          var $link = $(ev.currentTarget);\n\n          var data = {\n            message: $link.prop('className').substr(5),\n          };\n\n          Craft.queueActionRequest(\n            'app/shun-cp-alert',\n            data,\n            (response, textStatus) => {\n              if (textStatus === 'success') {\n                if (response.success) {\n                  $link.parent().remove();\n                } else {\n                  this.displayError(response.error);\n                }\n              }\n            }\n          );\n        });\n      }\n    },\n\n    checkForUpdates: function (forceRefresh, includeDetails, callback) {\n      // Make 'includeDetails' optional\n      if (typeof includeDetails === 'function') {\n        callback = includeDetails;\n        includeDetails = false;\n      }\n\n      // If forceRefresh == true, we're currently checking for updates, and not currently forcing a refresh,\n      // then just set a new callback that re-checks for updates when the current one is done.\n      if (\n        this.checkingForUpdates &&\n        ((forceRefresh === true && !this.forcingRefreshOnUpdatesCheck) ||\n          (includeDetails === true && !this.includingDetailsOnUpdatesCheck))\n      ) {\n        var realCallback = callback;\n        callback = () => {\n          this.checkForUpdates(forceRefresh, includeDetails, realCallback);\n        };\n      }\n\n      // Callback function?\n      if (typeof callback === 'function') {\n        if (!Garnish.isArray(this.checkForUpdatesCallbacks)) {\n          this.checkForUpdatesCallbacks = [];\n        }\n\n        this.checkForUpdatesCallbacks.push(callback);\n      }\n\n      if (!this.checkingForUpdates) {\n        this.checkingForUpdates = true;\n        this.forcingRefreshOnUpdatesCheck = forceRefresh === true;\n        this.includingDetailsOnUpdatesCheck = includeDetails === true;\n\n        this._checkForUpdates(forceRefresh, includeDetails).then((info) => {\n          this.updateUtilitiesBadge();\n          this.checkingForUpdates = false;\n\n          if (Garnish.isArray(this.checkForUpdatesCallbacks)) {\n            var callbacks = this.checkForUpdatesCallbacks;\n            this.checkForUpdatesCallbacks = null;\n\n            for (var i = 0; i < callbacks.length; i++) {\n              callbacks[i](info);\n            }\n          }\n\n          this.trigger('checkForUpdates', {\n            updateInfo: info,\n          });\n        });\n      }\n    },\n\n    _checkForUpdates: function (forceRefresh, includeDetails) {\n      return new Promise((resolve, reject) => {\n        if (!forceRefresh) {\n          this._checkForCachedUpdates(includeDetails).then((info) => {\n            if (info.cached !== false) {\n              resolve(info);\n            }\n\n            this._getUpdates(includeDetails).then((info) => {\n              resolve(info);\n            });\n          });\n        } else {\n          this._getUpdates(includeDetails).then((info) => {\n            resolve(info);\n          });\n        }\n      });\n    },\n\n    _checkForCachedUpdates: function (includeDetails) {\n      return new Promise(function (resolve, reject) {\n        var data = {\n          onlyIfCached: true,\n          includeDetails: includeDetails,\n        };\n        Craft.postActionRequest(\n          'app/check-for-updates',\n          data,\n          function (info, textStatus) {\n            if (textStatus === 'success') {\n              resolve(info);\n            } else {\n              resolve({cached: false});\n            }\n          }\n        );\n      });\n    },\n\n    _getUpdates: function (includeDetails) {\n      return new Promise((resolve, reject) => {\n        Craft.sendApiRequest('GET', 'updates')\n          .then((updates) => {\n            this._cacheUpdates(updates, includeDetails).then(resolve);\n          })\n          .catch((e) => {\n            this._cacheUpdates({}).then(resolve);\n          });\n      });\n    },\n\n    _cacheUpdates: function (updates, includeDetails) {\n      return new Promise(function (resolve, reject) {\n        Craft.postActionRequest(\n          'app/cache-updates',\n          {\n            updates: updates,\n            includeDetails: includeDetails,\n          },\n          function (info, textStatus) {\n            if (textStatus === 'success') {\n              resolve(info);\n            } else {\n              reject();\n            }\n          },\n          {\n            contentType: 'json',\n          }\n        );\n      });\n    },\n\n    updateUtilitiesBadge: function () {\n      var $utilitiesLink = $('#nav-utilities').find('> a:not(.sel)');\n\n      // Ignore if there is no (non-selected) Utilities nav item\n      if (!$utilitiesLink.length) {\n        return;\n      }\n\n      Craft.queueActionRequest('app/get-utilities-badge-count', (response) => {\n        // Get the existing utility nav badge, if any\n        var $badge = $utilitiesLink.children('.badge');\n\n        if (response.badgeCount) {\n          if (!$badge.length) {\n            $badge = $('<span class=\"badge\"/>').appendTo($utilitiesLink);\n          }\n          $badge.text(response.badgeCount);\n        } else if ($badge.length) {\n          $badge.remove();\n        }\n      });\n    },\n\n    runQueue: function () {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      if (Craft.runQueueAutomatically) {\n        Craft.queueActionRequest('queue/run', (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.trackJobProgress(false, true);\n          }\n        });\n      } else {\n        this.trackJobProgress(false, true);\n      }\n    },\n\n    trackJobProgress: function (delay, force) {\n      if (force && this.trackJobProgressTimeout) {\n        clearTimeout(this.trackJobProgressTimeout);\n        this.trackJobProgressTimeout = null;\n      }\n\n      // Ignore if we're already tracking jobs, or the queue is disabled\n      if (this.trackJobProgressTimeout || !this.enableQueue) {\n        return;\n      }\n\n      if (delay === true) {\n        // Determine the delay based on how long the displayed job info has remained unchanged\n        var timeout = Math.min(60000, this.displayedJobInfoUnchanged * 500);\n        this.trackJobProgressTimeout = setTimeout(\n          this._trackJobProgressInternal.bind(this),\n          timeout\n        );\n      } else {\n        this._trackJobProgressInternal();\n      }\n    },\n\n    _trackJobProgressInternal: function () {\n      Craft.queueActionRequest(\n        'queue/get-job-info?limit=50&dontExtendSession=1',\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.trackJobProgressTimeout = null;\n            this.totalJobs = response.total;\n            this.setJobInfo(response.jobs);\n\n            if (this.jobInfo.length) {\n              // Check again after a delay\n              this.trackJobProgress(true);\n            }\n          }\n        }\n      );\n    },\n\n    setJobInfo: function (jobInfo) {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      this.jobInfo = jobInfo;\n\n      // Update the displayed job info\n      var oldInfo = this.displayedJobInfo;\n      this.displayedJobInfo = this.getDisplayedJobInfo();\n\n      // Same old same old?\n      if (\n        oldInfo &&\n        this.displayedJobInfo &&\n        oldInfo.id === this.displayedJobInfo.id &&\n        oldInfo.progress === this.displayedJobInfo.progress &&\n        oldInfo.progressLabel === this.displayedJobInfo.progressLabel &&\n        oldInfo.status === this.displayedJobInfo.status\n      ) {\n        this.displayedJobInfoUnchanged++;\n      } else {\n        // Reset the counter\n        this.displayedJobInfoUnchanged = 1;\n      }\n\n      this.updateJobIcon();\n\n      // Fire a setJobInfo event\n      this.trigger('setJobInfo');\n    },\n\n    /**\n     * Returns info for the job that should be displayed in the CP sidebar\n     */\n    getDisplayedJobInfo: function () {\n      if (!this.enableQueue) {\n        return null;\n      }\n\n      // Set the status preference order\n      var statuses = [\n        Craft.CP.JOB_STATUS_RESERVED,\n        Craft.CP.JOB_STATUS_FAILED,\n        Craft.CP.JOB_STATUS_WAITING,\n      ];\n\n      for (var i = 0; i < statuses.length; i++) {\n        for (var j = 0; j < this.jobInfo.length; j++) {\n          if (\n            this.jobInfo[j].status === statuses[i] &&\n            (statuses[i] !== Craft.CP.JOB_STATUS_WAITING ||\n              !this.jobInfo[j].delay)\n          ) {\n            return this.jobInfo[j];\n          }\n        }\n      }\n\n      return null;\n    },\n\n    updateJobIcon: function () {\n      if (!this.enableQueue || !this.$nav.length) {\n        return;\n      }\n\n      if (this.displayedJobInfo) {\n        if (!this.jobProgressIcon) {\n          this.jobProgressIcon = new JobProgressIcon();\n        }\n\n        if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_RESERVED ||\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_WAITING\n        ) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.setDescription(\n            this.displayedJobInfo.description,\n            this.displayedJobInfo.progressLabel\n          );\n          this.jobProgressIcon.setProgress(this.displayedJobInfo.progress);\n        } else if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_FAILED\n        ) {\n          this.jobProgressIcon.showFailMode(Craft.t('app', 'Failed'));\n        }\n      } else {\n        if (this.jobProgressIcon) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.complete();\n          delete this.jobProgressIcon;\n        }\n      }\n    },\n\n    /**\n     * Returns the active site for the control panel\n     *\n     * @return {number}\n     */\n    getSiteId: function () {\n      // If the old BaseElementIndex.siteId value is in localStorage, go aheand and remove & return that\n      let siteId = Craft.getLocalStorage('BaseElementIndex.siteId');\n      if (typeof siteId !== 'undefined') {\n        Craft.removeLocalStorage('BaseElementIndex.siteId');\n        this.setSiteId(siteId);\n        return siteId;\n      }\n      return Craft.getCookie('siteId');\n    },\n\n    /**\n     * Sets the active site for the control panel\n     * @param {number} siteId\n     */\n    setSiteId: function (siteId) {\n      Craft.setCookie('siteId', siteId, {\n        maxAge: 31536000, // 1 year\n      });\n    },\n  },\n  {\n    //maxWidth: 1051, //1024,\n    notificationDuration: 2000,\n\n    JOB_STATUS_WAITING: 1,\n    JOB_STATUS_RESERVED: 2,\n    JOB_STATUS_DONE: 3,\n    JOB_STATUS_FAILED: 4,\n  }\n);\n\nGarnish.$scrollContainer = Garnish.$win;\nCraft.cp = new Craft.CP();\n\n/**\n * Job progress icon class\n */\nvar JobProgressIcon = Garnish.Base.extend({\n  $li: null,\n  $a: null,\n  $label: null,\n  $progressLabel: null,\n\n  progress: null,\n  failMode: false,\n\n  _$bgCanvas: null,\n  _$staticCanvas: null,\n  _$hoverCanvas: null,\n  _$failCanvas: null,\n\n  _staticCtx: null,\n  _hoverCtx: null,\n  _canvasSize: null,\n  _arcPos: null,\n  _arcRadius: null,\n  _lineWidth: null,\n\n  _arcStartPos: 0,\n  _arcEndPos: 0,\n  _arcStartStepSize: null,\n  _arcEndStepSize: null,\n  _arcStep: null,\n  _arcStepTimeout: null,\n  _arcAnimateCallback: null,\n\n  _progressBar: null,\n\n  init: function () {\n    this.$li = $('<li/>').appendTo(Craft.cp.$nav.children('ul'));\n    this.$a = $('<a/>', {\n      id: 'job-icon',\n      href: Craft.canAccessQueueManager\n        ? Craft.getUrl('utilities/queue-manager')\n        : null,\n    }).appendTo(this.$li);\n    this.$canvasContainer = $('<span class=\"icon\"/>').appendTo(this.$a);\n    var $labelContainer = $('<span class=\"label\"/>').appendTo(this.$a);\n    this.$label = $('<span/>').appendTo($labelContainer);\n    this.$progressLabel = $('<span class=\"progress-label\"/>')\n      .appendTo($labelContainer)\n      .hide();\n\n    let m = window.devicePixelRatio > 1 ? 2 : 1;\n    this._canvasSize = 18 * m;\n    this._arcPos = this._canvasSize / 2;\n    this._arcRadius = 7 * m;\n    this._lineWidth = 3 * m;\n\n    this._$bgCanvas = this._createCanvas('bg', '#61666b');\n    this._$staticCanvas = this._createCanvas('static', '#d7d9db');\n    this._$hoverCanvas = this._createCanvas('hover', '#fff');\n    this._$failCanvas = this._createCanvas('fail', '#da5a47').hide();\n\n    this._staticCtx = this._$staticCanvas[0].getContext('2d');\n    this._hoverCtx = this._$hoverCanvas[0].getContext('2d');\n\n    this._drawArc(this._$bgCanvas[0].getContext('2d'), 0, 1);\n    this._drawArc(this._$failCanvas[0].getContext('2d'), 0, 1);\n  },\n\n  setDescription: function (description, progressLabel) {\n    this.$a.attr('title', description);\n    this.$label.text(description);\n    if (progressLabel) {\n      this.$progressLabel.text(progressLabel).show();\n    } else {\n      this.$progressLabel.hide();\n    }\n  },\n\n  setProgress: function (progress) {\n    if (progress == 0) {\n      this._$staticCanvas.hide();\n      this._$hoverCanvas.hide();\n    } else {\n      this._$staticCanvas.show();\n      this._$hoverCanvas.show();\n      if (this.progress && progress > this.progress) {\n        this._animateArc(0, progress / 100);\n      } else {\n        this._setArc(0, progress / 100);\n      }\n    }\n\n    this.progress = progress;\n  },\n\n  complete: function () {\n    this._animateArc(0, 1, () => {\n      this._$bgCanvas.velocity('fadeOut');\n\n      this._animateArc(1, 1, () => {\n        this.$a.remove();\n        this.destroy();\n      });\n    });\n  },\n\n  showFailMode: function (message) {\n    if (this.failMode) {\n      return;\n    }\n\n    this.failMode = true;\n    this.progress = null;\n\n    this._$bgCanvas.hide();\n    this._$staticCanvas.hide();\n    this._$hoverCanvas.hide();\n    this._$failCanvas.show();\n\n    this.setDescription(message);\n  },\n\n  hideFailMode: function () {\n    if (!this.failMode) {\n      return;\n    }\n\n    this.failMode = false;\n\n    this._$bgCanvas.show();\n    this._$staticCanvas.show();\n    this._$hoverCanvas.show();\n    this._$failCanvas.hide();\n  },\n\n  _createCanvas: function (id, color) {\n    var $canvas = $(\n        '<canvas id=\"job-icon-' +\n          id +\n          '\" width=\"' +\n          this._canvasSize +\n          '\" height=\"' +\n          this._canvasSize +\n          '\"/>'\n      ).appendTo(this.$canvasContainer),\n      ctx = $canvas[0].getContext('2d');\n\n    ctx.strokeStyle = color;\n    ctx.lineWidth = this._lineWidth;\n    ctx.lineCap = 'round';\n    return $canvas;\n  },\n\n  _setArc: function (startPos, endPos) {\n    this._arcStartPos = startPos;\n    this._arcEndPos = endPos;\n\n    this._drawArc(this._staticCtx, startPos, endPos);\n    this._drawArc(this._hoverCtx, startPos, endPos);\n  },\n\n  _drawArc: function (ctx, startPos, endPos) {\n    ctx.clearRect(0, 0, this._canvasSize, this._canvasSize);\n    ctx.beginPath();\n    ctx.arc(\n      this._arcPos,\n      this._arcPos,\n      this._arcRadius,\n      (1.5 + startPos * 2) * Math.PI,\n      (1.5 + endPos * 2) * Math.PI\n    );\n    ctx.stroke();\n    ctx.closePath();\n  },\n\n  _animateArc: function (targetStartPos, targetEndPos, callback) {\n    if (this._arcStepTimeout) {\n      clearTimeout(this._arcStepTimeout);\n    }\n\n    this._arcStep = 0;\n    this._arcStartStepSize = (targetStartPos - this._arcStartPos) / 10;\n    this._arcEndStepSize = (targetEndPos - this._arcEndPos) / 10;\n    this._arcAnimateCallback = callback;\n    this._takeNextArcStep();\n  },\n\n  _takeNextArcStep: function () {\n    this._setArc(\n      this._arcStartPos + this._arcStartStepSize,\n      this._arcEndPos + this._arcEndStepSize\n    );\n\n    this._arcStep++;\n\n    if (this._arcStep < 10) {\n      this._arcStepTimeout = setTimeout(this._takeNextArcStep.bind(this), 50);\n    } else if (this._arcAnimateCallback) {\n      this._arcAnimateCallback();\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category index class\n */\nCraft.CategoryIndex = Craft.BaseElementIndex.extend({\n  editableGroups: null,\n  $newCategoryBtnGroup: null,\n  $newCategoryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible groups the user has permission to create new categories in\n    this.editableGroups = [];\n\n    for (var i = 0; i < Craft.editableCategoryGroups.length; i++) {\n      var group = Craft.editableCategoryGroups[i];\n\n      if (this.getSourceByKey('group:' + group.uid)) {\n        this.editableGroups.push(group);\n      }\n    }\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific category group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultGroupHandle !== 'undefined'\n    ) {\n      for (var i = 0; i < this.$sources.length; i++) {\n        var $source = $(this.$sources[i]);\n\n        if ($source.data('handle') === defaultGroupHandle) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    // Get the handle of the selected source\n    var selectedSourceHandle = this.$source.data('handle');\n\n    var i, href, label;\n\n    // Update the New Category button\n    // ---------------------------------------------------------------------\n\n    if (this.editableGroups.length) {\n      // Remove the old button, if there is one\n      if (this.$newCategoryBtnGroup) {\n        this.$newCategoryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a group that they have permission to create categories in\n      var selectedGroup;\n\n      if (selectedSourceHandle) {\n        for (i = 0; i < this.editableGroups.length; i++) {\n          if (this.editableGroups[i].handle === selectedSourceHandle) {\n            selectedGroup = this.editableGroups[i];\n            break;\n          }\n        }\n      }\n\n      this.$newCategoryBtnGroup = $('<div class=\"btngroup submit\"/>');\n      var $menuBtn;\n\n      // If they are, show a primary \"New category\" button, and a dropdown of the other groups (if any).\n      // Otherwise only show a menu button\n      if (selectedGroup) {\n        href = this._getGroupTriggerHref(selectedGroup);\n        label =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New category')\n            : Craft.t('app', 'New {group} category', {\n                group: selectedGroup.name,\n              });\n        this.$newCategoryBtn = $(\n          '<a class=\"btn submit add icon\" ' +\n            href +\n            ' role=\"button\">' +\n            Craft.escapeHtml(label) +\n            '</a>'\n        ).appendTo(this.$newCategoryBtnGroup);\n\n        if (this.settings.context !== 'index') {\n          this.addListener(this.$newCategoryBtn, 'click', function (ev) {\n            this._openCreateCategoryModal(\n              ev.currentTarget.getAttribute('data-id')\n            );\n          });\n        }\n\n        if (this.editableGroups.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn',\n          }).appendTo(this.$newCategoryBtnGroup);\n        }\n      } else {\n        this.$newCategoryBtn = $menuBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit add icon menubtn',\n          text: Craft.t('app', 'New category'),\n        }).appendTo(this.$newCategoryBtnGroup);\n      }\n\n      if ($menuBtn) {\n        var menuHtml = '<div class=\"menu\"><ul>';\n\n        for (i = 0; i < this.editableGroups.length; i++) {\n          var group = this.editableGroups[i];\n\n          if (this.settings.context === 'index' || group !== selectedGroup) {\n            href = this._getGroupTriggerHref(group);\n            label =\n              this.settings.context === 'index'\n                ? group.name\n                : Craft.t('app', 'New {group} category', {group: group.name});\n            menuHtml +=\n              '<li><a ' + href + '>' + Craft.escapeHtml(label) + '</a></li>';\n          }\n        }\n\n        menuHtml += '</ul></div>';\n\n        $(menuHtml).appendTo(this.$newCategoryBtnGroup);\n        var menuBtn = new Garnish.MenuBtn($menuBtn);\n\n        if (this.settings.context !== 'index') {\n          menuBtn.on('optionSelect', (ev) => {\n            this._openCreateCategoryModal(ev.option.getAttribute('data-id'));\n          });\n        }\n      }\n\n      this.addButton(this.$newCategoryBtnGroup);\n    }\n\n    // Update the URL if we're on the Categories index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index' && typeof history !== 'undefined') {\n      var uri = 'categories';\n\n      if (selectedSourceHandle) {\n        uri += '/' + selectedSourceHandle;\n      }\n\n      history.replaceState({}, '', Craft.getUrl(uri));\n    }\n  },\n\n  _getGroupTriggerHref: function (group) {\n    if (this.settings.context === 'index') {\n      const uri = `categories/${group.handle}/new`;\n      const site = this.getSite();\n      const params = site ? {site: site.handle} : undefined;\n      return `href=\"${Craft.getUrl(uri, params)}\"`;\n    }\n\n    return `data-id=\"${group.id}\"`;\n  },\n\n  _openCreateCategoryModal: function (groupId) {\n    if (this.$newCategoryBtn.hasClass('loading')) {\n      return;\n    }\n\n    // Find the group\n    var group;\n\n    for (var i = 0; i < this.editableGroups.length; i++) {\n      if (this.editableGroups[i].id == groupId) {\n        group = this.editableGroups[i];\n        break;\n      }\n    }\n\n    if (!group) {\n      return;\n    }\n\n    this.$newCategoryBtn.addClass('inactive');\n    var newCategoryBtnText = this.$newCategoryBtn.text();\n    this.$newCategoryBtn.text(\n      Craft.t('app', 'New {group} category', {group: group.name})\n    );\n\n    Craft.createElementEditor(this.elementType, {\n      hudTrigger: this.$newCategoryBtnGroup,\n      siteId: this.siteId,\n      attributes: {\n        groupId: groupId,\n      },\n      onHideHud: () => {\n        this.$newCategoryBtn.removeClass('inactive').text(newCategoryBtnText);\n      },\n      onSaveElement: (response) => {\n        // Make sure the right group is selected\n        var groupSourceKey = 'group:' + group.uid;\n\n        if (this.sourceKey !== groupSourceKey) {\n          this.selectSourceByKey(groupSourceKey);\n        }\n\n        this.clearSearch();\n        this.selectElementAfterUpdate(response.id);\n        this.updateElements();\n      },\n    });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass(\n  'craft\\\\elements\\\\Category',\n  Craft.CategoryIndex\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category Select input\n */\nCraft.CategorySelectInput = Craft.BaseElementSelectInput.extend({\n  setSettings: function () {\n    this.base.apply(this, arguments);\n    this.settings.sortable = false;\n  },\n\n  getModalSettings: function () {\n    var settings = this.base();\n    settings.hideOnSelect = false;\n    return settings;\n  },\n\n  getElements: function () {\n    return this.$elementsContainer.find('.element');\n  },\n\n  onModalSelect: function (elements) {\n    // Disable the modal\n    this.modal.disable();\n    this.modal.disableCancelBtn();\n    this.modal.disableSelectBtn();\n    this.modal.showFooterSpinner();\n\n    // Get the new category HTML\n    var selectedCategoryIds = this.getSelectedElementIds();\n\n    for (var i = 0; i < elements.length; i++) {\n      selectedCategoryIds.push(elements[i].id);\n    }\n\n    var data = {\n      categoryIds: selectedCategoryIds,\n      siteId: elements[0].siteId,\n      id: this.settings.id,\n      name: this.settings.name,\n      branchLimit: this.settings.branchLimit,\n      selectionLabel: this.settings.selectionLabel,\n    };\n\n    Craft.postActionRequest(\n      'elements/get-categories-input-html',\n      data,\n      (response, textStatus) => {\n        this.modal.enable();\n        this.modal.enableCancelBtn();\n        this.modal.enableSelectBtn();\n        this.modal.hideFooterSpinner();\n\n        if (textStatus === 'success') {\n          var $newInput = $(response.html),\n            $newElementsContainer = $newInput.children('.elements');\n\n          this.$elementsContainer.replaceWith($newElementsContainer);\n          this.$elementsContainer = $newElementsContainer;\n          this.resetElements();\n\n          var filteredElements = [];\n\n          for (var i = 0; i < elements.length; i++) {\n            var element = elements[i],\n              $element = this.getElementById(element.id);\n\n            if ($element) {\n              this.animateElementIntoPlace(element.$element, $element);\n              filteredElements.push(element);\n            }\n          }\n\n          this.updateDisabledElementsInModal();\n          this.modal.hide();\n          this.onSelectElements(filteredElements);\n        }\n      }\n    );\n  },\n\n  removeElement: function ($element) {\n    // Find any descendants this category might have\n    const $allCategories = $element.add(\n      $element.parent().siblings('ul').find('.element')\n    );\n\n    // Remove our record of them all at once\n    this.removeElements($allCategories);\n\n    // Animate them away one at a time\n    for (let i = 0; i < $allCategories.length; i++) {\n      this._animateCategoryAway($allCategories, i);\n    }\n  },\n\n  _animateCategoryAway: function ($allCategories, i) {\n    let callback;\n\n    // Is this the last one?\n    if (i === $allCategories.length - 1) {\n      callback = () => {\n        const $li = $allCategories.first().parent().parent();\n        const $ul = $li.parent();\n\n        if ($ul[0] === this.$elementsContainer[0] || $li.siblings().length) {\n          $li.remove();\n        } else {\n          $ul.remove();\n        }\n      };\n    }\n\n    const func = () => {\n      this.animateElementAway($allCategories.eq(i), callback);\n    };\n\n    if (i === 0) {\n      func();\n    } else {\n      setTimeout(func, 100 * i);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Craft Charts\n */\n\nCraft.charts = {};\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.DataTable\n */\nCraft.charts.DataTable = Garnish.Base.extend({\n  columns: null,\n  rows: null,\n\n  init: function (data) {\n    let columns = data.columns;\n    let rows = data.rows;\n\n    rows.forEach((d) => {\n      $.each(d, function (cellIndex) {\n        var column = columns[cellIndex];\n\n        var parseTime;\n\n        switch (column.type) {\n          case 'date':\n            parseTime = d3.timeParse('%Y-%m-%d');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'datetime':\n            parseTime = d3.timeParse('%Y-%m-%d %H:00:00');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'percent':\n            d[cellIndex] = d[cellIndex] / 100;\n            break;\n\n          case 'number':\n            d[cellIndex] = +d[cellIndex];\n            break;\n\n          default:\n          // do nothing\n        }\n      });\n    });\n\n    this.columns = columns;\n    this.rows = rows;\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Tip\n */\n\nCraft.charts.Tip = Garnish.Base.extend({\n  $container: null,\n  $tip: null,\n\n  init: function ($container) {\n    this.$container = $container;\n\n    this.$tip = $('<div class=\"tooltip\"></div>').appendTo(this.$container);\n\n    this.hide();\n  },\n\n  setContent: function (html) {\n    this.$tip.html(html);\n  },\n\n  setPosition: function (position) {\n    this.$tip.css('left', `${position.left}px`);\n    this.$tip.css('top', `${position.top}px`);\n  },\n\n  show: function () {\n    this.$tip.css('display', 'block');\n  },\n\n  hide: function () {\n    this.$tip.css('display', 'none');\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.BaseChart\n */\nCraft.charts.BaseChart = Garnish.Base.extend(\n  {\n    $container: null,\n    $chart: null,\n\n    chartBaseClass: 'cp-chart',\n    dataTable: null,\n\n    formatLocale: null,\n    timeFormatLocale: null,\n    orientation: null,\n\n    svg: null,\n    width: null,\n    height: null,\n\n    init: function (container, settings) {\n      this.$container = container;\n\n      this.setSettings(Craft.charts.BaseChart.defaults);\n      this.setSettings(settings);\n\n      var globalSettings = {\n        formats: window.d3Formats,\n        formatLocaleDefinition: window.d3FormatLocaleDefinition,\n        timeFormatLocaleDefinition: window.d3TimeFormatLocaleDefinition,\n      };\n\n      this.setSettings(globalSettings);\n\n      d3.select(window).on('resize', () => {\n        this.resize();\n      });\n    },\n\n    setSettings: function (settings, defaults) {\n      var baseSettings =\n        typeof this.settings === 'undefined' ? {} : this.settings;\n      this.settings = $.extend(true, {}, baseSettings, defaults, settings);\n    },\n\n    draw: function (dataTable, settings) {\n      // Settings and chart attributes\n\n      this.setSettings(settings);\n\n      this.dataTable = dataTable;\n      this.formatLocale = d3.formatLocale(this.settings.formatLocaleDefinition);\n      this.timeFormatLocale = d3.timeFormatLocale(\n        this.settings.timeFormatLocaleDefinition\n      );\n      this.orientation = this.settings.orientation;\n\n      // Set (or reset) the chart element\n\n      if (this.$chart) {\n        this.$chart.remove();\n      }\n\n      var className = this.chartBaseClass;\n\n      if (this.settings.chartClass) {\n        className += ' ' + this.settings.chartClass;\n      }\n\n      this.$chart = $(`<div class=\"${className}\" />`).appendTo(this.$container);\n    },\n\n    resize: function () {\n      this.draw(this.dataTable, this.settings);\n    },\n\n    onAfterDrawTicks: function () {\n      // White border for ticks' text\n      $('.tick', this.$chart).each(function (tickKey, tick) {\n        var $tickText = $('text', tick);\n\n        var $clone = $tickText.clone();\n        $clone.appendTo(tick);\n\n        $tickText.attr('stroke', '#ffffff');\n        $tickText.attr('stroke-width', 3);\n      });\n    },\n  },\n  {\n    defaults: {\n      formatLocaleDefinition: null,\n      timeFormatLocaleDefinition: null,\n      formats: {\n        numberFormat: ',.2f',\n        percentFormat: ',.2%',\n        currencyFormat: '$,.2f',\n        shortDateFormats: {\n          day: '%-m/%-d',\n          month: '%-m/%y',\n          year: '%Y',\n        },\n      },\n      margin: {top: 0, right: 0, bottom: 0, left: 0},\n      chartClass: null,\n      colors: ['#0594D1', '#DE3800', '#FF9A00', '#009802', '#9B009B'],\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Area\n */\nCraft.charts.Area = Craft.charts.BaseChart.extend(\n  {\n    tip: null,\n    drawingArea: null,\n\n    init: function (container, settings) {\n      this.base(container, Craft.charts.Area.defaults);\n\n      this.setSettings(settings);\n    },\n\n    draw: function (dataTable, settings) {\n      this.base(dataTable, settings);\n\n      if (this.tip) {\n        this.tip = null;\n      }\n\n      var margin = this.getChartMargin();\n\n      this.width = this.$chart.width() - margin.left - margin.right;\n      this.height = this.$chart.height() - margin.top - margin.bottom;\n\n      // Append SVG to chart element\n\n      var svg = {\n        width: this.width + (margin.left + margin.right),\n        height: this.height + (margin.top + margin.bottom),\n        translateX: this.orientation !== 'rtl' ? margin.left : margin.right,\n        translateY: margin.top,\n      };\n\n      this.svg = d3\n        .select(this.$chart.get(0))\n        .append('svg')\n        .attr('width', svg.width)\n        .attr('height', svg.height);\n\n      this.drawingArea = this.svg\n        .append('g')\n        .attr('transform', `translate(${svg.translateX},${svg.translateY})`);\n\n      // Draw elements\n\n      this.drawTicks();\n      this.drawAxes();\n      this.drawChart();\n      this.drawTipTriggers();\n    },\n\n    drawTicks: function () {\n      // Draw X ticks\n\n      var x = this.getX(true);\n      var xTicks = 3;\n      var xAxis = d3\n        .axisBottom(x)\n        .tickFormat(this.getXFormatter())\n        .ticks(xTicks);\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'x ticks-axis')\n        .attr('transform', `translate(0, ${this.height})`)\n        .call(xAxis);\n\n      // Draw Y ticks\n\n      var y = this.getY();\n      var yTicks = 2;\n      var yAxis;\n\n      if (this.orientation !== 'rtl') {\n        yAxis = d3\n          .axisLeft(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea.append('g').attr('class', 'y ticks-axis').call(yAxis);\n      } else {\n        yAxis = d3\n          .axisRight(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y ticks-axis')\n          .attr('transform', `translate(${this.width},0)`)\n          .call(yAxis);\n      }\n\n      // On after draw ticks\n\n      this.onAfterDrawTicks();\n    },\n\n    drawAxes: function () {\n      if (this.settings.xAxis.showAxis) {\n        var x = this.getX();\n        var xAxis = d3.axisBottom(x).ticks(0).tickSizeOuter(0);\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x axis')\n          .attr('transform', `translate(0, ${this.height})`)\n          .call(xAxis);\n      }\n\n      if (this.settings.yAxis.showAxis) {\n        var y = this.getY();\n        var chartPadding = 0;\n        var yAxis;\n\n        if (this.orientation === 'rtl') {\n          yAxis = d3.axisLeft(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${this.width - chartPadding}, 0)`)\n            .call(yAxis);\n        } else {\n          yAxis = d3.axisRight(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${chartPadding}, 0)`)\n            .call(yAxis);\n        }\n      }\n    },\n\n    drawChart: function () {\n      var x = this.getX(true);\n      var y = this.getY();\n\n      // X & Y grid lines\n\n      if (this.settings.xAxis.gridlines) {\n        var xLineAxis = d3.axisBottom(x);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x grid-line')\n          .attr('transform', `translate(0,${this.height})`)\n          .call(xLineAxis.tickSize(-this.height, 0, 0).tickFormat(''));\n      }\n\n      var yTicks = 2;\n\n      if (this.settings.yAxis.gridlines) {\n        var yLineAxis = d3.axisLeft(y);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y grid-line')\n          .attr('transform', 'translate(0 , 0)')\n          .call(\n            yLineAxis\n              .tickSize(-this.width, 0)\n              .tickFormat('')\n              .tickValues(this.getYTickValues())\n              .ticks(yTicks)\n          );\n      }\n\n      // Line\n\n      var line = d3\n        .line()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-line')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', 'none')\n        .style('stroke', this.settings.colors[0])\n        .style('stroke-width', '3px')\n        .attr('d', line);\n\n      // Area\n\n      var area = d3\n        .area()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y0(this.height)\n        .y1(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-area')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', this.settings.colors[0])\n        .style('fill-opacity', '0.3')\n        .attr('d', area);\n\n      // Plots\n\n      if (this.settings.plots) {\n        this.drawingArea\n          .append('g')\n          .attr('class', 'plots')\n          .selectAll('circle')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('circle')\n          .style('fill', this.settings.colors[0])\n          .attr('class', (d, index) => `plot plot-${index}`)\n          .attr('r', 4)\n          .attr('cx', (d) => x(d[0]))\n          .attr('cy', (d) => y(d[1]));\n      }\n    },\n\n    drawTipTriggers: function () {\n      if (this.settings.tips) {\n        if (!this.tip) {\n          this.tip = new Craft.charts.Tip(this.$chart);\n        }\n\n        // Define xAxisTickInterval\n\n        var chartMargin = this.getChartMargin();\n        var tickSizeOuter = 6;\n        var length =\n          this.drawingArea.select('.x path.domain').node().getTotalLength() -\n          chartMargin.left -\n          chartMargin.right -\n          tickSizeOuter * 2;\n        var xAxisTickInterval = length / (this.dataTable.rows.length - 1);\n\n        // Tip trigger width\n\n        var tipTriggerWidth = Math.max(0, xAxisTickInterval);\n\n        // Draw triggers\n\n        var x = this.getX(true);\n        var y = this.getY();\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'tip-triggers')\n          .selectAll('rect')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('rect')\n          .attr('class', 'tip-trigger')\n          .style('fill', 'transparent')\n          .style('fill-opacity', '1')\n          .attr('width', tipTriggerWidth)\n          .attr('height', this.height)\n          .attr('x', (d) => x(d[0]) - tipTriggerWidth / 2)\n          .on('mouseover', (d, index) => {\n            // Expand plot\n\n            this.drawingArea.select('.plot-' + index).attr('r', 5);\n\n            // Set tip content\n\n            var $content = $('<div />');\n            var $xValue = $('<div class=\"x-value\" />').appendTo($content);\n            var $yValue = $('<div class=\"y-value\" />').appendTo($content);\n\n            $xValue.html(this.getXFormatter()(d[0]));\n            $yValue.html(this.getYFormatter()(d[1]));\n\n            var content = $content.get(0);\n\n            this.tip.setContent(content);\n\n            // Set tip position\n\n            var margin = this.getChartMargin();\n\n            var offset = 24;\n            var top = y(d[1]) + offset;\n            var left;\n\n            if (this.orientation !== 'rtl') {\n              left = x(d[0]) + margin.left + offset;\n\n              var calcLeft =\n                this.$chart.offset().left + left + this.tip.$tip.width();\n              var maxLeft =\n                this.$chart.offset().left + this.$chart.width() - offset;\n\n              if (calcLeft > maxLeft) {\n                left = x(d[0]) - (this.tip.$tip.width() + offset);\n              }\n            } else {\n              left = x(d[0]) - (this.tip.$tip.width() + margin.left + offset);\n            }\n\n            if (left < 0) {\n              left = x(d[0]) + margin.left + offset;\n            }\n\n            var position = {\n              top: top,\n              left: left,\n            };\n\n            this.tip.setPosition(position);\n\n            // Show tip\n\n            this.tip.show();\n          })\n          .on('mouseout', (d, index) => {\n            // Unexpand Plot\n            this.drawingArea.select('.plot-' + index).attr('r', 4);\n\n            // Hide tip\n            this.tip.hide();\n          });\n      }\n    },\n\n    getChartMargin: function () {\n      var margin = this.settings.margin;\n\n      // Estimate the max width of y ticks and set it as the left margin\n\n      var values = this.getYTickValues();\n      var yTicksMaxWidth = 0;\n\n      $.each(values, (key, value) => {\n        var characterWidth = 8;\n\n        var formatter = this.getYFormatter();\n\n        var formattedValue = formatter(value);\n        var computedTickWidth = formattedValue.length * characterWidth;\n\n        if (computedTickWidth > yTicksMaxWidth) {\n          yTicksMaxWidth = computedTickWidth;\n        }\n      });\n\n      yTicksMaxWidth += 10;\n\n      margin.left = yTicksMaxWidth;\n\n      return margin;\n    },\n\n    getX: function (padded) {\n      var xDomainMin = d3.min(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomainMax = d3.max(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomain = [xDomainMin, xDomainMax];\n\n      if (this.orientation === 'rtl') {\n        xDomain = [xDomainMax, xDomainMin];\n      }\n\n      var left = 0;\n      var right = 0;\n\n      if (padded) {\n        left = 0;\n        right = 0;\n      }\n\n      var x = d3.scaleTime().range([left, this.width - right]);\n\n      x.domain(xDomain);\n\n      return x;\n    },\n\n    getY: function () {\n      var yDomain = [0, this.getYMaxValue()];\n\n      var y = d3.scaleLinear().range([this.height, 0]);\n\n      y.domain(yDomain);\n\n      return y;\n    },\n\n    getXFormatter: function () {\n      var formatter;\n\n      if (this.settings.xAxis.formatter !== $.noop) {\n        formatter = this.settings.xAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getTimeFormatter(\n          this.timeFormatLocale,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYFormatter: function () {\n      var formatter;\n\n      if (this.settings.yAxis.formatter !== $.noop) {\n        formatter = this.settings.yAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getNumberFormatter(\n          this.formatLocale,\n          this.dataTable.columns[1].type,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYMaxValue: function () {\n      return d3.max(this.dataTable.rows, function (d) {\n        return d[1];\n      });\n    },\n\n    getYTickValues: function () {\n      var maxValue = this.getYMaxValue();\n\n      if (maxValue > 1) {\n        return [maxValue / 2, maxValue];\n      } else {\n        return [0, maxValue];\n      }\n    },\n  },\n  {\n    defaults: {\n      chartClass: 'area',\n      margin: {top: 25, right: 5, bottom: 25, left: 0},\n      plots: true,\n      tips: true,\n      xAxis: {\n        gridlines: false,\n        showAxis: true,\n        formatter: $.noop,\n      },\n      yAxis: {\n        gridlines: true,\n        showAxis: false,\n        formatter: $.noop,\n      },\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Utils\n */\nCraft.charts.utils = {\n  getDuration: function (seconds) {\n    var secondsNum = parseInt(seconds, 10);\n\n    var duration = {\n      hours: Math.floor(secondsNum / 3600),\n      minutes: Math.floor((secondsNum - duration.hours * 3600) / 60),\n      seconds: secondsNum - duration.hours * 3600 - duration.minutes * 60,\n    };\n\n    if (duration.hours < 10) {\n      duration.hours = `0${duration.hours}`;\n    }\n\n    if (duration.minutes < 10) {\n      duration.minutes = `0${duration.minutes}`;\n    }\n\n    if (duration.seconds < 10) {\n      duration.seconds = `0${duration.seconds}`;\n    }\n\n    return `${duration.hours}:${duration.minutes}:${duration.seconds}`;\n  },\n\n  getTimeFormatter: function (timeFormatLocale, chartSettings) {\n    switch (chartSettings.dataScale) {\n      case 'year':\n        return timeFormatLocale.format('%Y');\n\n      case 'month':\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.month\n        );\n\n      case 'hour':\n        return timeFormatLocale.format(\n          `${chartSettings.formats.shortDateFormats.day} %H:00:00`\n        );\n\n      default:\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.day\n        );\n    }\n  },\n\n  getNumberFormatter: function (formatLocale, type, chartSettings) {\n    switch (type) {\n      case 'currency':\n        return formatLocale.format(chartSettings.formats.currencyFormat);\n\n      case 'percent':\n        return formatLocale.format(chartSettings.formats.percentFormat);\n\n      case 'time':\n        return Craft.charts.utils.getDuration;\n\n      case 'number':\n        return formatLocale.format(chartSettings.formats.numberFormat);\n    }\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Color input\n */\nCraft.ColorInput = Garnish.Base.extend(\n  {\n    $container: null,\n    $input: null,\n    $colorContainer: null,\n    $colorPreview: null,\n    $colorInput: null,\n\n    init: function (container) {\n      this.$container = $(container);\n      this.$input = this.$container.find('.color-input');\n      this.$colorContainer = this.$container.children('.color');\n      this.$colorPreview = this.$colorContainer.children('.color-preview');\n\n      this.createColorInput();\n      this.handleTextChange();\n\n      this.addListener(this.$input, 'input', 'handleTextChange');\n    },\n\n    createColorInput: function () {\n      var input = document.createElement('input');\n      input.setAttribute('type', 'color');\n\n      if (input.type !== 'color') {\n        // The browser doesn't support input[type=color]\n        return;\n      }\n\n      this.$colorContainer.removeClass('static');\n      this.$colorInput = $(input)\n        .addClass('color-preview-input')\n        .attr({\n          'aria-controls': this.$input.attr('id'),\n          'aria-label': Craft.t('app', 'Color picker'),\n        })\n        .appendTo(this.$colorPreview);\n\n      this.addListener(this.$colorInput, 'click', function (ev) {\n        ev.stopPropagation();\n      });\n\n      this.addListener(this.$colorContainer, 'click', function () {\n        this.$colorInput.trigger('click');\n      });\n\n      this.addListener(this.$colorInput, 'input', 'updateColor');\n    },\n\n    updateColor: function () {\n      this.$input.val(this.$colorInput.val());\n      this.handleTextChange();\n    },\n\n    handleTextChange: function () {\n      let val = this.$input.val();\n\n      if (val !== (val = Craft.trim(val))) {\n        this.$input.val(val);\n      }\n\n      // Chop off the #\n      if (val.length && val[0] === '#') {\n        val = val.substr(1);\n        this.$input.val(val);\n      }\n\n      // If empty, set the preview to transparent\n      if (!val.length) {\n        this.$colorPreview.css('background-color', '');\n        return;\n      }\n\n      // Now normalize it for the UI stuff\n      if (val.length === 3) {\n        val = val[0].repeat(2) + val[1].repeat(2) + val[2].repeat(2);\n      }\n\n      if (val.match(/^[0-9a-f]{6}$/i)) {\n        this.$colorPreview.css('background-color', `#${val}`);\n        if (this.$colorInput) {\n          this.$colorInput.val(`#${val}`);\n        }\n      } else {\n        this.$colorPreview.css('background-color', '');\n      }\n    },\n  },\n  {\n    _browserSupportsColorInputs: null,\n\n    doesBrowserSupportColorInputs: function () {\n      if (Craft.ColorInput._browserSupportsColorInputs === null) {\n      }\n\n      return Craft.ColorInput._browserSupportsColorInputs;\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n// Use old jQuery prefilter behavior\n// see https://jquery.com/upgrade-guide/3.5/\nvar rxhtmlTag =\n  /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\\/\\0>\\x20\\t\\r\\n\\f]*)[^>]*)\\/>/gi;\njQuery.htmlPrefilter = function (html) {\n  return html.replace(rxhtmlTag, '<$1></$2>');\n};\n\n// Set all the standard Craft.* stuff\n$.extend(Craft, {\n  navHeight: 48,\n\n  /**\n   * @callback indexKeyCallback\n   * @param {object} currentValue\n   * @param {number} [index]\n   * @return {string}\n   */\n  /**\n   * Indexes an array of objects by a specified key\n   *\n   * @param {object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  index: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.index() must be an array.';\n    }\n\n    return arr.reduce((index, obj, i) => {\n      index[typeof key === 'string' ? obj[key] : key(obj, i)] = obj;\n      return index;\n    }, {});\n  },\n\n  /**\n   * @callback indexKeyCallback\n   * @param {object} currentValue\n   * @param {number} [index]\n   * @return {string}\n   */\n  /**\n   * Groups an array of objects by a specified key\n   *\n   * @param {object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  group: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.group() must be an array.';\n    }\n\n    let index = {};\n\n    return arr.reduce((grouped, obj, i) => {\n      const thisKey = typeof key === 'string' ? obj[key] : key(obj, i);\n      if (!index.hasOwnProperty(thisKey)) {\n        index[thisKey] = [[], thisKey];\n        grouped.push(index[thisKey]);\n      }\n      index[thisKey][0].push(obj);\n      return grouped;\n    }, []);\n  },\n\n  /**\n   * Get a translated message.\n   *\n   * @param {string} category\n   * @param {string} message\n   * @param {object} params\n   * @return string\n   */\n  t: function (category, message, params) {\n    if (\n      typeof Craft.translations[category] !== 'undefined' &&\n      typeof Craft.translations[category][message] !== 'undefined'\n    ) {\n      message = Craft.translations[category][message];\n    }\n\n    if (params) {\n      return this.formatMessage(message, params);\n    }\n\n    return message;\n  },\n\n  formatMessage: function (pattern, args) {\n    let tokens;\n    if ((tokens = this._tokenizePattern(pattern)) === false) {\n      throw 'Message pattern is invalid.';\n    }\n    for (let i = 0; i < tokens.length; i++) {\n      let token = tokens[i];\n      if (typeof token === 'object') {\n        if ((tokens[i] = this._parseToken(token, args)) === false) {\n          throw 'Message pattern is invalid.';\n        }\n      }\n    }\n    return tokens.join('');\n  },\n\n  _tokenizePattern: function (pattern) {\n    let depth = 1,\n      start,\n      pos;\n    // Get an array of the string characters (factoring in 3+ byte chars)\n    const chars = [...pattern];\n    if ((start = pos = chars.indexOf('{')) === -1) {\n      return [pattern];\n    }\n    let tokens = [chars.slice(0, pos).join('')];\n    while (true) {\n      let open = chars.indexOf('{', pos + 1);\n      let close = chars.indexOf('}', pos + 1);\n      if (open === -1) {\n        open = false;\n      }\n      if (close === -1) {\n        close = false;\n      }\n      if (open === false && close === false) {\n        break;\n      }\n      if (open === false) {\n        open = chars.length;\n      }\n      if (close > open) {\n        depth++;\n        pos = open;\n      } else {\n        depth--;\n        pos = close;\n      }\n      if (depth === 0) {\n        tokens.push(\n          chars\n            .slice(start + 1, pos)\n            .join('')\n            .split(',', 3)\n        );\n        start = pos + 1;\n        tokens.push(chars.slice(start, open).join(''));\n        start = open;\n      }\n\n      if (depth !== 0 && (open === false || close === false)) {\n        break;\n      }\n    }\n    if (depth !== 0) {\n      return false;\n    }\n\n    return tokens;\n  },\n\n  _parseToken: function (token, args) {\n    // parsing pattern based on ICU grammar:\n    // http://icu-project.org/apiref/icu4c/classMessageFormat.html#details\n    const param = Craft.trim(token[0]);\n    if (typeof args[param] === 'undefined') {\n      return `{${token.join(',')}}`;\n    }\n    const arg = args[param];\n    const type =\n      typeof token[1] !== 'undefined' ? Craft.trim(token[1]) : 'none';\n    switch (type) {\n      case 'number':\n        return (() => {\n          let format =\n            typeof token[2] !== 'undefined' ? Craft.trim(token[2]) : null;\n          if (format !== null && format !== 'integer') {\n            throw `Message format 'number' is only supported for integer values.`;\n          }\n          let number = Craft.formatNumber(arg);\n          let pos;\n          if (format === null && (pos = `${arg}`.indexOf('.')) !== -1) {\n            number += `.${arg.substr(pos + 1)}`;\n          }\n          return number;\n        })();\n      case 'none':\n        return arg;\n      case 'select':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html\n                        selectStyle = (selector '{' message '}')+\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let select = this._tokenizePattern(token[2]);\n          let c = select.length;\n          let message = false;\n          for (let i = 0; i + 1 < c; i++) {\n            if (Garnish.isArray(select[i]) || !Garnish.isArray(select[i + 1])) {\n              return false;\n            }\n            let selector = Craft.trim(select[i++]);\n            if (\n              (message === false && selector === 'other') ||\n              selector == arg\n            ) {\n              message = select[i].join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      case 'plural':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html\n                        pluralStyle = [offsetValue] (selector '{' message '}')+\n                        offsetValue = \"offset:\" number\n                        selector = explicitValue | keyword\n                        explicitValue = '=' number  // adjacent, no white space in between\n                        keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+\n                        message: see MessageFormat\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let plural = this._tokenizePattern(token[2]);\n          const c = plural.length;\n          let message = false;\n          let offset = 0;\n          for (let i = 0; i + 1 < c; i++) {\n            if (\n              typeof plural[i] === 'object' ||\n              typeof plural[i + 1] !== 'object'\n            ) {\n              return false;\n            }\n            let selector = Craft.trim(plural[i++]);\n            let selectorChars = [...selector];\n\n            if (i === 1 && selector.substring(0, 7) === 'offset:') {\n              let pos = [...selector.replace(/[\\n\\r\\t]/g, ' ')].indexOf(' ', 7);\n              if (pos === -1) {\n                throw 'Message pattern is invalid.';\n              }\n              offset = parseInt(\n                Craft.trim(selectorChars.slice(7, pos).join(''))\n              );\n              selector = Craft.trim(\n                selectorChars\n                  .slice(pos + 1, pos + 1 + selectorChars.length)\n                  .join('')\n              );\n            }\n            if (\n              (message === false && selector === 'other') ||\n              (selector[0] === '=' &&\n                parseInt(\n                  selectorChars.slice(1, 1 + selectorChars.length).join('')\n                ) === arg) ||\n              (selector === 'one' && arg - offset === 1)\n            ) {\n              message = (\n                typeof plural[i] === 'string' ? [plural[i]] : plural[i]\n              )\n                .map((p) => {\n                  return p.replace('#', arg - offset);\n                })\n                .join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      default:\n        throw `Message format '${type}' is not supported.`;\n    }\n  },\n\n  formatDate: function (date) {\n    if (typeof date !== 'object') {\n      date = new Date(date);\n    }\n\n    return $.datepicker.formatDate(Craft.datepickerOptions.dateFormat, date);\n  },\n\n  /**\n   * Formats a number.\n   *\n   * @param {string} number\n   * @return string D3 format\n   */\n  formatNumber: function (number, format) {\n    if (typeof format == 'undefined') {\n      format = ',.0f';\n    }\n\n    var formatter = d3.formatLocale(d3FormatLocaleDefinition).format(format);\n\n    return formatter(number);\n  },\n\n  /**\n   * @param {string} key\n   * @param {boolean} shift\n   * @param {boolean} alt\n   */\n  shortcutText: function (key, shift, alt) {\n    if (Craft.clientOs === 'Mac') {\n      return (alt ? '⌥' : '') + (shift ? '⇧' : '') + '⌘' + key;\n    }\n    return 'Ctrl+' + (alt ? 'Alt+' : '') + (shift ? 'Shift+' : '') + key;\n  },\n\n  /**\n   * Escapes some HTML.\n   *\n   * @param {string} str\n   * @return string\n   */\n  escapeHtml: function (str) {\n    return $('<div/>').text(str).html();\n  },\n\n  /**\n   * Escapes special regular expression characters.\n   *\n   * @param {string} str\n   * @return string\n   */\n  escapeRegex: function (str) {\n    // h/t https://stackoverflow.com/a/9310752\n    return str.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n  },\n\n  /**\n   * Returns the text in a string that might contain HTML tags.\n   *\n   * @param {string} str\n   * @return string\n   */\n  getText: function (str) {\n    return $('<div/>').html(str).text();\n  },\n\n  /**\n   * Encodes a URI copmonent. Mirrors PHP's rawurlencode().\n   *\n   * @param {string} str\n   * @return string\n   * @see http://stackoverflow.com/questions/1734250/what-is-the-equivalent-of-javascripts-encodeuricomponent-in-php\n   */\n  encodeUriComponent: function (str) {\n    str = encodeURIComponent(str);\n\n    var differences = {\n      '!': '%21',\n      '*': '%2A',\n      \"'\": '%27',\n      '(': '%28',\n      ')': '%29',\n    };\n\n    for (var chr in differences) {\n      var re = new RegExp('\\\\' + chr, 'g');\n      str = str.replace(re, differences[chr]);\n    }\n\n    return str;\n  },\n\n  /**\n   * Selects the full value of a given text input.\n   *\n   * @param input\n   */\n  selectFullValue: function (input) {\n    var $input = $(input);\n    var val = $input.val();\n\n    // Does the browser support setSelectionRange()?\n    if (typeof $input[0].setSelectionRange !== 'undefined') {\n      // Select the whole value\n      var length = val.length * 2;\n      $input[0].setSelectionRange(0, length);\n    } else {\n      // Refresh the value to get the cursor positioned at the end\n      $input.val(val);\n    }\n  },\n\n  /**\n   * Formats an ID out of an input name.\n   *\n   * @param {string} inputName\n   * @return string\n   */\n  formatInputId: function (inputName) {\n    return this.rtrim(inputName.replace(/[^\\w]+/g, '-'), '-');\n  },\n\n  /**\n   * @return string\n   * @param path\n   * @param params\n   * @param baseUrl\n   */\n  getUrl: function (path, params, baseUrl) {\n    if (typeof path !== 'string') {\n      path = '';\n    }\n\n    // Normalize the params\n    var anchor = '';\n\n    if ($.isPlainObject(params)) {\n      var aParams = [];\n\n      for (var name in params) {\n        if (!params.hasOwnProperty(name)) {\n          continue;\n        }\n\n        var value = params[name];\n\n        if (name === '#') {\n          anchor = value;\n        } else if (value !== null && value !== '') {\n          aParams.push(name + '=' + value);\n        }\n      }\n\n      params = aParams;\n    }\n\n    if (Garnish.isArray(params)) {\n      params = params.join('&');\n    } else {\n      params = Craft.trim(params, '&?');\n    }\n\n    // Was there already an anchor on the path?\n    var apos = path.indexOf('#');\n    if (apos !== -1) {\n      // Only keep it if the params didn't specify a new anchor\n      if (!anchor) {\n        anchor = path.substr(apos + 1);\n      }\n      path = path.substr(0, apos);\n    }\n\n    // Were there already any query string params in the path?\n    var qpos = path.indexOf('?');\n    if (qpos !== -1) {\n      params = path.substr(qpos + 1) + (params ? '&' + params : '');\n      path = path.substr(0, qpos);\n    }\n\n    // Return path if it appears to be an absolute URL.\n    if (path.search('://') !== -1 || path[0] === '/') {\n      return path + (params ? '?' + params : '') + (anchor ? '#' + anchor : '');\n    }\n\n    path = Craft.trim(path, '/');\n\n    // Put it all together\n    var url;\n\n    if (baseUrl) {\n      url = baseUrl;\n\n      if (path && Craft.pathParam) {\n        // Does baseUrl already contain a path?\n        var pathMatch = url.match(\n          new RegExp('[&?]' + Craft.escapeRegex(Craft.pathParam) + '=[^&]+')\n        );\n        if (pathMatch) {\n          url = url.replace(\n            pathMatch[0],\n            Craft.rtrim(pathMatch[0], '/') + '/' + path\n          );\n          path = '';\n        }\n      }\n    } else {\n      url = Craft.baseUrl;\n    }\n\n    // Does the base URL already have a query string?\n    qpos = url.indexOf('?');\n    if (qpos !== -1) {\n      params = url.substr(qpos + 1) + (params ? '&' + params : '');\n      url = url.substr(0, qpos);\n    }\n\n    if (!Craft.omitScriptNameInUrls && path) {\n      if (Craft.usePathInfo || !Craft.pathParam) {\n        // Make sure that the script name is in the URL\n        if (url.search(Craft.scriptName) === -1) {\n          url = Craft.rtrim(url, '/') + '/' + Craft.scriptName;\n        }\n      } else {\n        // Move the path into the query string params\n\n        // Is the path param already set?\n        if (\n          params &&\n          params.substr(0, Craft.pathParam.length + 1) === Craft.pathParam + '='\n        ) {\n          var basePath,\n            endPath = params.indexOf('&');\n\n          if (endPath !== -1) {\n            basePath = params.substring(2, endPath);\n            params = params.substr(endPath + 1);\n          } else {\n            basePath = params.substr(2);\n            params = null;\n          }\n\n          // Just in case\n          basePath = Craft.rtrim(basePath);\n\n          path = basePath + (path ? '/' + path : '');\n        }\n\n        // Now move the path into the params\n        params = Craft.pathParam + '=' + path + (params ? '&' + params : '');\n        path = null;\n      }\n    }\n\n    if (path) {\n      url = Craft.rtrim(url, '/') + '/' + path;\n    }\n\n    if (params) {\n      url += '?' + params;\n    }\n\n    if (anchor) {\n      url += '#' + anchor;\n    }\n\n    return url;\n  },\n\n  /**\n   * @return string\n   * @param path\n   * @param params\n   */\n  getCpUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseCpUrl);\n  },\n\n  /**\n   * @return string\n   * @param path\n   * @param params\n   */\n  getSiteUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseSiteUrl);\n  },\n\n  /**\n   * Returns an action URL.\n   *\n   * @param {string} path\n   * @param {object|string|undefined} params\n   * @return string\n   */\n  getActionUrl: function (path, params) {\n    return Craft.getUrl(path, params, Craft.actionUrl);\n  },\n\n  /**\n   * Redirects the window to a given URL.\n   *\n   * @param {string} url\n   */\n  redirectTo: function (url) {\n    document.location.href = this.getUrl(url);\n  },\n\n  /**\n   * Returns a hidden CSRF token input, if CSRF protection is enabled.\n   *\n   * @return string\n   */\n  getCsrfInput: function () {\n    if (Craft.csrfTokenName) {\n      return (\n        '<input type=\"hidden\" name=\"' +\n        Craft.csrfTokenName +\n        '\" value=\"' +\n        Craft.csrfTokenValue +\n        '\"/>'\n      );\n    } else {\n      return '';\n    }\n  },\n\n  /**\n   * Posts an action request to the server.\n   *\n   * @param {string} action\n   * @param {object|undefined} data\n   * @param {function|undefined} callback\n   * @param {object|undefined} options\n   * @return jqXHR\n   * @deprecated in 3.4.6. sendActionRequest() should be used instead\n   */\n  postActionRequest: function (action, data, callback, options) {\n    // Make 'data' optional\n    if (typeof data === 'function') {\n      options = callback;\n      callback = data;\n      data = {};\n    }\n\n    options = options || {};\n\n    if (options.contentType && options.contentType.match(/\\bjson\\b/)) {\n      if (typeof data === 'object') {\n        data = JSON.stringify(data);\n      }\n      options.contentType = 'application/json; charset=utf-8';\n    }\n\n    var jqXHR = $.ajax(\n      $.extend(\n        {\n          url: Craft.getActionUrl(action),\n          type: 'POST',\n          dataType: 'json',\n          headers: this._actionHeaders(),\n          data: data,\n          success: callback,\n          error: function (jqXHR, textStatus, errorThrown) {\n            // Ignore incomplete requests, likely due to navigating away from the page\n            // h/t https://stackoverflow.com/a/22107079/1688568\n            if (jqXHR.readyState !== 4) {\n              return;\n            }\n\n            if (typeof Craft.cp !== 'undefined') {\n              Craft.cp.displayError();\n            } else {\n              alert(Craft.t('app', 'A server error occurred.'));\n            }\n\n            if (callback) {\n              callback(null, textStatus, jqXHR);\n            }\n          },\n        },\n        options\n      )\n    );\n\n    // Call the 'send' callback\n    if (typeof options.send === 'function') {\n      options.send(jqXHR);\n    }\n\n    return jqXHR;\n  },\n\n  _waitingOnAjax: false,\n  _ajaxQueue: [],\n\n  /**\n   * Queues up an action request to be posted to the server.\n   */\n  queueActionRequest: function (action, data, callback, options) {\n    // Make 'data' optional\n    if (typeof data === 'function') {\n      options = callback;\n      callback = data;\n      data = undefined;\n    }\n\n    Craft._ajaxQueue.push([action, data, callback, options]);\n\n    if (!Craft._waitingOnAjax) {\n      Craft._postNextActionRequestInQueue();\n    }\n  },\n\n  _postNextActionRequestInQueue: function () {\n    Craft._waitingOnAjax = true;\n\n    var args = Craft._ajaxQueue.shift();\n\n    Craft.postActionRequest(\n      args[0],\n      args[1],\n      function (data, textStatus, jqXHR) {\n        if (args[2] && typeof args[2] === 'function') {\n          args[2](data, textStatus, jqXHR);\n        }\n\n        if (Craft._ajaxQueue.length) {\n          Craft._postNextActionRequestInQueue();\n        } else {\n          Craft._waitingOnAjax = false;\n        }\n      },\n      args[3]\n    );\n  },\n\n  _actionHeaders: function () {\n    let headers = {\n      'X-Registered-Asset-Bundles': Object.keys(\n        Craft.registeredAssetBundles\n      ).join(','),\n      'X-Registered-Js-Files': Object.keys(Craft.registeredJsFiles).join(','),\n    };\n\n    if (Craft.csrfTokenValue) {\n      headers['X-CSRF-Token'] = Craft.csrfTokenValue;\n    }\n\n    return headers;\n  },\n\n  /**\n   * Sends a request to a Craft/plugin action\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {string} action The action to request\n   * @param {Object} options Axios request options\n   * @returns {Promise}\n   * @since 3.4.6\n   */\n  sendActionRequest: function (method, action, options) {\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      options.method = method;\n      options.url = Craft.getActionUrl(action);\n      options.headers = $.extend(\n        {\n          'X-Requested-With': 'XMLHttpRequest',\n        },\n        options.headers || {},\n        this._actionHeaders()\n      );\n      options.params = $.extend({}, options.params || {}, {\n        // Force Safari to not load from cache\n        v: new Date().getTime(),\n      });\n      axios.request(options).then(resolve).catch(reject);\n    });\n  },\n\n  /**\n   * Sends a request to the Craftnet API.\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {string} uri The API endpoint URI\n   * @param {Object} options Axios request options\n   * @returns {Promise}\n   * @since 3.3.16\n   */\n  sendApiRequest: function (method, uri, options) {\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      let cancelToken = options.cancelToken || null;\n\n      // Get the latest headers\n      this._getApiHeaders(cancelToken)\n        .then((apiHeaders) => {\n          // Send the API request\n          options.method = method;\n          options.baseURL = Craft.baseApiUrl;\n          options.url = uri;\n          options.headers = $.extend(apiHeaders, options.headers || {});\n          options.params = $.extend(\n            Craft.apiParams || {},\n            options.params || {},\n            {\n              // Force Safari to not load from cache\n              v: new Date().getTime(),\n            }\n          );\n\n          // Force the API to process the Craft headers if this is the first API request\n          if (!this._apiHeaders) {\n            options.params.processCraftHeaders = 1;\n          }\n\n          if (Craft.httpProxy) {\n            options.proxy = Craft.httpProxy;\n          }\n\n          axios\n            .request(options)\n            .then((apiResponse) => {\n              // Process the response headers\n              this._processApiHeaders(apiResponse.headers, cancelToken)\n                .then(() => {\n                  // Finally return the API response data\n                  resolve(apiResponse.data);\n                })\n                .catch(reject);\n            })\n            .catch(reject);\n        })\n        .catch(reject);\n    });\n  },\n\n  _loadingApiHeaders: false,\n  _apiHeaders: null,\n  _apiHeaderWaitlist: [],\n\n  /**\n   * Returns the headers that should be sent with API requests.\n   *\n   * @param {Object|null} cancelToken\n   * @return {Promise}\n   */\n  _getApiHeaders: function (cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Are we already loading them?\n      if (this._loadingApiHeaders) {\n        this._apiHeaderWaitlist.push([resolve, reject]);\n        return;\n      }\n\n      // Are the headers already cached?\n      if (this._apiHeaders) {\n        resolve(this._apiHeaders);\n        return;\n      }\n\n      this._loadingApiHeaders = true;\n      this.sendActionRequest('POST', 'app/api-headers', {\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          resolve(response.data);\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _processApiHeaders: function (headers, cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Have we already processed them?\n      if (this._apiHeaders) {\n        resolve();\n        return;\n      }\n\n      this.sendActionRequest('POST', 'app/process-api-response-headers', {\n        data: {\n          headers: headers,\n        },\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          this._apiHeaders = response.data;\n          this._loadingApiHeaders = false;\n\n          resolve();\n\n          // Was anything else waiting for them?\n          while (this._apiHeaderWaitlist.length) {\n            this._apiHeaderWaitlist.shift()[0](this._apiHeaders);\n          }\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _rejectApiRequests: function (reject, e) {\n    this._loadingApiHeaders = false;\n    reject(e);\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1](e);\n    }\n  },\n\n  /**\n   * Clears the cached API headers.\n   */\n  clearCachedApiHeaders: function () {\n    this._apiHeaders = null;\n    this._loadingApiHeaders = false;\n\n    // Reject anything in the header waitlist\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1]();\n    }\n  },\n\n  /**\n   * Requests a URL and downloads the response.\n   *\n   * @param {string} method the request method to use\n   * @param {string} url the URL\n   * @param {string|Object} [body] the request body, if method = POST\n   * @return {Promise}\n   */\n  downloadFromUrl: function (method, url, body) {\n    return new Promise((resolve, reject) => {\n      // h/t https://nehalist.io/downloading-files-from-post-requests/\n      let request = new XMLHttpRequest();\n      request.open(method, url, true);\n      if (typeof body === 'object') {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/json; charset=UTF-8'\n        );\n        body = JSON.stringify(body);\n      } else {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/x-www-form-urlencoded; charset=UTF-8'\n        );\n      }\n      request.responseType = 'blob';\n\n      request.onload = () => {\n        // Only handle status code 200\n        if (request.status === 200) {\n          // Try to find out the filename from the content disposition `filename` value\n          let disposition = request.getResponseHeader('content-disposition');\n          let matches = /\"([^\"]*)\"/.exec(disposition);\n          let filename =\n            matches != null && matches[1] ? matches[1] : 'Download';\n\n          // Encode the download into an anchor href\n          let contentType = request.getResponseHeader('content-type');\n          let blob = new Blob([request.response], {type: contentType});\n          let link = document.createElement('a');\n          link.href = window.URL.createObjectURL(blob);\n          link.download = filename;\n          document.body.appendChild(link);\n          link.click();\n          document.body.removeChild(link);\n\n          resolve();\n        } else {\n          reject();\n        }\n      };\n\n      request.send(body);\n    });\n  },\n\n  /**\n   * Converts a comma-delimited string into an array.\n   *\n   * @param {string} str\n   * @return array\n   */\n  stringToArray: function (str) {\n    if (typeof str !== 'string') {\n      return str;\n    }\n\n    var arr = str.split(',');\n    for (var i = 0; i < arr.length; i++) {\n      arr[i] = $.trim(arr[i]);\n    }\n    return arr;\n  },\n\n  /**\n   * Compares old and new post data, and removes any values that haven't\n   * changed within the given list of delta namespaces.\n   *\n   * @param {string} oldData\n   * @param {string} newData\n   * @param {object} deltaNames\n   * @param {function} [callback] Callback function that should be called whenever a new group of modified params has been found\n   * @param {object} [initialDeltaValues] Initial delta values. If undefined, `Craft.initialDeltaValues` will be used.\n   * @return {string}\n   */\n  findDeltaData: function (\n    oldData,\n    newData,\n    deltaNames,\n    callback,\n    initialDeltaValues\n  ) {\n    // Make sure oldData and newData are always strings. This is important because further below String.split is called.\n    oldData = typeof oldData === 'string' ? oldData : '';\n    newData = typeof newData === 'string' ? newData : '';\n\n    // Sort the delta namespaces from least -> most specific\n    deltaNames.sort(function (a, b) {\n      if (a.length === b.length) {\n        return 0;\n      }\n      return a.length > b.length ? 1 : -1;\n    });\n\n    // Group all of the old & new params by namespace\n    if (typeof initialDeltaValues === 'undefined') {\n      initialDeltaValues = Craft.initialDeltaValues;\n    }\n    var groupedOldParams = this._groupParamsByDeltaNames(\n      oldData.split('&'),\n      deltaNames,\n      false,\n      initialDeltaValues\n    );\n    var groupedNewParams = this._groupParamsByDeltaNames(\n      newData.split('&'),\n      deltaNames,\n      true,\n      false\n    );\n\n    // Figure out which of the new params should actually be posted\n    var params = groupedNewParams.__root__;\n    for (var n = 0; n < deltaNames.length; n++) {\n      if (\n        Craft.inArray(deltaNames[n], Craft.modifiedDeltaNames) ||\n        (typeof groupedNewParams[deltaNames[n]] === 'object' &&\n          (typeof groupedOldParams[deltaNames[n]] !== 'object' ||\n            JSON.stringify(groupedOldParams[deltaNames[n]]) !==\n              JSON.stringify(groupedNewParams[deltaNames[n]])))\n      ) {\n        params = params.concat(groupedNewParams[deltaNames[n]]);\n        params.push('modifiedDeltaNames[]=' + deltaNames[n]);\n        if (callback) {\n          callback(deltaNames[n], groupedNewParams[deltaNames[n]]);\n        }\n      }\n    }\n\n    return params.join('&');\n  },\n\n  /**\n   * @param {object} params\n   * @param {object} deltaNames\n   * @param {boolean} withRoot\n   * @param {boolean|object} initialValues\n   * @returns {{}}\n   * @private\n   */\n  _groupParamsByDeltaNames: function (\n    params,\n    deltaNames,\n    withRoot,\n    initialValues\n  ) {\n    const grouped = {};\n\n    if (withRoot) {\n      grouped.__root__ = [];\n    }\n\n    const encodeURIComponentExceptEqualChar = (o) =>\n      encodeURIComponent(o).replace('%3D', '=');\n\n    params = params.map((p) => decodeURIComponent(p));\n\n    paramLoop: for (let p = 0; p < params.length; p++) {\n      // loop through the delta names from most -> least specific\n      for (let n = deltaNames.length - 1; n >= 0; n--) {\n        const paramName = params[p].substr(0, deltaNames[n].length + 1);\n        if (\n          paramName === deltaNames[n] + '=' ||\n          paramName === deltaNames[n] + '['\n        ) {\n          if (typeof grouped[deltaNames[n]] === 'undefined') {\n            grouped[deltaNames[n]] = [];\n          }\n          grouped[deltaNames[n]].push(\n            encodeURIComponentExceptEqualChar(params[p])\n          );\n          continue paramLoop;\n        }\n      }\n\n      if (withRoot) {\n        grouped.__root__.push(encodeURIComponentExceptEqualChar(params[p]));\n      }\n    }\n\n    if (initialValues) {\n      const serializeParam = (name, value) => {\n        if ($.isArray(value) || $.isPlainObject(value)) {\n          value = $.param(value);\n        } else if (typeof value === 'string') {\n          value = encodeURIComponent(value);\n        } else if (value === null) {\n          value = '';\n        }\n        return `${encodeURIComponent(name)}=${value}`;\n      };\n\n      for (let name in initialValues) {\n        if (initialValues.hasOwnProperty(name)) {\n          if ($.isPlainObject(initialValues[name])) {\n            grouped[name] = [];\n            for (let subName in initialValues[name]) {\n              if (initialValues[name].hasOwnProperty(subName)) {\n                grouped[name].push(\n                  serializeParam(\n                    `${name}[${subName}]`,\n                    initialValues[name][subName]\n                  )\n                );\n              }\n            }\n          } else {\n            grouped[name] = [serializeParam(name, initialValues[name])];\n          }\n        }\n      }\n    }\n\n    return grouped;\n  },\n\n  /**\n   * Expands an array of POST array-style strings into an actual array.\n   *\n   * @param {object} arr\n   * @return array\n   */\n  expandPostArray: function (arr) {\n    var expanded = {};\n    var i;\n\n    for (var key in arr) {\n      if (!arr.hasOwnProperty(key)) {\n        continue;\n      }\n\n      var value = arr[key],\n        m = key.match(/^(\\w+)(\\[.*)?/),\n        keys;\n\n      if (m[2]) {\n        // Get all of the nested keys\n        keys = m[2].match(/\\[[^\\[\\]]*\\]/g);\n\n        // Chop off the brackets\n        for (i = 0; i < keys.length; i++) {\n          keys[i] = keys[i].substring(1, keys[i].length - 1);\n        }\n      } else {\n        keys = [];\n      }\n\n      keys.unshift(m[1]);\n\n      var parentElem = expanded;\n\n      for (i = 0; i < keys.length; i++) {\n        if (i < keys.length - 1) {\n          if (typeof parentElem[keys[i]] !== 'object') {\n            // Figure out what this will be by looking at the next key\n            if (!keys[i + 1] || parseInt(keys[i + 1]) == keys[i + 1]) {\n              parentElem[keys[i]] = [];\n            } else {\n              parentElem[keys[i]] = {};\n            }\n          }\n\n          parentElem = parentElem[keys[i]];\n        } else {\n          // Last one. Set the value\n          if (!keys[i]) {\n            keys[i] = parentElem.length;\n          }\n\n          parentElem[keys[i]] = value;\n        }\n      }\n    }\n\n    return expanded;\n  },\n\n  /**\n   * Creates a form element populated with hidden inputs based on a string of serialized form data.\n   *\n   * @param {string} data\n   * @returns {jQuery|HTMLElement}\n   */\n  createForm: function (data) {\n    var $form = $('<form/>', {\n      attr: {\n        method: 'post',\n        action: '',\n        'accept-charset': 'UTF-8',\n      },\n    });\n\n    if (typeof data === 'string') {\n      var values = data.split('&');\n      var chunks;\n      for (var i = 0; i < values.length; i++) {\n        chunks = values[i].split('=', 2);\n        $('<input/>', {\n          type: 'hidden',\n          name: decodeURIComponent(chunks[0]),\n          value: decodeURIComponent(chunks[1] || ''),\n        }).appendTo($form);\n      }\n    }\n\n    return $form;\n  },\n\n  /**\n   * Compares two variables and returns whether they are equal in value.\n   * Recursively compares array and object values.\n   *\n   * @param obj1\n   * @param obj2\n   * @param sortObjectKeys Whether object keys should be sorted before being compared. Default is true.\n   * @return boolean\n   */\n  compare: function (obj1, obj2, sortObjectKeys) {\n    // Compare the types\n    if (typeof obj1 !== typeof obj2) {\n      return false;\n    }\n\n    if (typeof obj1 === 'object') {\n      // Compare the lengths\n      if (obj1.length !== obj2.length) {\n        return false;\n      }\n\n      // Is one of them an array but the other is not?\n      if (obj1 instanceof Array !== obj2 instanceof Array) {\n        return false;\n      }\n\n      // If they're actual objects (not arrays), compare the keys\n      if (!(obj1 instanceof Array)) {\n        if (typeof sortObjectKeys === 'undefined' || sortObjectKeys === true) {\n          if (\n            !Craft.compare(\n              Craft.getObjectKeys(obj1).sort(),\n              Craft.getObjectKeys(obj2).sort()\n            )\n          ) {\n            return false;\n          }\n        } else {\n          if (\n            !Craft.compare(Craft.getObjectKeys(obj1), Craft.getObjectKeys(obj2))\n          ) {\n            return false;\n          }\n        }\n      }\n\n      // Compare each value\n      for (var i in obj1) {\n        if (!obj1.hasOwnProperty(i)) {\n          continue;\n        }\n\n        if (!Craft.compare(obj1[i], obj2[i])) {\n          return false;\n        }\n      }\n\n      // All clear\n      return true;\n    } else {\n      return obj1 === obj2;\n    }\n  },\n\n  /**\n   * Returns an array of an object's keys.\n   *\n   * @param {object} obj\n   * @return string\n   */\n  getObjectKeys: function (obj) {\n    var keys = [];\n\n    for (var key in obj) {\n      if (!obj.hasOwnProperty(key)) {\n        continue;\n      }\n\n      keys.push(key);\n    }\n\n    return keys;\n  },\n\n  /**\n   * Takes an array or string of chars, and places a backslash before each one, returning the combined string.\n   *\n   * Userd by ltrim() and rtrim()\n   *\n   * @param {string|object} chars\n   * @return string\n   */\n  escapeChars: function (chars) {\n    if (!Garnish.isArray(chars)) {\n      chars = chars.split();\n    }\n\n    var escaped = '';\n\n    for (var i = 0; i < chars.length; i++) {\n      escaped += '\\\\' + chars[i];\n    }\n\n    return escaped;\n  },\n\n  /**\n   * Trim characters off of the beginning of a string.\n   *\n   * @param {string} str\n   * @param {string|object|undefined} chars The characters to trim off. Defaults to a space if left blank.\n   * @return string\n   */\n  ltrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('^[' + Craft.escapeChars(chars) + ']+');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the end of a string.\n   *\n   * @param {string} str\n   * @param {string|object|undefined} chars The characters to trim off. Defaults to a space if left blank.\n   * @return string\n   */\n  rtrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('[' + Craft.escapeChars(chars) + ']+$');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the beginning and end of a string.\n   *\n   * @param {string} str\n   * @param {string|object|undefined} chars The characters to trim off. Defaults to a space if left blank.\n   * @return string\n   */\n  trim: function (str, chars) {\n    str = Craft.ltrim(str, chars);\n    str = Craft.rtrim(str, chars);\n    return str;\n  },\n\n  /**\n   * Returns whether a string starts with another string.\n   *\n   * @param {string} str\n   * @param {string} substr\n   * @return boolean\n   */\n  startsWith: function (str, substr) {\n    return str.substr(0, substr.length) === substr;\n  },\n\n  /**\n   * Filters an array.\n   *\n   * @param {object} arr\n   * @param {function} callback A user-defined callback function. If null, we'll just remove any elements that equate to false.\n   * @return array\n   */\n  filterArray: function (arr, callback) {\n    var filtered = [];\n\n    for (var i = 0; i < arr.length; i++) {\n      var include;\n\n      if (typeof callback === 'function') {\n        include = callback(arr[i], i);\n      } else {\n        include = arr[i];\n      }\n\n      if (include) {\n        filtered.push(arr[i]);\n      }\n    }\n\n    return filtered;\n  },\n\n  /**\n   * Returns whether an element is in an array (unlike jQuery.inArray(), which returns the element's index, or -1).\n   *\n   * @param elem\n   * @param arr\n   * @return boolean\n   */\n  inArray: function (elem, arr) {\n    if ($.isPlainObject(arr)) {\n      arr = Object.values(arr);\n    }\n    return arr.includes(elem);\n  },\n\n  /**\n   * Removes an element from an array.\n   *\n   * @param elem\n   * @param {object} arr\n   * @return boolean Whether the element could be found or not.\n   */\n  removeFromArray: function (elem, arr) {\n    var index = $.inArray(elem, arr);\n    if (index !== -1) {\n      arr.splice(index, 1);\n      return true;\n    } else {\n      return false;\n    }\n  },\n\n  /**\n   * Returns the last element in an array.\n   *\n   * @param {object} arr\n   * @return mixed\n   */\n  getLast: function (arr) {\n    if (!arr.length) {\n      return null;\n    } else {\n      return arr[arr.length - 1];\n    }\n  },\n\n  /**\n   * Makes the first character of a string uppercase.\n   *\n   * @param {string} str\n   * @return string\n   */\n  uppercaseFirst: function (str) {\n    return str.charAt(0).toUpperCase() + str.slice(1);\n  },\n\n  /**\n   * Makes the first character of a string lowercase.\n   *\n   * @param {string} str\n   * @return string\n   */\n  lowercaseFirst: function (str) {\n    return str.charAt(0).toLowerCase() + str.slice(1);\n  },\n\n  parseUrl: function (url) {\n    var m = url.match(\n      /^(?:(https?):\\/\\/|\\/\\/)([^\\/\\:]*)(?:\\:(\\d+))?(\\/[^\\?]*)?(?:\\?([^#]*))?(#.*)?/\n    );\n    if (!m) {\n      return {};\n    }\n    return {\n      scheme: m[1],\n      host: m[2] + (m[3] ? ':' + m[3] : ''),\n      hostname: m[2],\n      port: m[3] || null,\n      path: m[4] || '/',\n      query: m[5] || null,\n      hash: m[6] || null,\n    };\n  },\n\n  isSameHost: function (url) {\n    var requestUrlInfo = this.parseUrl(document.location.href);\n    if (!requestUrlInfo) {\n      return false;\n    }\n    var urlInfo = this.parseUrl(url);\n    if (!urlInfo) {\n      return false;\n    }\n    return requestUrlInfo.host === urlInfo.host;\n  },\n\n  /**\n   * Converts a number of seconds into a human-facing time duration.\n   */\n  secondsToHumanTimeDuration: function (seconds, showSeconds) {\n    if (typeof showSeconds === 'undefined') {\n      showSeconds = true;\n    }\n\n    var secondsInWeek = 604800,\n      secondsInDay = 86400,\n      secondsInHour = 3600,\n      secondsInMinute = 60;\n\n    var weeks = Math.floor(seconds / secondsInWeek);\n    seconds = seconds % secondsInWeek;\n\n    var days = Math.floor(seconds / secondsInDay);\n    seconds = seconds % secondsInDay;\n\n    var hours = Math.floor(seconds / secondsInHour);\n    seconds = seconds % secondsInHour;\n\n    var minutes;\n\n    if (showSeconds) {\n      minutes = Math.floor(seconds / secondsInMinute);\n      seconds = seconds % secondsInMinute;\n    } else {\n      minutes = Math.round(seconds / secondsInMinute);\n      seconds = 0;\n    }\n\n    var timeComponents = [];\n\n    if (weeks) {\n      timeComponents.push(\n        weeks +\n          ' ' +\n          (weeks === 1 ? Craft.t('app', 'week') : Craft.t('app', 'weeks'))\n      );\n    }\n\n    if (days) {\n      timeComponents.push(\n        days +\n          ' ' +\n          (days === 1 ? Craft.t('app', 'day') : Craft.t('app', 'days'))\n      );\n    }\n\n    if (hours) {\n      timeComponents.push(\n        hours +\n          ' ' +\n          (hours === 1 ? Craft.t('app', 'hour') : Craft.t('app', 'hours'))\n      );\n    }\n\n    if (minutes || (!showSeconds && !weeks && !days && !hours)) {\n      timeComponents.push(\n        minutes +\n          ' ' +\n          (minutes === 1 ? Craft.t('app', 'minute') : Craft.t('app', 'minutes'))\n      );\n    }\n\n    if (seconds || (showSeconds && !weeks && !days && !hours && !minutes)) {\n      timeComponents.push(\n        seconds +\n          ' ' +\n          (seconds === 1 ? Craft.t('app', 'second') : Craft.t('app', 'seconds'))\n      );\n    }\n\n    return timeComponents.join(', ');\n  },\n\n  /**\n   * Converts extended ASCII characters to ASCII.\n   *\n   * @param {string} str\n   * @param {object|undefined} charMap\n   * @return string\n   */\n  asciiString: function (str, charMap) {\n    // Normalize NFD chars to NFC\n    str = str.normalize('NFC');\n\n    var asciiStr = '';\n    var char;\n\n    for (var i = 0; i < str.length; i++) {\n      char = str.charAt(i);\n      asciiStr +=\n        typeof (charMap || Craft.asciiCharMap)[char] === 'string'\n          ? (charMap || Craft.asciiCharMap)[char]\n          : char;\n    }\n\n    return asciiStr;\n  },\n\n  randomString: function (length) {\n    // h/t https://stackoverflow.com/a/1349426/1688568\n    var result = '';\n    var characters =\n      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n    for (var i = 0; i < length; i++) {\n      result += characters.charAt(Math.floor(Math.random() * 62));\n    }\n    return result;\n  },\n\n  /**\n   * Creates a validation error list.\n   *\n   * @param {object} errors\n   * @return jQuery\n   */\n  createErrorList: function (errors) {\n    var $ul = $(document.createElement('ul')).addClass('errors');\n\n    for (var i = 0; i < errors.length; i++) {\n      var $li = $(document.createElement('li'));\n      $li.appendTo($ul);\n      $li.html(errors[i]);\n    }\n\n    return $ul;\n  },\n\n  appendHeadHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any link tags that are already included\n    var $existingCss = $('link[href]');\n\n    if ($existingCss.length) {\n      var existingCss = [];\n      var href;\n\n      for (var i = 0; i < $existingCss.length; i++) {\n        href = $existingCss.eq(i).attr('href').replace(/&/g, '&amp;');\n        existingCss.push(Craft.escapeRegex(href));\n      }\n\n      const regexp = new RegExp(\n        '<link\\\\s[^>]*href=\"(?:' + existingCss.join('|') + ')\".*?></link>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    $('head').append(html);\n  },\n\n  appendFootHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any script tags that are already included\n    var $existingJs = $('script[src]');\n\n    if ($existingJs.length) {\n      var existingJs = [];\n      var src;\n\n      for (var i = 0; i < $existingJs.length; i++) {\n        src = $existingJs.eq(i).attr('src').replace(/&/g, '&amp;');\n        existingJs.push(Craft.escapeRegex(src));\n      }\n\n      var regexp = new RegExp(\n        '<script\\\\s[^>]*src=\"(?:' + existingJs.join('|') + ')\".*?></script>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    Garnish.$bod.append(html);\n  },\n\n  /**\n   * Initializes any common UI elements in a given container.\n   *\n   * @param {object} $container\n   */\n  initUiElements: function ($container) {\n    $('.grid', $container).grid();\n    $('.info', $container).infoicon();\n    $('.checkbox-select', $container).checkboxselect();\n    $('.fieldtoggle', $container).fieldtoggle();\n    $('.lightswitch', $container).lightswitch();\n    $('.nicetext', $container).nicetext();\n    $('.formsubmit', $container).formsubmit();\n    $('.menubtn:not([data-disclosure-trigger])', $container).menubtn();\n    $('[data-disclosure-trigger]', $container).disclosureMenu();\n    $('.datetimewrapper', $container).datetime();\n    $(\n      '.datewrapper > input[type=\"date\"], .timewrapper > input[type=\"time\"]',\n      $container\n    ).datetimeinput();\n\n    // Open outbound links in new windows\n    // hat tip: https://stackoverflow.com/a/2911045/1688568\n    $('a', $container).each(function () {\n      if (\n        this.hostname.length &&\n        this.hostname !== location.hostname &&\n        typeof $(this).attr('target') === 'undefined'\n      ) {\n        $(this).attr('rel', 'noopener').attr('target', '_blank');\n      }\n    });\n  },\n\n  _elementIndexClasses: {},\n  _elementSelectorModalClasses: {},\n  _elementEditorClasses: {},\n\n  /**\n   * Registers an element index class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementIndexClass: function (elementType, func) {\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      throw (\n        'An element index class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementIndexClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element selector modal class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementSelectorModalClass: function (elementType, func) {\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      throw (\n        'An element selector modal class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementSelectorModalClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element editor class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementEditorClass: function (elementType, func) {\n    if (typeof this._elementEditorClasses[elementType] !== 'undefined') {\n      throw (\n        'An element editor class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementEditorClasses[elementType] = func;\n  },\n\n  /**\n   * Creates a new element index for a given element type.\n   *\n   * @param {string} elementType\n   * @param $container\n   * @param {object} settings\n   * @return BaseElementIndex\n   */\n  createElementIndex: function (elementType, $container, settings) {\n    var func;\n\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      func = this._elementIndexClasses[elementType];\n    } else {\n      func = Craft.BaseElementIndex;\n    }\n\n    return new func(elementType, $container, settings);\n  },\n\n  /**\n   * Creates a new element selector modal for a given element type.\n   *\n   * @param {string} elementType\n   * @param {object} settings\n   */\n  createElementSelectorModal: function (elementType, settings) {\n    var func;\n\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      func = this._elementSelectorModalClasses[elementType];\n    } else {\n      func = Craft.BaseElementSelectorModal;\n    }\n\n    return new func(elementType, settings);\n  },\n\n  /**\n   * Creates a new element editor HUD for a given element type.\n   *\n   * @param {string} elementType\n   * @param element $element\n   * @param {object} settings\n   */\n  createElementEditor: function (elementType, element, settings) {\n    // Param mapping\n    if (typeof settings === 'undefined' && $.isPlainObject(element)) {\n      // (settings)\n      settings = element;\n      element = null;\n    } else if (typeof settings !== 'object') {\n      settings = {};\n    }\n\n    if (!settings.elementType) {\n      settings.elementType = elementType;\n    }\n\n    var func;\n    if (typeof this._elementEditorClasses[elementType] !== 'undefined') {\n      func = this._elementEditorClasses[elementType];\n    } else {\n      func = Craft.BaseElementEditor;\n    }\n\n    return new func(element, settings);\n  },\n\n  /**\n   * Retrieves a value from localStorage if it exists.\n   *\n   * @param {string} key\n   * @param defaultValue\n   */\n  getLocalStorage: function (key, defaultValue) {\n    key = 'Craft-' + Craft.systemUid + '.' + key;\n\n    if (\n      typeof localStorage !== 'undefined' &&\n      typeof localStorage[key] !== 'undefined'\n    ) {\n      return JSON.parse(localStorage[key]);\n    } else {\n      return defaultValue;\n    }\n  },\n\n  /**\n   * Saves a value to localStorage.\n   *\n   * @param {string} key\n   * @param value\n   */\n  setLocalStorage: function (key, value) {\n    if (typeof localStorage !== 'undefined') {\n      key = 'Craft-' + Craft.systemUid + '.' + key;\n\n      // localStorage might be filled all the way up.\n      // Especially likely if this is a private window in Safari 8+, where localStorage technically exists,\n      // but has a max size of 0 bytes.\n      try {\n        localStorage[key] = JSON.stringify(value);\n      } catch (e) {}\n    }\n  },\n\n  /**\n   * Removes a value from localStorage.\n   * @param key\n   */\n  removeLocalStorage: function (key) {\n    if (typeof localStorage !== 'undefined') {\n      localStorage.removeItem(`Craft-${Craft.systemUid}.${key}`);\n    }\n  },\n\n  /**\n   * Returns a cookie value, if it exists, otherwise returns `false`\n   * @return {(string|boolean)}\n   */\n  getCookie: function (name) {\n    // Adapted from https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie\n    return document.cookie.replace(\n      new RegExp(\n        `(?:(?:^|.*;\\\\s*)Craft-${Craft.systemUid}:${name}\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$`\n      ),\n      '$1'\n    );\n  },\n\n  /**\n   * Sets a cookie value.\n   * @param {string} name\n   * @param {string} value\n   * @param {Object} [options]\n   * @param {string} [options.path] The cookie path.\n   * @param {string} [options.domain] The cookie domain. Defaults to the `defaultCookieDomain` config setting.\n   * @param {number} [options.maxAge] The max age of the cookie (in seconds)\n   * @param {Date} [options.expires] The expiry date of the cookie. Defaults to none (session-based cookie).\n   * @param {boolean} [options.secure] Whether this is a secure cookie. Defaults to the `useSecureCookies`\n   * config setting.\n   * @param {string} [options.sameSite] The SameSite value (`lax` or `strict`). Defaults to the\n   * `sameSiteCookieValue` config setting.\n   */\n  setCookie: function (name, value, options) {\n    options = $.extend({}, this.defaultCookieOptions, options);\n    let cookie = `Craft-${Craft.systemUid}:${name}=${encodeURIComponent(\n      value\n    )}`;\n    if (options.path) {\n      cookie += `;path=${options.path}`;\n    }\n    if (options.domain) {\n      cookie += `;domain=${options.domain}`;\n    }\n    if (options.maxAge) {\n      cookie += `;max-age-in-seconds=${options.maxAge}`;\n    } else if (options.expires) {\n      cookie += `;expires=${options.expires.toUTCString()}`;\n    }\n    if (options.secure) {\n      cookie += ';secure';\n    }\n    document.cookie = cookie;\n  },\n\n  /**\n   * Removes a cookie\n   * @param {string} name\n   */\n  removeCookie: function (name) {\n    this.setCookie(name, '', new Date('1970-01-01T00:00:00'));\n  },\n\n  /**\n   * Returns element information from it's HTML.\n   *\n   * @param element\n   * @returns object\n   */\n  getElementInfo: function (element) {\n    var $element = $(element);\n\n    if (!$element.hasClass('element')) {\n      $element = $element.find('.element:first');\n    }\n\n    return {\n      id: $element.data('id'),\n      siteId: $element.data('site-id'),\n      label: $element.data('label'),\n      status: $element.data('status'),\n      url: $element.data('url'),\n      hasThumb: $element.hasClass('hasthumb'),\n      $element: $element,\n    };\n  },\n\n  /**\n   * Changes an element to the requested size.\n   *\n   * @param element\n   * @param size\n   */\n  setElementSize: function (element, size) {\n    var $element = $(element);\n\n    if (size !== 'small' && size !== 'large') {\n      size = 'small';\n    }\n\n    if ($element.hasClass(size)) {\n      return;\n    }\n\n    var otherSize = size === 'small' ? 'large' : 'small';\n\n    $element.addClass(size).removeClass(otherSize);\n\n    if ($element.hasClass('hasthumb')) {\n      var $oldImg = $element.find('> .elementthumb > img'),\n        imgSize = size === 'small' ? '30' : '100',\n        $newImg = $('<img/>', {\n          sizes: imgSize + 'px',\n          srcset: $oldImg.attr('srcset') || $oldImg.attr('data-pfsrcset'),\n        });\n\n      $oldImg.replaceWith($newImg);\n\n      picturefill({\n        elements: [$newImg[0]],\n      });\n    }\n  },\n\n  /**\n   * Submits a form.\n   * @param {Object} $form\n   * @param {Object} [options]\n   * @param {string} [options.action] The `action` param value override\n   * @param {string} [options.redirect] The `redirect` param value override\n   * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n   * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n   * @param {Object} [options.data] Additional data to be passed to the submit event\n   * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n   */\n  submitForm: function ($form, options) {\n    if (typeof options === 'undefined') {\n      options = {};\n    }\n\n    if (options.confirm && !confirm(options.confirm)) {\n      return;\n    }\n\n    if (options.action) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'action',\n        val: options.action,\n      }).appendTo($form);\n    }\n\n    if (options.redirect) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'redirect',\n        val: options.redirect,\n      }).appendTo($form);\n    }\n\n    if (options.params) {\n      for (let name in options.params) {\n        let value = options.params[name];\n        $('<input/>', {\n          type: 'hidden',\n          name: name,\n          val: value,\n        }).appendTo($form);\n      }\n    }\n\n    if (options.retainScroll) {\n      this.setLocalStorage('scrollY', window.scrollY);\n    }\n\n    $form.trigger($.extend({type: 'submit'}, options.data));\n  },\n\n  /**\n   * Traps focus within a container, so when focus is tabbed out of it, it’s cycled back into it.\n   * @param {Object} container\n   */\n  trapFocusWithin: function (container) {\n    Garnish.trapFocusWithin(container);\n  },\n\n  /**\n   * Sets focus to the first focusable element within a container.\n   * @param {Object} container\n   */\n  setFocusWithin: function (container) {\n    Garnish.setFocusWithin(container);\n  },\n});\n\n// -------------------------------------------\n//  Custom jQuery plugins\n// -------------------------------------------\n\n$.extend($.fn, {\n  animateLeft: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({left: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({right: pos}, duration, easing, complete);\n    }\n  },\n\n  animateRight: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({right: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({left: pos}, duration, easing, complete);\n    }\n  },\n\n  /**\n   * Disables elements by adding a .disabled class and preventing them from receiving focus.\n   */\n  disable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.addClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.removeAttr('tabindex');\n      }\n    });\n  },\n\n  /**\n   * Enables elements by removing their .disabled class and allowing them to receive focus.\n   */\n  enable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.removeClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.attr('tabindex', '0');\n      }\n    });\n  },\n\n  /**\n   * Sets the element as the container of a grid.\n   */\n  grid: function () {\n    return this.each(function () {\n      var $container = $(this),\n        settings = {};\n\n      if ($container.data('item-selector')) {\n        settings.itemSelector = $container.data('item-selector');\n      }\n      if ($container.data('cols')) {\n        settings.cols = parseInt($container.data('cols'));\n      }\n      if ($container.data('max-cols')) {\n        settings.maxCols = parseInt($container.data('max-cols'));\n      }\n      if ($container.data('min-col-width')) {\n        settings.minColWidth = parseInt($container.data('min-col-width'));\n      }\n      if ($container.data('mode')) {\n        settings.mode = $container.data('mode');\n      }\n      if ($container.data('fill-mode')) {\n        settings.fillMode = $container.data('fill-mode');\n      }\n      if ($container.data('col-class')) {\n        settings.colClass = $container.data('col-class');\n      }\n      if ($container.data('snap-to-grid')) {\n        settings.snapToGrid = !!$container.data('snap-to-grid');\n      }\n\n      new Craft.Grid(this, settings);\n    });\n  },\n\n  infoicon: function () {\n    return this.each(function () {\n      new Craft.InfoIcon(this);\n    });\n  },\n\n  /**\n   * Sets the element as a container for a checkbox select.\n   */\n  checkboxselect: function () {\n    return this.each(function () {\n      if (!$.data(this, 'checkboxselect')) {\n        new Garnish.CheckboxSelect(this);\n      }\n    });\n  },\n\n  /**\n   * Sets the element as a field toggle trigger.\n   */\n  fieldtoggle: function () {\n    return this.each(function () {\n      if (!$.data(this, 'fieldtoggle')) {\n        new Craft.FieldToggle(this);\n      }\n    });\n  },\n\n  lightswitch: function (settings, settingName, settingValue) {\n    // param mapping\n    if (settings === 'settings') {\n      if (typeof settingName === 'string') {\n        settings = {};\n        settings[settingName] = settingValue;\n      } else {\n        settings = settingName;\n      }\n\n      return this.each(function () {\n        var obj = $.data(this, 'lightswitch');\n        if (obj) {\n          obj.setSettings(settings);\n        }\n      });\n    } else {\n      if (!$.isPlainObject(settings)) {\n        settings = {};\n      }\n\n      return this.each(function () {\n        var thisSettings = $.extend({}, settings);\n\n        if (Garnish.hasAttr(this, 'data-value')) {\n          thisSettings.value = $(this).attr('data-value');\n        }\n\n        if (Garnish.hasAttr(this, 'data-indeterminate-value')) {\n          thisSettings.indeterminateValue = $(this).attr(\n            'data-indeterminate-value'\n          );\n        }\n\n        if (!$.data(this, 'lightswitch')) {\n          new Craft.LightSwitch(this, thisSettings);\n        }\n      });\n    }\n  },\n\n  nicetext: function () {\n    return this.each(function () {\n      if (!$.data(this, 'nicetext')) {\n        new Garnish.NiceText(this);\n      }\n    });\n  },\n\n  formsubmit: function () {\n    // Secondary form submit buttons\n    return this.on('click', function (ev) {\n      let $btn = $(ev.currentTarget);\n      let params = $btn.data('params') || {};\n      if ($btn.data('param')) {\n        params[$btn.data('param')] = $btn.data('value');\n      }\n\n      let $anchor = $btn.data('menu') ? $btn.data('menu').$anchor : $btn;\n      let $form = $anchor.attr('data-form')\n        ? $('#' + $anchor.attr('data-form'))\n        : $anchor.closest('form');\n\n      Craft.submitForm($form, {\n        confirm: $btn.data('confirm'),\n        action: $btn.data('action'),\n        redirect: $btn.data('redirect'),\n        params: params,\n        data: $.extend(\n          {\n            customTrigger: $btn,\n          },\n          $btn.data('event-data')\n        ),\n      });\n    });\n  },\n\n  menubtn: function () {\n    return this.each(function () {\n      var $btn = $(this);\n\n      if (!$btn.data('menubtn') && $btn.next().hasClass('menu')) {\n        var settings = {};\n\n        if ($btn.data('menu-anchor')) {\n          settings.menuAnchor = $btn.data('menu-anchor');\n        }\n\n        new Garnish.MenuBtn($btn, settings);\n      }\n    });\n  },\n\n  disclosureMenu: function () {\n    return this.each(function () {\n      const $trigger = $(this);\n      // Only instantiate if it's not already a disclosure trigger, and it references a disclosure content\n      if (!$trigger.data('trigger') && $trigger.attr('aria-controls')) {\n        new Garnish.DisclosureMenu($trigger);\n      }\n    });\n  },\n\n  datetime: function () {\n    return this.each(function () {\n      let $wrapper = $(this);\n      let $inputs = $wrapper.find('input:not([name$=\"[timezone]\"])');\n      let checkValue = () => {\n        let hasValue = false;\n        for (let i = 0; i < $inputs.length; i++) {\n          if ($inputs.eq(i).val()) {\n            hasValue = true;\n            break;\n          }\n        }\n        if (hasValue) {\n          if (!$wrapper.children('.clear-btn').length) {\n            let $btn = $('<button/>', {\n              type: 'button',\n              class: 'clear-btn',\n              title: Craft.t('app', 'Clear'),\n              'aria-label': Craft.t('app', 'Clear'),\n            })\n              .appendTo($wrapper)\n              .on('click', () => {\n                for (let i = 0; i < $inputs.length; i++) {\n                  $inputs.eq(i).val('').trigger('input').trigger('change');\n                }\n                $btn.remove();\n                $inputs.first().filter('[type=\"text\"]').focus();\n              });\n          }\n        } else {\n          $wrapper.children('.clear-btn').remove();\n        }\n      };\n      $inputs.on('change', checkValue);\n      checkValue();\n    });\n  },\n\n  datetimeinput: function () {\n    return this.each(function () {\n      const $input = $(this);\n      const checkValue = () => {\n        if ($input.val() === '') {\n          $input.addClass('empty-value');\n        } else {\n          $input.removeClass('empty-value');\n        }\n      };\n      $input.on('input', checkValue);\n      checkValue();\n    });\n  },\n});\n\n// Override Garnish.NiceText.charsLeftHtml() to be more accessible\nGarnish.NiceText.charsLeftHtml = (charsLeft) => {\n  return Craft.t(\n    'app',\n    '<span class=\"visually-hidden\">Characters left:</span> {chars, number}',\n    {\n      chars: charsLeft,\n    }\n  );\n};\n\nGarnish.$doc.ready(function () {\n  Craft.initUiElements();\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Customize Sources modal\n */\nCraft.CustomizeSourcesModal = Garnish.Modal.extend({\n  elementIndex: null,\n  $elementIndexSourcesContainer: null,\n\n  $sidebar: null,\n  $sourcesContainer: null,\n  $sourceSettingsContainer: null,\n  $newHeadingBtn: null,\n  $footer: null,\n  $footerBtnContainer: null,\n  $saveBtn: null,\n  $cancelBtn: null,\n  $saveSpinner: null,\n  $loadingSpinner: null,\n\n  sourceSort: null,\n  sources: null,\n  selectedSource: null,\n  updateSourcesOnSave: false,\n\n  availableTableAttributes: null,\n\n  init: function (elementIndex, settings) {\n    this.base();\n\n    this.setSettings(settings, {\n      resizable: true,\n    });\n\n    this.elementIndex = elementIndex;\n    this.$elementIndexSourcesContainer = this.elementIndex.$sidebar\n      .children('nav')\n      .children('ul');\n\n    var $container = $(\n      '<form class=\"modal customize-sources-modal\"/>'\n    ).appendTo(Garnish.$bod);\n\n    this.$sidebar = $('<div class=\"cs-sidebar block-types\"/>').appendTo(\n      $container\n    );\n    this.$sourcesContainer = $('<div class=\"sources\">').appendTo(this.$sidebar);\n    this.$sourceSettingsContainer = $('<div class=\"source-settings\">').appendTo(\n      $container\n    );\n\n    this.$footer = $('<div class=\"footer\"/>').appendTo($container);\n    this.$footerBtnContainer = $('<div class=\"buttons right\"/>').appendTo(\n      this.$footer\n    );\n    this.$cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$footerBtnContainer);\n    this.$saveBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn submit disabled',\n      text: Craft.t('app', 'Save'),\n    }).appendTo(this.$footerBtnContainer);\n    this.$saveSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n      this.$footerBtnContainer\n    );\n    this.$newHeadingBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn submit add icon',\n      text: Craft.t('app', 'New heading'),\n    }).appendTo(\n      $('<div class=\"buttons left secondary-buttons\"/>').appendTo(this.$footer)\n    );\n\n    this.$loadingSpinner = $('<div class=\"spinner\"/>').appendTo($container);\n\n    this.setContainer($container);\n    this.show();\n\n    var data = {\n      elementType: this.elementIndex.elementType,\n    };\n\n    Craft.postActionRequest(\n      'element-index-settings/get-customize-sources-modal-data',\n      data,\n      (response, textStatus) => {\n        this.$loadingSpinner.remove();\n\n        if (textStatus === 'success') {\n          this.$saveBtn.removeClass('disabled');\n          this.buildModal(response);\n        }\n      }\n    );\n\n    this.addListener(this.$newHeadingBtn, 'click', 'handleNewHeadingBtnClick');\n    this.addListener(this.$cancelBtn, 'click', 'hide');\n    this.addListener(this.$saveBtn, 'click', 'save');\n    this.addListener(this.$container, 'submit', 'save');\n  },\n\n  buildModal: function (response) {\n    // Store the available table attribute options\n    this.availableTableAttributes = response.availableTableAttributes;\n\n    // Create the source item sorter\n    this.sourceSort = new Garnish.DragSort({\n      handle: '.move',\n      axis: 'y',\n      onSortChange: () => {\n        this.updateSourcesOnSave = true;\n      },\n    });\n\n    // Create the sources\n    this.sources = [];\n\n    for (var i = 0; i < response.sources.length; i++) {\n      var source = this.addSource(response.sources[i]);\n      this.sources.push(source);\n    }\n\n    if (!this.selectedSource && typeof this.sources[0] !== 'undefined') {\n      this.sources[0].select();\n    }\n  },\n\n  addSource: function (sourceData) {\n    var $item = $('<div class=\"customize-sources-item\"/>').appendTo(\n      this.$sourcesContainer\n    );\n    var $itemLabel = $('<div class=\"label\"/>').appendTo($item);\n    var $itemInput = $('<input type=\"hidden\"/>').appendTo($item);\n    $(\n      '<a class=\"move icon\" title=\"' +\n        Craft.t('app', 'Reorder') +\n        '\" role=\"button\"></a>'\n    ).appendTo($item);\n\n    var source;\n\n    // Is this a heading?\n    if (typeof sourceData.heading !== 'undefined') {\n      $item.addClass('heading');\n      $itemInput.attr('name', 'sourceOrder[][heading]');\n      source = new Craft.CustomizeSourcesModal.Heading(\n        this,\n        $item,\n        $itemLabel,\n        $itemInput,\n        sourceData\n      );\n      source.updateItemLabel(sourceData.heading);\n    } else {\n      $itemInput.attr('name', 'sourceOrder[][key]').val(sourceData.key);\n      source = new Craft.CustomizeSourcesModal.Source(\n        this,\n        $item,\n        $itemLabel,\n        $itemInput,\n        sourceData\n      );\n      source.updateItemLabel(sourceData.label);\n\n      // Select this by default?\n      if (\n        (this.elementIndex.sourceKey + '/').substr(\n          0,\n          sourceData.key.length + 1\n        ) ===\n        sourceData.key + '/'\n      ) {\n        source.select();\n      }\n    }\n\n    this.sourceSort.addItems($item);\n\n    return source;\n  },\n\n  handleNewHeadingBtnClick: function () {\n    var source = this.addSource({\n      heading: '',\n    });\n\n    Garnish.scrollContainerToElement(this.$sidebar, source.$item);\n\n    source.select();\n    this.updateSourcesOnSave = true;\n  },\n\n  save: function (ev) {\n    if (ev) {\n      ev.preventDefault();\n    }\n\n    if (\n      this.$saveBtn.hasClass('disabled') ||\n      !this.$saveSpinner.hasClass('hidden')\n    ) {\n      return;\n    }\n\n    this.$saveSpinner.removeClass('hidden');\n    var data =\n      this.$container.serialize() +\n      '&elementType=' +\n      this.elementIndex.elementType;\n\n    Craft.postActionRequest(\n      'element-index-settings/save-customize-sources-modal-settings',\n      data,\n      (response, textStatus) => {\n        this.$saveSpinner.addClass('hidden');\n\n        if (textStatus === 'success' && response.success) {\n          // Have any changes been made to the source list?\n          if (this.updateSourcesOnSave) {\n            if (this.$elementIndexSourcesContainer.length) {\n              var $lastSource = null,\n                $pendingHeading;\n\n              for (var i = 0; i < this.sourceSort.$items.length; i++) {\n                var $item = this.sourceSort.$items.eq(i),\n                  source = $item.data('source'),\n                  $indexSource = source.getIndexSource();\n\n                if (!$indexSource) {\n                  continue;\n                }\n\n                if (source.isHeading()) {\n                  $pendingHeading = $indexSource;\n                } else {\n                  if ($pendingHeading) {\n                    this.appendSource($pendingHeading, $lastSource);\n                    $lastSource = $pendingHeading;\n                    $pendingHeading = null;\n                  }\n\n                  this.appendSource($indexSource, $lastSource);\n                  $lastSource = $indexSource;\n                }\n              }\n\n              // Remove any additional sources (most likely just old headings)\n              if ($lastSource) {\n                var $extraSources = $lastSource.nextAll();\n                this.elementIndex.sourceSelect.removeItems($extraSources);\n                $extraSources.remove();\n              }\n            }\n          }\n\n          // If a source is selected, have the element index select that one by default on the next request\n          if (this.selectedSource && this.selectedSource.sourceData.key) {\n            this.elementIndex.selectSourceByKey(\n              this.selectedSource.sourceData.key\n            );\n            this.elementIndex.updateElements();\n          }\n\n          Craft.cp.displayNotice(Craft.t('app', 'Source settings saved'));\n          this.hide();\n        } else {\n          var error =\n            textStatus === 'success' && response.error\n              ? response.error\n              : Craft.t('app', 'A server error occurred.');\n          Craft.cp.displayError(error);\n        }\n      }\n    );\n  },\n\n  appendSource: function ($source, $lastSource) {\n    if (!$lastSource) {\n      $source.prependTo(this.$elementIndexSourcesContainer);\n    } else {\n      $source.insertAfter($lastSource);\n    }\n  },\n\n  destroy: function () {\n    for (var i = 0; i < this.sources.length; i++) {\n      this.sources[i].destroy();\n    }\n\n    delete this.sources;\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.BaseSource = Garnish.Base.extend({\n  modal: null,\n\n  $item: null,\n  $itemLabel: null,\n  $itemInput: null,\n  $settingsContainer: null,\n\n  sourceData: null,\n\n  init: function (modal, $item, $itemLabel, $itemInput, sourceData) {\n    this.modal = modal;\n    this.$item = $item;\n    this.$itemLabel = $itemLabel;\n    this.$itemInput = $itemInput;\n    this.sourceData = sourceData;\n\n    this.$item.data('source', this);\n\n    this.addListener(this.$item, 'click', 'select');\n  },\n\n  isHeading: function () {\n    return false;\n  },\n\n  isSelected: function () {\n    return this.modal.selectedSource === this;\n  },\n\n  select: function () {\n    if (this.isSelected()) {\n      return;\n    }\n\n    if (this.modal.selectedSource) {\n      this.modal.selectedSource.deselect();\n    }\n\n    this.$item.addClass('sel');\n    this.modal.selectedSource = this;\n\n    if (!this.$settingsContainer) {\n      this.$settingsContainer = this.createSettings().appendTo(\n        this.modal.$sourceSettingsContainer\n      );\n    } else {\n      this.$settingsContainer.removeClass('hidden');\n    }\n\n    this.modal.$sourceSettingsContainer.scrollTop(0);\n  },\n\n  createSettings: function () {\n    return $('<div/>');\n  },\n\n  getIndexSource: function () {},\n\n  deselect: function () {\n    this.$item.removeClass('sel');\n    this.modal.selectedSource = null;\n    this.$settingsContainer.addClass('hidden');\n  },\n\n  updateItemLabel: function (val) {\n    this.$itemLabel.text(val);\n  },\n\n  destroy: function () {\n    this.$item.data('source', null);\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.Source =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    createSettings: function () {\n      let $settings = $('<div/>').append(\n        Craft.ui.createTextField({\n          label: Craft.t('app', 'Header Column Heading'),\n          id: 'defaultHeaderColHeading' + Math.floor(Math.random() * 100000),\n          name: `sources[${this.sourceData.key}][headerColHeading]`,\n          value: this.sourceData.headerColHeading,\n          placeholder: this.sourceData.defaultHeaderColHeading,\n        })\n      );\n\n      if (this.sourceData.tableAttributes.length) {\n        $settings.append(this.createTableColumnsField());\n      }\n\n      return $settings;\n    },\n\n    createTableColumnsField: function () {\n      // Create the title column option\n      let [firstKey, firstLabel] = this.sourceData.tableAttributes[0];\n      let $titleColumnCheckbox = this.createTableColumnOption(\n        firstKey,\n        firstLabel,\n        true,\n        true\n      );\n\n      // Create the rest of the options\n      let $columnCheckboxes = $('<div/>');\n      let selectedAttributes = [firstKey];\n\n      $(\n        '<input type=\"hidden\" name=\"sources[' +\n          this.sourceData.key +\n          '][tableAttributes][]\" value=\"\"/>'\n      ).appendTo($columnCheckboxes);\n\n      // Add the selected columns, in the selected order\n      for (let i = 1; i < this.sourceData.tableAttributes.length; i++) {\n        let [key, label] = this.sourceData.tableAttributes[i];\n        $columnCheckboxes.append(\n          this.createTableColumnOption(key, label, false, true)\n        );\n        selectedAttributes.push(key);\n      }\n\n      // Add the rest\n      let availableTableAttributes =\n        this.modal.availableTableAttributes.slice(0);\n      availableTableAttributes.push(\n        ...this.sourceData.availableTableAttributes\n      );\n\n      for (let i = 0; i < availableTableAttributes.length; i++) {\n        let [key, label] = availableTableAttributes[i];\n        if (!Craft.inArray(key, selectedAttributes)) {\n          $columnCheckboxes.append(\n            this.createTableColumnOption(key, label, false, false)\n          );\n        }\n      }\n\n      new Garnish.DragSort($columnCheckboxes.children(), {\n        handle: '.move',\n        axis: 'y',\n      });\n\n      return Craft.ui.createField(\n        $([$titleColumnCheckbox[0], $columnCheckboxes[0]]),\n        {\n          label: Craft.t('app', 'Table Columns'),\n          instructions: Craft.t(\n            'app',\n            'Choose which table columns should be visible for this source, and in which order.'\n          ),\n        }\n      );\n    },\n\n    createTableColumnOption: function (key, label, first, checked) {\n      var $option = $('<div class=\"customize-sources-table-column\"/>')\n        .append('<div class=\"icon move\"/>')\n        .append(\n          Craft.ui.createCheckbox({\n            label: Craft.escapeHtml(label),\n            name: 'sources[' + this.sourceData.key + '][tableAttributes][]',\n            value: key,\n            checked: checked,\n            disabled: first,\n          })\n        );\n\n      if (first) {\n        $option.children('.move').addClass('disabled');\n      }\n\n      return $option;\n    },\n\n    getIndexSource: function () {\n      var $source = this.modal.elementIndex.getSourceByKey(this.sourceData.key);\n\n      if ($source) {\n        return $source.closest('li');\n      }\n    },\n  });\n\nCraft.CustomizeSourcesModal.Heading =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    $labelField: null,\n    $labelInput: null,\n    $deleteBtn: null,\n\n    isHeading: function () {\n      return true;\n    },\n\n    select: function () {\n      this.base();\n      this.$labelInput.trigger('focus');\n    },\n\n    createSettings: function () {\n      let $settings = $('<div/>');\n\n      this.$labelField = Craft.ui\n        .createTextField({\n          label: Craft.t('app', 'Heading'),\n          instructions: Craft.t(\n            'app',\n            'This can be left blank if you just want an unlabeled separator.'\n          ),\n          value: this.sourceData.heading,\n        })\n        .appendTo($settings);\n\n      this.$labelInput = this.$labelField.find('.text');\n\n      $settings.append('<hr/>');\n\n      this.$deleteBtn = $('<a class=\"error delete\"/>')\n        .text(Craft.t('app', 'Delete heading'))\n        .appendTo($settings);\n\n      this.addListener(this.$labelInput, 'input', 'handleLabelInputChange');\n      this.addListener(this.$deleteBtn, 'click', 'deleteHeading');\n\n      return $settings;\n    },\n\n    handleLabelInputChange: function () {\n      this.updateItemLabel(this.$labelInput.val());\n      this.modal.updateSourcesOnSave = true;\n    },\n\n    updateItemLabel: function (val) {\n      this.$itemLabel.html(\n        (val\n          ? Craft.escapeHtml(val)\n          : '<em class=\"light\">' + Craft.t('app', '(blank)') + '</em>') +\n          '&nbsp;'\n      );\n      this.$itemInput.val(val);\n    },\n\n    deleteHeading: function () {\n      this.modal.sourceSort.removeItems(this.$item);\n      this.modal.sources.splice($.inArray(this, this.modal.sources), 1);\n      this.modal.updateSourcesOnSave = true;\n\n      if (this.isSelected()) {\n        this.deselect();\n\n        if (this.modal.sources.length) {\n          this.modal.sources[0].select();\n        }\n      }\n\n      this.$item.remove();\n      this.$settingsContainer.remove();\n      this.destroy();\n    },\n\n    getIndexSource: function () {\n      var label = this.$labelInput\n        ? this.$labelInput.val()\n        : this.sourceData.heading;\n      return $('<li class=\"heading\"/>').append($('<span/>').text(label));\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * DataTableSorter\n */\nCraft.DataTableSorter = Garnish.DragSort.extend(\n  {\n    $table: null,\n\n    init: function (table, settings) {\n      this.$table = $(table);\n      var $rows = this.$table.children('tbody').children(':not(.filler)');\n\n      settings = $.extend({}, Craft.DataTableSorter.defaults, settings);\n\n      settings.container = this.$table.children('tbody');\n      settings.helper = this.getHelper.bind(this);\n      settings.caboose = '<tr/>';\n      settings.axis = Garnish.Y_AXIS;\n      settings.magnetStrength = 4;\n      settings.helperLagBase = 1.5;\n\n      this.base($rows, settings);\n    },\n\n    getHelper: function ($helperRow) {\n      var $helper = $(\n          '<div class=\"' + this.settings.helperClass + '\"/>'\n        ).appendTo(Garnish.$bod),\n        $table = $('<table/>').appendTo($helper),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the table width and classes\n      $table.width(this.$table.width());\n      $table.prop('className', this.$table.prop('className'));\n\n      // Copy the column widths\n      var $firstRow = this.$table.find('tr:first'),\n        $cells = $firstRow.children(),\n        $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        $($helperCells[i]).width($($cells[i]).width());\n      }\n\n      return $helper;\n    },\n  },\n  {\n    defaults: {\n      handle: '.move',\n      helperClass: 'datatablesorthelper',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Delete User Modal\n */\nCraft.DeleteUserModal = Garnish.Modal.extend(\n  {\n    id: null,\n    userId: null,\n\n    $deleteActionRadios: null,\n    $deleteSpinner: null,\n\n    userSelect: null,\n    _deleting: false,\n\n    init: function (userId, settings) {\n      this.id = Math.floor(Math.random() * 1000000000);\n      this.userId = userId;\n      settings = $.extend(Craft.DeleteUserModal.defaults, settings);\n\n      let $form = $(\n        '<form class=\"modal fitted deleteusermodal\" method=\"post\" accept-charset=\"UTF-8\">' +\n          Craft.getCsrfInput() +\n          '<input type=\"hidden\" name=\"action\" value=\"users/delete-user\"/>' +\n          (!Garnish.isArray(this.userId)\n            ? '<input type=\"hidden\" name=\"userId\" value=\"' + this.userId + '\"/>'\n            : '') +\n          (settings.redirect\n            ? '<input type=\"hidden\" name=\"redirect\" value=\"' +\n              settings.redirect +\n              '\"/>'\n            : '') +\n          '</form>'\n      ).appendTo(Garnish.$bod);\n      let $body = $(\n        '<div class=\"body\">' +\n          '<div class=\"content-summary\">' +\n          '<p>' +\n          Craft.t('app', 'What do you want to do with their content?') +\n          '</p>' +\n          '<ul class=\"bullets\"></ul>' +\n          '</div>' +\n          '<div class=\"options\">' +\n          '<label><input type=\"radio\" name=\"contentAction\" value=\"transfer\"/> ' +\n          Craft.t('app', 'Transfer it to:') +\n          '</label>' +\n          '<div id=\"transferselect' +\n          this.id +\n          '\" class=\"elementselect\">' +\n          '<div class=\"elements\"></div>' +\n          '<button type=\"button\" class=\"btn add icon dashed\">' +\n          Craft.t('app', 'Choose a user') +\n          '</button>' +\n          '</div>' +\n          '</div>' +\n          '<div>' +\n          '<label class=\"error\"><input type=\"radio\" name=\"contentAction\" value=\"delete\"/> ' +\n          Craft.t('app', 'Delete their content') +\n          '</label>' +\n          '</div>' +\n          '</div>'\n      ).appendTo($form);\n      let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n      let $cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo($buttons);\n\n      if (settings.contentSummary.length) {\n        for (let i = 0; i < settings.contentSummary.length; i++) {\n          $body\n            .find('ul')\n            .append($('<li/>', {text: settings.contentSummary[i]}));\n        }\n      } else {\n        $body.find('ul').remove();\n      }\n\n      this.$deleteActionRadios = $body.find('input[type=radio]');\n      this.$deleteSubmitBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit disabled',\n        text: this._submitBtnLabel(false),\n      }).appendTo($buttons);\n      this.$deleteSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n        $buttons\n      );\n\n      var idParam;\n\n      if (Garnish.isArray(this.userId)) {\n        idParam = ['and'];\n\n        for (let i = 0; i < this.userId.length; i++) {\n          idParam.push('not ' + this.userId[i]);\n        }\n      } else {\n        idParam = 'not ' + this.userId;\n      }\n\n      this.userSelect = new Craft.BaseElementSelectInput({\n        id: 'transferselect' + this.id,\n        name: 'transferContentTo',\n        elementType: 'craft\\\\elements\\\\User',\n        criteria: {\n          id: idParam,\n        },\n        limit: 1,\n        modalSettings: {\n          closeOtherModals: false,\n        },\n        onSelectElements: () => {\n          this.updateSizeAndPosition();\n\n          if (!this.$deleteActionRadios.first().prop('checked')) {\n            this.$deleteActionRadios.first().trigger('click');\n          } else {\n            this.validateDeleteInputs();\n          }\n        },\n        onRemoveElements: this.validateDeleteInputs.bind(this),\n        selectable: false,\n        editable: false,\n      });\n\n      this.addListener($cancelBtn, 'click', 'hide');\n\n      this.addListener(\n        this.$deleteActionRadios,\n        'change',\n        'validateDeleteInputs'\n      );\n      this.addListener($form, 'submit', 'handleSubmit');\n\n      this.base($form, settings);\n    },\n\n    _submitBtnLabel: function (withContent) {\n      let message = withContent\n        ? 'Delete {num, plural, =1{user} other{users}} and content'\n        : 'Delete {num, plural, =1{user} other{users}}';\n\n      return Craft.t('app', message, {\n        num: Garnish.isArray(this.userId) ? this.userId.length : 1,\n      });\n    },\n\n    validateDeleteInputs: function () {\n      var validates = false;\n\n      if (this.$deleteActionRadios.eq(1).prop('checked')) {\n        validates = true;\n        this.$deleteSubmitBtn.text(this._submitBtnLabel(true));\n      } else {\n        this.$deleteSubmitBtn.text(this._submitBtnLabel(false));\n        if (this.$deleteActionRadios.eq(0).prop('checked')) {\n          validates = !!this.userSelect.totalSelected;\n        }\n      }\n\n      this.updateSizeAndPosition();\n\n      if (validates) {\n        this.$deleteSubmitBtn.removeClass('disabled');\n      } else {\n        this.$deleteSubmitBtn.addClass('disabled');\n      }\n\n      return validates;\n    },\n\n    handleSubmit: function (ev) {\n      if (this._deleting || !this.validateDeleteInputs()) {\n        ev.preventDefault();\n        return;\n      }\n\n      this.$deleteSubmitBtn.addClass('active');\n      this.$deleteSpinner.removeClass('hidden');\n      this.disable();\n      this.userSelect.disable();\n      this._deleting = true;\n\n      // Let the onSubmit callback prevent the form from getting submitted\n      try {\n        if (this.settings.onSubmit() === false) {\n          ev.preventDefault();\n        }\n      } catch (e) {\n        ev.preventDefault();\n        this.$deleteSpinner.addClass('hidden');\n        throw e;\n      }\n    },\n\n    onFadeIn: function () {\n      // Auto-focus the first radio\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$deleteActionRadios.first().trigger('focus');\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      contentSummary: [],\n      onSubmit: $.noop,\n      redirect: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element draft editor\n */\nCraft.DraftEditor = Garnish.Base.extend(\n  {\n    $revisionBtn: null,\n    $revisionLabel: null,\n    $spinner: null,\n    $expandSiteStatusesBtn: null,\n    $statusIcon: null,\n\n    $editMetaBtn: null,\n    metaHud: null,\n    $nameTextInput: null,\n    $saveMetaBtn: null,\n\n    $siteStatusPane: null,\n    $globalLightswitch: null,\n    $siteLightswitches: null,\n    $addlSiteField: null,\n\n    siteIds: null,\n    newSiteIds: null,\n\n    enableAutosave: null,\n    lastSerializedValue: null,\n    listeningForChanges: false,\n    pauseLevel: 0,\n    timeout: null,\n    saving: false,\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    queue: null,\n    submittingForm: false,\n\n    duplicatedElements: null,\n    errors: null,\n    httpStatus: null,\n    httpError: null,\n\n    openingPreview: false,\n    preview: null,\n    activatingPreviewToken: false,\n    activatedPreviewToken: false,\n    previewTokenQueue: null,\n    previewLinks: null,\n    scrollY: null,\n    createdProvisionalDraft: false,\n\n    bc: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.DraftEditor.defaults);\n\n      this.queue = [];\n      this.previewTokenQueue = [];\n      this.duplicatedElements = {};\n      this.enableAutosave = Craft.autosaveDrafts;\n      this.previewLinks = [];\n\n      this.siteIds = Object.keys(this.settings.siteStatuses).map((siteId) => {\n        return parseInt(siteId);\n      });\n\n      this.$revisionBtn = $('#context-btn');\n      this.$revisionLabel = $('#revision-label');\n      this.$spinner = $('#revision-spinner');\n      this.$expandSiteStatusesBtn = $('#expand-status-btn');\n      this.$statusIcon = $('#revision-status');\n      this.$statusMessage = $('#revision-status-message');\n\n      if (this.settings.canEditMultipleSites) {\n        this.addListener(\n          this.$expandSiteStatusesBtn,\n          'click',\n          'expandSiteStatuses'\n        );\n      }\n\n      if (this.settings.previewTargets.length) {\n        if (this.settings.enablePreview) {\n          this.addListener($('#preview-btn'), 'click', 'openPreview');\n        }\n\n        const $previewBtnContainer = $('#preview-btn-container');\n\n        if (this.settings.previewTargets.length === 1) {\n          const [target] = this.settings.previewTargets;\n          this.createPreviewLink(target)\n            .attr('id', 'share-btn')\n            .addClass('btn')\n            .appendTo($previewBtnContainer);\n        } else {\n          this.createShareMenu($previewBtnContainer);\n        }\n      }\n\n      // If this is a revision, we're done here\n      if (this.settings.revisionId) {\n        return;\n      }\n\n      // Override the serializer to use our own\n      Craft.cp.$primaryForm.data('serializer', () => this.serializeForm(true));\n\n      this.addListener(Craft.cp.$primaryForm, 'submit', 'handleFormSubmit');\n\n      if (this.settings.isProvisionalDraft) {\n        this.initForProvisionalDraft();\n      } else if (this.settings.draftId && !this.settings.isUnpublishedDraft) {\n        this.initForDraft();\n      } else if (!this.settings.canUpdateSource) {\n        // Override the save shortcut to create a draft too\n        this.addListener(Craft.cp.$primaryForm, 'submit.saveShortcut', (ev) => {\n          if (ev.saveShortcut) {\n            ev.preventDefault();\n            this.createDraft();\n            this.removeListener(Craft.cp.$primaryForm, 'submit.saveShortcut');\n          }\n        });\n      }\n\n      this.listenForChanges();\n\n      this.addListener(this.$statusIcon, 'click', () => {\n        this.showStatusHud(this.$statusIcon);\n      });\n\n      if (\n        typeof BroadcastChannel !== 'undefined' &&\n        !this.settings.revisionId\n      ) {\n        this.bc = new BroadcastChannel('DraftEditor');\n        this.bc.onmessage = (ev) => {\n          if (\n            ev.data.event === 'saveDraft' &&\n            ev.data.canonicalId === this.settings.sourceId &&\n            (ev.data.draftId === this.settings.draftId ||\n              (ev.data.isProvisionalDraft && !this.settings.draftId))\n          ) {\n            window.location.reload();\n          }\n        };\n      }\n    },\n\n    listenForChanges: function () {\n      if (\n        this.listeningForChanges ||\n        this.pauseLevel > 0 ||\n        !this.enableAutosave ||\n        !this.settings.saveDraftAction\n      ) {\n        return;\n      }\n\n      this.listeningForChanges = true;\n\n      this.addListener(\n        Garnish.$bod,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup',\n        function (ev) {\n          if ($(ev.target).is(this.statusIcons())) {\n            return;\n          }\n          clearTimeout(this.timeout);\n          // If they are typing, wait half a second before checking the form\n          if (['keypress', 'keyup', 'change'].includes(ev.type)) {\n            this.timeout = setTimeout(this.checkForm.bind(this), 500);\n          } else {\n            this.checkForm();\n          }\n        }\n      );\n    },\n\n    stopListeningForChanges: function () {\n      if (!this.listeningForChanges) {\n        return;\n      }\n\n      this.removeListener(\n        Garnish.$bod,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup'\n      );\n      clearTimeout(this.timeout);\n      this.listeningForChanges = false;\n    },\n\n    pause: function () {\n      this.pauseLevel++;\n      this.stopListeningForChanges();\n    },\n\n    resume: function () {\n      if (this.pauseLevel === 0) {\n        throw 'Craft.DraftEditor::resume() should only be called after pause().';\n      }\n\n      // Only actually resume operation if this has been called the same\n      // number of times that pause() was called\n      this.pauseLevel--;\n      if (this.pauseLevel === 0) {\n        if (this.enableAutosave) {\n          this.checkForm();\n          this.listenForChanges();\n        }\n      }\n    },\n\n    initForProvisionalDraft: function () {\n      let $button = $('#discard-changes');\n      if (!$button.length) {\n        $button = this.$revisionBtn.data('menubtn')\n          ? this.$revisionBtn\n              .data('menubtn')\n              .menu.$container.find('#discard-changes')\n          : null;\n      }\n      if ($button && $button.length) {\n        this.addListener($button, 'click', () => {\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to discard your changes?')\n            )\n          ) {\n            Craft.submitForm(Craft.cp.$primaryForm, {\n              action: this.settings.deleteDraftAction,\n              redirect: this.settings.hashedCpEditUrl,\n              params: {\n                draftId: this.settings.draftId,\n                provisional: this.settings.isProvisionalDraft,\n              },\n            });\n          }\n        });\n      }\n    },\n\n    initForDraft: function () {\n      // Create the edit draft button\n      this.createEditMetaBtn();\n\n      if (this.settings.canUpdateSource) {\n        Garnish.uiLayerManager.registerShortcut(\n          {\n            keyCode: Garnish.S_KEY,\n            ctrl: true,\n            alt: true,\n          },\n          () => {\n            Craft.submitForm(Craft.cp.$primaryForm, {\n              action: this.settings.publishDraftAction,\n              redirect: this.settings.hashedCpEditUrl,\n            });\n          },\n          0\n        );\n      }\n    },\n\n    expandSiteStatuses: function () {\n      this.removeListener(this.$expandSiteStatusesBtn, 'click');\n      this.$expandSiteStatusesBtn.velocity({opacity: 0}, 'fast', () => {\n        this.$expandSiteStatusesBtn.remove();\n      });\n\n      const $enabledForSiteField = $(\n        `#enabledForSite-${this.settings.siteId}-field`\n      );\n      this.$siteStatusPane = $enabledForSiteField.parent();\n\n      // If this is a revision, just show the site statuses statically and be done\n      if (this.settings.revisionId) {\n        this._getOtherSupportedSites().forEach((s) =>\n          this._createSiteStatusField(s)\n        );\n        return;\n      }\n\n      $enabledForSiteField.addClass('nested');\n      const $globalField = Craft.ui\n        .createLightswitchField({\n          id: 'enabled',\n          label: Craft.t('app', 'Enabled'),\n          name: 'enabled',\n        })\n        .insertBefore($enabledForSiteField);\n      $globalField.find('label').css('font-weight', 'bold');\n      this.$globalLightswitch = $globalField.find('.lightswitch');\n\n      if (!this.settings.revisionId) {\n        this._showField($globalField);\n      }\n\n      // Figure out what the \"Enabled everywhere\" lightswitch would have been set to when the page first loaded\n      const siteStatusValues = Object.values(this.settings.siteStatuses);\n      const hasEnabled = siteStatusValues.includes(true);\n      const hasDisabled = siteStatusValues.includes(false);\n      const originalEnabledValue =\n        hasEnabled && hasDisabled ? '-' : hasEnabled ? '1' : '';\n      const originalSerializedStatus =\n        encodeURIComponent(`enabledForSite[${this.settings.siteId}]`) +\n        '=' +\n        (this.settings.enabledForSite ? '1' : '');\n\n      this.$siteLightswitches = $enabledForSiteField\n        .find('.lightswitch')\n        .on('change', this._updateGlobalStatus.bind(this));\n\n      this._getOtherSupportedSites().forEach((s) =>\n        this._createSiteStatusField(s)\n      );\n\n      let serializedStatuses = `enabled=${originalEnabledValue}`;\n      for (let i = 0; i < this.$siteLightswitches.length; i++) {\n        const $input = this.$siteLightswitches.eq(i).data('lightswitch').$input;\n        serializedStatuses +=\n          '&' + encodeURIComponent($input.attr('name')) + '=' + $input.val();\n      }\n\n      Craft.cp.$primaryForm.data(\n        'initialSerializedValue',\n        Craft.cp.$primaryForm\n          .data('initialSerializedValue')\n          .replace(originalSerializedStatus, serializedStatuses)\n      );\n\n      if (this.lastSerializedValue) {\n        this.lastSerializedValue = this.lastSerializedValue.replace(\n          originalSerializedStatus,\n          serializedStatuses\n        );\n      }\n\n      // Are there additional sites that can be added?\n      if (this.settings.addlSites && this.settings.addlSites.length) {\n        this._createAddlSiteField();\n      }\n\n      this.$globalLightswitch.on('change', this._updateSiteStatuses.bind(this));\n      this._updateGlobalStatus();\n    },\n\n    /**\n     * @returns {Array}\n     */\n    _getOtherSupportedSites: function () {\n      return Craft.sites.filter(\n        (s) => s.id != this.settings.siteId && this.siteIds.includes(s.id)\n      );\n    },\n\n    _showField: function ($field) {\n      const height = $field.height();\n      $field\n        .css('overflow', 'hidden')\n        .height(0)\n        .velocity({height}, 'fast', () => {\n          $field.css({\n            overflow: '',\n            height: '',\n          });\n        });\n    },\n\n    _removeField: function ($field) {\n      const height = $field.height();\n      $field.css('overflow', 'hidden').velocity({height: 0}, 'fast', () => {\n        $field.remove();\n      });\n    },\n\n    _updateGlobalStatus: function () {\n      let allEnabled = true,\n        allDisabled = true;\n      this.$siteLightswitches.each(function () {\n        const enabled = $(this).data('lightswitch').on;\n        if (enabled) {\n          allDisabled = false;\n        } else {\n          allEnabled = false;\n        }\n        if (!allEnabled && !allDisabled) {\n          return false;\n        }\n      });\n      if (allEnabled) {\n        this.$globalLightswitch.data('lightswitch').turnOn(true);\n      } else if (allDisabled) {\n        this.$globalLightswitch.data('lightswitch').turnOff(true);\n      } else {\n        this.$globalLightswitch.data('lightswitch').turnIndeterminate(true);\n      }\n    },\n\n    _updateSiteStatuses: function () {\n      const enabled = this.$globalLightswitch.data('lightswitch').on;\n      this.$siteLightswitches.each(function () {\n        if (enabled) {\n          $(this).data('lightswitch').turnOn(true);\n        } else {\n          $(this).data('lightswitch').turnOff(true);\n        }\n      });\n    },\n\n    _createSiteStatusField: function (site, status) {\n      const $field = Craft.ui.createLightswitchField({\n        id: `enabledForSite-${site.id}`,\n        label: Craft.t('app', 'Enabled for {site}', {site: site.name}),\n        name: `enabledForSite[${site.id}]`,\n        on:\n          typeof status != 'undefined'\n            ? status\n            : this.settings.siteStatuses.hasOwnProperty(site.id)\n            ? this.settings.siteStatuses[site.id]\n            : true,\n        disabled: !!this.settings.revisionId,\n      });\n\n      if (this.$addlSiteField) {\n        $field.insertBefore(this.$addlSiteField);\n      } else {\n        $field.appendTo(this.$siteStatusPane);\n      }\n\n      if (!this.settings.revisionId) {\n        $field.addClass('nested');\n        const $lightswitch = $field\n          .find('.lightswitch')\n          .on('change', this._updateGlobalStatus.bind(this));\n        this.$siteLightswitches = this.$siteLightswitches.add($lightswitch);\n      }\n\n      this._showField($field);\n\n      return $field;\n    },\n\n    _createAddlSiteField: function () {\n      const addlSites = Craft.sites.filter((site) => {\n        return (\n          !this.siteIds.includes(site.id) &&\n          this.settings.addlSites.some((s) => s.siteId == site.id)\n        );\n      });\n\n      if (!addlSites.length) {\n        return;\n      }\n\n      const $addlSiteSelectContainer = Craft.ui\n        .createSelect({\n          options: [\n            {label: Craft.t('app', 'Add a site…')},\n            ...addlSites.map((s) => {\n              return {label: s.name, value: s.id};\n            }),\n          ],\n        })\n        .addClass('fullwidth');\n\n      this.$addlSiteField = Craft.ui\n        .createField($addlSiteSelectContainer, {})\n        .addClass('nested add')\n        .appendTo(this.$siteStatusPane);\n\n      const $addlSiteSelect = $addlSiteSelectContainer.find('select');\n\n      $addlSiteSelect.on('change', () => {\n        const siteId = parseInt($addlSiteSelect.val());\n        const site = Craft.sites.find((s) => s.id === siteId);\n\n        if (!site) {\n          return;\n        }\n\n        const addlSiteInfo = this.settings.addlSites.find(\n          (s) => s.siteId == site.id\n        );\n        this._createSiteStatusField(site, addlSiteInfo.enabledByDefault);\n        this._updateGlobalStatus();\n\n        $addlSiteSelect.val('').find(`option[value=\"${siteId}\"]`).remove();\n\n        if (this.newSiteIds === null) {\n          this.newSiteIds = [];\n        }\n\n        this.siteIds.push(siteId);\n        this.newSiteIds.push(siteId);\n\n        // Was that the last site?\n        if ($addlSiteSelect.find('option').length === 1) {\n          this._removeField(this.$addlSiteField);\n        }\n      });\n\n      this._showField(this.$addlSiteField);\n    },\n\n    showStatusHud: function (target) {\n      let bodyHtml;\n\n      if (this.errors === null) {\n        bodyHtml = `<p>${this._saveSuccessMessage()}</p>`;\n      } else {\n        bodyHtml = `<p class=\"error\"><strong>${this._saveFailMessage()}</strong></p>`;\n\n        if (this.errors.length) {\n          bodyHtml +=\n            '<ul class=\"errors\">' +\n            this.errors.map((e) => `<li>${Craft.escapeHtml(e)}</li>`).join('') +\n            '</ul>';\n        }\n\n        if (this.httpError) {\n          bodyHtml += `<p class=\"http-error code\">${Craft.escapeHtml(\n            this.httpError\n          )}</p>`;\n        }\n\n        if (this.httpStatus === 400) {\n          bodyHtml += `<button class=\"btn refresh-btn\">${Craft.t(\n            'app',\n            'Refresh'\n          )}</button>`;\n        }\n      }\n\n      const hud = new Garnish.HUD(target, bodyHtml, {\n        hudClass: 'hud revision-status-hud',\n        onHide: function () {\n          hud.destroy();\n        },\n      });\n\n      hud.$mainContainer.find('.refresh-btn').on('click', () => {\n        window.location.reload();\n      });\n    },\n\n    /**\n     * @return {string}\n     */\n    _saveSuccessMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes have been stored.')\n        : Craft.t('app', 'The draft has been saved.');\n    },\n\n    /**\n     * @return {string}\n     */\n    _saveFailMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes could not be stored.')\n        : Craft.t('app', 'The draft could not be saved.');\n    },\n\n    spinners: function () {\n      return this.preview\n        ? this.$spinner.add(this.preview.$spinner)\n        : this.$spinner;\n    },\n\n    statusIcons: function () {\n      return this.preview\n        ? this.$statusIcon.add(this.preview.$statusIcon)\n        : this.$statusIcon;\n    },\n\n    statusMessage: function () {\n      return this.preview\n        ? this.$statusMessage.add(this.preview.$statusMessage)\n        : this.$statusMessage;\n    },\n\n    createEditMetaBtn: function () {\n      const $btnGroup = $('#context-btngroup');\n      this.$editMetaBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn edit icon',\n        title: Craft.t('app', 'Edit draft settings'),\n      }).appendTo($btnGroup);\n      $btnGroup.find('.btngroup-btn-last').removeClass('btngroup-btn-last');\n      this.addListener(this.$editMetaBtn, 'click', 'showMetaHud');\n    },\n\n    createPreviewLink: function (target, label) {\n      const $a = $('<a/>', {\n        href: this.getTokenizedPreviewUrl(target.url, null, false),\n        text: label || Craft.t('app', 'View'),\n        target: '_blank',\n        data: {\n          targetUrl: target.url,\n          targetLabel: target.label,\n        },\n      });\n\n      this.addListener($a, 'click', () => {\n        setTimeout(() => {\n          this.activatePreviewToken();\n        }, 1);\n      });\n\n      this.previewLinks.push($a);\n      return $a;\n    },\n\n    updatePreviewLinks: function () {\n      this.previewLinks.forEach(($a) => {\n        this.updatePreviewLinkHref($a);\n        if (this.activatedPreviewToken) {\n          this.removeListener($a, 'click');\n        }\n      });\n    },\n\n    updatePreviewLinkHref: function ($a) {\n      $a.attr(\n        'href',\n        this.getTokenizedPreviewUrl($a.data('targetUrl'), null, false)\n      );\n    },\n\n    activatePreviewToken: function () {\n      if (this.settings.isLive) {\n        // don't do anything yet, but leave the event in case we need it later\n        return;\n      }\n\n      this.activatedPreviewToken = true;\n      this.updatePreviewLinks();\n    },\n\n    createShareMenu: function ($container) {\n      $('<button/>', {\n        id: 'share-btn',\n        type: 'button',\n        class: 'btn menubtn',\n        text: Craft.t('app', 'View'),\n      }).appendTo($container);\n\n      const $menu = $('<div/>', {class: 'menu'}).appendTo($container);\n      const $ul = $('<ul/>').appendTo($menu);\n\n      this.settings.previewTargets.forEach((target) => {\n        $('<li/>')\n          .append(this.createPreviewLink(target, target.label))\n          .appendTo($ul);\n      });\n    },\n\n    getPreviewTokenParams: function () {\n      const params = {\n        elementType: this.settings.elementType,\n        sourceId: this.settings.sourceId,\n        siteId: this.settings.siteId,\n        revisionId: this.settings.revisionId,\n        previewToken: this.settings.previewToken,\n      };\n\n      if (this.settings.draftId && !this.settings.isProvisionalDraft) {\n        params.draftId = this.settings.draftId;\n      }\n\n      return params;\n    },\n\n    getPreviewToken: function () {\n      return new Promise((resolve, reject) => {\n        if (this.activatedPreviewToken) {\n          resolve(this.settings.previewToken);\n          return;\n        }\n\n        if (this.activatingPreviewToken) {\n          this.previewTokenQueue.push(resolve);\n          return;\n        }\n\n        this.activatingPreviewToken = true;\n\n        Craft.sendActionRequest('POST', 'preview/create-token', {\n          data: this.getPreviewTokenParams(),\n        })\n          .then(() => {\n            this.activatingPreviewToken = false;\n            this.activatePreviewToken();\n            resolve(this.settings.previewToken);\n\n            while (this.previewTokenQueue.length) {\n              this.previewTokenQueue.shift()(this.settings.previewToken);\n            }\n          })\n          .catch(reject);\n      });\n    },\n\n    /**\n     * @param {string} url\n     * @param {string|null} [randoParam]\n     * @param {boolean} [asPromise=false]\n     * @return Promise|string\n     */\n    getTokenizedPreviewUrl: function (url, randoParam, asPromise) {\n      if (typeof asPromise === 'undefined') {\n        asPromise = true;\n      }\n\n      const params = {};\n\n      if (randoParam || !this.settings.isLive) {\n        // Randomize the URL so CDNs don't return cached pages\n        params[randoParam || 'x-craft-preview'] = Craft.randomString(10);\n      }\n\n      if (this.settings.siteToken) {\n        params[Craft.siteToken] = this.settings.siteToken;\n      }\n\n      // No need for a token if we're looking at a live element\n      if (this.settings.isLive) {\n        const previewUrl = Craft.getUrl(url, params);\n\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (!this.settings.previewToken) {\n        throw 'Missing preview token';\n      }\n\n      params[Craft.tokenParam] = this.settings.previewToken;\n      const previewUrl = Craft.getUrl(url, params);\n\n      if (this.activatedPreviewToken) {\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (asPromise) {\n        return new Promise((resolve, reject) => {\n          this.getPreviewToken()\n            .then(() => {\n              resolve(previewUrl);\n            })\n            .catch(reject);\n        });\n      }\n\n      const createTokenParams = this.getPreviewTokenParams();\n      createTokenParams.redirect = encodeURIComponent(previewUrl);\n      return Craft.getActionUrl('preview/create-token', createTokenParams);\n    },\n\n    getPreview: function () {\n      if (!this.preview) {\n        this.preview = new Craft.Preview(this);\n        if (!this.enableAutosave) {\n          this.preview.on('open', () => {\n            this.enableAutosave = true;\n            this.listenForChanges();\n          });\n          this.preview.on('close', () => {\n            this.enableAutosave = false;\n            this.stopListeningForChanges();\n\n            // Hide the status icon if the save was successful\n            const $statusIcons = this.statusIcons();\n            if ($statusIcons.hasClass('checkmark-icon')) {\n              $statusIcons.addClass('hidden');\n            }\n          });\n        }\n        this.preview.on('close', () => {\n          if (this.scrollY) {\n            window.scrollTo(0, this.scrollY);\n            this.scrollY = null;\n          }\n        });\n      }\n      return this.preview;\n    },\n\n    openPreview: function () {\n      return new Promise((resolve, reject) => {\n        this.openingPreview = true;\n        this.ensureIsDraftOrRevision(true)\n          .then(() => {\n            this.scrollY = window.scrollY;\n            this.getPreview().open();\n            this.openingPreview = false;\n            resolve();\n          })\n          .catch(reject);\n      });\n    },\n\n    ensureIsDraftOrRevision: function (onlyIfChanged) {\n      return new Promise((resolve, reject) => {\n        if (!this.settings.draftId && !this.settings.revisionId) {\n          if (\n            onlyIfChanged &&\n            this.serializeForm(true) ===\n              Craft.cp.$primaryForm.data('initialSerializedValue')\n          ) {\n            resolve();\n            return;\n          }\n\n          this.createDraft().then(resolve).catch(reject);\n        } else {\n          resolve();\n        }\n      });\n    },\n\n    serializeForm: function (removeActionParams) {\n      let data = Craft.cp.$primaryForm.serialize();\n\n      if (this.isPreviewActive()) {\n        // Replace the temp input with the preview form data\n        data = data.replace(\n          '__PREVIEW_FIELDS__=1',\n          this.preview.$editor.serialize()\n        );\n      }\n\n      if (removeActionParams && !this.settings.isUnpublishedDraft) {\n        // Remove action and redirect params\n        data = data.replace(/&action=[^&]*/, '');\n        data = data.replace(/&redirect=[^&]*/, '');\n      }\n\n      return data;\n    },\n\n    checkForm: function (force) {\n      // If this isn't a draft and there's no active preview, then there's nothing to check\n      if (\n        this.settings.revisionId ||\n        this.pauseLevel > 0 ||\n        !this.enableAutosave ||\n        !this.settings.saveDraftAction\n      ) {\n        return;\n      }\n\n      clearTimeout(this.timeout);\n      this.timeout = null;\n\n      // If we haven't had a chance to fetch the initial data yet, try again in a bit\n      if (\n        typeof Craft.cp.$primaryForm.data('initialSerializedValue') ===\n        'undefined'\n      ) {\n        this.timeout = setTimeout(this.checkForm.bind(this), 500);\n        return;\n      }\n\n      // Has anything changed?\n      const data = this.serializeForm(true);\n      if (\n        force ||\n        data !==\n          (this.lastSerializedValue ||\n            Craft.cp.$primaryForm.data('initialSerializedValue'))\n      ) {\n        const provisional =\n          (!this.settings.draftId || this.settings.isProvisionalDraft) &&\n          !this.settings.revisionId;\n        this.saveDraft(data, provisional).catch((e) => {\n          console.warn('Couldn’t save draft:', e);\n        });\n      }\n    },\n\n    isPreviewActive: function () {\n      return this.preview && this.preview.isActive;\n    },\n\n    createDraft: function () {\n      return new Promise((resolve, reject) => {\n        this.saveDraft(this.serializeForm(true)).then(resolve).catch(reject);\n      });\n    },\n\n    /**\n     * @param {object} data\n     * @returns {Promise<unknown>}\n     */\n    saveDraft: function (data) {\n      return new Promise((resolve, reject) => {\n        // Ignore if we're already submitting the main form\n        if (this.submittingForm) {\n          reject('Form already being submitted.');\n          return;\n        }\n\n        if (this.saving) {\n          this.queue.push(() => {\n            this.checkForm();\n          });\n          return;\n        }\n\n        this.lastSerializedValue = data;\n        this.saving = true;\n        this.errors = null;\n        this.httpStatus = null;\n        this.httpError = null;\n        this.cancelToken = axios.CancelToken.source();\n        this.spinners().removeClass('hidden');\n\n        this.statusIcons()\n          .velocity('stop')\n          .css('opacity', '')\n          .removeClass('invisible checkmark-icon alert-icon fade-out')\n          .addClass('hidden');\n\n        // Clear previous status message\n        this.statusMessage().empty();\n\n        if (this.$saveMetaBtn) {\n          this.$saveMetaBtn.addClass('active');\n        }\n\n        // Prep the data to be saved, keeping track of the first input name for each delta group\n        let modifiedFieldNames = [];\n        let preparedData = this.prepareData(\n          data,\n          !this.settings.isUnpublishedDraft\n            ? (deltaName, params) => {\n                if (params.length) {\n                  modifiedFieldNames.push(\n                    decodeURIComponent(params[0].split('=')[0])\n                  );\n                }\n              }\n            : undefined\n        );\n\n        // Are we saving a provisional draft?\n        if (this.settings.isProvisionalDraft || !this.settings.draftId) {\n          preparedData += '&provisional=1';\n        }\n\n        Craft.sendActionRequest('POST', this.settings.saveDraftAction, {\n          cancelToken: this.cancelToken.token,\n          headers: {\n            'content-type': 'application/x-www-form-urlencoded',\n          },\n          data: preparedData,\n        })\n          .then((response) => {\n            this._afterSaveRequest();\n\n            if (response.data.errors) {\n              this.errors = response.data.errors;\n              this._showFailStatus();\n              reject(response.data.errors);\n            }\n\n            const createdProvisionalDraft = !this.settings.draftId;\n\n            if (createdProvisionalDraft) {\n              this.settings.isProvisionalDraft = true;\n              this.createdProvisionalDraft = true;\n            }\n\n            if (response.data.title) {\n              $('#header h1').text(response.data.title);\n            }\n\n            if (response.data.docTitle) {\n              document.title = response.data.docTitle;\n            }\n\n            if (this.settings.isProvisionalDraft) {\n              if (createdProvisionalDraft) {\n                this.$revisionLabel.append(\n                  $('<span/>', {\n                    text: ` — ${Craft.t('app', 'Edited')}`,\n                  })\n                );\n              }\n            } else {\n              this.$revisionLabel.text(response.data.draftName);\n              this.settings.draftName = response.data.draftName;\n            }\n\n            let revisionMenu = this.$revisionBtn.data('menubtn')\n              ? this.$revisionBtn.data('menubtn').menu\n              : null;\n\n            // Did we just add a site?\n            if (this.newSiteIds) {\n              // Do we need to create the revision menu?\n              if (!revisionMenu) {\n                this.$revisionBtn.removeClass('disabled').addClass('menubtn');\n                new Garnish.MenuBtn(this.$revisionBtn);\n                revisionMenu = this.$revisionBtn.data('menubtn').menu;\n                revisionMenu.$container.removeClass('hidden');\n              }\n              this.newSiteIds.forEach((siteId) => {\n                const $option = revisionMenu.$options.filter(\n                  `[data-site-id=${siteId}]`\n                );\n                const siteSettings = this.settings.addlSites.find(\n                  (s) => s.siteId == siteId\n                );\n                if (\n                  !siteSettings ||\n                  typeof siteSettings.enabledByDefault === 'undefined' ||\n                  siteSettings.enabledByDefault\n                ) {\n                  $option\n                    .find('.status')\n                    .removeClass('disabled')\n                    .addClass('enabled');\n                }\n                const $li = $option.parent().removeClass('hidden');\n                $li.closest('.site-group').removeClass('hidden');\n              });\n              revisionMenu.$container\n                .find('.revision-hr')\n                .removeClass('hidden');\n              this.newSiteIds = null;\n            }\n\n            if (this.settings.isProvisionalDraft) {\n              if (createdProvisionalDraft) {\n                // Replace the action\n                const $actionInput = $('#action').attr(\n                  'value',\n                  this.settings.publishDraftAction\n                );\n\n                // Update the editor settings\n                this.settings.draftId = response.data.draftId;\n                this.settings.isLive = false;\n                this.previewToken = null;\n\n                if (revisionMenu) {\n                  // Add edited description to the “Current” option\n                  revisionMenu.$container.find('#current-revision').append(\n                    $('<div/>', {\n                      class: 'edited-desc',\n                    })\n                      .append(\n                        $('<p/>', {\n                          text: Craft.t('app', 'Showing your unsaved changes.'),\n                        })\n                      )\n                      .append(\n                        $('<button/>', {\n                          id: 'discard-changes',\n                          class: 'btn',\n                          text: Craft.t('app', 'Discard changes'),\n                        })\n                      )\n                  );\n                }\n\n                this.initForProvisionalDraft();\n              }\n            } else if (revisionMenu) {\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-name')\n                .text(response.data.draftName);\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-meta')\n                .text(\n                  response.data.creator\n                    ? Craft.t('app', 'Saved {timestamp} by {creator}', {\n                        timestamp: response.data.timestamp,\n                        creator: response.data.creator,\n                      })\n                    : Craft.t('app', 'Saved {timestamp}', {\n                        timestamp: response.data.timestamp,\n                      })\n                );\n            }\n\n            // Did the controller send us updated preview targets?\n            if (\n              response.data.previewTargets &&\n              JSON.stringify(response.data.previewTargets) !==\n                JSON.stringify(this.settings.previewTargets)\n            ) {\n              this.updatePreviewTargets(response.data.previewTargets);\n            }\n\n            if (createdProvisionalDraft) {\n              this.updatePreviewLinks();\n              this.trigger('createProvisionalDraft');\n            }\n\n            if (this.$nameTextInput) {\n              this.checkMetaValues();\n            }\n\n            for (const oldId in response.data.duplicatedElements) {\n              if (\n                oldId != this.settings.sourceId &&\n                response.data.duplicatedElements.hasOwnProperty(oldId)\n              ) {\n                this.duplicatedElements[oldId] =\n                  response.data.duplicatedElements[oldId];\n              }\n            }\n\n            // Add missing field modified indicators\n            const selectors = response.data.modifiedAttributes\n              .map((attr) => `[name=\"${attr}\"],[name^=\"${attr}[\"]`)\n              .concat(modifiedFieldNames.map((name) => `[name=\"${name}\"]`));\n\n            const $fields = $(selectors.join(','))\n              .parents()\n              .filter('.field:not(:has(> .status-badge))');\n            for (let i = 0; i < $fields.length; i++) {\n              $fields.eq(i).prepend(\n                $('<div/>', {\n                  class: 'status-badge modified',\n                  title: Craft.t('app', 'This field has been modified.'),\n                }).append(\n                  $('<span/>', {\n                    class: 'visually-hidden',\n                    html: Craft.t('app', 'This field has been modified.'),\n                  })\n                )\n              );\n            }\n\n            this.afterUpdate(data);\n\n            if (this.bc) {\n              this.bc.postMessage({\n                event: 'saveDraft',\n                canonicalId: this.settings.sourceId,\n                draftId: this.settings.draftId,\n                isProvisionalDraft: this.settings.isProvisionalDraft,\n              });\n            }\n\n            resolve();\n          })\n          .catch((e) => {\n            this._afterSaveRequest();\n\n            if (!this.ignoreFailedRequest) {\n              this.errors = [];\n              if (e && e.response) {\n                this.httpStatus = e.response.status;\n                this.httpError = e.response.data ? e.response.data.error : null;\n              }\n              this._showFailStatus();\n              reject(e);\n            }\n\n            this.ignoreFailedRequest = false;\n          });\n      });\n    },\n\n    _afterSaveRequest: function () {\n      this.spinners().addClass('hidden');\n      if (this.$saveMetaBtn) {\n        this.$saveMetaBtn.removeClass('active');\n      }\n      this.saving = false;\n    },\n\n    _showFailStatus: function () {\n      this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden checkmark-icon')\n        .addClass('alert-icon');\n\n      this.setStatusMessage(this._saveFailMessage());\n    },\n\n    /**\n     * @param {string} data\n     * @param {function} [deltaCallback] Callback function that should be passed to `Craft.findDeltaData()`\n     * @returns {string}\n     */\n    prepareData: function (data, deltaCallback) {\n      // Filter out anything that hasn't changed since the last time the form was submitted\n      data = Craft.findDeltaData(\n        Craft.cp.$primaryForm.data('initialSerializedValue'),\n        data,\n        Craft.deltaNames,\n        deltaCallback\n      );\n\n      // Swap out element IDs with their duplicated ones\n      data = this.swapDuplicatedElementIds(data);\n\n      // Add the draft info\n      if (this.settings.draftId) {\n        data += `&draftId=${this.settings.draftId}`;\n        if (this.settings.isProvisionalDraft) {\n          data += '&provisional=1';\n        }\n      }\n\n      if (this.settings.draftName !== null) {\n        data += `&draftName=${this.settings.draftName}`;\n      }\n\n      return data;\n    },\n\n    /**\n     * @param {string} data\n     * @returns {string}\n     */\n    swapDuplicatedElementIds: function (data) {\n      const idsRE = Object.keys(this.duplicatedElements).join('|');\n      if (idsRE === '') {\n        return data;\n      }\n      const lb = encodeURIComponent('[');\n      const rb = encodeURIComponent(']');\n      // Keep replacing field IDs until data stops changing\n      while (true) {\n        if (\n          data ===\n          (data = data\n            // &fields[...][X]\n            .replace(\n              new RegExp(`(&fields${lb}[^=]+${rb}${lb})(${idsRE})(${rb})`, 'g'),\n              (m, pre, id, post) => {\n                return pre + this.duplicatedElements[id] + post;\n              }\n            )\n            // &fields[...=X\n            .replace(\n              new RegExp(`&(fields${lb}[^=]+)=(${idsRE})\\\\b`, 'g'),\n              (m, name, id) => {\n                // Ignore param names that end in `[enabled]`, `[type]`, etc.\n                // (`[sortOrder]` should pass here, which could be set to a specific order index, but *not* `[sortOrder][]`!)\n                if (\n                  name.match(\n                    new RegExp(`${lb}(enabled|sortOrder|type|typeId)${rb}$`)\n                  )\n                ) {\n                  return m;\n                }\n                return `&${name}=${this.duplicatedElements[id]}`;\n              }\n            ))\n        ) {\n          break;\n        }\n      }\n      return data;\n    },\n\n    updatePreviewTargets: function (previewTargets) {\n      previewTargets.forEach((newTarget) => {\n        const currentTarget = this.settings.previewTargets.find(\n          (t) => t.label === newTarget.label\n        );\n        if (currentTarget) {\n          currentTarget.url = newTarget.url;\n        }\n\n        const $previewLink = this.previewLinks.find(\n          ($a) => $a.data('targetLabel') === newTarget.label\n        );\n        if ($previewLink) {\n          $previewLink.data('targetUrl', newTarget.url);\n          this.updatePreviewLinkHref($previewLink);\n        }\n      });\n    },\n\n    afterUpdate: function (data) {\n      Craft.cp.$primaryForm.data('initialSerializedValue', data);\n      Craft.initialDeltaValues = {};\n\n      const $statusIcons = this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden')\n        .addClass('checkmark-icon');\n\n      this.setStatusMessage(this._saveSuccessMessage());\n\n      if (!Craft.autosaveDrafts) {\n        // Fade the icon out after a couple seconds, since it won't be accurate as content continues to change\n        $statusIcons.velocity('stop').velocity(\n          {\n            opacity: 0,\n          },\n          {\n            delay: 2000,\n            complete: () => {\n              $statusIcons.addClass('hidden');\n            },\n          }\n        );\n      }\n\n      this.trigger('update');\n\n      this.nextInQueue();\n    },\n\n    setStatusMessage: function (message) {\n      this.statusIcons().attr('title', message);\n      this.statusMessage()\n        .empty()\n        .append(\n          $('<span/>', {\n            class: 'visually-hidden',\n            text: message,\n          })\n        );\n    },\n\n    nextInQueue: function () {\n      if (this.queue.length) {\n        this.queue.shift()();\n      }\n    },\n\n    showMetaHud: function () {\n      if (!this.metaHud) {\n        this.createMetaHud();\n        this.onMetaHudShow();\n      } else {\n        this.metaHud.show();\n      }\n\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$nameTextInput.trigger('focus');\n      }\n    },\n\n    createMetaHud: function () {\n      const $hudBody = $('<div/>');\n\n      // Add the Name field\n      const $nameField = $(\n        '<div class=\"field\"><div class=\"heading\"><label for=\"draft-name\">' +\n          Craft.t('app', 'Draft Name') +\n          '</label></div></div>'\n      ).appendTo($hudBody);\n      const $nameInputContainer = $('<div class=\"input\"/>').appendTo(\n        $nameField\n      );\n      this.$nameTextInput = $(\n        '<input type=\"text\" class=\"text fullwidth\" id=\"draft-name\"/>'\n      )\n        .appendTo($nameInputContainer)\n        .val(this.settings.draftName);\n\n      // HUD footer\n      const $footer = $('<div class=\"hud-footer flex flex-center\"/>').appendTo(\n        $hudBody\n      );\n\n      $('<div class=\"flex-grow\"></div>').appendTo($footer);\n      this.$saveMetaBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit disabled',\n        text: Craft.t('app', 'Save'),\n      }).appendTo($footer);\n\n      this.metaHud = new Garnish.HUD(this.$editMetaBtn, $hudBody, {\n        onSubmit: this.saveMeta.bind(this),\n      });\n\n      this.addListener(this.$nameTextInput, 'input', 'checkMetaValues');\n\n      this.metaHud.on('show', this.onMetaHudShow.bind(this));\n      this.metaHud.on('hide', this.onMetaHudHide.bind(this));\n      this.metaHud.on('escape', this.onMetaHudEscape.bind(this));\n    },\n\n    onMetaHudShow: function () {\n      this.$editMetaBtn.addClass('active');\n    },\n\n    onMetaHudHide: function () {\n      this.$editMetaBtn.removeClass('active');\n    },\n\n    onMetaHudEscape: function () {\n      this.$nameTextInput.val(this.settings.draftName);\n    },\n\n    checkMetaValues: function () {\n      if (\n        this.$nameTextInput.val() &&\n        this.$nameTextInput.val() !== this.settings.draftName\n      ) {\n        this.$saveMetaBtn.removeClass('disabled');\n        return true;\n      }\n\n      this.$saveMetaBtn.addClass('disabled');\n      return false;\n    },\n\n    shakeMetaHud: function () {\n      Garnish.shake(this.metaHud.$hud);\n    },\n\n    saveMeta: function () {\n      if (!this.checkMetaValues()) {\n        this.shakeMetaHud();\n        return;\n      }\n\n      this.settings.draftName = this.$nameTextInput.val();\n\n      this.metaHud.hide();\n      this.checkForm(true);\n    },\n\n    handleFormSubmit: function (ev) {\n      ev.preventDefault();\n\n      // Prevent double form submits\n      if (this.submittingForm) {\n        return;\n      }\n\n      // If this a draft and was this a normal save (either via submit button or save shortcut),\n      // then trigger an autosave\n      if (\n        this.settings.draftId &&\n        !this.settings.isUnpublishedDraft &&\n        !this.settings.isProvisionalDraft &&\n        (typeof ev.autosave === 'undefined' || ev.autosave) &&\n        (ev.saveShortcut ||\n          (ev.customTrigger &&\n            ev.customTrigger.data('action') ===\n              this.settings.saveDraftAction)) &&\n        this.enableAutosave\n      ) {\n        this.checkForm(true);\n        return;\n      }\n\n      // Prevent the normal unload confirmation dialog\n      Craft.cp.$confirmUnloadForms = Craft.cp.$confirmUnloadForms.not(\n        Craft.cp.$primaryForm\n      );\n\n      // Abort the current save request if there is one\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n\n      // Duplicate the form with normalized data\n      const data = this.prepareData(this.serializeForm(false));\n      const $form = Craft.createForm(data);\n\n      $form.appendTo(Garnish.$bod);\n      $form.submit();\n      this.submittingForm = true;\n    },\n  },\n  {\n    defaults: {\n      elementType: null,\n      sourceId: null,\n      siteId: null,\n      isUnpublishedDraft: false,\n      enabled: false,\n      enabledForSite: false,\n      isLive: false,\n      isProvisionalDraft: false,\n      siteStatuses: null,\n      addlSites: [],\n      cpEditUrl: null,\n      draftId: null,\n      revisionId: null,\n      draftName: null,\n      canEditMultipleSites: false,\n      canUpdateSource: false,\n      saveDraftAction: null,\n      deleteDraftAction: null,\n      publishDraftAction: null,\n      hashedCpEditUrl: null,\n      hashedAddAnotherRedirectUrl: null,\n      enablePreview: false,\n      previewTargets: [],\n      previewToken: null,\n      siteToken: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.DynamicGenerator = Craft.BaseInputGenerator.extend({\n  callback: $.noop,\n\n  init: function (source, target, callback) {\n    this.callback = callback;\n    this.base(source, target);\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return this.callback(sourceVal);\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Editable table class\n */\nCraft.EditableTable = Garnish.Base.extend(\n  {\n    initialized: false,\n\n    id: null,\n    baseName: null,\n    columns: null,\n    sorter: null,\n    biggestId: -1,\n\n    $table: null,\n    $tbody: null,\n    $addRowBtn: null,\n    $tableParent: null,\n    $statusMessage: null,\n\n    rowCount: 0,\n    hasMaxRows: false,\n    hasMinRows: false,\n\n    radioCheckboxes: null,\n\n    init: function (id, baseName, columns, settings) {\n      this.id = id;\n      this.baseName = baseName;\n      this.columns = columns;\n      this.setSettings(settings, Craft.EditableTable.defaults);\n      this.radioCheckboxes = {};\n\n      this.$table = $('#' + id);\n      this.$tbody = this.$table.children('tbody');\n      this.$tableParent = this.$table.parent();\n      this.$statusMessage = this.$tableParent.find('[data-status-message]');\n      this.rowCount = this.$tbody.find('tr').length;\n\n      // Is this already an editable table?\n      if (this.$table.data('editable-table')) {\n        console.warn('Double-instantiating an editable table on an element');\n        this.$table.data('editable-table').destroy();\n      }\n\n      this.$table.data('editable-table', this);\n\n      this.sorter = new Craft.DataTableSorter(this.$table, {\n        helperClass: 'editabletablesorthelper',\n        copyDraggeeInputValuesToHelper: true,\n        onSortChange: () => {\n          this.updateAllRows();\n        },\n      });\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        // Give everything a chance to initialize\n        setTimeout(this.initializeIfVisible.bind(this), 500);\n      }\n\n      if (this.settings.minRows && this.rowCount < this.settings.minRows) {\n        for (var i = this.rowCount; i < this.settings.minRows; i++) {\n          this.addRow();\n        }\n      }\n    },\n\n    isVisible: function () {\n      return this.$table.parent().height() > 0;\n    },\n\n    initialize: function () {\n      if (this.initialized) {\n        return false;\n      }\n\n      this.initialized = true;\n      this.removeListener(Garnish.$win, 'resize');\n\n      var $rows = this.$tbody.children();\n\n      for (var i = 0; i < $rows.length; i++) {\n        this.createRowObj($rows[i]);\n      }\n\n      const $container = this.$table.parent('.input');\n      if ($container.length && this.$table.width() > $container.width()) {\n        $container.css('overflow-x', 'auto');\n      }\n\n      this.$addRowBtn = this.$table.next('.add');\n      this.updateAddRowButton();\n      this.addListener(this.$addRowBtn, 'activate', 'addRow');\n      return true;\n    },\n    initializeIfVisible: function () {\n      this.removeListener(Garnish.$win, 'resize');\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        this.addListener(Garnish.$win, 'resize', 'initializeIfVisible');\n      }\n    },\n    updateAddRowButton: function () {\n      if (!this.canAddRow()) {\n        this.$addRowBtn.css('opacity', '0.2');\n        this.$addRowBtn.css('pointer-events', 'none');\n        this.$addRowBtn.attr('aria-disabled', 'true');\n      } else {\n        this.$addRowBtn.css('opacity', '1');\n        this.$addRowBtn.css('pointer-events', 'auto');\n        this.$addRowBtn.attr('aria-disabled', 'false');\n      }\n    },\n    updateAllRows: function () {\n      if (this.settings.staticRows) {\n        return;\n      }\n      const $rows = this.$table.find('> tbody > tr');\n      for (let i = 0; i < $rows.length; i++) {\n        this.updateRow($rows.eq(i));\n      }\n    },\n    updateRow: function ($row) {\n      if (this.settings.staticRows) {\n        return;\n      }\n\n      const $deleteBtn = $row.find('button.delete');\n\n      if ($deleteBtn.length) {\n        $deleteBtn.attr(\n          'aria-label',\n          Craft.t('app', 'Delete row {index}', {\n            index: $row.index() + 1,\n          })\n        );\n        if (this.canDeleteRow()) {\n          $deleteBtn.removeAttr('disabled').removeClass('disabled');\n        } else {\n          $deleteBtn.attr('disabled', 'disabled').addClass('disabled');\n        }\n      }\n    },\n    /**\n     * @deprecated\n     */\n    updateDeleteRowButton: function (rowId) {\n      this.updateRow(this.$table.find(`tr[data-id=\"${rowId}\"]`));\n    },\n    updateStatusMessage: function () {\n      this.$statusMessage.empty();\n      let message;\n\n      if (!this.canAddRow()) {\n        message = Craft.t(\n          'app',\n          'Row could not be added. Maximum number of rows reached.'\n        );\n      } else {\n        message = Craft.t(\n          'app',\n          'Row could not be deleted. Minimum number of rows reached.'\n        );\n      }\n\n      setTimeout(() => {\n        this.$statusMessage.text(message);\n      }, 250);\n    },\n    canDeleteRow: function () {\n      return this.rowCount > this.settings.minRows;\n    },\n    deleteRow: function (row) {\n      if (!this.canDeleteRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      this.sorter.removeItems(row.$tr);\n      row.$tr.remove();\n\n      this.rowCount--;\n\n      this.updateAllRows();\n      this.updateAddRowButton();\n\n      if (this.rowCount === 0) {\n        this.$table.addClass('hidden');\n      }\n\n      // onDeleteRow callback\n      this.settings.onDeleteRow(row.$tr);\n\n      row.destroy();\n    },\n    canAddRow: function () {\n      if (this.settings.staticRows) {\n        return false;\n      }\n\n      if (this.settings.maxRows) {\n        return this.rowCount < this.settings.maxRows;\n      }\n\n      return true;\n    },\n    addRow: function (focus, prepend) {\n      if (!this.canAddRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      var rowId = this.settings.rowIdPrefix + (this.biggestId + 1),\n        $tr = this.createRow(\n          rowId,\n          this.columns,\n          this.baseName,\n          $.extend({}, this.settings.defaultValues)\n        );\n\n      if (prepend) {\n        $tr.prependTo(this.$tbody);\n      } else {\n        $tr.appendTo(this.$tbody);\n      }\n\n      var row = this.createRowObj($tr);\n      this.sorter.addItems($tr);\n\n      // Focus the first input in the row\n      if (focus !== false) {\n        $tr\n          .find('input:visible,textarea:visible,select:visible')\n          .first()\n          .trigger('focus');\n      }\n\n      this.rowCount++;\n      this.updateAllRows();\n      this.updateAddRowButton();\n      this.$table.removeClass('hidden');\n\n      // onAddRow callback\n      this.settings.onAddRow($tr);\n\n      return row;\n    },\n\n    createRow: function (rowId, columns, baseName, values) {\n      return Craft.EditableTable.createRow(rowId, columns, baseName, values);\n    },\n\n    createRowObj: function ($tr) {\n      return new Craft.EditableTable.Row(this, $tr);\n    },\n\n    focusOnPrevRow: function ($tr, tdIndex, blurTd) {\n      var $prevTr = $tr.prev('tr');\n      var prevRow;\n\n      if ($prevTr.length) {\n        prevRow = $prevTr.data('editable-table-row');\n      } else {\n        prevRow = this.addRow(false, true);\n      }\n\n      // Focus on the same cell in the previous row\n      if (!prevRow) {\n        return;\n      }\n\n      if (!prevRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(prevRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($prevTr) {\n          this.focusOnPrevRow($prevTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', prevRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    focusOnNextRow: function ($tr, tdIndex, blurTd) {\n      var $nextTr = $tr.next('tr');\n      var nextRow;\n\n      if ($nextTr.length) {\n        nextRow = $nextTr.data('editable-table-row');\n      } else {\n        nextRow = this.addRow(false);\n      }\n\n      // Focus on the same cell in the next row\n      if (!nextRow) {\n        return;\n      }\n\n      if (!nextRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(nextRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($nextTr) {\n          this.focusOnNextRow($nextTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', nextRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    importData: function (data, row, tdIndex) {\n      let lines = data.split(/\\r?\\n|\\r/);\n      for (let i = 0; i < lines.length; i++) {\n        let values = lines[i].split('\\t');\n        for (let j = 0; j < values.length; j++) {\n          let value = values[j];\n          row.$tds\n            .eq(tdIndex + j)\n            .find('textarea,input[type!=hidden]')\n            .val(value)\n            .trigger('input');\n        }\n\n        // move onto the next row\n        let $nextTr = row.$tr.next('tr');\n        if ($nextTr.length) {\n          row = $nextTr.data('editable-table-row');\n        } else {\n          row = this.addRow(false);\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$table.removeData('editable-table');\n      this.base();\n    },\n  },\n  {\n    textualColTypes: [\n      'autosuggest',\n      'color',\n      'date',\n      'email',\n      'multiline',\n      'number',\n      'singleline',\n      'template',\n      'time',\n      'url',\n    ],\n    defaults: {\n      rowIdPrefix: '',\n      defaultValues: {},\n      staticRows: false,\n      minRows: null,\n      maxRows: null,\n      onAddRow: $.noop,\n      onDeleteRow: $.noop,\n    },\n\n    createRow: function (rowId, columns, baseName, values) {\n      var $tr = $('<tr/>', {\n        'data-id': rowId,\n      });\n\n      for (var colId in columns) {\n        if (!columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        var col = columns[colId],\n          value = typeof values[colId] !== 'undefined' ? values[colId] : '',\n          $cell;\n\n        if (col.type === 'heading') {\n          $cell = $('<th/>', {\n            scope: 'row',\n            class: col['class'],\n            html: value,\n          });\n        } else {\n          var name = baseName + '[' + rowId + '][' + colId + ']';\n\n          $cell = $('<td/>', {\n            class: `${col.class} ${col.type}-cell`,\n            width: col.width,\n          });\n\n          if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n            $cell.addClass('textual');\n          }\n\n          if (col.code) {\n            $cell.addClass('code');\n          }\n\n          switch (col.type) {\n            case 'checkbox':\n              $('<div class=\"checkbox-wrapper\"/>')\n                .append(\n                  Craft.ui.createCheckbox({\n                    name: name,\n                    value: col.value || '1',\n                    checked: !!value,\n                  })\n                )\n                .appendTo($cell);\n              break;\n\n            case 'color':\n              Craft.ui\n                .createColorInput({\n                  name: name,\n                  value: value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'date':\n              Craft.ui\n                .createDateInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'lightswitch':\n              Craft.ui\n                .createLightswitch({\n                  name: name,\n                  value: col.value || '1',\n                  on: !!value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'select':\n              Craft.ui\n                .createSelect({\n                  name: name,\n                  options: col.options,\n                  value:\n                    value ||\n                    (function () {\n                      for (var key in col.options) {\n                        if (\n                          col.options.hasOwnProperty(key) &&\n                          col.options[key].default\n                        ) {\n                          return typeof col.options[key].value !== 'undefined'\n                            ? col.options[key].value\n                            : key;\n                        }\n                      }\n                      return null;\n                    })(),\n                  class: 'small',\n                })\n                .appendTo($cell);\n              break;\n\n            case 'time':\n              Craft.ui\n                .createTimeInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'email':\n            case 'url':\n              Craft.ui\n                .createTextInput({\n                  name: name,\n                  value: value,\n                  type: col.type,\n                  placeholder: col.placeholder || null,\n                })\n                .appendTo($cell);\n              break;\n\n            default:\n              $('<textarea/>', {\n                name: name,\n                rows: col.rows || 1,\n                val: value,\n                placeholder: col.placeholder,\n              }).appendTo($cell);\n          }\n        }\n\n        $cell.appendTo($tr);\n      }\n\n      $('<td/>', {\n        class: 'thin action',\n      })\n        .append(\n          $('<a/>', {\n            class: 'move icon',\n            title: Craft.t('app', 'Reorder'),\n          })\n        )\n        .appendTo($tr);\n\n      $('<td/>', {\n        class: 'thin action',\n      })\n        .append(\n          $('<button/>', {\n            class: 'delete icon',\n            title: Craft.t('app', 'Delete'),\n            type: 'button',\n          })\n        )\n        .appendTo($tr);\n\n      return $tr;\n    },\n  }\n);\n\n/**\n * Editable table row class\n */\nCraft.EditableTable.Row = Garnish.Base.extend(\n  {\n    table: null,\n    id: null,\n    niceTexts: null,\n\n    $tr: null,\n    $tds: null,\n    tds: null,\n    $textareas: null,\n    $deleteBtn: null,\n\n    init: function (table, tr) {\n      this.table = table;\n      this.$tr = $(tr);\n      this.$tds = this.$tr.children();\n      this.tds = [];\n      this.id = this.$tr.attr('data-id');\n\n      this.$tr.data('editable-table-row', this);\n\n      // Get the row ID, sans prefix\n      var id = parseInt(this.id.substr(this.table.settings.rowIdPrefix.length));\n\n      if (id > this.table.biggestId) {\n        this.table.biggestId = id;\n      }\n\n      this.$textareas = $();\n      this.niceTexts = [];\n      var textareasByColId = {};\n\n      var i = 0;\n      var colId, col, td, $textarea, $checkbox;\n\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n        td = this.tds[colId] = this.$tds[i];\n\n        if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n          $textarea = $('textarea', td);\n          this.$textareas = this.$textareas.add($textarea);\n\n          this.addListener($textarea, 'focus', 'onTextareaFocus');\n          this.addListener($textarea, 'mousedown', 'ignoreNextTextareaFocus');\n\n          this.niceTexts.push(\n            new Garnish.NiceText($textarea, {\n              onHeightChange: this.onTextareaHeightChange.bind(this),\n            })\n          );\n\n          this.addListener(\n            $textarea,\n            'keypress',\n            {tdIndex: i, type: col.type},\n            'handleKeypress'\n          );\n          this.addListener(\n            $textarea,\n            'input',\n            {type: col.type},\n            'validateValue'\n          );\n          $textarea.trigger('input');\n\n          if (col.type !== 'multiline') {\n            this.addListener(\n              $textarea,\n              'paste',\n              {tdIndex: i, type: col.type},\n              'handlePaste'\n            );\n          }\n\n          textareasByColId[colId] = $textarea;\n        } else if (col.type === 'checkbox') {\n          $checkbox = $('input[type=\"checkbox\"]', td);\n\n          if (col.radioMode) {\n            if (typeof this.table.radioCheckboxes[colId] === 'undefined') {\n              this.table.radioCheckboxes[colId] = [];\n            }\n            this.table.radioCheckboxes[colId].push($checkbox[0]);\n            this.addListener(\n              $checkbox,\n              'change',\n              {colId},\n              'onRadioCheckboxChange'\n            );\n          }\n\n          if (col.toggle) {\n            this.addListener($checkbox, 'change', {colId}, function (ev) {\n              this.applyToggleCheckbox(ev.data.colId);\n            });\n          }\n        }\n\n        if (!$(td).hasClass('disabled')) {\n          this.addListener(td, 'click', {td}, function (ev) {\n            if (ev.target === ev.data.td) {\n              $(ev.data.td).find('textarea,input,select,.lightswitch').focus();\n            }\n          });\n        }\n\n        i++;\n      }\n\n      // Now that all of the text cells have been nice-ified, let's normalize the heights\n      this.onTextareaHeightChange();\n\n      // See if we need to apply any checkbox toggles now that we've indexed all the TDs\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n        col = this.table.columns[colId];\n        if (col.type === 'checkbox' && col.toggle) {\n          this.applyToggleCheckbox(colId);\n        }\n      }\n\n      // Now look for any autopopulate columns\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n\n        if (\n          col.autopopulate &&\n          typeof textareasByColId[col.autopopulate] !== 'undefined' &&\n          !textareasByColId[colId].val()\n        ) {\n          new Craft.HandleGenerator(\n            textareasByColId[colId],\n            textareasByColId[col.autopopulate],\n            {\n              allowNonAlphaStart: true,\n            }\n          );\n        }\n      }\n\n      var $deleteBtn = this.$tr.children().last().find('.delete');\n      this.addListener($deleteBtn, 'click', 'deleteRow');\n\n      var $inputs = this.$tr.find('input,textarea,select,.lightswitch');\n      this.addListener($inputs, 'focus', function (ev) {\n        $(ev.currentTarget).closest('td:not(.disabled)').addClass('focus');\n      });\n      this.addListener($inputs, 'blur', function (ev) {\n        $(ev.currentTarget).closest('td').removeClass('focus');\n      });\n    },\n\n    onTextareaFocus: function (ev) {\n      this.onTextareaHeightChange();\n\n      var $textarea = $(ev.currentTarget);\n\n      if ($textarea.data('ignoreNextFocus')) {\n        $textarea.data('ignoreNextFocus', false);\n        return;\n      }\n\n      setTimeout(function () {\n        Craft.selectFullValue($textarea);\n      }, 0);\n    },\n\n    onRadioCheckboxChange: function (ev) {\n      if (ev.currentTarget.checked) {\n        for (\n          var i = 0;\n          i < this.table.radioCheckboxes[ev.data.colId].length;\n          i++\n        ) {\n          var checkbox = this.table.radioCheckboxes[ev.data.colId][i];\n          checkbox.checked = checkbox === ev.currentTarget;\n        }\n      }\n    },\n\n    applyToggleCheckbox: function (checkboxColId) {\n      var checkboxCol = this.table.columns[checkboxColId];\n      var checked = $('input[type=\"checkbox\"]', this.tds[checkboxColId]).prop(\n        'checked'\n      );\n      var colId, colIndex, neg;\n      for (var i = 0; i < checkboxCol.toggle.length; i++) {\n        colId = checkboxCol.toggle[i];\n        colIndex = this.table.colum;\n        neg = colId[0] === '!';\n        if (neg) {\n          colId = colId.substr(1);\n        }\n        if ((checked && !neg) || (!checked && neg)) {\n          $(this.tds[colId])\n            .removeClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', false);\n        } else {\n          $(this.tds[colId])\n            .addClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', true);\n        }\n      }\n    },\n\n    ignoreNextTextareaFocus: function (ev) {\n      $.data(ev.currentTarget, 'ignoreNextFocus', true);\n    },\n\n    handleKeypress: function (ev) {\n      var keyCode = ev.keyCode ? ev.keyCode : ev.charCode;\n      var ctrl = Garnish.isCtrlKeyPressed(ev);\n\n      // Going to the next/previous row?\n      if (\n        keyCode === Garnish.RETURN_KEY &&\n        (ev.data.type !== 'multiline' || ctrl)\n      ) {\n        ev.preventDefault();\n        if (ev.shiftKey) {\n          this.table.focusOnPrevRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        } else {\n          this.table.focusOnNextRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        }\n        return;\n      }\n\n      // Was this an invalid number character?\n      if (\n        ev.data.type === 'number' &&\n        !ctrl &&\n        !Craft.inArray(keyCode, Craft.EditableTable.Row.numericKeyCodes)\n      ) {\n        ev.preventDefault();\n      }\n    },\n\n    handlePaste: function (ev) {\n      let data = Craft.trim(\n        ev.originalEvent.clipboardData.getData('Text'),\n        ' \\n\\r'\n      );\n      if (!data.match(/[\\t\\r\\n]/)) {\n        return;\n      }\n      ev.preventDefault();\n      this.table.importData(data, this, ev.data.tdIndex);\n    },\n\n    validateValue: function (ev) {\n      if (ev.data.type === 'multiline') {\n        return;\n      }\n\n      var safeValue;\n\n      if (ev.data.type === 'number') {\n        // Only grab the number at the beginning of the value (if any)\n        var match = ev.currentTarget.value.match(/^\\s*(-?[\\d\\\\.]*)/);\n\n        if (match !== null) {\n          safeValue = match[1];\n        } else {\n          safeValue = '';\n        }\n      } else {\n        // Just strip any newlines\n        safeValue = ev.currentTarget.value.replace(/[\\r\\n]/g, '');\n      }\n\n      if (safeValue !== ev.currentTarget.value) {\n        ev.currentTarget.value = safeValue;\n      }\n    },\n\n    onTextareaHeightChange: function () {\n      // Keep all the textareas' heights in sync\n      var tallestTextareaHeight = -1;\n\n      for (var i = 0; i < this.niceTexts.length; i++) {\n        if (this.niceTexts[i].height > tallestTextareaHeight) {\n          tallestTextareaHeight = this.niceTexts[i].height;\n        }\n      }\n\n      this.$textareas.css('min-height', tallestTextareaHeight);\n\n      // If the <td> is still taller, go with that instead\n      var tdHeight = this.$textareas\n        .filter(':visible')\n        .first()\n        .parent()\n        .height();\n\n      if (tdHeight > tallestTextareaHeight) {\n        this.$textareas.css('min-height', tdHeight);\n      }\n    },\n\n    deleteRow: function () {\n      this.table.deleteRow(this);\n    },\n  },\n  {\n    numericKeyCodes: [\n      9 /* (tab) */, 8 /* (delete) */, 37, 38, 39, 40 /* (arrows) */, 45,\n      91 /* (minus) */, 46, 190 /* period */, 48, 49, 50, 51, 52, 53, 54, 55,\n      56, 57 /* (0-9) */,\n    ],\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Action Trigger\n */\nCraft.ElementActionTrigger = Garnish.Base.extend(\n  {\n    maxLevels: null,\n    newChildUrl: null,\n    $trigger: null,\n    $selectedItems: null,\n    triggerEnabled: true,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.ElementActionTrigger.defaults);\n\n      this.$trigger = $(\n        '#' + settings.type.replace(/[\\[\\]\\\\]+/g, '-') + '-actiontrigger'\n      );\n\n      // Do we have a custom handler?\n      if (this.settings.activate) {\n        // Prevent the element index's click handler\n        this.$trigger.data('custom-handler', true);\n\n        // Is this a custom trigger?\n        if (this.$trigger.prop('nodeName') === 'FORM') {\n          this.addListener(this.$trigger, 'submit', 'handleTriggerActivation');\n        } else {\n          this.addListener(this.$trigger, 'click', 'handleTriggerActivation');\n        }\n      }\n\n      this.updateTrigger();\n      Craft.elementIndex.on('selectionChange', this.updateTrigger.bind(this));\n    },\n\n    updateTrigger: function () {\n      // Ignore if the last element was just unselected\n      if (Craft.elementIndex.getSelectedElements().length === 0) {\n        return;\n      }\n\n      if (this.validateSelection()) {\n        this.enableTrigger();\n      } else {\n        this.disableTrigger();\n      }\n    },\n\n    /**\n     * Determines if this action can be performed on the currently selected elements.\n     *\n     * @return boolean\n     */\n    validateSelection: function () {\n      var valid = true;\n      this.$selectedItems = Craft.elementIndex.getSelectedElements();\n\n      if (!this.settings.batch && this.$selectedItems.length > 1) {\n        valid = false;\n      } else if (typeof this.settings.validateSelection === 'function') {\n        valid = this.settings.validateSelection(this.$selectedItems);\n      }\n\n      return valid;\n    },\n\n    enableTrigger: function () {\n      if (this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.removeClass('disabled');\n      this.triggerEnabled = true;\n    },\n\n    disableTrigger: function () {\n      if (!this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.addClass('disabled');\n      this.triggerEnabled = false;\n    },\n\n    handleTriggerActivation: function (ev) {\n      ev.preventDefault();\n      ev.stopPropagation();\n\n      if (this.triggerEnabled) {\n        this.settings.activate(this.$selectedItems);\n      }\n    },\n  },\n  {\n    defaults: {\n      type: null,\n      batch: true,\n      validateSelection: null,\n      activate: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.ElementThumbLoader = Garnish.Base.extend(\n  {\n    queue: null,\n    workers: [],\n\n    init: function () {\n      this.queue = [];\n\n      for (var i = 0; i < 3; i++) {\n        this.workers.push(new Craft.ElementThumbLoader.Worker(this));\n      }\n    },\n\n    load: function ($elements) {\n      // Only immediately load the visible images\n      let $thumbs = $elements.find('.elementthumb');\n      for (let i = 0; i < $thumbs.length; i++) {\n        let $thumb = $thumbs.eq(i);\n        let $scrollParent = $thumb.scrollParent();\n        if ($scrollParent.prop('nodeName') === 'FIELDSET') {\n          $scrollParent = $scrollParent.scrollParent();\n        }\n        if ($scrollParent[0] === document.body) {\n          $scrollParent = Garnish.$doc;\n        }\n        if (this.isVisible($thumb, $scrollParent)) {\n          this.addToQueue($thumb[0]);\n        } else {\n          let key = 'thumb' + Math.floor(Math.random() * 1000000);\n          Craft.ElementThumbLoader.invisibleThumbs[key] = [\n            this,\n            $thumb,\n            $scrollParent,\n          ];\n          $scrollParent.on(\n            `scroll.${key}`,\n            {\n              $thumb: $thumb,\n              $scrollParent: $scrollParent,\n              key: key,\n            },\n            (ev) => {\n              if (this.isVisible(ev.data.$thumb, ev.data.$scrollParent)) {\n                delete Craft.ElementThumbLoader.invisibleThumbs[ev.data.key];\n                $scrollParent.off(`scroll.${ev.data.key}`);\n                this.addToQueue(ev.data.$thumb[0]);\n              }\n            }\n          );\n        }\n      }\n    },\n\n    addToQueue: function (thumb) {\n      this.queue.push(thumb);\n\n      // See if there are any inactive workers\n      for (var i = 0; i < this.workers.length; i++) {\n        if (!this.workers[i].active) {\n          this.workers[i].loadNext();\n        }\n      }\n    },\n\n    isVisible: function ($thumb, $scrollParent) {\n      let thumbOffset = $thumb.offset().top;\n      let scrollParentOffset, scrollParentHeight;\n      if ($scrollParent[0] === document) {\n        scrollParentOffset = $scrollParent.scrollTop();\n        scrollParentHeight = Garnish.$win.height();\n      } else {\n        scrollParentOffset = $scrollParent.offset().top;\n        scrollParentHeight = $scrollParent.height();\n      }\n      return (\n        thumbOffset > scrollParentOffset &&\n        thumbOffset < scrollParentOffset + scrollParentHeight + 1000\n      );\n    },\n\n    destroy: function () {\n      for (var i = 0; i < this.workers.length; i++) {\n        this.workers[i].destroy();\n      }\n\n      this.base();\n    },\n  },\n  {\n    invisibleThumbs: {},\n    retryAll: function () {\n      for (let key in Craft.ElementThumbLoader.invisibleThumbs) {\n        let [queue, $thumb, $scrollParent] =\n          Craft.ElementThumbLoader.invisibleThumbs[key];\n        delete Craft.ElementThumbLoader.invisibleThumbs[key];\n        $scrollParent.off(`scroll.${key}`);\n        queue.load($thumb.parent());\n      }\n    },\n  }\n);\n\nCraft.ElementThumbLoader.Worker = Garnish.Base.extend({\n  loader: null,\n  active: false,\n\n  init: function (loader) {\n    this.loader = loader;\n  },\n\n  loadNext: function () {\n    var container = this.loader.queue.shift();\n    if (typeof container === 'undefined') {\n      this.active = false;\n      return;\n    }\n\n    this.active = true;\n    var $container = $(container);\n    if ($container.find('img').length) {\n      this.loadNext();\n      return;\n    }\n    var $img = $('<img/>', {\n      sizes: $container.attr('data-sizes'),\n      srcset: $container.attr('data-srcset'),\n      alt: '',\n    });\n    this.addListener($img, 'load,error', 'loadNext');\n    $img.appendTo($container);\n    picturefill({\n      elements: [$img[0]],\n    });\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Form\n */\nCraft.ElevatedSessionForm = Garnish.Base.extend({\n  $form: null,\n  inputs: null,\n\n  init: function (form, inputs) {\n    this.$form = $(form);\n\n    // Only check specific inputs?\n    if (typeof inputs !== 'undefined') {\n      this.inputs = [];\n      inputs = $.makeArray(inputs);\n\n      for (var i = 0; i < inputs.length; i++) {\n        var $inputs = $(inputs[i]);\n\n        for (var j = 0; j < $inputs.length; j++) {\n          var $input = $inputs.eq(j);\n\n          this.inputs.push({\n            input: $input,\n            val: Garnish.getInputPostVal($input),\n          });\n        }\n      }\n    }\n\n    this.addListener(this.$form, 'submit', 'handleFormSubmit');\n  },\n\n  handleFormSubmit: function (ev) {\n    // Ignore if we're in the middle of getting the elevated session timeout\n    if (Craft.elevatedSessionManager.fetchingTimeout) {\n      ev.preventDefault();\n      ev.stopImmediatePropagation();\n      return;\n    }\n\n    // Are we only interested in certain inputs?\n    if (this.inputs) {\n      var inputsChanged = false;\n      var $input;\n\n      for (var i = 0; i < this.inputs.length; i++) {\n        $input = this.inputs[i].input;\n        // Is this a password input?\n        if ($input.data('passwordInput')) {\n          $input = $input.data('passwordInput').$currentInput;\n        }\n\n        // Has this input's value changed?\n        if (Garnish.getInputPostVal($input) !== this.inputs[i].val) {\n          inputsChanged = true;\n          break;\n        }\n      }\n\n      if (!inputsChanged) {\n        // No need to interrupt the submit\n        return;\n      }\n    }\n\n    // Prevent the form from submitting until the user has an elevated session\n    ev.preventDefault();\n    ev.stopImmediatePropagation();\n    Craft.elevatedSessionManager.requireElevatedSession(\n      this.submitForm.bind(this)\n    );\n  },\n\n  submitForm: function () {\n    // Don't let handleFormSubmit() interrupt this time\n    this.disable();\n    this.$form.trigger('submit');\n    this.enable();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Manager\n */\nCraft.ElevatedSessionManager = Garnish.Base.extend(\n  {\n    fetchingTimeout: false,\n\n    passwordModal: null,\n    $passwordInput: null,\n    $passwordSpinner: null,\n    $submitBtn: null,\n    $errorPara: null,\n\n    callback: null,\n\n    /**\n     * Requires that the user has an elevated session.\n     *\n     * @param {function} callback The callback function that should be called once the user has an elevated session\n     */\n    requireElevatedSession: function (callback) {\n      this.callback = callback;\n\n      // Check the time remaining on the user's elevated session (if any)\n      this.fetchingTimeout = true;\n\n      Craft.postActionRequest(\n        'users/get-elevated-session-timeout',\n        (response, textStatus) => {\n          this.fetchingTimeout = false;\n\n          if (textStatus === 'success') {\n            // Is there still enough time left or has it been disabled?\n            if (\n              response.timeout === false ||\n              response.timeout >=\n                Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout\n            ) {\n              this.callback();\n            } else {\n              // Show the password modal\n              this.showPasswordModal();\n            }\n          }\n        }\n      );\n    },\n\n    showPasswordModal: function () {\n      if (!this.passwordModal) {\n        var $passwordModal = $(\n            '<form id=\"elevatedsessionmodal\" class=\"modal secure fitted\"/>'\n          ),\n          $body = $(\n            '<div class=\"body\"><p>' +\n              Craft.t('app', 'Enter your password to continue.') +\n              '</p></div>'\n          ).appendTo($passwordModal),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<td/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\" autocomplete=\"current-password\"/>'\n        ).appendTo($passwordWrapper);\n        this.$passwordSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n          $inputContainer\n        );\n        this.$submitBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit disabled',\n          text: Craft.t('app', 'Submit'),\n        }).appendTo($buttonContainer);\n        this.$errorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.passwordModal = new Garnish.Modal($passwordModal, {\n          closeOtherModals: false,\n          onFadeIn: () => {\n            setTimeout(this.focusPasswordInput.bind(this), 100);\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($passwordModal, 'submit', 'submitPassword');\n      } else {\n        this.passwordModal.show();\n      }\n    },\n\n    focusPasswordInput: function () {\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$passwordInput.trigger('focus');\n      }\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$submitBtn.removeClass('disabled');\n        return true;\n      } else {\n        this.$submitBtn.addClass('disabled');\n        return false;\n      }\n    },\n\n    submitPassword: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (!this.validatePassword()) {\n        return;\n      }\n\n      this.$passwordSpinner.removeClass('hidden');\n      this.clearLoginError();\n\n      var data = {\n        currentPassword: this.$passwordInput.val(),\n      };\n\n      Craft.postActionRequest(\n        'users/start-elevated-session',\n        data,\n        (response, textStatus) => {\n          this.$passwordSpinner.addClass('hidden');\n\n          if (textStatus === 'success') {\n            if (response.success) {\n              this.passwordModal.hide();\n              this.callback();\n            } else {\n              this.showPasswordError(\n                response.message || Craft.t('app', 'Incorrect password.')\n              );\n              Garnish.shake(this.passwordModal.$container);\n              this.focusPasswordInput();\n            }\n          } else {\n            this.showPasswordError();\n          }\n        }\n      );\n    },\n\n    showPasswordError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$errorPara.text(error);\n      this.passwordModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showPasswordError('');\n    },\n  },\n  {\n    minSafeElevatedSessionTimeout: 5,\n  }\n);\n\n// Instantiate it\nCraft.elevatedSessionManager = new Craft.ElevatedSessionManager();\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Entry index class\n */\nCraft.EntryIndex = Craft.BaseElementIndex.extend({\n  publishableSections: null,\n  $newEntryBtnGroup: null,\n  $newEntryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible sections the user has permission to create new entries in\n    this.publishableSections = [];\n\n    for (var i = 0; i < Craft.publishableSections.length; i++) {\n      var section = Craft.publishableSections[i];\n\n      if (this.getSourceByKey('section:' + section.uid)) {\n        this.publishableSections.push(section);\n      }\n    }\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific section in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSectionHandle !== 'undefined'\n    ) {\n      if (defaultSectionHandle === 'singles') {\n        return 'singles';\n      } else {\n        for (var i = 0; i < this.$sources.length; i++) {\n          var $source = $(this.$sources[i]);\n\n          if ($source.data('handle') === defaultSectionHandle) {\n            return $source.data('key');\n          }\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    var handle;\n\n    // Get the handle of the selected source\n    if (this.$source.data('key') === 'singles') {\n      handle = 'singles';\n    } else {\n      handle = this.$source.data('handle');\n    }\n\n    // Update the New Entry button\n    // ---------------------------------------------------------------------\n\n    var i, href, label;\n\n    if (this.publishableSections.length) {\n      // Remove the old button, if there is one\n      if (this.$newEntryBtnGroup) {\n        this.$newEntryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a section that they have permission to create entries in\n      var selectedSection;\n\n      if (handle) {\n        for (i = 0; i < this.publishableSections.length; i++) {\n          if (this.publishableSections[i].handle === handle) {\n            selectedSection = this.publishableSections[i];\n            break;\n          }\n        }\n      }\n\n      this.$newEntryBtnGroup = $('<div class=\"btngroup submit\"/>');\n      var $menuBtn;\n\n      // If they are, show a primary \"New entry\" button, and a dropdown of the other sections (if any).\n      // Otherwise only show a menu button\n      if (selectedSection) {\n        href = this._getSectionTriggerHref(selectedSection);\n        label =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New entry')\n            : Craft.t('app', 'New {section} entry', {\n                section: selectedSection.name,\n              });\n        this.$newEntryBtn = $(\n          '<a class=\"btn submit add icon\" ' +\n            href +\n            ' role=\"button\" tabindex=\"0\">' +\n            Craft.escapeHtml(label) +\n            '</a>'\n        ).appendTo(this.$newEntryBtnGroup);\n\n        if (this.settings.context !== 'index') {\n          this.addListener(this.$newEntryBtn, 'click', function (ev) {\n            this._openCreateEntryModal(\n              ev.currentTarget.getAttribute('data-id')\n            );\n          });\n        }\n\n        if (this.publishableSections.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn',\n          }).appendTo(this.$newEntryBtnGroup);\n        }\n      } else {\n        this.$newEntryBtn = $menuBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit add icon menubtn',\n          text: Craft.t('app', 'New entry'),\n        }).appendTo(this.$newEntryBtnGroup);\n      }\n\n      if ($menuBtn) {\n        var menuHtml = '<div class=\"menu\"><ul>';\n\n        for (i = 0; i < this.publishableSections.length; i++) {\n          var section = this.publishableSections[i];\n\n          if (\n            (this.settings.context === 'index' &&\n              $.inArray(this.siteId, section.sites) !== -1) ||\n            (this.settings.context !== 'index' && section !== selectedSection)\n          ) {\n            href = this._getSectionTriggerHref(section);\n            label =\n              this.settings.context === 'index'\n                ? section.name\n                : Craft.t('app', 'New {section} entry', {\n                    section: section.name,\n                  });\n            menuHtml +=\n              '<li><a ' + href + '>' + Craft.escapeHtml(label) + '</a></li>';\n          }\n        }\n\n        menuHtml += '</ul></div>';\n\n        $(menuHtml).appendTo(this.$newEntryBtnGroup);\n        var menuBtn = new Garnish.MenuBtn($menuBtn);\n\n        if (this.settings.context !== 'index') {\n          menuBtn.on('optionSelect', (ev) => {\n            this._openCreateEntryModal(ev.option.getAttribute('data-id'));\n          });\n        }\n      }\n\n      this.addButton(this.$newEntryBtnGroup);\n    }\n\n    // Update the URL if we're on the Entries index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index' && typeof history !== 'undefined') {\n      var uri = 'entries';\n\n      if (handle) {\n        uri += '/' + handle;\n      }\n\n      history.replaceState({}, '', Craft.getUrl(uri));\n    }\n  },\n\n  _getSectionTriggerHref: function (section) {\n    if (this.settings.context === 'index') {\n      const uri = `entries/${section.handle}/new`;\n      const site = this.getSite();\n      const params = site ? {site: site.handle} : undefined;\n      return `href=\"${Craft.getUrl(uri, params)}\"`;\n    }\n\n    return `data-id=\"${section.id}\"`;\n  },\n\n  _openCreateEntryModal: function (sectionId) {\n    if (this.$newEntryBtn.hasClass('loading')) {\n      return;\n    }\n\n    // Find the section\n    var section;\n\n    for (var i = 0; i < this.publishableSections.length; i++) {\n      if (this.publishableSections[i].id == sectionId) {\n        section = this.publishableSections[i];\n        break;\n      }\n    }\n\n    if (!section) {\n      return;\n    }\n\n    this.$newEntryBtn.addClass('inactive');\n    var newEntryBtnText = this.$newEntryBtn.text();\n    this.$newEntryBtn.text(\n      Craft.t('app', 'New {section} entry', {section: section.name})\n    );\n\n    Craft.createElementEditor(this.elementType, {\n      hudTrigger: this.$newEntryBtnGroup,\n      siteId: this.siteId,\n      attributes: {\n        sectionId: sectionId,\n        typeId: section.entryTypes[0].id,\n        enabled: section.canPublish ? 1 : 0,\n      },\n      onHideHud: () => {\n        this.$newEntryBtn.removeClass('inactive').text(newEntryBtnText);\n      },\n      onSaveElement: (response) => {\n        // Make sure the right section is selected\n        var sectionSourceKey = 'section:' + section.uid;\n\n        if (this.sourceKey !== sectionSourceKey) {\n          this.selectSourceByKey(sectionSourceKey);\n        }\n\n        this.clearSearch();\n        this.setSortAttribute('dateCreated');\n        this.setSortDirection('desc');\n        this.selectElementAfterUpdate(response.id);\n        this.updateElements();\n      },\n    });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Entry', Craft.EntryIndex);\n","/** global: Craft */\n/** global: Garnish */\nCraft.FieldLayoutDesigner = Garnish.Base.extend(\n  {\n    $container: null,\n    $tabContainer: null,\n    $newTabBtn: null,\n    $sidebar: null,\n    $libraryToggle: null,\n    $selectedLibrary: null,\n    $fieldLibrary: null,\n    $uiLibrary: null,\n    $uiLibraryElements: null,\n    $fieldSearch: null,\n    $clearFieldSearchBtn: null,\n    $fieldGroups: null,\n    $fields: null,\n\n    tabGrid: null,\n    elementDrag: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.FieldLayoutDesigner.defaults);\n\n      let $workspace = this.$container.children('.fld-workspace');\n      this.$tabContainer = $workspace.children('.fld-tabs');\n      this.$newTabBtn = $workspace.children('.fld-new-tab-btn');\n      this.$sidebar = this.$container.children('.fld-sidebar');\n\n      this.$fieldLibrary = this.$selectedLibrary =\n        this.$sidebar.children('.fld-field-library');\n      let $fieldSearchContainer = this.$fieldLibrary.children('.search');\n      this.$fieldSearch = $fieldSearchContainer.children('input');\n      this.$clearFieldSearchBtn = $fieldSearchContainer.children('.clear');\n      this.$fieldGroups = this.$sidebar.find('.fld-field-group');\n      this.$fields = this.$fieldGroups.children('.fld-element');\n      this.$uiLibrary = this.$sidebar.children('.fld-ui-library');\n      this.$uiLibraryElements = this.$uiLibrary.children();\n\n      // Set up the layout grids\n      this.tabGrid = new Craft.Grid(this.$tabContainer, {\n        itemSelector: '.fld-tab',\n        minColWidth: 24 * 11,\n        fillMode: 'grid',\n        snapToGrid: 24,\n      });\n\n      let $tabs = this.$tabContainer.children();\n      for (let i = 0; i < $tabs.length; i++) {\n        this.initTab($($tabs[i]));\n      }\n\n      // create a placeholder input so *something* gets posted even if there are no tabs/elements\n      $('<input/>', {\n        type: 'hidden',\n        name: this.settings.elementPlacementInputName.replace(\n          '[__TAB_NAME__][]',\n          ''\n        ),\n        value: '',\n      }).insertBefore(this.$container);\n\n      this.elementDrag = new Craft.FieldLayoutDesigner.ElementDrag(this);\n\n      if (this.settings.customizableTabs) {\n        this.tabDrag = new Craft.FieldLayoutDesigner.TabDrag(this);\n\n        this.addListener(this.$newTabBtn, 'activate', 'addTab');\n      }\n\n      // Set up the sidebar\n      if (this.settings.customizableUi) {\n        let $libraryPicker = this.$sidebar.children('.btngroup');\n        new Craft.Listbox($libraryPicker, {\n          onChange: ($selectedOption) => {\n            this.$selectedLibrary.addClass('hidden');\n            this.$selectedLibrary =\n              this[`$${$selectedOption.data('library')}Library`].removeClass(\n                'hidden'\n              );\n          },\n        });\n      }\n\n      this.addListener(this.$fieldSearch, 'input', () => {\n        let val = this.$fieldSearch.val().toLowerCase().replace(/['\"]/g, '');\n        if (!val) {\n          this.$fieldLibrary.find('.filtered').removeClass('filtered');\n          this.$clearFieldSearchBtn.addClass('hidden');\n          return;\n        }\n\n        this.$clearFieldSearchBtn.removeClass('hidden');\n        let $matches = this.$fields\n          .filter(`[data-keywords*=\"${val}\"]`)\n          .add(\n            this.$fieldGroups\n              .filter(`[data-name*=\"${val}\"]`)\n              .children('.fld-element')\n          )\n          .removeClass('filtered');\n        this.$fields.not($matches).addClass('filtered');\n\n        // hide any groups that don't have any results\n        for (let i = 0; i < this.$fieldGroups.length; i++) {\n          let $group = this.$fieldGroups.eq(i);\n          if ($group.find('.fld-element:not(.hidden):not(.filtered)').length) {\n            $group.removeClass('filtered');\n          } else {\n            $group.addClass('filtered');\n          }\n        }\n      });\n\n      this.addListener(this.$fieldSearch, 'keydown', (ev) => {\n        switch (ev.keyCode) {\n          case Garnish.ESC_KEY:\n            this.$fieldSearch.val('').trigger('input');\n            break;\n          case Garnish.RETURN_KEY:\n            // they most likely don't want to submit the form from here\n            ev.preventDefault();\n            break;\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearFieldSearchBtn, 'click', () => {\n        this.$fieldSearch.val('').trigger('input');\n      });\n    },\n\n    initTab: function ($tab) {\n      if (this.settings.customizableTabs) {\n        let $editBtn = $tab.find('.tabs .settings');\n        $('<div class=\"menu\" data-align=\"center\"/>')\n          .insertAfter($editBtn)\n          .append(\n            $('<ul/>')\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'rename',\n                    text: Craft.t('app', 'Rename'),\n                  })\n                )\n              )\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'remove',\n                    text: Craft.t('app', 'Remove'),\n                  })\n                )\n              )\n          )\n          .append($('<hr/>'))\n          .append(\n            $('<ul/>')\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'moveLeft',\n                    text: Craft.t('app', 'Move to the left'),\n                  })\n                )\n              )\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'moveRight',\n                    text: Craft.t('app', 'Move to the right'),\n                  })\n                )\n              )\n          );\n\n        let menuBtn = new Garnish.MenuBtn($editBtn, {\n          onOptionSelect: this.onTabOptionSelect.bind(this),\n        });\n        menuBtn.menu.on('show', () => {\n          if ($tab.prev('.fld-tab').length) {\n            menuBtn.menu.$container\n              .find('[data-action=moveLeft]')\n              .removeClass('disabled');\n          } else {\n            menuBtn.menu.$container\n              .find('[data-action=moveLeft]')\n              .addClass('disabled');\n          }\n\n          if ($tab.next('.fld-tab').length) {\n            menuBtn.menu.$container\n              .find('[data-action=moveRight]')\n              .removeClass('disabled');\n          } else {\n            menuBtn.menu.$container\n              .find('[data-action=moveRight]')\n              .addClass('disabled');\n          }\n        });\n      }\n\n      // initialize the elements\n      let $elements = $tab.children('.fld-tabcontent').children();\n\n      for (let i = 0; i < $elements.length; i++) {\n        this.initElement($($elements[i]));\n      }\n    },\n\n    initElement: function ($element) {\n      new Craft.FieldLayoutDesigner.Element(this, $element);\n    },\n\n    onTabOptionSelect: function (option) {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      let $option = $(option);\n      let $tab = $option.data('menu').$anchor.parent().parent().parent();\n      let action = $option.data('action');\n\n      switch (action) {\n        case 'rename':\n          this.renameTab($tab);\n          break;\n        case 'remove':\n          this.removeTab($tab);\n          break;\n        case 'moveLeft':\n          let $prev = $tab.prev('.fld-tab');\n          if ($prev.length) {\n            $tab.insertBefore($prev);\n          }\n          break;\n        case 'moveRight':\n          let $next = $tab.next('.fld-tab');\n          if ($next.length) {\n            $tab.insertAfter($next);\n          }\n          break;\n      }\n    },\n\n    renameTab: function ($tab) {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      const $labelSpan = $tab.find('.tabs .tab span');\n      const oldName = $labelSpan.text();\n      const newName = this.promptForTabName(oldName);\n\n      if (newName && newName !== oldName) {\n        $labelSpan.text(newName);\n        $tab\n          .find('.placement-input')\n          .attr('name', this.getElementPlacementInputName(newName));\n      }\n    },\n\n    promptForTabName: function (oldName) {\n      return Craft.escapeHtml(\n        prompt(Craft.t('app', 'Give your tab a name.'), oldName)\n      );\n    },\n\n    removeTab: function ($tab) {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      // Find all the fields in this tab\n      let $fields = $tab.find('.fld-element');\n\n      for (let i = 0; i < $fields.length; i++) {\n        let attribute = $($fields[i]).attr('data-attribute');\n        this.removeFieldByHandle(attribute);\n      }\n\n      this.tabGrid.removeItems($tab);\n      this.tabDrag.removeItems($tab);\n\n      $tab.remove();\n    },\n\n    removeField: function ($field) {\n      let attribute = $field.attr('data-attribute');\n\n      $field.remove();\n\n      this.removeFieldByHandle(attribute);\n      this.tabGrid.refreshCols(true);\n    },\n\n    removeFieldByHandle: function (attribute) {\n      this.$fields\n        .filter(`[data-attribute=\"${attribute}\"]:first`)\n        .removeClass('hidden')\n        .closest('.fld-field-group')\n        .removeClass('hidden');\n    },\n\n    addTab: function () {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      const name = this.promptForTabName();\n      if (!name) {\n        return;\n      }\n\n      const $tab = $(`\n<div class=\"fld-tab\">\n  <div class=\"tabs\">\n    <div class=\"tab sel draggable\">\n      <span>${name}</span>\n      <a class=\"settings icon\" title=\"${Craft.t('app', 'Rename')}\"></a>\n    </div>\n  </div>\n  <div class=\"fld-tabcontent\"></div>\n</div>\n`).appendTo(this.$tabContainer);\n\n      this.tabGrid.addItems($tab);\n      this.tabDrag.addItems($tab);\n\n      this.initTab($tab);\n    },\n\n    getElementPlacementInputName: function (tabName) {\n      return this.settings.elementPlacementInputName.replace(\n        /__TAB_NAME__/g,\n        Craft.encodeUriComponent(tabName)\n      );\n    },\n  },\n  {\n    defaults: {\n      customizableTabs: true,\n      customizableUi: true,\n      elementPlacementInputName: 'elementPlacements[__TAB_NAME__][]',\n      elementConfigInputName: 'elementConfigs[__ELEMENT_KEY__]',\n    },\n  }\n);\n\nCraft.FieldLayoutDesigner.Element = Garnish.Base.extend({\n  designer: null,\n  $container: null,\n  $placementInput: null,\n  $configInput: null,\n  $settingsContainer: null,\n  $editBtn: null,\n\n  config: null,\n  isField: false,\n  attribute: null,\n  requirable: false,\n  key: null,\n  hasCustomWidth: false,\n  hasSettings: false,\n  hud: null,\n\n  init: function (designer, $container) {\n    this.designer = designer;\n    this.$container = $container;\n    this.$container.data('fld-element', this);\n\n    this.config = this.$container.data('config');\n    if (!$.isPlainObject(this.config)) {\n      this.config = {};\n    }\n    this.config.type = this.$container.data('type');\n\n    this.isField = this.$container.hasClass('fld-field');\n    this.requirable =\n      this.isField && Garnish.hasAttr(this.$container, 'data-requirable');\n    this.key = Craft.randomString(10);\n\n    if (this.isField) {\n      this.attribute = this.$container.data('attribute');\n    }\n\n    let settingsHtml = this.$container.data('settings-html');\n    let isRequired =\n      this.requirable && this.$container.hasClass('fld-required');\n    this.hasCustomWidth =\n      this.designer.settings.customizableUi &&\n      Garnish.hasAttr(this.$container, 'data-has-custom-width');\n    this.hasSettings = settingsHtml || this.requirable;\n\n    if (this.hasSettings) {\n      // swap the __ELEMENT_KEY__ placeholder for the actual element key\n      settingsHtml = settingsHtml\n        ? settingsHtml.replace(/\\b__ELEMENT_KEY__\\b/g, this.key)\n        : '';\n\n      // create the setting container\n      this.$settingsContainer = $('<div/>', {\n        class: 'hidden',\n      });\n\n      // create the edit button\n      this.$editBtn = $('<a/>', {\n        role: 'button',\n        tabindex: 0,\n        class: 'settings icon',\n        title: Craft.t('app', 'Edit'),\n      });\n\n      this.$editBtn.on('click', () => {\n        if (!this.hud) {\n          this.createSettingsHud(settingsHtml, isRequired);\n        } else {\n          this.hud.show();\n          this.hud.updateSizeAndPosition(true);\n        }\n      });\n    }\n\n    this.initUi();\n\n    // cleanup\n    this.$container.attr('data-config', null);\n    this.$container.attr('data-keywords', null);\n    this.$container.attr('data-settings-html', null);\n  },\n\n  initUi: function () {\n    this.$placementInput = $('<input/>', {\n      class: 'placement-input',\n      type: 'hidden',\n      name: '',\n      value: this.key,\n    }).appendTo(this.$container);\n    this.updatePlacementInput();\n\n    this.$configInput = $('<input/>', {\n      type: 'hidden',\n      name: this.designer.settings.elementConfigInputName.replace(\n        /\\b__ELEMENT_KEY__\\b/g,\n        this.key\n      ),\n    }).appendTo(this.$container);\n    this.updateConfigInput();\n\n    if (this.hasCustomWidth) {\n      let widthSlider = new Craft.SlidePicker(this.config.width || 100, {\n        min: 25,\n        max: 100,\n        step: 25,\n        valueLabel: (width) => {\n          return Craft.t('app', '{pct} width', {pct: `${width}%`});\n        },\n        onChange: (width) => {\n          this.config.width = width;\n          this.updateConfigInput();\n        },\n      });\n      widthSlider.$container.appendTo(this.$container);\n    }\n\n    if (this.hasSettings) {\n      this.$editBtn.appendTo(this.$container);\n    }\n  },\n\n  createSettingsHud: function (settingsHtml, isRequired) {\n    let bodyHtml = `\n<div class=\"fld-element-settings\">\n  ${settingsHtml}\n  <div class=\"hud-footer\">\n    <div class=\"buttons right\">\n      <button class=\"btn submit\" type=\"submit\">${Craft.t(\n        'app',\n        'Apply'\n      )}</button>\n      <div class=\"spinner hidden\"></div>\n    </div>\n  </div>\n</div>\n`;\n    this.hud = new Garnish.HUD(this.$container, bodyHtml, {\n      onShow: (e) => {\n        // Hold off a sec until it's positioned...\n        Garnish.requestAnimationFrame(() => {\n          // Focus on the first text input\n          this.hud.$main.find('.text:first').trigger('focus');\n        });\n      },\n      onSubmit: () => {\n        this.applyHudSettings();\n      },\n    });\n\n    Craft.initUiElements(this.hud.$main);\n\n    if (this.requirable) {\n      let $lightswitchField = Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Required'),\n          id: `${this.key}-required`,\n          name: 'required',\n          on: isRequired,\n        })\n        .prependTo(this.hud.$main);\n    }\n\n    this.trigger('createSettingsHud');\n  },\n\n  applyHudSettings: function () {\n    this.hud.$body.serializeArray().forEach(({name, value}) => {\n      this.config[name] = value;\n    });\n    this.updateConfigInput();\n\n    // update the UI\n    let $spinner = this.hud.$body.find('.spinner').removeClass('hidden');\n\n    Craft.sendActionRequest('POST', 'fields/render-layout-element-selector', {\n      data: {\n        config: this.config,\n      },\n    })\n      .then((response) => {\n        $spinner.addClass('hidden');\n        this.$editBtn.detach();\n        this.$container.html($(response.data.html).html());\n        this.initUi();\n        this.updateRequiredClass();\n        this.hud.hide();\n      })\n      .catch((e) => {\n        // oh well, not worth fussing over\n        console.error(e);\n        $spinner.addClass('hidden');\n        this.updateRequiredClass();\n        this.hud.hide();\n      });\n  },\n\n  updatePlacementInput: function () {\n    let $tab = this.$container.closest('.fld-tab').find('.tab span');\n    if (!$tab.length) {\n      return;\n    }\n    let inputName = this.designer.getElementPlacementInputName($tab.text());\n    this.$placementInput.attr('name', inputName);\n  },\n\n  updateConfigInput: function () {\n    this.$configInput.val(JSON.stringify(this.config));\n  },\n\n  updateRequiredClass: function () {\n    if (!this.requirable) {\n      return;\n    }\n\n    if (this.config.required) {\n      this.$container.addClass('fld-required');\n    } else {\n      this.$container.removeClass('fld-required');\n    }\n  },\n});\n\nCraft.FieldLayoutDesigner.BaseDrag = Garnish.Drag.extend({\n  designer: null,\n  $insertion: null,\n  showingInsertion: false,\n  $caboose: null,\n\n  /**\n   * Constructor\n   */\n  init: function (designer, settings) {\n    this.designer = designer;\n    this.base(this.findItems(), settings);\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n\n    // Create the insertion\n    this.$insertion = this.createInsertion();\n\n    // Add the caboose\n    this.$caboose = this.createCaboose();\n    this.$items = $().add(this.$items.add(this.$caboose));\n\n    Garnish.$bod.addClass('dragging');\n  },\n\n  removeCaboose: function () {\n    this.$items = this.$items.not(this.$caboose);\n    this.$caboose.remove();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.$insertion.insertBefore(this.$draggee);\n    this.$draggee.detach();\n    this.$items = $().add(this.$items.not(this.$draggee).add(this.$insertion));\n    this.showingInsertion = true;\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.$insertion.replaceWith(this.$draggee);\n    this.$items = $().add(this.$items.not(this.$insertion).add(this.$draggee));\n    this.showingInsertion = false;\n  },\n\n  /**\n   * Sets the item midpoints up front so we don't have to keep checking on every mouse move\n   */\n  setMidpoints: function () {\n    for (let i = 0; i < this.$items.length; i++) {\n      let $item = $(this.$items[i]);\n      let offset = $item.offset();\n\n      // Skip library elements\n      if ($item.hasClass('unused')) {\n        continue;\n      }\n\n      $item.data('midpoint', {\n        left: offset.left + $item.outerWidth() / 2,\n        top: offset.top + $item.outerHeight() / 2,\n      });\n    }\n  },\n\n  /**\n   * Returns the closest item to the cursor.\n   */\n  getClosestItem: function () {\n    this.getClosestItem._closestItem = null;\n    this.getClosestItem._closestItemMouseDiff = null;\n\n    for (\n      this.getClosestItem._i = 0;\n      this.getClosestItem._i < this.$items.length;\n      this.getClosestItem._i++\n    ) {\n      this.getClosestItem._$item = $(this.$items[this.getClosestItem._i]);\n\n      this.getClosestItem._midpoint =\n        this.getClosestItem._$item.data('midpoint');\n      if (!this.getClosestItem._midpoint) {\n        continue;\n      }\n\n      this.getClosestItem._mouseDiff = Garnish.getDist(\n        this.getClosestItem._midpoint.left,\n        this.getClosestItem._midpoint.top,\n        this.mouseX,\n        this.mouseY\n      );\n\n      if (\n        this.getClosestItem._closestItem === null ||\n        this.getClosestItem._mouseDiff <\n          this.getClosestItem._closestItemMouseDiff\n      ) {\n        this.getClosestItem._closestItem = this.getClosestItem._$item[0];\n        this.getClosestItem._closestItemMouseDiff =\n          this.getClosestItem._mouseDiff;\n      }\n    }\n\n    return this.getClosestItem._closestItem;\n  },\n\n  checkForNewClosestItem: function () {\n    // Is there a new closest item?\n    this.checkForNewClosestItem._closestItem = this.getClosestItem();\n\n    if (this.checkForNewClosestItem._closestItem === this.$insertion[0]) {\n      return;\n    }\n\n    if (\n      this.showingInsertion &&\n      $.inArray(this.$insertion[0], this.$items) <\n        $.inArray(this.checkForNewClosestItem._closestItem, this.$items) &&\n      $.inArray(this.checkForNewClosestItem._closestItem, this.$caboose) === -1\n    ) {\n      this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem);\n    } else {\n      this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem);\n    }\n\n    this.$items = $().add(this.$items.add(this.$insertion));\n    this.showingInsertion = true;\n    this.designer.tabGrid.refreshCols(true);\n    this.setMidpoints();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    if (this.showingInsertion) {\n      this.swapInsertionWithDraggee();\n    }\n\n    this.removeCaboose();\n\n    this.designer.tabGrid.refreshCols(true);\n\n    // return the helpers to the draggees\n    let offset = this.$draggee.offset();\n    if (!offset || (offset.top === 0 && offset.left === 0)) {\n      this.$draggee\n        .css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n          opacity: 0,\n        })\n        .velocity({opacity: 1}, Garnish.FX_DURATION);\n      this.helpers[0].velocity({opacity: 0}, Garnish.FX_DURATION, () => {\n        this._showDraggee();\n      });\n    } else {\n      this.returnHelpersToDraggees();\n    }\n\n    this.base();\n\n    Garnish.$bod.removeClass('dragging');\n  },\n});\n\nCraft.FieldLayoutDesigner.TabDrag = Craft.FieldLayoutDesigner.BaseDrag.extend({\n  /**\n   * Constructor\n   */\n  init: function (designer) {\n    let settings = {\n      handle: '.tab',\n    };\n\n    this.base(designer, settings);\n  },\n\n  findItems: function () {\n    return this.designer.$tabContainer.find('> div.fld-tab');\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n    this.swapDraggeeWithInsertion();\n    this.setMidpoints();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$draggee);\n    this.designer.tabGrid.addItems(this.$insertion);\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$insertion);\n    this.designer.tabGrid.addItems(this.$draggee);\n  },\n\n  /**\n   * On Drag\n   */\n  onDrag: function () {\n    this.checkForNewClosestItem();\n    this.base();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    this.base();\n\n    // \"show\" the tab, but make it invisible\n    this.$draggee.css({\n      display: this.draggeeDisplay,\n      visibility: 'hidden',\n    });\n  },\n\n  /**\n   * Creates the caboose\n   */\n  createCaboose: function () {\n    let $caboose = $('<div class=\"fld-tab fld-tab-caboose\"/>').appendTo(\n      this.designer.$tabContainer\n    );\n    this.designer.tabGrid.addItems($caboose);\n    return $caboose;\n  },\n\n  /**\n   * Removes the caboose\n   */\n  removeCaboose: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$caboose);\n  },\n\n  /**\n   * Creates the insertion\n   */\n  createInsertion: function () {\n    let $tab = this.$draggee.find('.tab');\n\n    return $(`\n<div class=\"fld-tab fld-insertion\" style=\"height: ${this.$draggee.height()}px;\">\n  <div class=\"tabs\"><div class=\"tab sel draggable\" style=\"width: ${$tab.width()}px; height: ${$tab.height()}px;\"></div></div>\n  <div class=\"fld-tabcontent\" style=\"height: ${this.$draggee\n    .find('.fld-tabcontent')\n    .height()}px;\"></div>\n</div>\n`);\n  },\n});\n\nCraft.FieldLayoutDesigner.ElementDrag =\n  Craft.FieldLayoutDesigner.BaseDrag.extend({\n    draggingLibraryElement: false,\n    draggingField: false,\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      this.base();\n\n      // Are we dragging an element from the library?\n      this.draggingLibraryElement = this.$draggee.hasClass('unused');\n\n      // Is it a field?\n      this.draggingField = this.$draggee.hasClass('fld-field');\n\n      // keep UI elements visible\n      if (this.draggingLibraryElement && !this.draggingField) {\n        this.$draggee.css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n        });\n      }\n\n      // Swap the draggee with the insertion if dragging a selected item\n      if (!this.draggingLibraryElement) {\n        this.swapDraggeeWithInsertion();\n      }\n\n      this.setMidpoints();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      if (this.isDraggeeMandatory() || this.isHoveringOverTab()) {\n        this.checkForNewClosestItem();\n      } else if (this.showingInsertion) {\n        this.$insertion.remove();\n        this.$items = $().add(this.$items.not(this.$insertion));\n        this.showingInsertion = false;\n        this.designer.tabGrid.refreshCols(true);\n        this.setMidpoints();\n      }\n\n      this.base();\n    },\n\n    isDraggeeMandatory: function () {\n      return Garnish.hasAttr(this.$draggee, 'data-mandatory');\n    },\n\n    isHoveringOverTab: function () {\n      for (let i = 0; i < this.designer.tabGrid.$items.length; i++) {\n        if (\n          Garnish.hitTest(\n            this.mouseX,\n            this.mouseY,\n            this.designer.tabGrid.$items.eq(i)\n          )\n        ) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    findItems: function () {\n      // Return all of the used + unused fields\n      return this.designer.$tabContainer\n        .find('.fld-element')\n        .add(this.designer.$sidebar.find('.fld-element'));\n    },\n\n    /**\n     * Creates the caboose\n     */\n    createCaboose: function () {\n      let $caboose = $();\n      let $fieldContainers = this.designer.$tabContainer.find(\n        '> .fld-tab > .fld-tabcontent'\n      );\n\n      for (let i = 0; i < $fieldContainers.length; i++) {\n        $caboose = $caboose.add($('<div/>').appendTo($fieldContainers[i]));\n      }\n\n      return $caboose;\n    },\n\n    /**\n     * Creates the insertion\n     */\n    createInsertion: function () {\n      return $(\n        `<div class=\"fld-element fld-insertion\" style=\"height: ${this.$draggee.outerHeight()}px;\"/>`\n      );\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      let showingInsertion = this.showingInsertion;\n      if (showingInsertion) {\n        if (this.draggingLibraryElement) {\n          // Create a new element based on that one\n          let $element = this.$draggee.clone().removeClass('unused');\n          this.designer.initElement($element);\n\n          if (this.draggingField) {\n            // Hide the library field\n            this.$draggee\n              .css({visibility: 'inherit', display: 'field'})\n              .addClass('hidden');\n\n            // Hide the group too?\n            if (\n              this.$draggee.siblings('.fld-field:not(.hidden)').length === 0\n            ) {\n              this.$draggee.closest('.fld-field-group').addClass('hidden');\n            }\n          }\n\n          // Set this.$draggee to the clone, as if we were dragging that all along\n          this.$draggee = $element;\n\n          // Remember it for later\n          this.addItems($element);\n        }\n      } else if (!this.draggingLibraryElement) {\n        let $libraryElement = this.draggingField\n          ? this.designer.$fields.filter(\n              `[data-attribute=\"${this.$draggee.data('attribute')}\"]:first`\n            )\n          : this.designer.$uiLibraryElements.filter(\n              `[data-type=\"${this.$draggee\n                .data('type')\n                .replace(/\\\\/g, '\\\\\\\\')}\"]:first`\n            );\n\n        if (this.draggingField) {\n          // show the field in the library\n          $libraryElement.removeClass('hidden');\n          $libraryElement.closest('.fld-field-group').removeClass('hidden');\n        }\n\n        // forget the original element\n        this.removeItems(this.$draggee);\n\n        // Set this.$draggee to the library element, as if we were dragging that all along\n        this.$draggee = $libraryElement;\n      }\n\n      this.base();\n\n      this.$draggee.css({\n        display: this.draggeeDisplay,\n        visibility:\n          this.draggingField || showingInsertion ? 'hidden' : 'visible',\n      });\n\n      if (showingInsertion) {\n        this.$draggee.data('fld-element').updatePlacementInput();\n      }\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * FieldToggle\n */\nCraft.FieldToggle = Garnish.Base.extend({\n  $toggle: null,\n  targetPrefix: null,\n  targetSelector: null,\n  reverseTargetSelector: null,\n\n  _$target: null,\n  _$reverseTarget: null,\n  type: null,\n\n  init: function (toggle) {\n    this.$toggle = $(toggle);\n\n    // Is this already a field toggle?\n    if (this.$toggle.data('fieldtoggle')) {\n      console.warn('Double-instantiating a field toggle on an element');\n      this.$toggle.data('fieldtoggle').destroy();\n    }\n\n    this.$toggle.data('fieldtoggle', this);\n\n    this.type = this.getType();\n\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.targetPrefix = this.$toggle.attr('data-target-prefix') || '';\n    } else {\n      this.targetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('target')\n      );\n      this.reverseTargetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('reverse-target')\n      );\n    }\n\n    this.findTargets();\n\n    switch (this.type) {\n      case 'link':\n        this.addListener(this.$toggle, 'click', 'onToggleChange');\n        break;\n      case 'fieldset':\n        this.addListener(\n          this.$toggle.find('input'),\n          'change',\n          'onToggleChange'\n        );\n        break;\n      default:\n        this.addListener(this.$toggle, 'change', 'onToggleChange');\n        this.onToggleChange();\n    }\n  },\n\n  normalizeTargetSelector: function (selector) {\n    if (selector && !selector.match(/^[#\\.]/)) {\n      selector = '#' + selector;\n    }\n\n    return selector;\n  },\n\n  getType: function () {\n    let nodeName = this.$toggle.prop('nodeName');\n    if (\n      (nodeName === 'INPUT' && this.$toggle.attr('type') === 'checkbox') ||\n      this.$toggle.attr('role') === 'checkbox' ||\n      this.$toggle.attr('role') === 'switch'\n    ) {\n      return 'checkbox';\n    }\n\n    switch (nodeName) {\n      case 'SELECT':\n        if (Garnish.hasAttr(this.$toggle, 'data-boolean-menu')) {\n          return 'booleanMenu';\n        }\n        return 'select';\n      case 'A':\n        return 'link';\n      case 'FIELDSET':\n        return 'fieldset';\n    }\n\n    console.warn('Unexpected field toggle:', this.$toggle[0]);\n  },\n\n  findTargets: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      var toggleVal = this.getToggleVal();\n      this._$target = $(\n        this.normalizeTargetSelector(this.targetPrefix + this.getToggleVal())\n      );\n    } else {\n      if (this.targetSelector) {\n        this._$target = $(this.targetSelector);\n      }\n\n      if (this.reverseTargetSelector) {\n        this._$reverseTarget = $(this.reverseTargetSelector);\n      }\n    }\n  },\n\n  getToggleVal: function () {\n    switch (this.type) {\n      case 'checkbox':\n        if (typeof this.$toggle.prop('checked') !== 'undefined') {\n          return this.$toggle.prop('checked');\n        }\n        return this.$toggle.attr('aria-checked') === 'true';\n\n      case 'booleanMenu':\n        const boolean = this.$toggle.data('boolean');\n        if (typeof boolean !== 'undefined') {\n          return boolean;\n        }\n        const val = this.$toggle.val();\n        return val && val !== '0';\n\n      default:\n        let postVal;\n        if (this.type === 'fieldset') {\n          postVal = this.$toggle.find('input:checked:first').val();\n        } else {\n          postVal = Garnish.getInputPostVal(this.$toggle);\n        }\n\n        // Normalize the value\n        return typeof postVal === 'undefined' || postVal === null\n          ? null\n          : postVal.replace(/[^\\w]+/g, '-');\n    }\n  },\n\n  onToggleChange: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.hideTarget(this._$target);\n      this.findTargets();\n      this.showTarget(this._$target);\n    } else {\n      this.findTargets();\n\n      if (this.type === 'link') {\n        this.onToggleChange._show =\n          this.$toggle.hasClass('collapsed') ||\n          !this.$toggle.hasClass('expanded');\n      } else {\n        this.onToggleChange._show = !!this.getToggleVal();\n      }\n\n      if (this.onToggleChange._show) {\n        this.showTarget(this._$target);\n        this.hideTarget(this._$reverseTarget);\n      } else {\n        this.hideTarget(this._$target);\n        this.showTarget(this._$reverseTarget);\n      }\n\n      delete this.onToggleChange._show;\n    }\n  },\n\n  showTarget: function ($target) {\n    if ($target && $target.length) {\n      this.showTarget._currentHeight = $target.height();\n\n      $target.removeClass('hidden');\n\n      if (this.type !== 'select' && this.type !== 'fieldset') {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('collapsed');\n          this.$toggle.addClass('expanded');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.prop('nodeName') !== 'SPAN') {\n              $t.height('auto');\n              this.showTarget._targetHeight = $t.height();\n              $t.css({\n                height: this.showTarget._currentHeight,\n                overflow: 'hidden',\n              });\n\n              $t.velocity('stop');\n\n              $t.velocity(\n                {height: this.showTarget._targetHeight},\n                'fast',\n                function () {\n                  $t.css({\n                    height: '',\n                    overflow: '',\n                  });\n                }\n              );\n            }\n          })($target.eq(i));\n        }\n\n        delete this.showTarget._targetHeight;\n      }\n\n      delete this.showTarget._currentHeight;\n\n      // Trigger a resize event in case there are any grids in the target that need to initialize\n      Garnish.$win.trigger('resize');\n    }\n  },\n\n  hideTarget: function ($target) {\n    if ($target && $target.length) {\n      if (this.type === 'select' || this.type === 'fieldset') {\n        $target.addClass('hidden');\n      } else {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('expanded');\n          this.$toggle.addClass('collapsed');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.hasClass('hidden')) {\n              return;\n            }\n            if ($t.prop('nodeName') === 'SPAN') {\n              $t.addClass('hidden');\n            } else {\n              $t.css('overflow', 'hidden');\n              $t.velocity('stop');\n              $t.velocity({height: 0}, 'fast', function () {\n                $t.addClass('hidden');\n              });\n            }\n          })($target.eq(i));\n        }\n      }\n    }\n  },\n\n  destroy: function () {\n    this.$toggle.removeData('fieldtoggle');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.Grid = Garnish.Base.extend(\n  {\n    $container: null,\n\n    $items: null,\n    items: null,\n    totalCols: null,\n    colGutterDrop: null,\n    colPctWidth: null,\n\n    possibleItemColspans: null,\n    possibleItemPositionsByColspan: null,\n\n    itemPositions: null,\n    itemColspansByPosition: null,\n\n    layouts: null,\n    layout: null,\n    itemHeights: null,\n    leftPadding: null,\n\n    _refreshingCols: false,\n    _refreshColsAfterRefresh: false,\n    _forceRefreshColsAfterRefresh: false,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n\n      // Is this already a grid?\n      if (this.$container.data('grid')) {\n        console.warn('Double-instantiating a grid on an element');\n        this.$container.data('grid').destroy();\n      }\n\n      this.$container.data('grid', this);\n\n      this.setSettings(settings, Craft.Grid.defaults);\n\n      // Set the refreshCols() proxy that container resizes will trigger\n      this.handleContainerHeightProxy = () => {\n        this.refreshCols(false, true);\n      };\n\n      this.$items = this.$container.children(this.settings.itemSelector);\n      this.setItems();\n      this.refreshCols(true, false);\n\n      Garnish.$doc.ready(() => {\n        this.refreshCols(false, false);\n      });\n    },\n\n    addItems: function (items) {\n      this.$items = $().add(this.$items.add(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    removeItems: function (items) {\n      this.$items = $().add(this.$items.not(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    resetItemOrder: function () {\n      this.$items = $().add(this.$items);\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    setItems: function () {\n      this.setItems._ = {};\n\n      this.items = [];\n\n      for (\n        this.setItems._.i = 0;\n        this.setItems._.i < this.$items.length;\n        this.setItems._.i++\n      ) {\n        this.items.push($(this.$items[this.setItems._.i]));\n      }\n\n      delete this.setItems._;\n    },\n\n    refreshCols: function (force) {\n      if (this._refreshingCols) {\n        this._refreshColsAfterRefresh = true;\n        if (force) {\n          this._forceRefreshColsAfterRefresh = true;\n        }\n        return;\n      }\n\n      this._refreshingCols = true;\n\n      if (!this.items.length) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.refreshCols._ = {};\n\n      // Check to see if the grid is actually visible\n      this.refreshCols._.oldHeight = this.$container[0].style.height;\n      this.$container[0].style.height = 1;\n      this.refreshCols._.scrollHeight = this.$container[0].scrollHeight;\n      this.$container[0].style.height = this.refreshCols._.oldHeight;\n\n      if (this.refreshCols._.scrollHeight === 0) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      if (this.settings.cols) {\n        this.refreshCols._.totalCols = this.settings.cols;\n      } else {\n        this.refreshCols._.totalCols = Math.floor(\n          this.$container.width() / this.settings.minColWidth\n        );\n\n        // If we're adding a new column, require an extra 20 pixels in case a scrollbar shows up\n        if (\n          this.totalCols !== null &&\n          this.refreshCols._.totalCols > this.totalCols\n        ) {\n          this.refreshCols._.totalCols = Math.floor(\n            (this.$container.width() - 20) / this.settings.minColWidth\n          );\n        }\n\n        if (\n          this.settings.maxCols &&\n          this.refreshCols._.totalCols > this.settings.maxCols\n        ) {\n          this.refreshCols._.totalCols = this.settings.maxCols;\n        }\n      }\n\n      if (this.refreshCols._.totalCols === 0) {\n        this.refreshCols._.totalCols = 1;\n      }\n\n      // Same number of columns as before?\n      if (force !== true && this.totalCols === this.refreshCols._.totalCols) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.totalCols = this.refreshCols._.totalCols;\n      this.colGutterDrop =\n        (this.settings.gutter * (this.totalCols - 1)) / this.totalCols;\n\n      // Temporarily stop listening to container resizes\n      this.removeListener(this.$container, 'resize');\n\n      if (this.settings.fillMode === 'grid') {\n        this.refreshCols._.itemIndex = 0;\n\n        while (this.refreshCols._.itemIndex < this.items.length) {\n          // Append the next X items and figure out which one is the tallest\n          this.refreshCols._.tallestItemHeight = -1;\n          this.refreshCols._.colIndex = 0;\n\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.itemHeight = this.items[this.refreshCols._.i]\n              .height('auto')\n              .height();\n\n            if (\n              this.refreshCols._.itemHeight >\n              this.refreshCols._.tallestItemHeight\n            ) {\n              this.refreshCols._.tallestItemHeight =\n                this.refreshCols._.itemHeight;\n            }\n\n            this.refreshCols._.colIndex++;\n          }\n\n          if (this.settings.snapToGrid) {\n            this.refreshCols._.remainder =\n              this.refreshCols._.tallestItemHeight % this.settings.snapToGrid;\n\n            if (this.refreshCols._.remainder) {\n              this.refreshCols._.tallestItemHeight +=\n                this.settings.snapToGrid - this.refreshCols._.remainder;\n            }\n          }\n\n          // Now set their heights to the tallest one\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.items[this.refreshCols._.i].height(\n              this.refreshCols._.tallestItemHeight\n            );\n          }\n\n          // set the this.refreshCols._.itemIndex pointer to the next one up\n          this.refreshCols._.itemIndex += this.totalCols;\n        }\n      } else {\n        this.removeListener(this.$items, 'resize');\n\n        // If there's only one column, sneak out early\n        if (this.totalCols === 1) {\n          this.$container.height('auto');\n          this.$items\n            .show()\n            .css({\n              position: 'relative',\n              width: 'auto',\n              top: 0,\n            })\n            .css(Craft.left, 0);\n        } else {\n          this.$items.css('position', 'absolute');\n          this.colPctWidth = 100 / this.totalCols;\n\n          // The setup\n\n          this.layouts = [];\n\n          this.itemPositions = [];\n          this.itemColspansByPosition = [];\n\n          // Figure out all of the possible colspans for each item,\n          // as well as all the possible positions for each item at each of its colspans\n\n          this.possibleItemColspans = [];\n          this.possibleItemPositionsByColspan = [];\n          this.itemHeightsByColspan = [];\n\n          for (\n            this.refreshCols._.item = 0;\n            this.refreshCols._.item < this.items.length;\n            this.refreshCols._.item++\n          ) {\n            this.possibleItemColspans[this.refreshCols._.item] = [];\n            this.possibleItemPositionsByColspan[this.refreshCols._.item] = {};\n            this.itemHeightsByColspan[this.refreshCols._.item] = {};\n\n            this.refreshCols._.$item =\n              this.items[this.refreshCols._.item].show();\n            this.refreshCols._.positionRight =\n              this.refreshCols._.$item.data('position') === 'right';\n            this.refreshCols._.positionLeft =\n              this.refreshCols._.$item.data('position') === 'left';\n            this.refreshCols._.minColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('min-colspan')\n              ? this.refreshCols._.$item.data('min-colspan')\n              : 1;\n            this.refreshCols._.maxColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('max-colspan')\n              ? this.refreshCols._.$item.data('max-colspan')\n              : this.totalCols;\n\n            if (this.refreshCols._.minColspan > this.totalCols) {\n              this.refreshCols._.minColspan = this.totalCols;\n            }\n            if (this.refreshCols._.maxColspan > this.totalCols) {\n              this.refreshCols._.maxColspan = this.totalCols;\n            }\n\n            for (\n              this.refreshCols._.colspan = this.refreshCols._.minColspan;\n              this.refreshCols._.colspan <= this.refreshCols._.maxColspan;\n              this.refreshCols._.colspan++\n            ) {\n              // Get the height for this colspan\n              this.refreshCols._.$item.css(\n                'width',\n                this.getItemWidthCss(this.refreshCols._.colspan)\n              );\n              this.itemHeightsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = this.refreshCols._.$item.outerHeight();\n\n              this.possibleItemColspans[this.refreshCols._.item].push(\n                this.refreshCols._.colspan\n              );\n              this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = [];\n\n              if (this.refreshCols._.positionLeft) {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition = 0;\n              } else if (this.refreshCols._.positionRight) {\n                this.refreshCols._.minPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n                this.refreshCols._.maxPosition = this.refreshCols._.minPosition;\n              } else {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n              }\n\n              for (\n                this.refreshCols._.position = this.refreshCols._.minPosition;\n                this.refreshCols._.position <= this.refreshCols._.maxPosition;\n                this.refreshCols._.position++\n              ) {\n                this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                  this.refreshCols._.colspan\n                ].push(this.refreshCols._.position);\n              }\n            }\n          }\n\n          // Find all the possible layouts\n\n          this.refreshCols._.colHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.totalCols;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.colHeights.push(0);\n          }\n\n          this.createLayouts(0, [], [], this.refreshCols._.colHeights, 0);\n\n          // Now find the layout that looks the best.\n\n          // First find the layouts with the highest number of used columns\n          this.refreshCols._.layoutTotalCols = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutTotalCols[this.refreshCols._.i] = 0;\n\n            for (\n              this.refreshCols._.j = 0;\n              this.refreshCols._.j < this.totalCols;\n              this.refreshCols._.j++\n            ) {\n              if (\n                this.layouts[this.refreshCols._.i].colHeights[\n                  this.refreshCols._.j\n                ]\n              ) {\n                this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;\n              }\n            }\n          }\n\n          this.refreshCols._.highestTotalCols = Math.max.apply(\n            null,\n            this.refreshCols._.layoutTotalCols\n          );\n\n          // Filter out the ones that aren't using as many columns as they could be\n          for (\n            this.refreshCols._.i = this.layouts.length - 1;\n            this.refreshCols._.i >= 0;\n            this.refreshCols._.i--\n          ) {\n            if (\n              this.refreshCols._.layoutTotalCols[this.refreshCols._.i] !==\n              this.refreshCols._.highestTotalCols\n            ) {\n              this.layouts.splice(this.refreshCols._.i, 1);\n            }\n          }\n\n          // Find the layout(s) with the least overall height\n          this.refreshCols._.layoutHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutHeights.push(\n              Math.max.apply(\n                null,\n                this.layouts[this.refreshCols._.i].colHeights\n              )\n            );\n          }\n\n          this.refreshCols._.shortestHeight = Math.min.apply(\n            null,\n            this.refreshCols._.layoutHeights\n          );\n          this.refreshCols._.shortestLayouts = [];\n          this.refreshCols._.emptySpaces = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.refreshCols._.layoutHeights.length;\n            this.refreshCols._.i++\n          ) {\n            if (\n              this.refreshCols._.layoutHeights[this.refreshCols._.i] ===\n              this.refreshCols._.shortestHeight\n            ) {\n              this.refreshCols._.shortestLayouts.push(\n                this.layouts[this.refreshCols._.i]\n              );\n\n              // Now get its total empty space, including any trailing empty space\n              this.refreshCols._.emptySpace =\n                this.layouts[this.refreshCols._.i].emptySpace;\n\n              for (\n                this.refreshCols._.j = 0;\n                this.refreshCols._.j < this.totalCols;\n                this.refreshCols._.j++\n              ) {\n                this.refreshCols._.emptySpace +=\n                  this.refreshCols._.shortestHeight -\n                  this.layouts[this.refreshCols._.i].colHeights[\n                    this.refreshCols._.j\n                  ];\n              }\n\n              this.refreshCols._.emptySpaces.push(\n                this.refreshCols._.emptySpace\n              );\n            }\n          }\n\n          // And the layout with the least empty space is...\n          this.layout =\n            this.refreshCols._.shortestLayouts[\n              $.inArray(\n                Math.min.apply(null, this.refreshCols._.emptySpaces),\n                this.refreshCols._.emptySpaces\n              )\n            ];\n\n          // Set the item widths and left positions\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.css = {\n              width: this.getItemWidthCss(\n                this.layout.colspans[this.refreshCols._.i]\n              ),\n            };\n            this.refreshCols._.css[Craft.left] = this.getItemLeftPosCss(\n              this.layout.positions[this.refreshCols._.i]\n            );\n            this.items[this.refreshCols._.i].css(this.refreshCols._.css);\n          }\n\n          // If every item is at position 0, then let them lay out au naturel\n          if (this.isSimpleLayout()) {\n            this.$container.height('auto');\n            this.$items.css({\n              position: 'relative',\n              top: 0,\n              'margin-bottom': this.settings.gutter + 'px',\n            });\n          } else {\n            this.$items.css('position', 'absolute');\n\n            // Now position the items\n            this.positionItems();\n\n            // Update the positions as the items' heigthts change\n            this.addListener(this.$items, 'resize', 'onItemResize');\n          }\n        }\n      }\n\n      this.completeRefreshCols();\n\n      // Resume container resize listening\n      this.addListener(\n        this.$container,\n        'resize',\n        this.handleContainerHeightProxy\n      );\n\n      this.onRefreshCols();\n    },\n\n    completeRefreshCols: function () {\n      // Delete the internal variable object\n      if (typeof this.refreshCols._ !== 'undefined') {\n        delete this.refreshCols._;\n      }\n\n      this._refreshingCols = false;\n\n      if (this._refreshColsAfterRefresh) {\n        var force = this._forceRefreshColsAfterRefresh;\n        this._refreshColsAfterRefresh = false;\n        this._forceRefreshColsAfterRefresh = false;\n\n        Garnish.requestAnimationFrame(() => {\n          this.refreshCols(force);\n        });\n      }\n    },\n\n    getItemWidth: function (colspan) {\n      return this.colPctWidth * colspan;\n    },\n\n    getItemWidthCss: function (colspan) {\n      return (\n        'calc(' +\n        this.getItemWidth(colspan) +\n        '% - ' +\n        this.colGutterDrop +\n        'px)'\n      );\n    },\n\n    getItemWidthInPx: function (colspan) {\n      return (\n        (this.getItemWidth(colspan) / 100) * this.$container.width() -\n        this.colGutterDrop\n      );\n    },\n\n    getItemLeftPosCss: function (position) {\n      return (\n        'calc(' +\n        '(' +\n        this.getItemWidth(1) +\n        '% + ' +\n        (this.settings.gutter - this.colGutterDrop) +\n        'px) * ' +\n        position +\n        ')'\n      );\n    },\n\n    getItemLeftPosInPx: function (position) {\n      return (\n        ((this.getItemWidth(1) / 100) * this.$container.width() +\n          (this.settings.gutter - this.colGutterDrop)) *\n        position\n      );\n    },\n\n    createLayouts: function (\n      item,\n      prevPositions,\n      prevColspans,\n      prevColHeights,\n      prevEmptySpace\n    ) {\n      new Craft.Grid.LayoutGenerator(this).createLayouts(\n        item,\n        prevPositions,\n        prevColspans,\n        prevColHeights,\n        prevEmptySpace\n      );\n    },\n\n    isSimpleLayout: function () {\n      this.isSimpleLayout._ = {};\n\n      for (\n        this.isSimpleLayout._.i = 0;\n        this.isSimpleLayout._.i < this.layout.positions.length;\n        this.isSimpleLayout._.i++\n      ) {\n        if (this.layout.positions[this.isSimpleLayout._.i] !== 0) {\n          delete this.isSimpleLayout._;\n          return false;\n        }\n      }\n\n      delete this.isSimpleLayout._;\n      return true;\n    },\n\n    positionItems: function () {\n      this.positionItems._ = {};\n\n      this.positionItems._.colHeights = [];\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.totalCols;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.colHeights.push(0);\n      }\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.items.length;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.endingCol =\n          this.layout.positions[this.positionItems._.i] +\n          this.layout.colspans[this.positionItems._.i] -\n          1;\n        this.positionItems._.affectedColHeights = [];\n\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.affectedColHeights.push(\n            this.positionItems._.colHeights[this.positionItems._.col]\n          );\n        }\n\n        this.positionItems._.top = Math.max.apply(\n          null,\n          this.positionItems._.affectedColHeights\n        );\n        if (this.positionItems._.top > 0) {\n          this.positionItems._.top += this.settings.gutter;\n        }\n\n        this.items[this.positionItems._.i].css('top', this.positionItems._.top);\n\n        // Now add the new heights to those columns\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.colHeights[this.positionItems._.col] =\n            this.positionItems._.top +\n            this.itemHeightsByColspan[this.positionItems._.i][\n              this.layout.colspans[this.positionItems._.i]\n            ];\n        }\n      }\n\n      // Set the container height\n      this.$container.height(\n        Math.max.apply(null, this.positionItems._.colHeights)\n      );\n\n      delete this.positionItems._;\n    },\n\n    onItemResize: function (ev) {\n      this.onItemResize._ = {};\n\n      // Prevent this from bubbling up to the container, which has its own resize listener\n      ev.stopPropagation();\n\n      this.onItemResize._.item = $.inArray(ev.currentTarget, this.$items);\n\n      if (this.onItemResize._.item !== -1) {\n        // Update the height and reposition the items\n        this.onItemResize._.newHeight =\n          this.items[this.onItemResize._.item].outerHeight();\n\n        if (\n          this.onItemResize._.newHeight !==\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ]\n        ) {\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ] = this.onItemResize._.newHeight;\n          this.positionItems(false);\n        }\n      }\n\n      delete this.onItemResize._;\n    },\n\n    onRefreshCols: function () {\n      this.trigger('refreshCols');\n      this.settings.onRefreshCols();\n    },\n\n    destroy: function () {\n      this.$container.removeData('grid');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      itemSelector: '.item',\n      cols: null,\n      maxCols: null,\n      minColWidth: 320,\n      gutter: 14,\n      fillMode: 'top',\n      colClass: 'col',\n      snapToGrid: null,\n\n      onRefreshCols: $.noop,\n    },\n  }\n);\n\nCraft.Grid.LayoutGenerator = Garnish.Base.extend({\n  grid: null,\n  _: null,\n\n  init: function (grid) {\n    this.grid = grid;\n  },\n\n  createLayouts: function (\n    item,\n    prevPositions,\n    prevColspans,\n    prevColHeights,\n    prevEmptySpace\n  ) {\n    this._ = {};\n\n    // Loop through all possible colspans\n    for (\n      this._.c = 0;\n      this._.c < this.grid.possibleItemColspans[item].length;\n      this._.c++\n    ) {\n      this._.colspan = this.grid.possibleItemColspans[item][this._.c];\n\n      // Loop through all the possible positions for this colspan,\n      // and find the one that is closest to the top\n\n      this._.tallestColHeightsByPosition = [];\n\n      for (\n        this._.p = 0;\n        this._.p <\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan].length;\n        this._.p++\n      ) {\n        this._.position =\n          this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n            this._.p\n          ];\n\n        this._.colHeightsForPosition = [];\n        this._.endingCol = this._.position + this._.colspan - 1;\n\n        for (\n          this._.col = this._.position;\n          this._.col <= this._.endingCol;\n          this._.col++\n        ) {\n          this._.colHeightsForPosition.push(prevColHeights[this._.col]);\n        }\n\n        this._.tallestColHeightsByPosition[this._.p] = Math.max.apply(\n          null,\n          this._.colHeightsForPosition\n        );\n      }\n\n      // And the shortest position for this colspan is...\n      this._.p = $.inArray(\n        Math.min.apply(null, this._.tallestColHeightsByPosition),\n        this._.tallestColHeightsByPosition\n      );\n      this._.position =\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n          this._.p\n        ];\n\n      // Now log the colspan/position placement\n      this._.positions = prevPositions.slice(0);\n      this._.colspans = prevColspans.slice(0);\n      this._.colHeights = prevColHeights.slice(0);\n      this._.emptySpace = prevEmptySpace;\n\n      this._.positions.push(this._.position);\n      this._.colspans.push(this._.colspan);\n\n      // Add the new heights to those columns\n      this._.tallestColHeight = this._.tallestColHeightsByPosition[this._.p];\n      this._.endingCol = this._.position + this._.colspan - 1;\n\n      for (\n        this._.col = this._.position;\n        this._.col <= this._.endingCol;\n        this._.col++\n      ) {\n        this._.emptySpace +=\n          this._.tallestColHeight - this._.colHeights[this._.col];\n        this._.colHeights[this._.col] =\n          this._.tallestColHeight +\n          this.grid.itemHeightsByColspan[item][this._.colspan];\n      }\n\n      // If this is the last item, create the layout\n      if (item === this.grid.items.length - 1) {\n        this.grid.layouts.push({\n          positions: this._.positions,\n          colspans: this._.colspans,\n          colHeights: this._.colHeights,\n          emptySpace: this._.emptySpace,\n        });\n      } else {\n        // Dive deeper\n        this.grid.createLayouts(\n          item + 1,\n          this._.positions,\n          this._.colspans,\n          this._.colHeights,\n          this._.emptySpace\n        );\n      }\n    }\n\n    delete this._;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.HandleGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    var handle = sourceVal.replace('/<(.*?)>/g', '');\n\n    // Remove inner-word punctuation\n    handle = handle.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    handle = handle.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    handle = Craft.asciiString(handle);\n\n    if (!this.settings.allowNonAlphaStart) {\n      // Handle must start with a letter\n      handle = handle.replace(/^[^a-z]+/, '');\n    }\n\n    // Get the \"words\"\n    var words = Craft.filterArray(handle.split(/[^a-z0-9]+/));\n    handle = '';\n\n    if (Craft.handleCasing === 'snake') {\n      return words.join('_');\n    }\n\n    // Make it camelCase\n    for (let i = 0; i < words.length; i++) {\n      if (Craft.handleCasing !== 'pascal' && i === 0) {\n        handle += words[i];\n      } else {\n        handle += words[i].charAt(0).toUpperCase() + words[i].substr(1);\n      }\n    }\n\n    return handle;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Image upload class for user photos, site icon and logo.\n */\nCraft.ImageUpload = Garnish.Base.extend(\n  {\n    $container: null,\n    progressBar: null,\n    uploader: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.ImageUpload.defaults);\n      this.initImageUpload();\n    },\n\n    initImageUpload: function () {\n      this.$container = $(this.settings.containerSelector);\n      this.progressBar = new Craft.ProgressBar(\n        $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n      );\n\n      var options = {\n        url: Craft.getActionUrl(this.settings.uploadAction),\n        formData: this.settings.postParameters,\n        fileInput: this.$container.find(this.settings.fileInputSelector),\n        paramName: this.settings.uploadParamName,\n      };\n\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      options.events = {};\n      options.events.fileuploadstart = this._onUploadStart.bind(this);\n      options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n      options.events.fileuploaddone = this._onUploadComplete.bind(this);\n      options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n      this.uploader = new Craft.Uploader(this.$container, options);\n\n      this.initButtons();\n    },\n\n    initButtons: function () {\n      this.$container\n        .find(this.settings.uploadButtonSelector)\n        .on('click', (ev) => {\n          this.$container\n            .find(this.settings.fileInputSelector)\n            .trigger('click');\n        });\n\n      this.$container\n        .find(this.settings.deleteButtonSelector)\n        .on('click', (ev) => {\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to delete this image?')\n            )\n          ) {\n            $(ev.currentTarget)\n              .parent()\n              .append('<div class=\"blocking-modal\"></div>');\n            Craft.postActionRequest(\n              this.settings.deleteAction,\n              this.settings.postParameters,\n              (response, textStatus) => {\n                if (textStatus === 'success') {\n                  this.refreshImage(response);\n                }\n              }\n            );\n          }\n        });\n    },\n\n    refreshImage: function (response) {\n      $(this.settings.containerSelector).replaceWith(response.html);\n      this.settings.onAfterRefreshImage(response);\n      this.initImageUpload();\n    },\n\n    /**\n     * On upload start.\n     */\n    _onUploadStart: function (event) {\n      this.progressBar.$progressBar.css({\n        top: Math.round(this.$container.outerHeight() / 2) - 6,\n      });\n\n      this.$container.addClass('uploading');\n      this.progressBar.resetProgressBar();\n      this.progressBar.showProgressBar();\n    },\n\n    /**\n     * On upload progress.\n     */\n    _onUploadProgress: function (event, data) {\n      var progress = parseInt((data.loaded / data.total) * 100, 10);\n      this.progressBar.setProgressPercentage(progress);\n    },\n\n    /**\n     * On a file being uploaded.\n     */\n    _onUploadComplete: function (event, data) {\n      if (data.result.error) {\n        alert(data.result.error);\n      } else {\n        var html = $(data.result.html);\n        this.refreshImage(data.result);\n      }\n\n      // Last file\n      if (this.uploader.isLastUpload()) {\n        this.progressBar.hideProgressBar();\n        this.$container.removeClass('uploading');\n      }\n    },\n\n    /**\n     * On Upload Failure.\n     */\n    _onUploadFailure: function (event, data) {\n      if (data.jqXHR.responseJSON.error) {\n        alert(data.jqXHR.responseJSON.error);\n        this.progressBar.hideProgressBar();\n        this.$container.removeClass('uploading');\n      }\n    },\n  },\n  {\n    defaults: {\n      postParameters: {},\n      uploadAction: '',\n      deleteAction: '',\n      fileInputSelector: '',\n\n      onAfterRefreshImage: $.noop,\n      containerSelector: null,\n\n      uploadButtonSelector: null,\n      deleteButtonSelector: null,\n\n      uploadParamName: 'files',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Info icon class\n */\nCraft.InfoIcon = Garnish.Base.extend({\n  $icon: null,\n  content: null,\n  hud: null,\n\n  init: function (icon) {\n    this.$icon = $(icon);\n\n    if (this.$icon.data('infoicon')) {\n      console.warn('Double-instantiating an info icon on an element');\n      this.content = this.$icon.data('infoicon').content;\n      this.$icon.data('infoicon').destroy();\n    } else {\n      this.content = this.$icon.html();\n      this.$icon.html('').attr({\n        tabindex: 0,\n        role: 'button',\n        'aria-label': Craft.t('app', 'Information'),\n      });\n    }\n\n    this.$icon.data('infoicon', this);\n\n    if (\n      this.$icon[0].previousSibling &&\n      this.$icon[0].previousSibling.nodeType === Node.TEXT_NODE\n    ) {\n      // Make sure it's in a .nowrap container\n      const $parent = this.$icon.parent();\n      if (!$parent.hasClass('nowrap')) {\n        // Find the last word in the text\n        const m = this.$icon[0].previousSibling.nodeValue.match(/[^\\s\\-]+\\s*$/);\n        if (m) {\n          this.$icon[0].previousSibling.nodeValue =\n            this.$icon[0].previousSibling.nodeValue.substr(0, m.index);\n          $('<span/>', {\n            class: 'nowrap',\n            html: m[0].replace(/\\s+$/, '') + ' ',\n          })\n            .insertAfter(this.$icon[0].previousSibling)\n            .append(this.$icon);\n        }\n      }\n    }\n\n    this.addListener(this.$icon, 'click', (ev) => {\n      ev.preventDefault();\n      ev.stopPropagation();\n      this.showHud();\n    });\n\n    this.addListener(this.$icon, 'keydown', (ev) => {\n      if (\n        !(this.hud && this.hud.showing) &&\n        [Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)\n      ) {\n        ev.preventDefault();\n        ev.stopPropagation();\n        this.showHud();\n      }\n    });\n  },\n\n  showHud: function (ev) {\n    if (!this.hud) {\n      this.hud = new Garnish.HUD(this.$icon, this.content, {\n        hudClass: 'hud info-hud',\n        closeOtherHUDs: false,\n        onShow: () => {\n          Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY, () => {\n            this.hud.hide();\n          });\n        },\n      });\n      Craft.initUiElements(this.hud.$body);\n    } else {\n      this.hud.show();\n    }\n  },\n\n  destroy: function () {\n    this.$icon.removeData('infoicon');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Light Switch\n */\nCraft.LightSwitch = Garnish.Base.extend(\n  {\n    settings: null,\n    $outerContainer: null,\n    $innerContainer: null,\n    $input: null,\n    small: false,\n    on: false,\n    indeterminate: false,\n    dragger: null,\n\n    dragStartMargin: null,\n\n    init: function (outerContainer, settings) {\n      this.$outerContainer = $(outerContainer);\n\n      // Is this already a lightswitch?\n      if (this.$outerContainer.data('lightswitch')) {\n        console.warn('Double-instantiating a lightswitch on an element');\n        this.$outerContainer.data('lightswitch').destroy();\n      }\n\n      this.$outerContainer.data('lightswitch', this);\n\n      this.small = this.$outerContainer.hasClass('small');\n\n      this.setSettings(settings, Craft.LightSwitch.defaults);\n\n      this.$innerContainer = this.$outerContainer.find(\n        '.lightswitch-container:first'\n      );\n      this.$input = this.$outerContainer.find('input:first');\n\n      // If the input is disabled, go no further\n      if (this.$input.prop('disabled')) {\n        return;\n      }\n\n      this.on = this.$outerContainer.hasClass('on');\n      this.indeterminate = this.$outerContainer.hasClass('indeterminate');\n\n      this.addListener(this.$outerContainer, 'mousedown', '_onMouseDown');\n      this.addListener(this.$outerContainer, 'keydown', '_onKeyDown');\n\n      this.dragger = new Garnish.BaseDrag(this.$outerContainer, {\n        axis: Garnish.X_AXIS,\n        ignoreHandleSelector: null,\n        onDragStart: this._onDragStart.bind(this),\n        onDrag: this._onDrag.bind(this),\n        onDragStop: this._onDragStop.bind(this),\n      });\n\n      // Does the input have on/off labels?\n      let $wrapper = this.$outerContainer.parent(\n        '.lightswitch-inner-container'\n      );\n      if ($wrapper.length) {\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"off\"]'),\n          'click',\n          this.turnOff\n        );\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"on\"]'),\n          'click',\n          this.turnOn\n        );\n      }\n    },\n\n    turnOn: function (muteEvent) {\n      var changed = !this.on;\n\n      this.on = true;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, 0);\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = 0;\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val(this.settings.value);\n      this.$outerContainer.addClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'true');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnOff: function (muteEvent) {\n      var changed = this.on || this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, this._getOffMargin());\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = this._getOffMargin();\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val('');\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'false');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnIndeterminate: function (muteEvent) {\n      var changed = !this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = true;\n\n      this.$outerContainer.addClass('dragging');\n      var animateCss = {};\n      animateCss['margin-' + Craft.left] = this._getOffMargin() / 2;\n      this.$innerContainer\n        .velocity('stop')\n        .velocity(\n          animateCss,\n          Craft.LightSwitch.animationDuration,\n          this._onSettle.bind(this)\n        );\n\n      this.$input.val(this.settings.indeterminateValue);\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.addClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'mixed');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    toggle: function () {\n      if (this.indeterminate || !this.on) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    onChange: function () {\n      this.trigger('change');\n      this.settings.onChange(this.on);\n      this.$outerContainer.trigger('change');\n    },\n\n    _onMouseDown: function () {\n      this.addListener(Garnish.$doc, 'mouseup', '_onMouseUp');\n    },\n\n    _onMouseUp: function () {\n      this.removeListener(Garnish.$doc, 'mouseup');\n\n      // Was this a click?\n      if (!this.dragger.dragging) {\n        this.toggle();\n      }\n    },\n\n    _onKeyDown: function (event) {\n      switch (event.keyCode) {\n        case Garnish.SPACE_KEY: {\n          this.toggle();\n          event.preventDefault();\n          break;\n        }\n        case Garnish.RIGHT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOn();\n          } else {\n            this.turnOff();\n          }\n\n          event.preventDefault();\n          break;\n        }\n        case Garnish.LEFT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOff();\n          } else {\n            this.turnOn();\n          }\n\n          event.preventDefault();\n          break;\n        }\n      }\n    },\n\n    _getMargin: function () {\n      return parseInt(this.$innerContainer.css('margin-' + Craft.left));\n    },\n\n    _onDragStart: function () {\n      this.$outerContainer.addClass('dragging');\n      this.dragStartMargin = this._getMargin();\n    },\n\n    _onDrag: function () {\n      var margin;\n\n      if (Craft.orientation === 'ltr') {\n        margin = this.dragStartMargin + this.dragger.mouseDistX;\n      } else {\n        margin = this.dragStartMargin - this.dragger.mouseDistX;\n      }\n\n      if (margin < this._getOffMargin()) {\n        margin = this._getOffMargin();\n      } else if (margin > 0) {\n        margin = 0;\n      }\n\n      this.$innerContainer.css('margin-' + Craft.left, margin);\n    },\n\n    _onDragStop: function () {\n      var margin = this._getMargin();\n      console.log(margin);\n\n      if (margin > this._getOffMargin() / 2) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    _onSettle: function () {\n      this.$outerContainer.removeClass('dragging');\n    },\n\n    destroy: function () {\n      this.$outerContainer.removeData('lightswitch');\n      this.base();\n      this.dragger.destroy();\n    },\n\n    _getOffMargin: function () {\n      return this.small ? -10 : -12;\n    },\n  },\n  {\n    animationDuration: 100,\n    defaults: {\n      value: '1',\n      indeterminateValue: '-',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Listbox\n */\nCraft.Listbox = Garnish.Base.extend(\n  {\n    $container: null,\n    $options: null,\n    $selectedOption: null,\n    selectedOptionIndex: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Listbox.defaults);\n\n      // Is this already a listbox?\n      if (this.$container.data('listbox')) {\n        console.warn('Double-instantiating a listbox on an element');\n        this.$container.data('listbox').destroy();\n      }\n\n      this.$container.data('listbox', this);\n      this.$options = this.$container.find('[role=option]');\n\n      // is there already a selected option?\n      this.$selectedOption = this.$options.filter('[aria-selected=true]');\n      if (this.$selectedOption.length) {\n        this.selectedOptionIndex = this.$options.index(this.$selectedOption);\n      } else {\n        this.$selectedOption = null;\n      }\n\n      this.addListener(this.$container, 'keydown', (ev) => {\n        switch (ev.keyCode) {\n          case Garnish.UP_KEY:\n            this.selectPrev();\n            ev.preventDefault();\n            break;\n          case Garnish.DOWN_KEY:\n            this.selectNext();\n            ev.preventDefault();\n            break;\n          case Garnish.LEFT_KEY:\n            if (Craft.orientation === 'ltr') {\n              this.selectPrev();\n            } else {\n              this.selectNext();\n            }\n            ev.preventDefault();\n            break;\n          case Garnish.RIGHT_KEY:\n            if (Craft.orientation === 'ltr') {\n              this.selectNext();\n            } else {\n              this.selectPrev();\n            }\n            ev.preventDefault();\n            break;\n        }\n      });\n\n      this.addListener(this.$options, 'click', (ev) => {\n        this.select(this.$options.index($(ev.currentTarget)));\n        ev.preventDefault();\n      });\n    },\n\n    select: function (index) {\n      if (\n        index < 0 ||\n        index >= this.$options.length ||\n        index === this.selectedOptionIndex\n      ) {\n        return;\n      }\n\n      this.$selectedOption\n        .removeClass(this.settings.selectedClass)\n        .attr('aria-selected', 'false');\n\n      this.$selectedOption = this.$options\n        .eq(index)\n        .addClass(this.settings.selectedClass)\n        .attr('aria-selected', 'true');\n\n      this.selectedOptionIndex = index;\n\n      this.settings.onChange(this.$selectedOption, index);\n      this.trigger('change', {\n        $selectedOption: this.$selectedOption,\n        selectedOptionIndex: index,\n      });\n    },\n\n    selectPrev: function () {\n      if (this.selectedOptionIndex === null) {\n        this.select(0);\n      } else {\n        this.select(this.selectedOptionIndex - 1);\n      }\n    },\n\n    selectNext: function () {\n      if (this.selectedOptionIndex === null) {\n        this.select(0);\n      } else {\n        this.select(this.selectedOptionIndex + 1);\n      }\n    },\n\n    destroy: function () {\n      this.$container.removeData('listbox');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      selectedClass: 'active',\n      focusClass: 'focus',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Live Preview\n */\nCraft.LivePreview = Garnish.Base.extend(\n  {\n    $extraFields: null,\n    $trigger: null,\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $dragHandle: null,\n    $previewContainer: null,\n    $iframeContainer: null,\n    $iframe: null,\n    $fieldPlaceholder: null,\n\n    previewUrl: null,\n    token: null,\n    basePostData: null,\n    inPreviewMode: false,\n    fields: null,\n    lastPostData: null,\n    updateIframeInterval: null,\n    loading: false,\n    checkAgain: false,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _slideInOnIframeLoad: false,\n    _forceUpdateIframeProxy: null,\n\n    _scrollX: null,\n    _scrollY: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.LivePreview.defaults);\n\n      // Should preview requests use a specific URL?\n      // This won't affect how the request gets routed (the action param will override it),\n      // but it will allow the templates to change behavior based on the request URI.\n      if (this.settings.previewUrl) {\n        this.previewUrl = this.settings.previewUrl;\n      } else {\n        this.previewUrl = Craft.baseSiteUrl.replace(/\\/+$/, '') + '/';\n      }\n\n      // Load the preview over SSL if the current request is\n      if (document.location.protocol === 'https:') {\n        this.previewUrl = this.previewUrl.replace(/^http:/, 'https:');\n      }\n\n      // Set the base post data\n      this.basePostData = $.extend({}, this.settings.previewParams);\n\n      this._forceUpdateIframeProxy = this.forceUpdateIframe.bind(this);\n\n      // Find the DOM elements\n      this.$extraFields = $(this.settings.extraFields);\n      this.$trigger = $(this.settings.trigger);\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.LivePreview.defaultEditorWidth\n      );\n\n      // Event Listeners\n      this.addListener(this.$trigger, 'activate', 'toggle');\n\n      Craft.cp.on('beforeSaveShortcut', () => {\n        if (this.inPreviewMode) {\n          this.moveFieldsBack();\n        }\n      });\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.LivePreview.minEditorWidthInPx) {\n        inPx = Craft.LivePreview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    toggle: function () {\n      if (this.inPreviewMode) {\n        this.exit();\n      } else {\n        this.enter();\n      }\n    },\n\n    enter: function () {\n      if (this.inPreviewMode) {\n        return;\n      }\n\n      if (!this.token) {\n        this.createToken();\n        return;\n      }\n\n      this.trigger('beforeEnter');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n        }).appendTo(Garnish.$bod);\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(Garnish.$bod);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        let $saveBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit',\n          text: Craft.t('app', 'Save'),\n        }).appendTo($editorHeader);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'exit');\n        this.addListener($saveBtn, 'click', 'save');\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Move all the fields into the editor rather than copying them\n      // so any JS that's referencing the elements won't break.\n      this.fields = [];\n      var $fields = $(this.settings.fields);\n\n      for (var i = 0; i < $fields.length; i++) {\n        var $field = $($fields[i]),\n          $clone = this._getClone($field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter($field);\n        $field.detach();\n        this.$fieldPlaceholder.replaceWith($clone);\n        $field.appendTo(this.$editor);\n\n        this.fields.push({\n          $field: $field,\n          $clone: $clone,\n        });\n      }\n\n      if (this.updateIframe()) {\n        this._slideInOnIframeLoad = true;\n      } else {\n        this.slideIn();\n      }\n\n      Garnish.on(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._forceUpdateIframeProxy\n      );\n      Garnish.on(Craft.AssetImageEditor, 'save', this._forceUpdateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.exit();\n      });\n\n      this.inPreviewMode = true;\n      this.trigger('enter');\n    },\n\n    createToken: function () {\n      Craft.postActionRequest(\n        'live-preview/create-token',\n        {\n          previewAction: this.settings.previewAction,\n        },\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.token = response.token;\n            this.enter();\n          }\n        }\n      );\n    },\n\n    save: function () {\n      Craft.cp.submitPrimaryForm();\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(0, 'slow', () => {\n          this.trigger('slideIn');\n          Garnish.$win.trigger('resize');\n        });\n\n      this.$previewContainer\n        .show()\n        .velocity('stop')\n        .animateRight(0, 'slow', () => {\n          this.updateIframeInterval = setInterval(\n            this.updateIframe.bind(this),\n            1000\n          );\n        });\n    },\n\n    exit: function () {\n      if (!this.inPreviewMode) {\n        return;\n      }\n\n      this.trigger('beforeExit');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n\n      if (this.updateIframeInterval) {\n        clearInterval(this.updateIframeInterval);\n      }\n\n      this.moveFieldsBack();\n\n      this.$shade.delay(200).velocity('fadeOut');\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(-this.editorWidthInPx, 'slow', () => {\n          for (var i = 0; i < this.fields.length; i++) {\n            this.fields[i].$newClone.remove();\n          }\n          this.$editorContainer.hide();\n          this.trigger('slideOut');\n        });\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(-this.getIframeWidth(), 'slow', () => {\n          this.$previewContainer.hide();\n        });\n\n      Garnish.off(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._forceUpdateIframeProxy\n      );\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.inPreviewMode = false;\n      this.trigger('exit');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n    },\n\n    updateIframe: function (force) {\n      if (force) {\n        this.lastPostData = null;\n      }\n\n      if (!this.inPreviewMode) {\n        return false;\n      }\n\n      if (this.loading) {\n        this.checkAgain = true;\n        return false;\n      }\n\n      // Has the post data changed?\n      var postData = $.extend(\n        Garnish.getPostData(this.$editor),\n        Garnish.getPostData(this.$extraFields)\n      );\n\n      if (\n        !this.lastPostData ||\n        !Craft.compare(postData, this.lastPostData, false)\n      ) {\n        this.lastPostData = postData;\n        this.loading = true;\n\n        var $doc = this.$iframe\n          ? $(this.$iframe[0].contentWindow.document)\n          : null;\n\n        this._scrollX = $doc ? $doc.scrollLeft() : 0;\n        this._scrollY = $doc ? $doc.scrollTop() : 0;\n\n        $.ajax({\n          url:\n            this.previewUrl +\n            (this.previewUrl.indexOf('?') !== -1 ? '&' : '?') +\n            Craft.tokenParam +\n            '=' +\n            this.token,\n          method: 'POST',\n          data: $.extend({}, postData, this.basePostData),\n          headers: {\n            'X-Craft-Token': this.token,\n          },\n          xhrFields: {\n            withCredentials: true,\n          },\n          crossDomain: true,\n          success: this.handleSuccess.bind(this),\n          error: this.handleError.bind(this),\n        });\n\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    forceUpdateIframe: function () {\n      return this.updateIframe(true);\n    },\n\n    handleSuccess: function (data) {\n      var html =\n        data +\n        '<script type=\"text/javascript\">window.scrollTo(' +\n        this._scrollX +\n        ', ' +\n        this._scrollY +\n        ');</script>';\n\n      // Create a new iframe\n      var $iframe = $('<iframe class=\"lp-preview\" frameborder=\"0\"/>');\n      if (this.$iframe) {\n        $iframe.insertBefore(this.$iframe);\n      } else {\n        $iframe.appendTo(this.$iframeContainer);\n      }\n\n      this.addListener($iframe, 'load', function () {\n        if (this.$iframe) {\n          this.$iframe.remove();\n        }\n        this.$iframe = $iframe;\n\n        if (this._slideInOnIframeLoad) {\n          this.slideIn();\n          this._slideInOnIframeLoad = false;\n        }\n\n        this.removeListener($iframe, 'load');\n      });\n\n      Garnish.requestAnimationFrame(() => {\n        $iframe[0].contentWindow.document.open();\n        $iframe[0].contentWindow.document.write(html);\n        $iframe[0].contentWindow.document.close();\n        this.onResponse();\n      });\n    },\n\n    handleError: function () {\n      this.onResponse();\n    },\n\n    onResponse: function () {\n      this.loading = false;\n\n      if (this.checkAgain) {\n        this.checkAgain = false;\n        this.updateIframe();\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n\n    defaults: {\n      trigger: '.livepreviewbtn',\n      fields: null,\n      extraFields: null,\n      previewUrl: null,\n      previewAction: null,\n      previewParams: {},\n    },\n  }\n);\n\nCraft.LivePreview.init = function (settings) {\n  Craft.livePreview = new Craft.LivePreview(settings);\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Password Input\n */\nCraft.PasswordInput = Garnish.Base.extend(\n  {\n    $passwordWrapper: null,\n    $passwordInput: null,\n    $textInput: null,\n    $currentInput: null,\n\n    $showPasswordToggle: null,\n    showingPassword: null,\n\n    init: function (passwordInput, settings) {\n      this.$passwordInput = $(passwordInput);\n      this.$passwordWrapper = this.$passwordInput.parent('.passwordwrapper');\n      this.settings = $.extend({}, Craft.PasswordInput.defaults, settings);\n\n      // Is this already a password input?\n      if (this.$passwordInput.data('passwordInput')) {\n        console.warn('Double-instantiating a password input on an element');\n        this.$passwordInput.data('passwordInput').destroy();\n      }\n\n      this.$passwordInput.data('passwordInput', this);\n\n      this.$showPasswordToggle = $(\n        '<button type=\"button\" class=\"invisible\" />'\n      );\n      this.$showPasswordToggle.addClass('password-toggle');\n      this.$showPasswordToggle.insertAfter(this.$passwordInput);\n\n      this.initInputFocusEvents(this.$passwordInput);\n      this.addListener(this.$showPasswordToggle, 'click', 'onClick');\n      this.hidePassword();\n\n      this.addListener(\n        this.$passwordWrapper.closest('form'),\n        'submit',\n        'hidePassword'\n      );\n    },\n\n    setCurrentInput: function ($input) {\n      if (this.$currentInput) {\n        // Swap the inputs, while preventing the focus animation\n        $input.insertAfter(this.$currentInput);\n        this.$currentInput.detach();\n        $input.trigger('focus');\n\n        // Restore the input value\n        $input.val(this.$currentInput.val());\n      }\n\n      this.$currentInput = $input;\n\n      this.addListener(\n        this.$currentInput,\n        'keypress,keyup,change,blur',\n        'onInputChange'\n      );\n    },\n\n    updateToggleLabel: function (label) {\n      this.$showPasswordToggle.text(label);\n    },\n\n    initInputFocusEvents: function ($input) {\n      this.addListener($input, 'focus', function () {\n        this.$passwordWrapper.addClass('focus');\n      });\n      this.addListener($input, 'blur', function () {\n        this.$passwordWrapper.removeClass('focus');\n      });\n    },\n\n    showPassword: function () {\n      if (this.showingPassword) {\n        return;\n      }\n\n      if (!this.$textInput) {\n        this.$textInput = this.$passwordInput.clone(true);\n        this.$textInput.attr({\n          type: 'text',\n          autocapitalize: 'off',\n        });\n        this.initInputFocusEvents(this.$textInput);\n      }\n\n      this.setCurrentInput(this.$textInput);\n      this.updateToggleLabel(Craft.t('app', 'Hide'));\n      this.showingPassword = true;\n    },\n\n    hidePassword: function () {\n      // showingPassword could be null, which is acceptable\n      if (this.showingPassword === false) {\n        return;\n      }\n\n      this.setCurrentInput(this.$passwordInput);\n      this.updateToggleLabel(Craft.t('app', 'Show'));\n      this.showingPassword = false;\n\n      // Alt key temporarily shows the password\n      this.addListener(this.$passwordInput, 'keydown', 'onKeyDown');\n    },\n\n    togglePassword: function () {\n      if (this.showingPassword) {\n        this.hidePassword();\n      } else {\n        this.showPassword();\n      }\n\n      this.settings.onToggleInput(this.$currentInput);\n    },\n\n    onKeyDown: function (ev) {\n      if (ev.keyCode === Garnish.ALT_KEY && this.$currentInput.val()) {\n        this.showPassword();\n        this.$showPasswordToggle.addClass('invisible');\n        this.addListener(this.$textInput, 'keyup', 'onKeyUp');\n      }\n    },\n\n    onKeyUp: function (ev) {\n      ev.preventDefault();\n\n      if (ev.keyCode === Garnish.ALT_KEY) {\n        this.hidePassword();\n        this.$showPasswordToggle.removeClass('invisible');\n      }\n    },\n\n    onInputChange: function () {\n      if (this.$currentInput.val()) {\n        this.$showPasswordToggle.removeClass('invisible');\n      } else {\n        this.$showPasswordToggle.addClass('invisible');\n      }\n    },\n\n    onClick: function (ev) {\n      if (this.$currentInput[0].setSelectionRange) {\n        var selectionStart = this.$currentInput[0].selectionStart,\n          selectionEnd = this.$currentInput[0].selectionEnd;\n\n        this.togglePassword();\n        this.$currentInput[0].setSelectionRange(selectionStart, selectionEnd);\n      } else {\n        this.togglePassword();\n      }\n    },\n\n    destroy: function () {\n      this.$passwordInput.removeData('passwordInput');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      onToggleInput: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview\n */\nCraft.Preview = Garnish.Base.extend(\n  {\n    draftEditor: null,\n\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $spinner: null,\n    $statusIcon: null,\n    $dragHandle: null,\n    $previewContainer: null,\n    $iframeContainer: null,\n    $previewHeader: null,\n    $targetBtn: null,\n    $targetMenu: null,\n    $deviceTypeContainer: null,\n    $orientationBtn: null,\n    $refreshBtn: null,\n    $deviceMask: null,\n    $devicePreviewContainer: null,\n    $iframe: null,\n    iframeLoaded: false,\n    $tempInput: null,\n    $fieldPlaceholder: null,\n\n    isActive: false,\n    isVisible: false,\n    activeTarget: 0,\n\n    currentDeviceType: 'desktop',\n    deviceOrientation: null,\n    deviceWidth: '',\n    deviceHeight: '',\n    deviceMaskDimensions: {\n      phone: {\n        width: 375,\n        height: 753,\n      },\n      tablet: {\n        width: 768,\n        height: 1110,\n      },\n    },\n\n    draftId: null,\n    url: null,\n    fields: null,\n\n    iframeHeight: null,\n    scrollTop: null,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _updateIframeProxy: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (draftEditor) {\n      this.draftEditor = draftEditor;\n\n      this._updateIframeProxy = this.updateIframe.bind(this);\n\n      this.$tempInput = $('<input/>', {\n        type: 'hidden',\n        name: '__PREVIEW_FIELDS__',\n        value: '1',\n      });\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.Preview.defaultEditorWidth\n      );\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.Preview.minEditorWidthInPx) {\n        inPx = Craft.Preview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    open: function () {\n      if (this.isActive) {\n        return;\n      }\n\n      this.isActive = true;\n      this.trigger('beforeOpen');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n        }).appendTo(Garnish.$bod);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(Garnish.$bod);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        this.$spinner = $('<div/>', {\n          class: 'spinner hidden',\n          title: Craft.t('app', 'Saving'),\n        }).appendTo($editorHeader);\n        this.$statusIcon = $('<div/>', {class: 'invisible'}).appendTo(\n          $editorHeader\n        );\n        this.$statusMessage = $('<span/>', {\n          class: 'visually-hidden',\n          'aria-live': 'polite',\n        }).appendTo($editorHeader);\n\n        if (Craft.Pro) {\n          this.$previewHeader = $('<header/>', {\n            class: 'lp-preview-header',\n          }).appendTo(this.$previewContainer);\n\n          // Preview targets\n          if (this.draftEditor.settings.previewTargets.length > 1) {\n            this.$targetBtn = $('<button/>', {\n              type: 'button',\n              class: 'btn menubtn',\n              text: this.draftEditor.settings.previewTargets[0].label,\n            }).appendTo(this.$previewHeader);\n            this.$targetMenu = $('<div/>', {\n              class: 'menu lp-target-menu',\n            }).insertAfter(this.$targetBtn);\n            const $ul = $('<ul/>', {class: 'padded'}).appendTo(\n              this.$targetMenu\n            );\n            let $li, $a;\n            for (\n              let i = 0;\n              i < this.draftEditor.settings.previewTargets.length;\n              i++\n            ) {\n              $li = $('<li/>').appendTo($ul);\n              $a = $('<a/>', {\n                data: {target: i},\n                text: this.draftEditor.settings.previewTargets[i].label,\n                class: i === 0 ? 'sel' : null,\n              }).appendTo($li);\n            }\n            new Garnish.MenuBtn(this.$targetBtn, {\n              onOptionSelect: (option) => {\n                this.switchTarget($(option).data('target'));\n              },\n            });\n\n            $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          }\n\n          this._buildDeviceTypeFieldset();\n\n          $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          const $buttonContainer = $('<div class=\"buttons\"/>').appendTo(\n            this.$previewHeader\n          );\n\n          // Orientation toggle\n          this.$orientationBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn disabled',\n            'data-icon': 'rotate',\n            disabled: '',\n            text: Craft.t('app', 'Rotate'),\n            'aria-label': Craft.t('app', 'Rotate'),\n          }).appendTo($buttonContainer);\n          this.addListener(this.$orientationBtn, 'click', 'switchOrientation');\n\n          // Refresh button\n          this.$refreshBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn hidden',\n            text: Craft.t('app', 'Refresh'),\n            'data-icon': 'refresh',\n          }).appendTo($buttonContainer);\n          this._updateRefreshBtn();\n          this.addListener(this.$refreshBtn, 'click', () => {\n            this.updateIframe(false, true);\n          });\n\n          // Get the last stored orientation\n          this.deviceOrientation = Craft.getLocalStorage(\n            'LivePreview.orientation'\n          );\n\n          // Device type input change handler\n          this.addListener(\n            $('input', this.$deviceTypeContainer),\n            'change',\n            'switchDeviceType'\n          );\n        }\n\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$devicePreviewContainer = $('<div/>', {\n          class: 'lp-device-preview-container',\n        }).appendTo(this.$iframeContainer);\n        this.$deviceMask = $('<div/>', {\n          class: 'lp-device-mask',\n        }).appendTo(this.$iframeContainer);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'close');\n        this.addListener(this.$statusIcon, 'click', () => {\n          this.draftEditor.showStatusHud(this.$statusIcon);\n        });\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Find the fields, excluding nested fields\n      this.fields = [];\n      var $fields = $('#content .field').not($('#content .field .field'));\n\n      if ($fields.length) {\n        // Insert our temporary input before the first field so we know where to swap in the serialized form values\n        this.$tempInput.insertBefore($fields.get(0));\n\n        // Move all the fields into the editor rather than copying them\n        // so any JS that's referencing the elements won't break.\n        for (let i = 0; i < $fields.length; i++) {\n          let $field = $($fields[i]),\n            $clone = this._getClone($field);\n\n          // It's important that the actual field is added to the DOM *after* the clone,\n          // so any radio buttons in the field get deselected from the clone rather than the actual field.\n          this.$fieldPlaceholder.insertAfter($field);\n          $field.detach();\n          this.$fieldPlaceholder.replaceWith($clone);\n          $field.appendTo(this.$editor);\n\n          this.fields.push({\n            $field: $field,\n            $clone: $clone,\n          });\n        }\n      }\n\n      this.updateIframe();\n\n      this.draftEditor.on('update', this._updateIframeProxy);\n      Garnish.on(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._updateIframeProxy\n      );\n      Garnish.on(Craft.AssetImageEditor, 'save', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.trigger('open');\n    },\n\n    _buildDeviceTypeFieldset: function () {\n      this.$deviceTypeContainer = $('<fieldset/>', {\n        class: 'lp-device-type',\n      }).appendTo(this.$previewHeader);\n\n      $('<legend/>', {\n        text: Craft.t('app', 'Device type'),\n        class: 'visually-hidden',\n      }).appendTo(this.$deviceTypeContainer);\n\n      const $radioGroup = $('<div/>', {\n        class: 'lp-device-type__radio-group',\n      }).appendTo(this.$deviceTypeContainer);\n\n      // Desktop\n      const $desktopWrapper = $('<div/>', {\n        class: 'lp-device-type__item',\n      }).appendTo($radioGroup);\n\n      $('<input/>', {\n        class: 'lp-device-type__input visually-hidden',\n        type: 'radio',\n        name: 'device',\n        value: 'desktop',\n        id: 'device-desktop',\n        checked: true,\n        data: {\n          width: '',\n          height: '',\n        },\n      }).appendTo($desktopWrapper);\n\n      const $desktopLabel = $('<label/>', {\n        for: 'device-desktop',\n        class:\n          'btn lp-device-type__label lp-device-type__label--desktop active',\n        title: Craft.t('app', 'Desktop'),\n      }).appendTo($desktopWrapper);\n\n      $('<span/>', {\n        class: 'visually-hidden',\n        text: Craft.t('app', 'Desktop'),\n      }).appendTo($desktopLabel);\n\n      // Tablet\n      const $tabletWrapper = $('<div/>', {\n        class: 'lp-device-type__item',\n      }).appendTo($radioGroup);\n\n      $('<input/>', {\n        class: 'lp-device-type__input visually-hidden',\n        type: 'radio',\n        name: 'device',\n        value: 'tablet',\n        id: 'device-tablet',\n        data: {\n          width: 768,\n          height: 1024,\n        },\n      }).appendTo($tabletWrapper);\n\n      const $tabletLabel = $('<label/>', {\n        for: 'device-tablet',\n        class: 'btn lp-device-type__label lp-device-type__label--tablet',\n        title: Craft.t('app', 'Tablet'),\n      }).appendTo($tabletWrapper);\n\n      $('<span/>', {\n        class: 'visually-hidden',\n        text: Craft.t('app', 'Tablet'),\n      }).appendTo($tabletLabel);\n\n      // Mobile\n      const $mobileWrapper = $('<div/>', {\n        class: 'lp-device-type__item',\n      }).appendTo($radioGroup);\n\n      $('<input/>', {\n        class: 'lp-device-type__input visually-hidden',\n        type: 'radio',\n        name: 'device',\n        value: 'phone',\n        id: 'device-phone',\n        data: {\n          width: 375,\n          height: 667,\n        },\n      }).appendTo($mobileWrapper);\n\n      const $mobileLabel = $('<label/>', {\n        for: 'device-phone',\n        class: 'btn lp-device-type__label lp-device-type__label--phone',\n        title: Craft.t('app', 'Mobile'),\n      }).appendTo($mobileWrapper);\n\n      $('<span/>', {\n        class: 'visually-hidden',\n        text: Craft.t('app', 'Mobile'),\n      }).appendTo($mobileLabel);\n    },\n\n    _activeTarget: function () {\n      return this.draftEditor.settings.previewTargets[this.activeTarget];\n    },\n\n    /**\n     * @returns {boolean}\n     * @private\n     */\n    _autoRefresh: function () {\n      const target = this._activeTarget();\n      return typeof typeof target.refresh === 'undefined' || !!target.refresh;\n    },\n\n    _updateRefreshBtn: function () {\n      if (!this._autoRefresh()) {\n        this.$refreshBtn.removeClass('hidden');\n      } else {\n        this.$refreshBtn.addClass('hidden');\n      }\n    },\n\n    switchTarget: function (i) {\n      this.activeTarget = i;\n      this.$targetBtn.text(this.draftEditor.settings.previewTargets[i].label);\n      this.$targetMenu.find('a.sel').removeClass('sel');\n      this.$targetMenu.find('a').eq(i).addClass('sel');\n      this.updateIframe(true);\n      this._updateRefreshBtn();\n      this.trigger('switchTarget', {\n        previewTarget: this.draftEditor.settings.previewTargets[i],\n      });\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      if (!this.isActive || this.isVisible) {\n        return;\n      }\n\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(0, 'slow', () => {\n          this.trigger('slideIn');\n          Garnish.$win.trigger('resize');\n        });\n\n      this.$previewContainer.show().velocity('stop').animateRight(0, 'slow');\n\n      this.isVisible = true;\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.close();\n      });\n    },\n\n    close: function () {\n      if (!this.isActive || !this.isVisible) {\n        return;\n      }\n\n      this.trigger('beforeClose');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n\n      // Remove our temporary input and move the preview fields back into place\n      this.$tempInput.detach();\n      this.moveFieldsBack();\n\n      this.$shade.delay(200).velocity('fadeOut');\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(-this.editorWidthInPx, 'slow', () => {\n          for (var i = 0; i < this.fields.length; i++) {\n            this.fields[i].$newClone.remove();\n          }\n          this.$editorContainer.hide();\n          this.trigger('slideOut');\n        });\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(-this.getIframeWidth(), 'slow', () => {\n          this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n          this.$previewContainer.hide();\n        });\n\n      this.draftEditor.off('update', this._updateIframeProxy);\n      Garnish.off(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._updateIframeProxy\n      );\n      Garnish.off(Craft.AssetImageEditor, 'save', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.isActive = false;\n      this.isVisible = false;\n      this.trigger('close');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n      Garnish.$doc.trigger('scroll');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n      if (this._devicePreviewIsActive()) {\n        this.updateDevicePreview();\n      }\n    },\n\n    _useIframeResizer: function () {\n      return Craft.previewIframeResizerOptions !== false;\n    },\n\n    /**\n     * @param {boolean} [resetScroll=false]\n     * @param {boolean} [refresh]\n     */\n    updateIframe: function (resetScroll, refresh) {\n      if (!this.isActive) {\n        return false;\n      }\n\n      // Ignore non-boolean resetScroll values\n      resetScroll = resetScroll === true;\n\n      // If the draft ID has changed or there's no iframe, we definitely need to refresh\n      if (\n        this.draftId !== (this.draftId = this.draftEditor.settings.draftId) ||\n        !this.$iframe\n      ) {\n        refresh = true;\n      }\n\n      const target = this._activeTarget();\n      if (typeof refresh === 'undefined') {\n        refresh = resetScroll || this._autoRefresh();\n      }\n\n      this.trigger('beforeUpdateIframe', {\n        previewTarget: target,\n        resetScroll: resetScroll,\n        refresh: refresh,\n      });\n\n      // If this is an existing preview target, make sure it wants to be refreshed automatically\n      if (!refresh) {\n        this.slideIn();\n        return;\n      }\n\n      this.draftEditor\n        .getTokenizedPreviewUrl(target.url, 'x-craft-live-preview')\n        .then((url) => {\n          // Maintain the current scroll position?\n          let sameHost;\n          if (resetScroll) {\n            this.scrollTop = null;\n          } else if (this.iframeLoaded && this.$iframe) {\n            if (this._useIframeResizer()) {\n              this.iframeHeight = this.$iframe.height();\n              this.scrollTop = this.$iframeContainer.scrollTop();\n            } else {\n              sameHost = Craft.isSameHost(url);\n              if (sameHost && this.$iframe[0].contentWindow) {\n                this.scrollTop = $(\n                  this.$iframe[0].contentWindow.document\n                ).scrollTop();\n              }\n            }\n          }\n\n          this.iframeLoaded = false;\n\n          var $iframe = $('<iframe/>', {\n            class: 'lp-preview',\n            frameborder: 0,\n            src: url,\n            title: Craft.t('app', 'Preview'),\n          });\n\n          if (this.$iframe) {\n            this.$iframe.replaceWith($iframe);\n          } else {\n            $iframe.appendTo(this.$devicePreviewContainer);\n          }\n\n          // Keep the iframe height consistent with its content\n          if (this._useIframeResizer()) {\n            if (!resetScroll && this.iframeHeight !== null) {\n              $iframe.height(this.iframeHeight);\n              this.$iframeContainer.scrollTop(this.scrollTop);\n            }\n\n            iFrameResize(\n              $.extend(\n                {\n                  checkOrigin: false,\n                  // Allow iframe scrolling until we've successfully initialized the resizer\n                  scrolling: true,\n                  onInit: (iframe) => {\n                    this.iframeLoaded = true;\n                    this.iframeHeight = null;\n                    this.scrollTop = null;\n                    iframe.scrolling = 'no';\n                  },\n                },\n                Craft.previewIframeResizerOptions || {}\n              ),\n              $iframe[0]\n            );\n          } else {\n            $iframe.on('load', () => {\n              this.iframeLoaded = true;\n              if (!resetScroll && sameHost && this.scrollTop !== null) {\n                $($iframe[0].contentWindow.document).scrollTop(this.scrollTop);\n              }\n            });\n          }\n\n          this.url = url;\n          this.$iframe = $iframe;\n\n          if (this._devicePreviewIsActive()) {\n            this.updateDevicePreview();\n          }\n\n          this.trigger('afterUpdateIframe', {\n            previewTarget:\n              this.draftEditor.settings.previewTargets[this.activeTarget],\n            $iframe: this.$iframe,\n          });\n\n          this.slideIn();\n        });\n    },\n\n    _devicePreviewIsActive: function () {\n      return this.currentDeviceType !== 'desktop';\n    },\n\n    switchDeviceType: function (ev) {\n      this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n\n      const $input = $(ev.target);\n      const $inputWrapper = $input.closest('.lp-device-type__item');\n      const newDeviceType = $input.val();\n\n      // Bail if we’re just smashing the same button\n      if (newDeviceType === this.currentDeviceType) {\n        return false;\n      }\n\n      // Store new device type data\n      this.currentDeviceType = newDeviceType;\n      this.deviceWidth = $input.data('width');\n      this.deviceHeight = $input.data('height');\n\n      // Set the active state on the label\n      this.$deviceTypeContainer.find('.btn').removeClass('active');\n\n      $inputWrapper.find('.btn').addClass('active');\n\n      if (this.currentDeviceType === 'desktop') {\n        // Disable the orientation button\n        this.$orientationBtn.addClass('disabled').attr('disabled', '');\n\n        this.$iframeContainer.removeClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      } else {\n        // Enable the orientation button\n        this.$orientationBtn.removeClass('disabled').removeAttr('disabled');\n\n        this.$iframeContainer.addClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      }\n\n      // Add the tablet class if needed\n      if (this.currentDeviceType === 'tablet') {\n        this.$iframeContainer.addClass('lp-iframe-container--tablet');\n      } else {\n        this.$iframeContainer.removeClass('lp-iframe-container--tablet');\n      }\n\n      if (this.currentDeviceType !== 'desktop') {\n        this.updateDevicePreview();\n      }\n    },\n\n    switchOrientation: function () {\n      if (!this._devicePreviewIsActive()) {\n        return false;\n      }\n\n      // Switch to whichever orientation is currently not stored\n      if (!this.deviceOrientation || this.deviceOrientation === 'portrait') {\n        this.deviceOrientation = 'landscape';\n      } else {\n        this.deviceOrientation = 'portrait';\n      }\n\n      // Store the new one\n      Craft.setLocalStorage('LivePreview.orientation', this.deviceOrientation);\n\n      // Allow the animation to take place\n      this.$iframeContainer.addClass('lp-iframe-container--rotating');\n\n      // Update the device preview\n      this.updateDevicePreview();\n\n      setTimeout(() => {\n        this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n      }, 300);\n    },\n\n    updateDevicePreview: function () {\n      // Figure out the best zoom\n      let hZoom = 1;\n      let wZoom = 1;\n      let zoom = 1;\n      let previewHeight = this.$previewContainer.height() - 50 - 48; // 50px for the header bar and 24px clearance\n      let previewWidth = this.$previewContainer.width() - 48;\n      let maskHeight = this.deviceMaskDimensions[this.currentDeviceType].height;\n      let maskWidth = this.deviceMaskDimensions[this.currentDeviceType].width;\n\n      if (this.deviceOrientation === 'landscape') {\n        if (previewWidth < maskHeight) {\n          hZoom = previewWidth / maskHeight;\n        }\n        if (previewHeight < maskWidth) {\n          wZoom = previewHeight / maskWidth;\n        }\n      } else {\n        if (previewHeight < maskHeight) {\n          hZoom = previewHeight / maskHeight;\n        }\n        if (previewWidth < maskWidth) {\n          wZoom = previewWidth / maskWidth;\n        }\n      }\n\n      zoom = hZoom;\n      if (wZoom < hZoom) {\n        zoom = wZoom;\n      }\n\n      // Figure out the css values\n      const translate = -(100 / zoom / 2);\n      const rotationDeg =\n        this.deviceOrientation === 'landscape' ? '-90deg' : '0deg';\n\n      // Apply first to the device mask\n      this.$deviceMask.css({\n        width: this.deviceMaskDimensions[this.currentDeviceType].width + 'px',\n        height: this.deviceMaskDimensions[this.currentDeviceType].height + 'px',\n        transform:\n          'scale(' +\n          zoom +\n          ') translate(' +\n          translate +\n          '%, ' +\n          translate +\n          '%) rotate(' +\n          rotationDeg +\n          ')',\n      });\n\n      if (this.deviceOrientation === 'landscape') {\n        this.$devicePreviewContainer.css({\n          width: this.deviceHeight + 'px',\n          height: this.deviceWidth + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: 0,\n          marginLeft: '-' + 12 * zoom + 'px',\n        });\n      } else {\n        this.$devicePreviewContainer.css({\n          width: this.deviceWidth + 'px',\n          height: this.deviceHeight + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: '-' + 12 * zoom + 'px',\n          marginLeft: 0,\n        });\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      // Disable anything with a name attribute\n      $clone.find('[name]').prop('disabled', true);\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview File Modal\n */\nCraft.PreviewFileModal = Garnish.Modal.extend(\n  {\n    assetId: null,\n    $spinner: null,\n    elementSelect: null,\n    type: null,\n    loaded: null,\n    requestId: 0,\n\n    /**\n     * Initialize the preview file modal.\n     * @returns {*|void}\n     */\n    init: function (assetId, elementSelect, settings) {\n      settings = $.extend(this.defaultSettings, settings);\n\n      settings.onHide = this._onHide.bind(this);\n\n      if (Craft.PreviewFileModal.openInstance) {\n        var instance = Craft.PreviewFileModal.openInstance;\n\n        if (instance.assetId !== assetId) {\n          instance.loadAsset(\n            assetId,\n            settings.startingWidth,\n            settings.startingHeight\n          );\n          instance.elementSelect = elementSelect;\n        }\n\n        return this.destroy();\n      }\n\n      Craft.PreviewFileModal.openInstance = this;\n      this.elementSelect = elementSelect;\n\n      this.$container = $('<div class=\"modal previewmodal loading\"/>').appendTo(\n        Garnish.$bod\n      );\n\n      this.base(\n        this.$container,\n        $.extend(\n          {\n            resizable: true,\n          },\n          settings\n        )\n      );\n\n      // Cut the flicker, just show the nice person the preview.\n      if (this.$container) {\n        this.$container.velocity('stop');\n        this.$container.show().css('opacity', 1);\n\n        this.$shade.velocity('stop');\n        this.$shade.show().css('opacity', 1);\n      }\n\n      this.loadAsset(assetId, settings.startingWidth, settings.startingHeight);\n    },\n\n    /**\n     * When hiding, remove all traces and focus last focused element.\n     * @private\n     */\n    _onHide: function () {\n      Craft.PreviewFileModal.openInstance = null;\n      if (this.elementSelect) {\n        this.elementSelect.focusItem(this.elementSelect.$focusedItem);\n      }\n\n      this.$shade.remove();\n\n      return this.destroy();\n    },\n\n    /**\n     * Disappear immediately forever.\n     * @returns {boolean}\n     */\n    selfDestruct: function () {\n      var instance = Craft.PreviewFileModal.openInstance;\n\n      instance.hide();\n      instance.$shade.remove();\n      instance.destroy();\n\n      Craft.PreviewFileModal.openInstance = null;\n\n      return true;\n    },\n\n    /**\n     * Load an asset, using starting width and height, if applicable\n     * @param assetId\n     * @param startingWidth\n     * @param startingHeight\n     */\n    loadAsset: function (assetId, startingWidth, startingHeight) {\n      this.assetId = assetId;\n\n      this.$container.empty();\n      this.loaded = false;\n\n      this.desiredHeight = null;\n      this.desiredWidth = null;\n\n      var containerHeight = Garnish.$win.height() * 0.66;\n      var containerWidth = Math.min(\n        (containerHeight / 3) * 4,\n        Garnish.$win.width() - this.settings.minGutter * 2\n      );\n      containerHeight = (containerWidth / 4) * 3;\n\n      if (startingWidth && startingHeight) {\n        var ratio = startingWidth / startingHeight;\n        containerWidth = Math.min(\n          startingWidth,\n          Garnish.$win.width() - this.settings.minGutter * 2\n        );\n        containerHeight = Math.min(\n          containerWidth / ratio,\n          Garnish.$win.height() - this.settings.minGutter * 2\n        );\n        containerWidth = containerHeight * ratio;\n\n        // This might actually have put width over the viewport limits, so doublecheck\n        if (\n          containerWidth >\n          Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          )\n        ) {\n          containerWidth = Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          );\n          containerHeight = containerWidth / ratio;\n        }\n      }\n\n      this._resizeContainer(containerWidth, containerHeight);\n\n      this.$spinner = $('<div class=\"spinner centeralign\"></div>').appendTo(\n        this.$container\n      );\n      var top =\n          this.$container.height() / 2 - this.$spinner.height() / 2 + 'px',\n        left = this.$container.width() / 2 - this.$spinner.width() / 2 + 'px';\n\n      this.$spinner.css({left: left, top: top, position: 'absolute'});\n      this.requestId++;\n\n      Craft.postActionRequest(\n        'assets/preview-file',\n        {assetId: assetId, requestId: this.requestId},\n        (response, textStatus) => {\n          this.$container.removeClass('loading');\n          this.$spinner.remove();\n          this.loaded = true;\n\n          if (textStatus === 'success') {\n            if (response.success) {\n              if (response.requestId != this.requestId) {\n                return;\n              }\n\n              if (!response.previewHtml) {\n                this.$container.addClass('zilch');\n                this.$container.append(\n                  $('<p/>', {text: Craft.t('app', 'No preview available.')})\n                );\n                return;\n              }\n\n              this.$container.removeClass('zilch');\n              this.$container.append(response.previewHtml);\n              Craft.appendHeadHtml(response.headHtml);\n              Craft.appendFootHtml(response.footHtml);\n            } else {\n              alert(response.error);\n\n              this.hide();\n            }\n          }\n        }\n      );\n    },\n\n    /**\n     * Resize the container to specified dimensions\n     * @param containerWidth\n     * @param containerHeight\n     * @private\n     */\n    _resizeContainer: function (containerWidth, containerHeight) {\n      this.$container.css({\n        width: containerWidth,\n        'min-width': containerWidth,\n        'max-width': containerWidth,\n        height: containerHeight,\n        'min-height': containerHeight,\n        'max-height': containerHeight,\n        top: (Garnish.$win.height() - containerHeight) / 2,\n        left: (Garnish.$win.width() - containerWidth) / 2,\n      });\n    },\n  },\n  {\n    defaultSettings: {\n      startingWidth: null,\n      startingHeight: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.ProgressBar = Garnish.Base.extend({\n  $progressBar: null,\n  $innerProgressBar: null,\n  $progressBarStatus: null,\n\n  _itemCount: 0,\n  _processedItemCount: 0,\n  _displaySteps: false,\n\n  init: function ($element, displaySteps) {\n    if (displaySteps) {\n      this._displaySteps = true;\n    }\n\n    this.$progressBar = $('<div class=\"progressbar pending hidden\"/>').appendTo(\n      $element\n    );\n    this.$innerProgressBar = $('<div class=\"progressbar-inner\"/>').appendTo(\n      this.$progressBar\n    );\n    this.$progressBarStatus = $(\n      '<div class=\"progressbar-status hidden\" />'\n    ).insertAfter(this.$progressBar);\n\n    this.resetProgressBar();\n  },\n\n  /**\n   * Reset the progress bar\n   */\n  resetProgressBar: function () {\n    // Since setting the progress percentage implies that there is progress to be shown\n    // It removes the pending class - we must add it back.\n    this.setProgressPercentage(100);\n    this.$progressBar.addClass('pending');\n\n    // Reset all the counters\n    this.setItemCount(1);\n    this.setProcessedItemCount(0);\n    this.$progressBarStatus.html('');\n\n    if (this._displaySteps) {\n      this.$progressBar.addClass('has-status');\n    }\n  },\n\n  /**\n   * Fade to invisible, hide it using a class and reset opacity to visible\n   */\n  hideProgressBar: function () {\n    this.$progressBar.fadeTo('fast', 0.01, () => {\n      this.$progressBar.addClass('hidden').fadeTo(1, 1, $.noop);\n    });\n    this.$progressBarStatus.fadeTo('fast', 0.01, () => {\n      this.$progressBarStatus.addClass('hidden').fadeTo(1, 1, $.noop);\n    });\n  },\n\n  showProgressBar: function () {\n    this.$progressBar.removeClass('hidden');\n    this.$progressBarStatus.removeClass('hidden');\n  },\n\n  setItemCount: function (count) {\n    this._itemCount = count;\n  },\n\n  incrementItemCount: function (count) {\n    this._itemCount += count;\n  },\n\n  setProcessedItemCount: function (count) {\n    this._processedItemCount = count;\n  },\n\n  incrementProcessedItemCount: function (count) {\n    this._processedItemCount += count;\n  },\n\n  updateProgressBar: function () {\n    // Only fools would allow accidental division by zero.\n    this._itemCount = Math.max(this._itemCount, 1);\n\n    var width = Math.min(\n      100,\n      Math.round((100 * this._processedItemCount) / this._itemCount)\n    );\n\n    this.setProgressPercentage(width);\n\n    if (this._displaySteps) {\n      this.$progressBarStatus.html(\n        this._processedItemCount + ' / ' + this._itemCount\n      );\n    }\n  },\n\n  setProgressPercentage: function (percentage, animate) {\n    if (percentage === 0) {\n      this.$progressBar.addClass('pending');\n    } else {\n      this.$progressBar.removeClass('pending');\n\n      if (animate) {\n        this.$innerProgressBar\n          .velocity('stop')\n          .velocity({width: percentage + '%'}, 'fast');\n      } else {\n        this.$innerProgressBar.velocity('stop').width(percentage + '%');\n      }\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.PromptHandler = Garnish.Base.extend({\n  modal: null,\n  $modalContainerDiv: null,\n  $prompt: null,\n  $promptApplyToRemainingContainer: null,\n  $promptApplyToRemainingCheckbox: null,\n  $promptApplyToRemainingLabel: null,\n  $pomptChoices: null,\n\n  _prompts: [],\n  _promptBatchCallback: $.noop,\n  _promptBatchReturnData: [],\n  _promptBatchNum: 0,\n\n  resetPrompts: function () {\n    this._prompts = [];\n    this._promptBatchCallback = $.noop;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n  },\n\n  addPrompt: function (prompt) {\n    this._prompts.push(prompt);\n  },\n\n  getPromptCount: function () {\n    return this._prompts.length;\n  },\n\n  showBatchPrompts: function (callback) {\n    this._promptBatchCallback = callback;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n\n    this._showNextPromptInBatch();\n  },\n\n  _showNextPromptInBatch: function () {\n    var prompt = this._prompts[this._promptBatchNum].prompt,\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    this._showPrompt(\n      prompt.message,\n      prompt.choices,\n      this._handleBatchPromptSelection.bind(this),\n      remainingInBatch\n    );\n  },\n\n  /**\n   * Handles a prompt choice selection.\n   *\n   * @param choice\n   * @param applyToRemaining\n   * @private\n   */\n  _handleBatchPromptSelection: function (choice, applyToRemaining) {\n    var prompt = this._prompts[this._promptBatchNum],\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    // Record this choice\n    var choiceData = $.extend(prompt, {choice});\n    this._promptBatchReturnData.push(choiceData);\n\n    // Are there any remaining items in the batch?\n    if (remainingInBatch) {\n      // Get ready to deal with the next prompt\n      this._promptBatchNum++;\n\n      // Apply the same choice to the remaining items?\n      if (applyToRemaining) {\n        this._handleBatchPromptSelection(choice, true);\n      } else {\n        // Show the next prompt\n        this._showNextPromptInBatch();\n      }\n    } else {\n      // All done! Call the callback\n      if (typeof this._promptBatchCallback === 'function') {\n        this._promptBatchCallback(this._promptBatchReturnData);\n      }\n    }\n  },\n\n  /**\n   * Show the user prompt with a given message and choices, plus an optional \"Apply to remaining\" checkbox.\n   *\n   * @param {string} message\n   * @param {object} choices\n   * @param {function} callback\n   * @param {number} itemsToGo\n   */\n  _showPrompt: function (message, choices, callback, itemsToGo) {\n    this._promptCallback = callback;\n\n    if (this.modal === null) {\n      this.modal = new Garnish.Modal({closeOtherModals: false});\n    }\n\n    if (this.$modalContainerDiv === null) {\n      this.$modalContainerDiv = $(\n        '<div class=\"modal fitted prompt-modal\"></div>'\n      )\n        .addClass()\n        .appendTo(Garnish.$bod);\n    }\n\n    this.$prompt = $('<div class=\"body\"></div>').appendTo(\n      this.$modalContainerDiv.empty()\n    );\n\n    this.$promptMessage = $('<p class=\"prompt-msg\"/>').appendTo(this.$prompt);\n\n    this.$promptChoices = $('<div class=\"options\"></div>').appendTo(\n      this.$prompt\n    );\n\n    this.$promptApplyToRemainingContainer = $(\n      '<label class=\"assets-applytoremaining\"/>'\n    )\n      .appendTo(this.$prompt)\n      .hide();\n    this.$promptApplyToRemainingCheckbox = $(\n      '<input type=\"checkbox\"/>'\n    ).appendTo(this.$promptApplyToRemainingContainer);\n    this.$promptApplyToRemainingLabel = $('<span/>').appendTo(\n      this.$promptApplyToRemainingContainer\n    );\n\n    this.$promptButtons = $('<div class=\"buttons right\"/>').appendTo(\n      this.$prompt\n    );\n\n    this.modal.setContainer(this.$modalContainerDiv);\n\n    this.$promptMessage.html(message);\n\n    let $cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$promptButtons);\n    let $submitBtn = $('<button/>', {\n      type: 'submit',\n      class: 'btn submit disabled',\n      text: Craft.t('app', 'OK'),\n    }).appendTo(this.$promptButtons);\n\n    for (var i = 0; i < choices.length; i++) {\n      var $radioButtonHtml = $(\n          '<div><label><input type=\"radio\" name=\"promptAction\" value=\"' +\n            choices[i].value +\n            '\"/> ' +\n            choices[i].title +\n            '</label></div>'\n        ).appendTo(this.$promptChoices),\n        $radioButton = $radioButtonHtml.find('input');\n\n      this.addListener($radioButton, 'click', function () {\n        $submitBtn.removeClass('disabled');\n      });\n    }\n\n    this.addListener($submitBtn, 'activate', function (ev) {\n      var choice = $(ev.currentTarget)\n          .parents('.modal')\n          .find('input[name=promptAction]:checked')\n          .val(),\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    this.addListener($cancelBtn, 'activate', function () {\n      var choice = 'cancel',\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    if (itemsToGo) {\n      this.$promptApplyToRemainingContainer.show();\n      this.$promptApplyToRemainingLabel.html(\n        ' ' +\n          Craft.t('app', 'Apply this to the {number} remaining conflicts?', {\n            number: itemsToGo,\n          })\n      );\n    }\n\n    this.modal.show();\n    this.modal.removeListener(Garnish.Modal.$shade, 'click');\n    this.addListener(Garnish.Modal.$shade, 'click', '_cancelPrompt');\n  },\n\n  /**\n   * Handles when a user selects one of the prompt choices.\n   *\n   * @param choice\n   * @param applyToRemaining\n   * @private\n   */\n  _selectPromptChoice: function (choice, applyToRemaining) {\n    this.$prompt.fadeOut('fast', () => {\n      this.modal.hide();\n      this._promptCallback(choice, applyToRemaining);\n    });\n  },\n\n  /**\n   * Cancels the prompt.\n   */\n  _cancelPrompt: function () {\n    this._selectPromptChoice('cancel', true);\n  },\n});\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.SlidePicker = Garnish.Base.extend(\n    {\n      min: null,\n      max: null,\n      totalSteps: null,\n      value: null,\n\n      $container: null,\n      $buttons: null,\n\n      init: function (value, settings) {\n        this.setSettings(settings, Craft.SlidePicker.defaults);\n\n        this.$container = $('<div/>', {\n          class: 'slide-picker',\n          role: 'slider',\n          tabindex: 0,\n        });\n\n        this.refresh();\n        this.setValue(value, false);\n\n        this.addListener(this.$container, 'keydown', (ev) => {\n          switch (ev.keyCode) {\n            case Garnish.UP_KEY:\n              this.setValue(this.value + this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.DOWN_KEY:\n              this.setValue(this.value - this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.RIGHT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value + this.settings.step);\n              } else {\n                this.setValue(this.value - this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n            case Garnish.LEFT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value - this.settings.step);\n              } else {\n                this.setValue(this.value + this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n          }\n        });\n      },\n\n      refresh: function () {\n        // Figure out what the min/max values are\n        this.min = this._min();\n        this.max = this._max();\n        this.totalSteps = (this.max - this.min) / this.settings.step;\n\n        if (!Number.isInteger(this.totalSteps)) {\n          throw 'Invalid SlidePicker config';\n        }\n\n        if (this.$buttons) {\n          this.$buttons.remove();\n        }\n\n        this.$container.attr('aria-valuemin', this.min);\n        this.$container.attr('aria-valuemax', this.max);\n        this.$buttons = $();\n\n        // Create the buttons\n        for (\n          let value = this.min;\n          value <= this.max;\n          value += this.settings.step\n        ) {\n          this.$buttons = this.$buttons.add(\n            $('<a/>', {\n              title: this.settings.valueLabel(value),\n              data: {value},\n            })\n          );\n        }\n\n        this.$buttons.appendTo(this.$container);\n\n        if (this.value !== null) {\n          let value = this.value;\n          this.value = null;\n          this.setValue(value, false);\n        }\n\n        this.addListener(this.$buttons, 'mouseover', (ev) => {\n          this.$buttons.removeClass('active-hover last-active-hover');\n          $(ev.currentTarget)\n            .addClass('active-hover last-active-hover')\n            .prevAll()\n            .addClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'mouseout', () => {\n          this.$buttons.removeClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'click', (ev) => {\n          this.setValue($.data(ev.currentTarget, 'value'));\n          ev.stopPropagation();\n          this.$container.focus();\n        });\n      },\n\n      setValue: function (value, triggerEvent) {\n        value = Math.max(Math.min(value, this.max), this.min);\n\n        if (this.value === (this.value = value)) {\n          return;\n        }\n\n        this.$container.attr({\n          'aria-valuenow': this.value,\n          'aria-valuetext': this.settings.valueLabel(this.value),\n        });\n\n        this.$buttons.removeClass('last-active active');\n        let $activeButton = this.$buttons.eq(\n          (this.value - this.min) / this.settings.step\n        );\n        $activeButton.add($activeButton.prevAll()).addClass('active');\n        $activeButton.addClass('last-active');\n\n        if (triggerEvent !== false) {\n          this.settings.onChange(value);\n        }\n      },\n\n      _min: function () {\n        if (typeof this.settings.min === 'function') {\n          return this.settings.min();\n        }\n        return this.settings.min;\n      },\n\n      _max: function () {\n        if (typeof this.settings.max === 'function') {\n          return this.settings.max();\n        }\n        return this.settings.max;\n      },\n    },\n    {\n      defaults: {\n        min: 0,\n        max: 100,\n        step: 10,\n        valueLabel: null,\n        onChange: $.noop,\n      },\n    }\n  );\n})(jQuery);\n","/** global: Garnish */\n\nCraft.SlideRuleInput = Garnish.Base.extend({\n  $container: null,\n  $options: null,\n  $selectedOption: null,\n  $input: null,\n  value: null,\n\n  startPositionX: null,\n\n  init: function (id, settings) {\n    this.setSettings(settings, Craft.SlideRuleInput.defaultSettings);\n\n    this.value = 0;\n    this.graduationsMin = -70;\n    this.graduationsMax = 70;\n    this.slideMin = -45;\n    this.slideMax = 45;\n\n    this.$container = $('#' + id);\n    this.$overlay = $('<div class=\"overlay\"></div>').appendTo(this.$container);\n    this.$cursor = $('<div class=\"cursor\"></div>').appendTo(this.$container);\n    this.$graduations = $('<div class=\"graduations\"></div>').appendTo(\n      this.$container\n    );\n    this.$graduationsUl = $('<ul></ul>').appendTo(this.$graduations);\n\n    for (var i = this.graduationsMin; i <= this.graduationsMax; i++) {\n      var $li = $(\n        '<li class=\"graduation\" data-graduation=\"' +\n          i +\n          '\"><div class=\"label\">' +\n          i +\n          '</div></li>'\n      ).appendTo(this.$graduationsUl);\n\n      if (i % 5 === 0) {\n        $li.addClass('main-graduation');\n      }\n\n      if (i === 0) {\n        $li.addClass('selected');\n      }\n    }\n\n    this.$options = this.$container.find('.graduation');\n\n    this.addListener(this.$container, 'resize', this._handleResize.bind(this));\n    this.addListener(\n      this.$container,\n      'tapstart',\n      this._handleTapStart.bind(this)\n    );\n    this.addListener(Garnish.$bod, 'tapmove', this._handleTapMove.bind(this));\n    this.addListener(Garnish.$bod, 'tapend', this._handleTapEnd.bind(this));\n\n    // Set to zero\n\n    // this.setValue(0);\n\n    setTimeout(() => {\n      // (n -1) options because the border is placed on the left of the 10px box\n      this.graduationsCalculatedWidth = (this.$options.length - 1) * 10;\n      this.$graduationsUl.css(\n        'left',\n        -this.graduationsCalculatedWidth / 2 + this.$container.width() / 2\n      );\n    }, 50);\n  },\n\n  _handleResize: function () {\n    var left = this.valueToPosition(this.value);\n    this.$graduationsUl.css('left', left);\n  },\n\n  _handleTapStart: function (ev, touch) {\n    ev.preventDefault();\n\n    this.startPositionX = touch.position.x;\n    this.startLeft = this.$graduationsUl.position().left;\n\n    this.dragging = true;\n    this.onStart();\n  },\n\n  _handleTapMove: function (ev, touch) {\n    if (this.dragging) {\n      ev.preventDefault();\n\n      var curX = this.startPositionX - touch.position.x;\n      var left = this.startLeft - curX;\n      var value = this.positionToValue(left);\n\n      this.setValue(value);\n\n      this.onChange();\n    }\n  },\n\n  setValue: function (value) {\n    var left = this.valueToPosition(value);\n    if (value < this.slideMin) {\n      value = this.slideMin;\n      left = this.valueToPosition(value);\n    } else if (value > this.slideMax) {\n      value = this.slideMax;\n      left = this.valueToPosition(value);\n    }\n\n    this.$graduationsUl.css('left', left);\n\n    if (value >= this.slideMin && value <= this.slideMax) {\n      this.$options.removeClass('selected');\n\n      $.each(this.$options, function (key, option) {\n        if ($(option).data('graduation') > 0) {\n          if ($(option).data('graduation') <= value) {\n            $(option).addClass('selected');\n          }\n        }\n        if ($(option).data('graduation') < 0) {\n          if ($(option).data('graduation') >= value) {\n            $(option).addClass('selected');\n          }\n        }\n\n        if ($(option).data('graduation') == 0) {\n          $(option).addClass('selected');\n        }\n      });\n    }\n\n    this.value = value;\n  },\n\n  _handleTapEnd: function (ev) {\n    if (this.dragging) {\n      ev.preventDefault();\n      this.dragging = false;\n      this.onEnd();\n    }\n  },\n\n  positionToValue: function (position) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return (\n      ((this.$graduations.width() / 2 + position * -1) /\n        this.graduationsCalculatedWidth) *\n        scaleMax -\n      scaleMin\n    );\n  },\n\n  valueToPosition: function (value) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return -(\n      ((value + scaleMin) * this.graduationsCalculatedWidth) / scaleMax -\n      this.$graduations.width() / 2\n    );\n  },\n\n  onStart: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onStart(this);\n    }\n  },\n\n  onChange: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onChange(this);\n    }\n  },\n\n  onEnd: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onEnd(this);\n    }\n  },\n\n  defaultSettings: {\n    onStart: $.noop,\n    onChange: $.noop,\n    onEnd: $.noop,\n  },\n});\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.Slideout = Garnish.Base.extend(\n    {\n      $outerContainer: null,\n      $container: null,\n      $shade: null,\n      isOpen: false,\n\n      init: function (contents, settings) {\n        this.setSettings(settings, Craft.Slideout.defaults);\n\n        if (!Garnish.isMobileBrowser()) {\n          this.$shade = $('<div class=\"slideout-shade\"/>').appendTo(\n            Garnish.$bod\n          );\n\n          if (this.settings.closeOnShadeClick) {\n            this.addListener(this.$shade, 'click', (ev) => {\n              ev.stopPropagation();\n              this.close();\n            });\n          }\n        }\n\n        this.$outerContainer = $('<div/>', {\n          class: 'slideout-container hidden',\n        });\n        this.$container = $(\n          `<${this.settings.containerElement}/>`,\n          this.settings.containerAttributes\n        )\n          .addClass('slideout')\n          .append(contents)\n          .data('slideout', this)\n          .appendTo(this.$outerContainer);\n\n        Garnish.addModalAttributes(this.$outerContainer);\n\n        if (Garnish.isMobileBrowser()) {\n          this.$container.addClass('so-mobile');\n        }\n\n        Craft.trapFocusWithin(this.$container);\n\n        if (this.settings.autoOpen) {\n          this.open();\n        }\n      },\n\n      open: function () {\n        if (this.isOpen) {\n          return;\n        }\n\n        this.setTriggerElement(document.activeElement);\n\n        this._cancelTransitionListeners();\n\n        // Move the shade + container to the end of <body> so they get the highest sub-z-indexes\n        if (this.$shade) {\n          this.$shade.appendTo(Garnish.$bod).show();\n        }\n\n        this.$outerContainer.appendTo(Garnish.$bod).removeClass('hidden');\n\n        if (Garnish.isMobileBrowser()) {\n          this.$container.css('top', '100vh');\n        } else {\n          this.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n        }\n\n        this.$container.one('transitionend.slideout', () => {\n          Craft.setFocusWithin(this.$container);\n        });\n\n        if (this.$shade) {\n          this.$shade[0].offsetWidth;\n          this.$shade.addClass('so-visible');\n        }\n\n        this.$container[0].offsetWidth;\n        Craft.Slideout.addPanel(this);\n\n        this.enable();\n        Garnish.uiLayerManager.addLayer(this.$outerContainer);\n        Garnish.hideModalBackgroundLayers(this.$outerContainer);\n\n        if (this.settings.closeOnEsc) {\n          Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n            this.close();\n          });\n        }\n\n        this.isOpen = true;\n        this.trigger('open');\n      },\n\n      setTriggerElement: function (trigger) {\n        this.settings.triggerElement = trigger;\n      },\n\n      close: function () {\n        if (!this.isOpen) {\n          return;\n        }\n\n        this.trigger('beforeClose');\n        this.disable();\n        this.isOpen = false;\n\n        this._cancelTransitionListeners();\n\n        if (this.$shade) {\n          this.$shade\n            .removeClass('so-visible')\n            .one('transitionend.slideout', () => {\n              this.$shade.hide();\n            });\n        }\n\n        Craft.Slideout.removePanel(this);\n        Garnish.uiLayerManager.removeLayer();\n        Garnish.resetModalBackgroundLayerVisibility(this.$outerContainer);\n        this.$container.one('transitionend.slideout', () => {\n          this.$outerContainer.addClass('hidden');\n          this.trigger('close');\n        });\n\n        if (this.settings.triggerElement) {\n          this.settings.triggerElement.focus();\n        }\n      },\n\n      _cancelTransitionListeners: function () {\n        if (this.$shade) {\n          this.$shade.off('transitionend.slideout');\n        }\n\n        this.$container.off('transitionend.slideout');\n      },\n\n      /**\n       * Destroy\n       */\n      destroy: function () {\n        if (this.$shade) {\n          this.$shade.remove();\n          this.$shade = null;\n        }\n\n        this.$outerContainer.remove();\n        this.$outerContainer = null;\n        this.$container = null;\n\n        this.base();\n      },\n    },\n    {\n      defaults: {\n        containerElement: 'div',\n        containerAttributes: {},\n        autoOpen: true,\n        closeOnEsc: true,\n        closeOnShadeClick: true,\n        triggerElement: null,\n      },\n      openPanels: [],\n      addPanel: function (panel) {\n        Craft.Slideout.openPanels.unshift(panel);\n        if (Garnish.isMobileBrowser()) {\n          panel.$container.css('top', 0);\n        } else {\n          Craft.Slideout.updateStyles();\n        }\n      },\n      removePanel: function (panel) {\n        Craft.Slideout.openPanels = Craft.Slideout.openPanels.filter(\n          (m) => m !== panel\n        );\n        if (Garnish.isMobileBrowser()) {\n          panel.$container.css('top', '100vh');\n        } else {\n          panel.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n          Craft.Slideout.updateStyles();\n        }\n      },\n      updateStyles: function () {\n        const totalPanels = Craft.Slideout.openPanels.length;\n        Craft.Slideout.openPanels.forEach((panel, i) => {\n          panel.$container.css(\n            Garnish.ltr ? 'left' : 'right',\n            `${50 * ((totalPanels - i) / totalPanels)}vw`\n          );\n        });\n\n        if (totalPanels !== 0) {\n          Garnish.$bod.addClass('no-scroll');\n        } else {\n          Garnish.$bod.removeClass('no-scroll');\n        }\n      },\n    }\n  );\n})(jQuery);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Slug Generator\n */\nCraft.SlugGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Remove inner-word punctuation\n    sourceVal = sourceVal.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    if (!Craft.allowUppercaseInSlug) {\n      sourceVal = sourceVal.toLowerCase();\n    }\n\n    if (Craft.limitAutoSlugsToAscii) {\n      // Convert extended ASCII characters to basic ASCII\n      sourceVal = Craft.asciiString(sourceVal, this.settings.charMap);\n    }\n\n    // Get the \"words\". Split on anything that is not alphanumeric.\n    // Reference: http://www.regular-expressions.info/unicode.html\n    var words = Craft.filterArray(\n      XRegExp.matchChain(sourceVal, [XRegExp('[\\\\p{L}\\\\p{N}\\\\p{M}]+')])\n    );\n\n    if (words.length) {\n      return words.join(Craft.slugWordSeparator);\n    } else {\n      return '';\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure class\n */\nCraft.Structure = Garnish.Base.extend(\n  {\n    id: null,\n\n    $container: null,\n    state: null,\n    structureDrag: null,\n\n    /**\n     * Init\n     */\n    init: function (id, container, settings) {\n      this.id = id;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Structure.defaults);\n\n      // Is this already a structure?\n      if (this.$container.data('structure')) {\n        console.warn('Double-instantiating a structure on an element');\n        this.$container.data('structure').destroy();\n      }\n\n      this.$container.data('structure', this);\n\n      this.state = {};\n\n      if (this.settings.storageKey) {\n        $.extend(\n          this.state,\n          Craft.getLocalStorage(this.settings.storageKey, {})\n        );\n      }\n\n      if (typeof this.state.collapsedElementIds === 'undefined') {\n        this.state.collapsedElementIds = [];\n      }\n\n      var $parents = this.$container.find('ul').prev('.row');\n\n      for (var i = 0; i < $parents.length; i++) {\n        var $row = $($parents[i]),\n          $li = $row.parent(),\n          $toggle = $(\n            '<div class=\"toggle\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\"/>'\n          ).prependTo($row);\n\n        if (\n          $.inArray(\n            $row.children('.element').data('id'),\n            this.state.collapsedElementIds\n          ) !== -1\n        ) {\n          $li.addClass('collapsed');\n        }\n\n        this.initToggle($toggle);\n      }\n\n      if (this.settings.sortable) {\n        this.structureDrag = new Craft.StructureDrag(\n          this,\n          this.settings.maxLevels\n        );\n      }\n\n      if (this.settings.newChildUrl) {\n        this.initNewChildMenus(this.$container.find('.add'));\n      }\n    },\n\n    initToggle: function ($toggle) {\n      $toggle.on('click', (ev) => {\n        var $li = $(ev.currentTarget).closest('li'),\n          elementId = $li.children('.row').find('.element:first').data('id'),\n          viewStateKey = $.inArray(elementId, this.state.collapsedElementIds);\n\n        if ($li.hasClass('collapsed')) {\n          $li.removeClass('collapsed');\n\n          if (viewStateKey !== -1) {\n            this.state.collapsedElementIds.splice(viewStateKey, 1);\n          }\n        } else {\n          $li.addClass('collapsed');\n\n          if (viewStateKey === -1) {\n            this.state.collapsedElementIds.push(elementId);\n          }\n        }\n\n        if (this.settings.storageKey) {\n          Craft.setLocalStorage(this.settings.storageKey, this.state);\n        }\n      });\n    },\n\n    initNewChildMenus: function ($addBtns) {\n      this.addListener($addBtns, 'click', 'onNewChildMenuClick');\n    },\n\n    onNewChildMenuClick: function (ev) {\n      var $btn = $(ev.currentTarget);\n\n      if (!$btn.data('menubtn')) {\n        var elementId = $btn.parent().children('.element').data('id'),\n          newChildUrl = Craft.getUrl(\n            this.settings.newChildUrl,\n            'parentId=' + elementId\n          );\n\n        $(\n          '<div class=\"menu\"><ul><li><a href=\"' +\n            newChildUrl +\n            '\">' +\n            Craft.t('app', 'New child') +\n            '</a></li></ul></div>'\n        ).insertAfter($btn);\n\n        var menuBtn = new Garnish.MenuBtn($btn);\n        menuBtn.showMenu();\n      }\n    },\n\n    getIndent: function (level) {\n      return (\n        Craft.Structure.baseIndent + (level - 1) * Craft.Structure.nestedIndent\n      );\n    },\n\n    addElement: function ($element) {\n      var $li = $('<li data-level=\"1\"/>').appendTo(this.$container),\n        $row = $(\n          '<div class=\"row\" style=\"margin-' +\n            Craft.left +\n            ': -' +\n            Craft.Structure.baseIndent +\n            'px; padding-' +\n            Craft.left +\n            ': ' +\n            Craft.Structure.baseIndent +\n            'px;\">'\n        ).appendTo($li);\n\n      $row.append($element);\n\n      if (this.settings.sortable) {\n        $row.append(\n          '<a class=\"move icon\" title=\"' + Craft.t('app', 'Move') + '\"></a>'\n        );\n        this.structureDrag.addItems($li);\n      }\n\n      if (this.settings.newChildUrl) {\n        var $addBtn = $(\n          '<a class=\"add icon\" title=\"' + Craft.t('app', 'New child') + '\"></a>'\n        ).appendTo($row);\n        this.initNewChildMenus($addBtn);\n      }\n\n      $row.css('margin-bottom', -30);\n      $row.velocity({'margin-bottom': 0}, 'fast');\n    },\n\n    removeElement: function ($element) {\n      var $li = $element.parent().parent();\n\n      if (this.settings.sortable) {\n        this.structureDrag.removeItems($li);\n      }\n\n      var $parentUl;\n\n      if (!$li.siblings().length) {\n        $parentUl = $li.parent();\n      }\n\n      $li\n        .css('visibility', 'hidden')\n        .velocity({marginBottom: -$li.height()}, 'fast', () => {\n          $li.remove();\n\n          if (typeof $parentUl !== 'undefined') {\n            this._removeUl($parentUl);\n          }\n        });\n    },\n\n    _removeUl: function ($ul) {\n      $ul.siblings('.row').children('.toggle').remove();\n      $ul.remove();\n    },\n\n    destroy: function () {\n      this.$container.removeData('structure');\n      this.base();\n    },\n  },\n  {\n    baseIndent: 8,\n    nestedIndent: 35,\n\n    defaults: {\n      storageKey: null,\n      sortable: false,\n      newChildUrl: null,\n      maxLevels: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure drag class\n */\nCraft.StructureDrag = Garnish.Drag.extend({\n  structure: null,\n  maxLevels: null,\n  draggeeLevel: null,\n\n  $helperLi: null,\n  $targets: null,\n  draggeeHeight: null,\n\n  init: function (structure, maxLevels) {\n    this.structure = structure;\n    this.maxLevels = maxLevels;\n\n    this.$insertion = $('<li class=\"draginsertion\"/>');\n\n    var $items = this.structure.$container.find('li');\n\n    this.base($items, {\n      handle: '.element:first, .move:first',\n      helper: this.getHelper.bind(this),\n    });\n  },\n\n  getHelper: function ($helper) {\n    this.$helperLi = $helper;\n    var $ul = $('<ul class=\"structure draghelper\"/>').append($helper);\n    $helper.css(\n      'padding-' + Craft.left,\n      this.$draggee.css('padding-' + Craft.left)\n    );\n    $helper.find('.move').removeAttr('title');\n    return $ul;\n  },\n\n  onDragStart: function () {\n    this.$targets = $();\n\n    // Recursively find each of the targets, in the order they appear to be in\n    this.findTargets(this.structure.$container);\n\n    // How deep does the rabbit hole go?\n    this.draggeeLevel = 0;\n    var $level = this.$draggee;\n    do {\n      this.draggeeLevel++;\n      $level = $level.find('> ul > li');\n    } while ($level.length);\n\n    // Collapse the draggee\n    this.draggeeHeight = this.$draggee.height();\n    this.$draggee.velocity(\n      {\n        height: 0,\n      },\n      'fast',\n      () => {\n        this.$draggee.addClass('hidden');\n      }\n    );\n    this.base();\n\n    this.addListener(Garnish.$doc, 'keydown', function (ev) {\n      if (ev.keyCode === Garnish.ESC_KEY) {\n        this.cancelDrag();\n      }\n    });\n  },\n\n  findTargets: function ($ul) {\n    var $lis = $ul.children().not(this.$draggee);\n\n    for (var i = 0; i < $lis.length; i++) {\n      var $li = $($lis[i]);\n      this.$targets = this.$targets.add($li.children('.row'));\n\n      if (!$li.hasClass('collapsed')) {\n        this.findTargets($li.children('ul'));\n      }\n    }\n  },\n\n  onDrag: function () {\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n      this.$insertion.remove();\n    }\n\n    // First let's find the closest target\n    this._.$closestTarget = null;\n    this._.closestTargetPos = null;\n    this._.closestTargetYDiff = null;\n    this._.closestTargetOffset = null;\n    this._.closestTargetHeight = null;\n\n    for (this._.i = 0; this._.i < this.$targets.length; this._.i++) {\n      this._.$target = $(this.$targets[this._.i]);\n      this._.targetOffset = this._.$target.offset();\n      this._.targetHeight = this._.$target.outerHeight();\n      this._.targetYMidpoint =\n        this._.targetOffset.top + this._.targetHeight / 2;\n      this._.targetYDiff = Math.abs(this.mouseY - this._.targetYMidpoint);\n\n      if (\n        this._.i === 0 ||\n        (this.mouseY >= this._.targetOffset.top + 5 &&\n          this._.targetYDiff < this._.closestTargetYDiff)\n      ) {\n        this._.$closestTarget = this._.$target;\n        this._.closestTargetPos = this._.i;\n        this._.closestTargetYDiff = this._.targetYDiff;\n        this._.closestTargetOffset = this._.targetOffset;\n        this._.closestTargetHeight = this._.targetHeight;\n      } else {\n        // Getting colder\n        break;\n      }\n    }\n\n    if (!this._.$closestTarget) {\n      return;\n    }\n\n    // Are we hovering above the first row?\n    if (\n      this._.closestTargetPos === 0 &&\n      this.mouseY < this._.closestTargetOffset.top + 5\n    ) {\n      this.$insertion.prependTo(this.structure.$container);\n    } else {\n      this._.$closestTargetLi = this._.$closestTarget.parent();\n      this._.closestTargetLevel = this._.$closestTargetLi.data('level');\n\n      // Is there a next row?\n      if (this._.closestTargetPos < this.$targets.length - 1) {\n        this._.$nextTargetLi = $(\n          this.$targets[this._.closestTargetPos + 1]\n        ).parent();\n        this._.nextTargetLevel = this._.$nextTargetLi.data('level');\n      } else {\n        this._.$nextTargetLi = null;\n        this._.nextTargetLevel = null;\n      }\n\n      // Are we hovering between this row and the next one?\n      this._.hoveringBetweenRows =\n        this.mouseY >=\n        this._.closestTargetOffset.top + this._.closestTargetHeight - 5;\n\n      /**\n       * Scenario 1: Both rows have the same level.\n       *\n       *     * Row 1\n       *     ----------------------\n       *     * Row 2\n       */\n\n      if (\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel == this._.closestTargetLevel\n      ) {\n        if (this._.hoveringBetweenRows) {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel - 1\n          ) {\n            // Position the insertion after the closest target\n            this.$insertion.insertAfter(this._.$closestTargetLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      } else if (\n        /**\n         * Scenario 2: Next row is a child of this one.\n         *\n         *     * Row 1\n         *     ----------------------\n         *         * Row 2\n         */\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel > this._.closestTargetLevel\n      ) {\n        if (\n          !this.maxLevels ||\n          this.maxLevels >= this._.nextTargetLevel + this.draggeeLevel - 1\n        ) {\n          if (this._.hoveringBetweenRows) {\n            // Position the insertion as the first child of the closest target\n            this.$insertion.insertBefore(this._.$nextTargetLi);\n          } else {\n            this._.$closestTarget.addClass('draghover');\n            this.$insertion.appendTo(this._.$closestTargetLi.children('ul'));\n          }\n        }\n      } else {\n        /**\n         * Scenario 3: Next row is a child of a parent node, or there is no next row.\n         *\n         *         * Row 1\n         *     ----------------------\n         *     * Row 2\n         */\n        if (this._.hoveringBetweenRows) {\n          // Determine which <li> to position the insertion after\n          this._.draggeeX = this.mouseX - this.targetItemMouseDiffX;\n\n          if (Craft.orientation === 'rtl') {\n            this._.draggeeX += this.$helperLi.width();\n          }\n\n          this._.$parentLis = this._.$closestTarget.parentsUntil(\n            this.structure.$container,\n            'li'\n          );\n          this._.$closestParentLi = null;\n          this._.closestParentLiXDiff = null;\n          this._.closestParentLevel = null;\n\n          for (this._.i = 0; this._.i < this._.$parentLis.length; this._.i++) {\n            this._.$parentLi = $(this._.$parentLis[this._.i]);\n            this._.parentLiX = this._.$parentLi.offset().left;\n\n            if (Craft.orientation === 'rtl') {\n              this._.parentLiX += this._.$parentLi.width();\n            }\n\n            this._.parentLiXDiff = Math.abs(this._.parentLiX - this._.draggeeX);\n            this._.parentLevel = this._.$parentLi.data('level');\n\n            if (\n              (!this.maxLevels ||\n                this.maxLevels >= this._.parentLevel + this.draggeeLevel - 1) &&\n              (!this._.$closestParentLi ||\n                (this._.parentLiXDiff < this._.closestParentLiXDiff &&\n                  (!this._.$nextTargetLi ||\n                    this._.parentLevel >= this._.nextTargetLevel)))\n            ) {\n              this._.$closestParentLi = this._.$parentLi;\n              this._.closestParentLiXDiff = this._.parentLiXDiff;\n              this._.closestParentLevel = this._.parentLevel;\n            }\n          }\n\n          if (this._.$closestParentLi) {\n            this.$insertion.insertAfter(this._.$closestParentLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      }\n    }\n  },\n\n  cancelDrag: function () {\n    this.$insertion.remove();\n\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n    }\n\n    this.onMouseUp();\n  },\n\n  onDragStop: function () {\n    // Are we repositioning the draggee?\n    if (\n      this._.$closestTarget &&\n      (this.$insertion.parent().length ||\n        this._.$closestTarget.hasClass('draghover'))\n    ) {\n      var $draggeeParent, moved;\n\n      // Are we about to leave the draggee's original parent childless?\n      if (!this.$draggee.siblings().length) {\n        $draggeeParent = this.$draggee.parent();\n      }\n\n      if (this.$insertion.parent().length) {\n        // Make sure the insertion isn't right next to the draggee\n        var $closestSiblings = this.$insertion\n          .next()\n          .add(this.$insertion.prev());\n\n        if ($.inArray(this.$draggee[0], $closestSiblings) === -1) {\n          this.$insertion.replaceWith(this.$draggee);\n          moved = true;\n        } else {\n          this.$insertion.remove();\n          moved = false;\n        }\n      } else {\n        var $ul = this._.$closestTargetLi.children('ul');\n\n        // Make sure this is a different parent than the draggee's\n        if (!$draggeeParent || !$ul.length || $ul[0] !== $draggeeParent[0]) {\n          if (!$ul.length) {\n            var $toggle = $(\n              '<div class=\"toggle\" title=\"' +\n                Craft.t('app', 'Show/hide children') +\n                '\"/>'\n            ).prependTo(this._.$closestTarget);\n            this.structure.initToggle($toggle);\n\n            $ul = $('<ul>').appendTo(this._.$closestTargetLi);\n          } else if (this._.$closestTargetLi.hasClass('collapsed')) {\n            this._.$closestTarget.children('.toggle').trigger('click');\n          }\n\n          this.$draggee.appendTo($ul);\n          moved = true;\n        } else {\n          moved = false;\n        }\n      }\n\n      // Remove the class either way\n      this._.$closestTarget.removeClass('draghover');\n\n      if (moved) {\n        // Now deal with the now-childless parent\n        if ($draggeeParent) {\n          this.structure._removeUl($draggeeParent);\n        }\n\n        // Has the level changed?\n        var newLevel =\n          this.$draggee.parentsUntil(this.structure.$container, 'li').length +\n          1;\n\n        var animateCss;\n\n        if (newLevel != this.$draggee.data('level')) {\n          // Correct the helper's padding if moving to/from level 1\n          if (this.$draggee.data('level') == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = 38;\n            this.$helperLi.velocity(animateCss, 'fast');\n          } else if (newLevel == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = Craft.Structure.baseIndent;\n            this.$helperLi.velocity(animateCss, 'fast');\n          }\n\n          this.setLevel(this.$draggee, newLevel);\n        }\n\n        // Make it real\n        var $element = this.$draggee.children('.row').children('.element');\n\n        var data = {\n          structureId: this.structure.id,\n          elementId: $element.data('id'),\n          siteId: $element.data('site-id'),\n          prevId: this.$draggee\n            .prev()\n            .children('.row')\n            .children('.element')\n            .data('id'),\n          parentId: this.$draggee\n            .parent('ul')\n            .parent('li')\n            .children('.row')\n            .children('.element')\n            .data('id'),\n        };\n\n        Craft.postActionRequest(\n          'structures/move-element',\n          data,\n          function (response, textStatus) {\n            if (textStatus === 'success') {\n              Craft.cp.displayNotice(Craft.t('app', 'New order saved.'));\n            }\n          }\n        );\n      }\n    }\n\n    // Animate things back into place\n    this.$draggee\n      .velocity('stop')\n      .removeClass('hidden')\n      .velocity(\n        {\n          height: this.draggeeHeight,\n        },\n        'fast',\n        () => {\n          this.$draggee.css('height', 'auto');\n        }\n      );\n\n    this.returnHelpersToDraggees();\n\n    this.base();\n  },\n\n  setLevel: function ($li, level) {\n    $li.data('level', level);\n\n    var indent = this.structure.getIndent(level);\n\n    var css = {};\n    css['margin-' + Craft.left] = '-' + indent + 'px';\n    css['padding-' + Craft.left] = indent + 'px';\n    this.$draggee.children('.row').css(css);\n\n    var $childLis = $li.children('ul').children();\n\n    for (var i = 0; i < $childLis.length; i++) {\n      this.setLevel($($childLis[i]), level + 1);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.StructureTableSorter = Garnish.DragSort.extend(\n  {\n    tableView: null,\n    structureId: null,\n    maxLevels: null,\n\n    _basePadding: null,\n    _helperMargin: null,\n\n    _$firstRowCells: null,\n    _$titleHelperCell: null,\n\n    _titleHelperCellOuterWidth: null,\n\n    _ancestors: null,\n    _updateAncestorsFrame: null,\n\n    _draggeeLevel: null,\n    _draggeeLevelDelta: null,\n    draggingLastElements: null,\n    _loadingDraggeeLevelDelta: false,\n\n    _targetLevel: null,\n    _targetLevelBounds: null,\n\n    _positionChanged: null,\n\n    /**\n     * Constructor\n     */\n    init: function (tableView, $elements, settings) {\n      this.tableView = tableView;\n      this.structureId = this.tableView.$table.data('structure-id');\n      this.maxLevels = parseInt(this.tableView.$table.attr('data-max-levels'));\n\n      this._basePadding = 14 + (this.tableView.elementIndex.actions ? 14 : 24); // see _elements/tableview/elements.html\n      this._helperMargin = this.tableView.elementIndex.actions ? 54 : 0;\n\n      settings = $.extend({}, Craft.StructureTableSorter.defaults, settings, {\n        handle: '.move',\n        collapseDraggees: true,\n        singleHelper: true,\n        helperSpacingY: 2,\n        magnetStrength: 4,\n        helper: this.getHelper.bind(this),\n        helperLagBase: 1.5,\n        axis: Garnish.Y_AXIS,\n      });\n\n      this.base($elements, settings);\n    },\n\n    /**\n     * Returns the draggee rows (including any descendent rows).\n     */\n    findDraggee: function () {\n      this._draggeeLevel = this._targetLevel = this.$targetItem.data('level');\n      this._draggeeLevelDelta = 0;\n\n      var $draggee = $(this.$targetItem),\n        $nextRow = this.$targetItem.next();\n\n      while ($nextRow.length) {\n        // See if this row is a descendant of the draggee\n        var nextRowLevel = $nextRow.data('level');\n\n        if (nextRowLevel <= this._draggeeLevel) {\n          break;\n        }\n\n        // Is this the deepest descendant we've seen so far?\n        var nextRowLevelDelta = nextRowLevel - this._draggeeLevel;\n\n        if (nextRowLevelDelta > this._draggeeLevelDelta) {\n          this._draggeeLevelDelta = nextRowLevelDelta;\n        }\n\n        // Add it and prep the next row\n        $draggee = $draggee.add($nextRow);\n        $nextRow = $nextRow.next();\n      }\n\n      // Are we dragging the last elements on the page?\n      this.draggingLastElements = !$nextRow.length;\n\n      // Do we have a maxLevels to enforce,\n      // and does it look like this draggee has descendants we don't know about yet?\n      if (\n        this.maxLevels &&\n        this.draggingLastElements &&\n        this.tableView.getMorePending()\n      ) {\n        // Only way to know the true descendant level delta is to ask PHP\n        this._loadingDraggeeLevelDelta = true;\n\n        var data = this._getAjaxBaseData(this.$targetItem);\n\n        Craft.postActionRequest(\n          'structures/get-element-level-delta',\n          data,\n          (response, textStatus) => {\n            if (textStatus === 'success') {\n              this._loadingDraggeeLevelDelta = false;\n\n              if (this.dragging) {\n                this._draggeeLevelDelta = response.delta;\n                this.drag(false);\n              }\n            }\n          }\n        );\n      }\n\n      return $draggee;\n    },\n\n    /**\n     * Returns the drag helper.\n     */\n    getHelper: function ($helperRow) {\n      var $outerContainer = $(\n          '<div class=\"elements datatablesorthelper\"/>'\n        ).appendTo(Garnish.$bod),\n        $innerContainer = $('<div class=\"tableview\"/>').appendTo(\n          $outerContainer\n        ),\n        $table = $('<table class=\"data\"/>').appendTo($innerContainer),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the column widths\n      this._$firstRowCells = this.tableView.$elementContainer\n        .children('tr:first')\n        .children();\n      var $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        var $helperCell = $($helperCells[i]);\n\n        // Skip the checkbox cell\n        if ($helperCell.hasClass('checkbox-cell')) {\n          $helperCell.remove();\n          continue;\n        }\n\n        // Hard-set the cell widths\n        var $firstRowCell = $(this._$firstRowCells[i]);\n        var width = $firstRowCell[0].getBoundingClientRect().width;\n\n        $firstRowCell.css('width', width + 'px');\n        $helperCell.css('width', width + 'px');\n\n        // Is this the title cell?\n        if (Garnish.hasAttr($firstRowCell, 'data-titlecell')) {\n          this._$titleHelperCell = $helperCell;\n\n          var padding = parseInt($firstRowCell.css('padding-' + Craft.left));\n          this._titleHelperCellOuterWidth = width;\n\n          $helperCell.css('padding-' + Craft.left, this._basePadding);\n        }\n      }\n\n      return $outerContainer;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted before a given item.\n     */\n    canInsertBefore: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item.prev(), $item) !== false;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted after a given item.\n     */\n    canInsertAfter: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item, $item.next()) !== false;\n    },\n\n    // Events\n    // -------------------------------------------------------------------------\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      // Get the initial set of ancestors, before the item gets moved\n      this._ancestors = this._getAncestors(\n        this.$targetItem,\n        this.$targetItem.data('level')\n      );\n\n      // Set the initial target level bounds\n      this._setTargetLevelBounds();\n\n      // Check to see if we should load more elements now\n      this.tableView.maybeLoadMore();\n\n      this.base();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      this.base();\n      this._updateIndent();\n    },\n\n    /**\n     * On Insertion Point Change\n     */\n    onInsertionPointChange: function () {\n      this._setTargetLevelBounds();\n      this._updateAncestorsBeforeRepaint();\n      this.base();\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      this._positionChanged = false;\n      this.base();\n\n      // Update the draggee's padding if the position just changed\n      // ---------------------------------------------------------------------\n\n      if (this._targetLevel != this._draggeeLevel) {\n        var levelDiff = this._targetLevel - this._draggeeLevel;\n\n        for (var i = 0; i < this.$draggee.length; i++) {\n          var $draggee = $(this.$draggee[i]),\n            oldLevel = $draggee.data('level'),\n            newLevel = oldLevel + levelDiff,\n            padding = this._basePadding + this._getLevelIndent(newLevel);\n\n          $draggee.data('level', newLevel);\n          $draggee.find('.element').data('level', newLevel);\n          $draggee\n            .children('[data-titlecell]:first')\n            .css('padding-' + Craft.left, padding);\n        }\n\n        this._positionChanged = true;\n      }\n\n      // Keep in mind this could have also been set by onSortChange()\n      if (this._positionChanged) {\n        // Tell the server about the new position\n        // -----------------------------------------------------------------\n\n        var data = this._getAjaxBaseData(this.$draggee);\n\n        // Find the previous sibling/parent, if there is one\n        var $prevRow = this.$draggee.first().prev();\n\n        while ($prevRow.length) {\n          var prevRowLevel = $prevRow.data('level');\n\n          if (prevRowLevel == this._targetLevel) {\n            data.prevId = $prevRow.data('id');\n            break;\n          }\n\n          if (prevRowLevel < this._targetLevel) {\n            data.parentId = $prevRow.data('id');\n\n            // Is this row collapsed?\n            var $toggle = $prevRow.find('> th > .toggle');\n\n            if (!$toggle.hasClass('expanded')) {\n              // Make it look expanded\n              $toggle.addClass('expanded');\n\n              // Add a temporary row\n              var $spinnerRow = this.tableView._createSpinnerRowAfter($prevRow);\n\n              // Remove the target item\n              if (this.tableView.elementSelect) {\n                this.tableView.elementSelect.removeItems(this.$targetItem);\n              }\n\n              this.removeItems(this.$targetItem);\n              this.$targetItem.remove();\n              this.tableView._totalVisible--;\n            }\n\n            break;\n          }\n\n          $prevRow = $prevRow.prev();\n        }\n\n        Craft.postActionRequest(\n          'structures/move-element',\n          data,\n          (response, textStatus) => {\n            if (textStatus === 'success') {\n              if (!response.success) {\n                Craft.cp.displayError(\n                  Craft.t('app', 'A server error occurred.')\n                );\n                this.tableView.elementIndex.updateElements();\n                return;\n              }\n              Craft.cp.displayNotice(Craft.t('app', 'New position saved.'));\n              this.onPositionChange();\n\n              // Were we waiting on this to complete so we can expand the new parent?\n              if ($spinnerRow && $spinnerRow.parent().length) {\n                $spinnerRow.remove();\n                this.tableView._expandElement($toggle, true);\n              }\n\n              // See if we should run any pending tasks\n              Craft.cp.runQueue();\n            }\n          }\n        );\n      }\n    },\n\n    onSortChange: function () {\n      if (this.tableView.elementSelect) {\n        this.tableView.elementSelect.resetItemOrder();\n      }\n\n      this._positionChanged = true;\n      this.base();\n    },\n\n    onPositionChange: function () {\n      Garnish.requestAnimationFrame(() => {\n        this.trigger('positionChange');\n        this.settings.onPositionChange();\n      });\n    },\n\n    onReturnHelpersToDraggees: function () {\n      this._$firstRowCells.css('width', '');\n\n      // If we were dragging the last elements on the page and ended up loading any additional elements in,\n      // there could be a gap between the last draggee item and whatever now comes after it.\n      // So remove the post-draggee elements and possibly load up the next batch.\n      if (this.draggingLastElements && this.tableView.getMorePending()) {\n        // Update the element index's record of how many items are actually visible\n        this.tableView._totalVisible +=\n          this.newDraggeeIndexes[0] - this.oldDraggeeIndexes[0];\n\n        var $postDraggeeItems = this.$draggee.last().nextAll();\n\n        if ($postDraggeeItems.length) {\n          this.removeItems($postDraggeeItems);\n          $postDraggeeItems.remove();\n          this.tableView.maybeLoadMore();\n        }\n      }\n\n      this.base();\n    },\n\n    /**\n     * Returns the min and max levels that the draggee could occupy between\n     * two given rows, or false if it’s not going to work out.\n     */\n    _getLevelBounds: function ($prevRow, $nextRow) {\n      // Can't go any lower than the next row, if there is one\n      if ($nextRow && $nextRow.length) {\n        this._getLevelBounds._minLevel = $nextRow.data('level');\n      } else {\n        this._getLevelBounds._minLevel = 1;\n      }\n\n      // Can't go any higher than the previous row + 1\n      if ($prevRow && $prevRow.length) {\n        this._getLevelBounds._maxLevel = $prevRow.data('level') + 1;\n      } else {\n        this._getLevelBounds._maxLevel = 1;\n      }\n\n      // Does this structure have a max level?\n      if (this.maxLevels) {\n        // Make sure it's going to fit at all here\n        if (\n          this._getLevelBounds._minLevel != 1 &&\n          this._getLevelBounds._minLevel + this._draggeeLevelDelta >\n            this.maxLevels\n        ) {\n          return false;\n        }\n\n        // Limit the max level if we have to\n        if (\n          this._getLevelBounds._maxLevel + this._draggeeLevelDelta >\n          this.maxLevels\n        ) {\n          this._getLevelBounds._maxLevel =\n            this.maxLevels - this._draggeeLevelDelta;\n\n          if (this._getLevelBounds._maxLevel < this._getLevelBounds._minLevel) {\n            this._getLevelBounds._maxLevel = this._getLevelBounds._minLevel;\n          }\n        }\n      }\n\n      return {\n        min: this._getLevelBounds._minLevel,\n        max: this._getLevelBounds._maxLevel,\n      };\n    },\n\n    /**\n     * Determines the min and max possible levels at the current draggee's position.\n     */\n    _setTargetLevelBounds: function () {\n      this._targetLevelBounds = this._getLevelBounds(\n        this.$draggee.first().prev(),\n        this.$draggee.last().next()\n      );\n    },\n\n    /**\n     * Determines the target level based on the current mouse position.\n     */\n    _updateIndent: function (forcePositionChange) {\n      // Figure out the target level\n      // ---------------------------------------------------------------------\n\n      // How far has the cursor moved?\n      this._updateIndent._mouseDist = this.realMouseX - this.mousedownX;\n\n      // Flip that if this is RTL\n      if (Craft.orientation === 'rtl') {\n        this._updateIndent._mouseDist *= -1;\n      }\n\n      // What is that in indentation levels?\n      this._updateIndent._indentationDist = Math.round(\n        this._updateIndent._mouseDist / Craft.StructureTableSorter.LEVEL_INDENT\n      );\n\n      // Combine with the original level to get the new target level\n      this._updateIndent._targetLevel =\n        this._draggeeLevel + this._updateIndent._indentationDist;\n\n      // Contain it within our min/max levels\n      if (this._updateIndent._targetLevel < this._targetLevelBounds.min) {\n        this._updateIndent._indentationDist +=\n          this._targetLevelBounds.min - this._updateIndent._targetLevel;\n        this._updateIndent._targetLevel = this._targetLevelBounds.min;\n      } else if (\n        this._updateIndent._targetLevel > this._targetLevelBounds.max\n      ) {\n        this._updateIndent._indentationDist -=\n          this._updateIndent._targetLevel - this._targetLevelBounds.max;\n        this._updateIndent._targetLevel = this._targetLevelBounds.max;\n      }\n\n      // Has the target level changed?\n      if (\n        this._targetLevel !==\n        (this._targetLevel = this._updateIndent._targetLevel)\n      ) {\n        // Target level is changing, so update the ancestors\n        this._updateAncestorsBeforeRepaint();\n      }\n\n      // Update the UI\n      // ---------------------------------------------------------------------\n\n      // How far away is the cursor from the exact target level distance?\n      this._updateIndent._targetLevelMouseDiff =\n        this._updateIndent._mouseDist -\n        this._updateIndent._indentationDist *\n          Craft.StructureTableSorter.LEVEL_INDENT;\n\n      // What's the magnet impact of that?\n      this._updateIndent._magnetImpact = Math.round(\n        this._updateIndent._targetLevelMouseDiff / 15\n      );\n\n      // Put it on a leash\n      if (\n        Math.abs(this._updateIndent._magnetImpact) >\n        Craft.StructureTableSorter.MAX_GIVE\n      ) {\n        this._updateIndent._magnetImpact =\n          (this._updateIndent._magnetImpact > 0 ? 1 : -1) *\n          Craft.StructureTableSorter.MAX_GIVE;\n      }\n\n      // Apply the new margin/width\n      this._updateIndent._closestLevelMagnetIndent =\n        this._getLevelIndent(this._targetLevel) +\n        this._updateIndent._magnetImpact;\n      this.helpers[0].css(\n        'margin-' + Craft.left,\n        this._updateIndent._closestLevelMagnetIndent + this._helperMargin\n      );\n      this._$titleHelperCell.css(\n        'width',\n        this._titleHelperCellOuterWidth -\n          this._updateIndent._closestLevelMagnetIndent\n      );\n    },\n\n    /**\n     * Returns the indent size for a given level\n     */\n    _getLevelIndent: function (level) {\n      return (level - 1) * Craft.StructureTableSorter.LEVEL_INDENT;\n    },\n\n    /**\n     * Returns the base data that should be sent with StructureController Ajax requests.\n     */\n    _getAjaxBaseData: function ($row) {\n      return {\n        structureId: this.structureId,\n        elementId: $row.data('id'),\n        siteId: $row.find('.element:first').data('site-id'),\n      };\n    },\n\n    /**\n     * Returns a row's ancestor rows\n     */\n    _getAncestors: function ($row, targetLevel) {\n      this._getAncestors._ancestors = [];\n\n      if (targetLevel != 0) {\n        this._getAncestors._level = targetLevel;\n        this._getAncestors._$prevRow = $row.prev();\n\n        while (this._getAncestors._$prevRow.length) {\n          if (\n            this._getAncestors._$prevRow.data('level') <\n            this._getAncestors._level\n          ) {\n            this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow);\n            this._getAncestors._level =\n              this._getAncestors._$prevRow.data('level');\n\n            // Did we just reach the top?\n            if (this._getAncestors._level == 0) {\n              break;\n            }\n          }\n\n          this._getAncestors._$prevRow = this._getAncestors._$prevRow.prev();\n        }\n      }\n\n      return this._getAncestors._ancestors;\n    },\n\n    /**\n     * Prepares to have the ancestors updated before the screen is repainted.\n     */\n    _updateAncestorsBeforeRepaint: function () {\n      if (this._updateAncestorsFrame) {\n        Garnish.cancelAnimationFrame(this._updateAncestorsFrame);\n      }\n\n      this._updateAncestorsFrame = Garnish.requestAnimationFrame(\n        this._updateAncestors.bind(this)\n      );\n    },\n\n    _updateAncestors: function () {\n      this._updateAncestorsFrame = null;\n\n      // Update the old ancestors\n      // -----------------------------------------------------------------\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._ancestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._ancestors[this._updateAncestors._i];\n\n        // One less descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') - 1\n        );\n\n        // Is it now childless?\n        if (this._updateAncestors._$ancestor.data('descendants') == 0) {\n          // Remove its toggle\n          this._updateAncestors._$ancestor\n            .find('> th > .toggle:first')\n            .remove();\n        }\n      }\n\n      // Update the new ancestors\n      // -----------------------------------------------------------------\n\n      this._updateAncestors._newAncestors = this._getAncestors(\n        this.$targetItem,\n        this._targetLevel\n      );\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._updateAncestors._newAncestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._updateAncestors._newAncestors[this._updateAncestors._i];\n\n        // One more descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') + 1\n        );\n\n        // Is this its first child?\n        if (this._updateAncestors._$ancestor.data('descendants') == 1) {\n          // Create its toggle\n          $(\n            '<span class=\"toggle expanded\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\"></span>'\n          ).insertAfter(\n            this._updateAncestors._$ancestor.find('> th .move:first')\n          );\n        }\n      }\n\n      this._ancestors = this._updateAncestors._newAncestors;\n\n      delete this._updateAncestors._i;\n      delete this._updateAncestors._$ancestor;\n      delete this._updateAncestors._newAncestors;\n    },\n  },\n  {\n    HELPER_MARGIN: 0,\n    LEVEL_INDENT: 44,\n    MAX_GIVE: 22,\n\n    defaults: {\n      onPositionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Table Element Index View\n */\nCraft.TableElementIndexView = Craft.BaseElementIndexView.extend({\n  $table: null,\n  $selectedSortHeader: null,\n\n  structureTableSort: null,\n\n  _totalVisiblePostStructureTableDraggee: null,\n  _morePendingPostStructureTableDraggee: false,\n\n  getElementContainer: function () {\n    // Save a reference to the table\n    this.$table = this.$container.find('table:first');\n    return this.$table.children('tbody:first');\n  },\n\n  afterInit: function () {\n    // Set the sort header\n    this.initTableHeaders();\n\n    // Create the Structure Table Sorter\n    if (\n      this.elementIndex.settings.context === 'index' &&\n      this.elementIndex.getSelectedSortAttribute() === 'structure' &&\n      Garnish.hasAttr(this.$table, 'data-structure-id')\n    ) {\n      this.structureTableSort = new Craft.StructureTableSorter(\n        this,\n        this.getAllElements()\n      );\n    } else {\n      this.structureTableSort = null;\n    }\n\n    // Handle expand/collapse toggles for Structures\n    if (this.elementIndex.getSelectedSortAttribute() === 'structure') {\n      this.addListener(this.$elementContainer, 'click', function (ev) {\n        var $target = $(ev.target);\n\n        if ($target.hasClass('toggle')) {\n          if (this._collapseElement($target) === false) {\n            this._expandElement($target);\n          }\n        }\n      });\n    }\n  },\n\n  initTableHeaders: function () {\n    var selectedSortAttr = this.elementIndex.getSelectedSortAttribute(),\n      $tableHeaders = this.$table\n        .children('thead')\n        .children()\n        .children('[data-attribute]');\n\n    for (var i = 0; i < $tableHeaders.length; i++) {\n      var $header = $tableHeaders.eq(i),\n        attr = $header.attr('data-attribute');\n\n      // Is this the selected sort attribute?\n      if (attr === selectedSortAttr) {\n        this.$selectedSortHeader = $header;\n        var selectedSortDir = this.elementIndex.getSelectedSortDirection();\n\n        $header\n          .addClass('ordered ' + selectedSortDir)\n          .on('click', this._handleSelectedSortHeaderClick.bind(this));\n      } else {\n        // Is this attribute sortable?\n        var $sortAttribute = this.elementIndex.getSortAttributeOption(attr);\n\n        if ($sortAttribute.length) {\n          $header\n            .addClass('orderable')\n            .on('click', this._handleUnselectedSortHeaderClick.bind(this));\n        }\n      }\n    }\n  },\n\n  isVerticalList: function () {\n    return true;\n  },\n\n  getTotalVisible: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._totalVisiblePostStructureTableDraggee;\n    } else {\n      return this._totalVisible;\n    }\n  },\n\n  setTotalVisible: function (totalVisible) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._totalVisiblePostStructureTableDraggee = totalVisible;\n    } else {\n      this._totalVisible = totalVisible;\n    }\n  },\n\n  getMorePending: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._morePendingPostStructureTableDraggee;\n    } else {\n      return this._morePending;\n    }\n  },\n\n  setMorePending: function (morePending) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._morePendingPostStructureTableDraggee = morePending;\n    } else {\n      this._morePending = this._morePendingPostStructureTableDraggee =\n        morePending;\n    }\n  },\n\n  getLoadMoreParams: function () {\n    var params = this.base();\n\n    // If we are dragging the last elements on the page,\n    // tell the controller to only load elements positioned after the draggee.\n    if (this._isStructureTableDraggingLastElements()) {\n      params.criteria.positionedAfter =\n        this.structureTableSort.$targetItem.data('id');\n    }\n\n    return params;\n  },\n\n  appendElements: function ($newElements) {\n    this.base($newElements);\n\n    if (this.structureTableSort) {\n      this.structureTableSort.addItems($newElements);\n    }\n\n    Craft.cp.updateResponsiveTables();\n  },\n\n  createElementEditor: function ($element) {\n    Craft.createElementEditor($element.data('type'), $element, {\n      params: {\n        includeTableAttributesForSource: this.elementIndex.sourceKey,\n      },\n      onSaveElement: (response) => {\n        if (response.tableAttributes) {\n          this._updateTableAttributes($element, response.tableAttributes);\n        }\n      },\n      elementIndex: this.elementIndex,\n    });\n  },\n\n  _collapseElement: function ($toggle, force) {\n    if (!force && !$toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.removeClass('expanded');\n\n    // Find and remove the descendant rows\n    var $row = $toggle.parent().parent(),\n      id = $row.data('id'),\n      level = $row.data('level'),\n      $nextRow = $row.next();\n\n    while ($nextRow.length) {\n      if (!Garnish.hasAttr($nextRow, 'data-spinnerrow')) {\n        if ($nextRow.data('level') <= level) {\n          break;\n        }\n\n        if (this.elementSelect) {\n          this.elementSelect.removeItems($nextRow);\n        }\n\n        if (this.structureTableSort) {\n          this.structureTableSort.removeItems($nextRow);\n        }\n\n        this._totalVisible--;\n      }\n\n      var $nextNextRow = $nextRow.next();\n      $nextRow.remove();\n      $nextRow = $nextNextRow;\n    }\n\n    // Remember that this row should be collapsed\n    if (!this.elementIndex.instanceState.collapsedElementIds) {\n      this.elementIndex.instanceState.collapsedElementIds = [];\n    }\n\n    this.elementIndex.instanceState.collapsedElementIds.push(id);\n    this.elementIndex.setInstanceState(\n      'collapsedElementIds',\n      this.elementIndex.instanceState.collapsedElementIds\n    );\n\n    // Bottom of the index might be viewable now\n    this.maybeLoadMore();\n  },\n\n  _expandElement: function ($toggle, force) {\n    if (!force && $toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.addClass('expanded');\n\n    // Remove this element from our list of collapsed elements\n    if (this.elementIndex.instanceState.collapsedElementIds) {\n      var $row = $toggle.parent().parent(),\n        id = $row.data('id'),\n        index = $.inArray(\n          id,\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n      if (index !== -1) {\n        this.elementIndex.instanceState.collapsedElementIds.splice(index, 1);\n        this.elementIndex.setInstanceState(\n          'collapsedElementIds',\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n        // Add a temporary row\n        var $spinnerRow = this._createSpinnerRowAfter($row);\n\n        // Load the nested elements\n        let data = $.extend(true, {}, this.settings.params);\n        data.criteria.descendantOf = id;\n\n        Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n          data,\n        })\n          .then((response) => {\n            // Do we even care about this anymore?\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n\n            let $newElements = $(response.data.html);\n\n            // Are there more descendants we didn't get in this batch?\n            let totalVisible = this._totalVisible + $newElements.length;\n            let morePending =\n              this.settings.batchSize &&\n              $newElements.length === this.settings.batchSize;\n\n            if (morePending) {\n              // Remove all the elements after it\n              let $nextRows = $spinnerRow.nextAll();\n\n              if (this.elementSelect) {\n                this.elementSelect.removeItems($nextRows);\n              }\n\n              if (this.structureTableSort) {\n                this.structureTableSort.removeItems($nextRows);\n              }\n\n              $nextRows.remove();\n              totalVisible -= $nextRows.length;\n            } else {\n              // Maintain the current 'more' status\n              morePending = this._morePending;\n            }\n\n            $spinnerRow.replaceWith($newElements);\n            this.thumbLoader.load($newElements);\n\n            if (this.elementIndex.actions || this.settings.selectable) {\n              this.elementSelect.addItems(\n                $newElements.filter(':not(.disabled)')\n              );\n              this.elementIndex.updateActionTriggers();\n            }\n\n            if (this.structureTableSort) {\n              this.structureTableSort.addItems($newElements);\n            }\n\n            Craft.appendHeadHtml(response.data.headHtml);\n            Craft.appendFootHtml(response.data.footHtml);\n            Craft.cp.updateResponsiveTables();\n\n            this.setTotalVisible(totalVisible);\n            this.setMorePending(morePending);\n\n            // Is there room to load more right now?\n            this.maybeLoadMore();\n          })\n          .catch((e) => {\n            Craft.cp.displayError();\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n          });\n      }\n    }\n  },\n\n  _createSpinnerRowAfter: function ($row) {\n    return $(\n      '<tr data-spinnerrow>' +\n        '<td class=\"centeralign\" colspan=\"' +\n        $row.children().length +\n        '\">' +\n        '<div class=\"spinner\"/>' +\n        '</td>' +\n        '</tr>'\n    ).insertAfter($row);\n  },\n\n  _isStructureTableDraggingLastElements: function () {\n    return (\n      this.structureTableSort &&\n      this.structureTableSort.dragging &&\n      this.structureTableSort.draggingLastElements\n    );\n  },\n\n  _handleSelectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget);\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    // Reverse the sort direction\n    var selectedSortDir = this.elementIndex.getSelectedSortDirection(),\n      newSortDir = selectedSortDir === 'asc' ? 'desc' : 'asc';\n\n    this.elementIndex.setSortDirection(newSortDir);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleUnselectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget);\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    var attr = $header.attr('data-attribute');\n\n    this.elementIndex.setSortAttribute(attr);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleSortHeaderClick: function (ev, $header) {\n    if (this.$selectedSortHeader) {\n      this.$selectedSortHeader.removeClass('ordered asc desc');\n    }\n\n    $header.removeClass('orderable').addClass('ordered loading');\n    this.elementIndex.storeSortAttributeAndDirection();\n    this.elementIndex.updateElements();\n\n    // No need for two spinners\n    this.elementIndex.setIndexAvailable();\n  },\n\n  _updateTableAttributes: function ($element, tableAttributes) {\n    var $tr = $element.closest('tr');\n\n    for (var attr in tableAttributes) {\n      if (!tableAttributes.hasOwnProperty(attr)) {\n        continue;\n      }\n\n      $tr\n        .children('[data-attr=\"' + attr + '\"]:first')\n        .html(tableAttributes[attr]);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tab manager\n */\nCraft.Tabs = Garnish.Base.extend({\n  $container: null,\n  $ul: null,\n  $menuBtn: null,\n  $tabs: null,\n  $selectedTab: null,\n  $focusableTab: null,\n  menu: null,\n\n  init: function (container) {\n    this.$container = $(container);\n    this.$ul = this.$container.find('> ul:first');\n    this.$tabs = this.$ul.find('> li > a');\n    this.$selectedTab = this.$tabs.filter('.sel:first');\n    this.$focusableTab = this.$tabs.filter('[tabindex=0]:first');\n    this.$menuBtn = this.$container.find('> .menubtn:first').menubtn();\n    this.menu = this.$menuBtn.data('menubtn').menu;\n\n    // Is there already a tab manager?\n    if (this.$container.data('tabs')) {\n      console.warn('Double-instantiating a tab manager on an element');\n      this.$container.data('tabs').destroy();\n    }\n\n    this.$container.data('tabs', this);\n\n    for (let i = 0; i < this.$tabs.length; i++) {\n      const $a = this.$tabs.eq(i);\n\n      // Does it link to an anchor?\n      const href = $a.attr('href');\n      if (href && href.charAt(0) === '#') {\n        this.addListener($a, 'keydown', (ev) => {\n          if ([Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)) {\n            ev.preventDefault();\n            this.selectTab(ev.currentTarget);\n          }\n        });\n        this.addListener($a, 'click', (ev) => {\n          ev.preventDefault();\n          const $a = $(ev.currentTarget);\n          this.selectTab(ev.currentTarget);\n          this.makeTabFocusable(ev.currentTarget);\n        });\n\n        if (href.substr(1) === window.LOCATION_HASH) {\n          $initialTab = $a;\n        }\n      }\n\n      this.addListener($a, 'keydown', (ev) => {\n        if (\n          [Garnish.LEFT_KEY, Garnish.RIGHT_KEY].includes(ev.keyCode) &&\n          $.contains(this.$ul[0], ev.currentTarget)\n        ) {\n          let $tab;\n          if (\n            ev.keyCode ===\n            (Craft.orientation === 'ltr' ? Garnish.LEFT_KEY : Garnish.RIGHT_KEY)\n          ) {\n            $tab = $(ev.currentTarget).parent().prev('li').children('a');\n          } else {\n            $tab = $(ev.currentTarget).parent().next('li').children('a');\n          }\n          if ($tab.length) {\n            ev.preventDefault();\n            this.makeTabFocusable($tab);\n            $tab.focus();\n            this.scrollToTab($tab);\n          }\n        }\n      });\n    }\n\n    this.updateMenuBtn();\n\n    Garnish.$win.on('resize', () => {\n      this.updateMenuBtn();\n    });\n\n    // Prevent menu options from updating the URL\n    this.menu.$options.on('click', (ev) => {\n      const $option = $(ev.currentTarget);\n      const href = $option.attr('href');\n      if (href && href.charAt(0) === '#') {\n        ev.preventDefault();\n      }\n    });\n\n    this.menu.on('optionselect', (ev) => {\n      this.selectTab($(ev.selectedOption).data('id'));\n    });\n  },\n\n  selectTab: function (tab) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$selectedTab[0]) {\n      return;\n    }\n\n    this.deselectTab();\n    this.$selectedTab = $tab.addClass('sel');\n    this.makeTabFocusable($tab);\n    this.scrollToTab($tab);\n\n    this.menu.$options.removeClass('sel');\n    this.menu.$options.filter(`[data-id=\"${$tab.data('id')}\"]`).addClass('sel');\n\n    this.trigger('selectTab', {\n      $tab: $tab,\n    });\n\n    $('#content').trigger('scroll');\n  },\n\n  deselectTab: function () {\n    const $tab = this.$selectedTab.removeClass('sel');\n    this.$selectedTab = null;\n\n    this.trigger('deselectTab', {\n      $tab: $tab,\n    });\n  },\n\n  makeTabFocusable: function (tab) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$focusableTab[0]) {\n      return;\n    }\n\n    this.$focusableTab.attr('tabindex', '-1');\n    this.$focusableTab = $tab.attr('tabindex', '0');\n  },\n\n  scrollToTab: function (tab) {\n    const $tab = this._getTab(tab);\n    const scrollLeft = this.$ul.scrollLeft();\n    const tabOffset = $tab.offset().left;\n    const elemScrollOffset = tabOffset - this.$ul.offset().left;\n    let targetScrollLeft = false;\n\n    // Is the tab hidden on the left?\n    if (elemScrollOffset < 0) {\n      targetScrollLeft = scrollLeft + elemScrollOffset - 24;\n    } else {\n      const tabWidth = $tab.outerWidth();\n      const ulWidth = this.$ul.prop('clientWidth');\n\n      // Is it hidden to the right?\n      if (elemScrollOffset + tabWidth > ulWidth) {\n        targetScrollLeft =\n          scrollLeft + (elemScrollOffset - (ulWidth - tabWidth)) + 24;\n      }\n    }\n\n    if (targetScrollLeft !== false) {\n      this.$ul.scrollLeft(targetScrollLeft);\n    }\n  },\n\n  updateMenuBtn: function () {\n    if (\n      Math.floor(this.$ul.prop('scrollWidth') - 48) >\n      this.$container.prop('clientWidth')\n    ) {\n      this.$ul.addClass('scrollable');\n      this.$menuBtn.removeClass('hidden');\n    } else {\n      this.$ul.removeClass('scrollable');\n      this.$menuBtn.addClass('hidden');\n    }\n  },\n\n  _getTab: function (tab) {\n    if (tab instanceof jQuery) {\n      return tab;\n    }\n\n    if (tab instanceof HTMLElement) {\n      return $(tab);\n    }\n\n    if (typeof tab !== 'string') {\n      throw 'Invalid tab ID';\n    }\n\n    const $tab = this.$tabs.filter(`[data-id=\"${tab}\"]`);\n\n    if (!$tab.length) {\n      throw `Invalid tab ID: ${tab}`;\n    }\n\n    return $tab;\n  },\n\n  destroy: function () {\n    this.$container.removeData('tabs');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tag select input\n */\nCraft.TagSelectInput = Craft.BaseElementSelectInput.extend(\n  {\n    searchTimeout: null,\n    searchMenu: null,\n\n    $container: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addTagInput: null,\n    $spinner: null,\n\n    _ignoreBlur: false,\n\n    init: function (settings) {\n      // Normalize the settings\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = ['id', 'name', 'tagGroupId', 'sourceElementId'];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.base($.extend({}, Craft.TagSelectInput.defaults, settings));\n\n      this.$addTagInput = this.$container.children('.add').children('.text');\n      this.$spinner = this.$addTagInput.next();\n\n      this.addListener(this.$addTagInput, 'input', () => {\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(this.searchForTags.bind(this), 500);\n      });\n\n      this.addListener(this.$addTagInput, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n        }\n\n        let $option;\n\n        switch (ev.keyCode) {\n          case Garnish.RETURN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              this.selectTag(this.searchMenu.$options.filter('.hover'));\n            }\n            return;\n          }\n\n          case Garnish.DOWN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $nextOption = $hoverOption\n                  .parent()\n                  .nextAll()\n                  .find('a:not(.disabled)')\n                  .first();\n                if ($nextOption.length) {\n                  this.focusOption($nextOption);\n                }\n              } else {\n                this.focusOption(this.searchMenu.$options.eq(0));\n              }\n            }\n            return;\n          }\n\n          case Garnish.UP_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $prevOption = $hoverOption\n                  .parent()\n                  .prevAll()\n                  .find('a:not(.disabled)')\n                  .last();\n                if ($prevOption.length) {\n                  this.focusOption($prevOption);\n                }\n              } else {\n                this.focusOption(\n                  this.searchMenu.$options.eq(\n                    this.searchMenu.$options.length - 1\n                  )\n                );\n              }\n            }\n            return;\n          }\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'focus', function () {\n        if (this.searchMenu) {\n          this.searchMenu.show();\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'blur', function () {\n        if (this._ignoreBlur) {\n          this._ignoreBlur = false;\n          return;\n        }\n\n        setTimeout(() => {\n          if (this.searchMenu) {\n            this.searchMenu.hide();\n          }\n        }, 1);\n      });\n    },\n\n    focusOption: function ($option) {\n      this.searchMenu.$options.removeClass('hover');\n      $option.addClass('hover');\n      this.searchMenu.$menuList.attr(\n        'aria-activedescendant',\n        $option.attr('id')\n      );\n    },\n\n    // No \"add\" button\n    getAddElementsBtn: $.noop,\n\n    getElementSortAxis: function () {\n      return null;\n    },\n\n    searchForTags: function () {\n      if (this.searchMenu) {\n        this.killSearchMenu();\n      }\n\n      var val = this.$addTagInput.val();\n\n      if (val) {\n        this.$spinner.removeClass('hidden');\n\n        var excludeIds = [];\n\n        for (var i = 0; i < this.$elements.length; i++) {\n          var id = $(this.$elements[i]).data('id');\n\n          if (id) {\n            excludeIds.push(id);\n          }\n        }\n\n        if (this.settings.sourceElementId) {\n          excludeIds.push(this.settings.sourceElementId);\n        }\n\n        var data = {\n          search: this.$addTagInput.val(),\n          tagGroupId: this.settings.tagGroupId,\n          excludeIds: excludeIds,\n        };\n\n        Craft.postActionRequest(\n          'tags/search-for-tags',\n          data,\n          (response, textStatus) => {\n            // Just in case\n            if (this.searchMenu) {\n              this.killSearchMenu();\n            }\n\n            this.$spinner.addClass('hidden');\n\n            if (textStatus === 'success') {\n              var $menu = $('<div class=\"menu tagmenu\"/>').appendTo(\n                  Garnish.$bod\n                ),\n                $ul = $('<ul/>').appendTo($menu);\n\n              var $li;\n\n              for (var i = 0; i < response.tags.length; i++) {\n                $li = $('<li/>').appendTo($ul);\n\n                $('<a data-icon=\"tag\"/>')\n                  .appendTo($li)\n                  .text(response.tags[i].title)\n                  .data('id', response.tags[i].id)\n                  .addClass(response.tags[i].exclude ? 'disabled' : '');\n              }\n\n              if (!response.exactMatch) {\n                $li = $('<li/>').appendTo($ul);\n                $('<a data-icon=\"plus\"/>').appendTo($li).text(data.search);\n              }\n\n              $ul.find('a:not(.disabled):first').addClass('hover');\n\n              this.searchMenu = new Garnish.Menu($menu, {\n                attachToElement: this.$addTagInput,\n                onOptionSelect: this.selectTag.bind(this),\n              });\n\n              this.addListener($menu, 'mousedown', () => {\n                this._ignoreBlur = true;\n              });\n\n              this.searchMenu.show();\n            }\n          }\n        );\n      } else {\n        this.$spinner.addClass('hidden');\n      }\n    },\n\n    selectTag: function (option) {\n      var $option = $(option);\n\n      if ($option.hasClass('disabled')) {\n        return;\n      }\n\n      var id = $option.data('id');\n      var title = $option.text();\n\n      var $element = $('<div/>', {\n        class: 'element small removable',\n        'data-id': id,\n        'data-site-id': this.settings.targetSiteId,\n        'data-label': title,\n        'data-editable': '1',\n      }).appendTo(this.$elementsContainer);\n\n      var $input = $('<input/>', {\n        type: 'hidden',\n        name: this.settings.name + '[]',\n        value: id,\n      }).appendTo($element);\n\n      $('<a/>', {\n        class: 'delete icon',\n        title: Craft.t('app', 'Remove'),\n      }).appendTo($element);\n\n      var $titleContainer = $('<div/>', {\n        class: 'label',\n      }).appendTo($element);\n\n      $('<span/>', {\n        class: 'title',\n        text: title,\n      }).appendTo($titleContainer);\n\n      var margin = -($element.outerWidth() + 10);\n      this.$addTagInput.css('margin-' + Craft.left, margin + 'px');\n\n      var animateCss = {};\n      animateCss['margin-' + Craft.left] = 0;\n      this.$addTagInput.velocity(animateCss, 'fast');\n\n      this.$elements = this.$elements.add($element);\n\n      this.addElements($element);\n\n      this.killSearchMenu();\n      this.$addTagInput.val('');\n      this.$addTagInput.trigger('focus');\n\n      if (!id) {\n        // We need to create the tag first\n        $element.addClass('loading disabled');\n\n        var data = {\n          groupId: this.settings.tagGroupId,\n          title: title,\n        };\n\n        Craft.postActionRequest(\n          'tags/create-tag',\n          data,\n          (response, textStatus) => {\n            if (textStatus === 'success' && response.success) {\n              $element.attr('data-id', response.id);\n              $input.val(response.id);\n\n              $element.removeClass('loading disabled');\n            } else {\n              this.removeElement($element);\n\n              if (textStatus === 'success') {\n                // Some sort of validation error that still resulted in  a 200 response. Shouldn't be possible though.\n                Craft.cp.displayError(\n                  Craft.t('app', 'A server error occurred.')\n                );\n              }\n            }\n          }\n        );\n      }\n    },\n\n    killSearchMenu: function () {\n      this.searchMenu.hide();\n      this.searchMenu.destroy();\n      this.searchMenu = null;\n    },\n  },\n  {\n    defaults: {\n      tagGroupId: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Thumb Element Index View\n */\nCraft.ThumbsElementIndexView = Craft.BaseElementIndexView.extend({\n  getElementContainer: function () {\n    return this.$container.children('ul');\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.ui = {\n  createTextInput: function (config) {\n    config = $.extend(\n      {\n        autocomplete: false,\n      },\n      config\n    );\n    var $input = $('<input/>', {\n      attr: {\n        class: 'text',\n        type: config.type || 'text',\n        inputmode: config.inputmode,\n        id: config.id,\n        size: config.size,\n        name: config.name,\n        value: config.value,\n        maxlength: config.maxlength,\n        autofocus: this.getAutofocusValue(config.autofocus),\n        autocomplete:\n          typeof config.autocomplete === 'boolean'\n            ? config.autocomplete\n              ? 'on'\n              : 'off'\n            : config.autocomplete,\n        disabled: this.getDisabledValue(config.disabled),\n        readonly: config.readonly,\n        title: config.title,\n        placeholder: config.placeholder,\n        step: config.step,\n        min: config.min,\n        max: config.max,\n      },\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n    if (config.placeholder) {\n      $input.addClass('nicetext');\n    }\n    if (config.type === 'password') {\n      $input.addClass('password');\n    }\n    if (config.disabled) {\n      $input.addClass('disabled');\n    }\n    if (!config.size) {\n      $input.addClass('fullwidth');\n    }\n\n    if (config.showCharsLeft && config.maxlength) {\n      $input\n        .attr('data-show-chars-left')\n        .css(\n          'padding-' + (Craft.orientation === 'ltr' ? 'right' : 'left'),\n          7.2 * config.maxlength.toString().length + 14 + 'px'\n        );\n    }\n\n    if (config.placeholder || config.showCharsLeft) {\n      new Garnish.NiceText($input);\n    }\n\n    if (config.type === 'password') {\n      return $('<div class=\"passwordwrapper\"/>').append($input);\n    } else {\n      return $input;\n    }\n  },\n\n  createTextField: function (config) {\n    if (!config.id) {\n      config.id = 'text' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextInput(config), config);\n  },\n\n  createCopyTextInput: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let buttonId = config.buttonId || `${id}-btn`;\n\n    let $container = $('<div/>', {\n      class: 'copytext',\n    });\n\n    let $input = this.createTextInput(\n      $.extend({}, config, {\n        readonly: true,\n      })\n    ).appendTo($container);\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      id: buttonId,\n      class: 'btn',\n      'data-icon': 'clipboard',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n    }).appendTo($container);\n\n    $btn.on('click', () => {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $container.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n    });\n\n    return $container;\n  },\n\n  createCopyTextBtn: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let value = config.value;\n\n    let $btn = $('<div/>', {\n      id,\n      class: 'copytextbtn',\n      role: 'button',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n      tabindex: '0',\n    });\n\n    if (config.class) {\n      $btn.addClass(config.class);\n    }\n\n    let $input = $('<input/>', {\n      value,\n      readonly: true,\n      size: value.length,\n      tabindex: '-1',\n    }).appendTo($btn);\n\n    let $icon = $('<span/>', {\n      'data-icon': 'clipboard',\n      'aria-hidden': 'true',\n    }).appendTo($btn);\n\n    const copyValue = function () {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $btn.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n      $btn.focus();\n    };\n\n    $btn.on('click', () => {\n      copyValue();\n    });\n\n    $btn.on('keydown', (ev) => {\n      if (ev.keyCode === Garnish.SPACE_KEY) {\n        copyValue();\n        ev.preventDefault();\n      }\n    });\n\n    return $btn;\n  },\n\n  createCopyTextField: function (config) {\n    if (!config.id) {\n      config.id = 'copytext' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCopyTextInput(config), config);\n  },\n\n  createCopyTextPrompt: function (config) {\n    let $container = $('<div/>', {\n      class: 'modal fitted',\n    });\n    let $body = $('<div/>', {\n      class: 'body',\n    }).appendTo($container);\n    this.createCopyTextField(\n      $.extend(\n        {\n          size: Math.max(Math.min(config.value.length, 50), 25),\n        },\n        config\n      )\n    ).appendTo($body);\n    let modal = new Garnish.Modal($container, {\n      closeOtherModals: false,\n    });\n    $container.on('copy', () => {\n      modal.hide();\n    });\n    return $container;\n  },\n\n  createTextarea: function (config) {\n    var $textarea = $('<textarea/>', {\n      class: 'text',\n      rows: config.rows || 2,\n      cols: config.cols || 50,\n      id: config.id,\n      name: config.name,\n      maxlength: config.maxlength,\n      autofocus: config.autofocus && !Garnish.isMobileBrowser(true),\n      disabled: !!config.disabled,\n      placeholder: config.placeholder,\n      html: config.value,\n    });\n\n    if (config.showCharsLeft) {\n      $textarea.attr('data-show-chars-left', '');\n    }\n\n    if (config.class) {\n      $textarea.addClass(config.class);\n    }\n\n    if (!config.size) {\n      $textarea.addClass('fullwidth');\n    }\n\n    return $textarea;\n  },\n\n  createTextareaField: function (config) {\n    if (!config.id) {\n      config.id = 'textarea' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextarea(config), config);\n  },\n\n  createSelect: function (config) {\n    var $container = $('<div/>', {\n      class: 'select',\n    });\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var $select = $('<select/>', {\n      id: config.id,\n      name: config.name,\n      autofocus: config.autofocus && Garnish.isMobileBrowser(true),\n      disabled: config.disabled,\n      'data-target-prefix': config.targetPrefix,\n    }).appendTo($container);\n\n    // Normalize the options into an array\n    if ($.isPlainObject(config.options)) {\n      let options = [];\n      for (var key in config.options) {\n        if (!config.options.hasOwnProperty(key)) {\n          continue;\n        }\n        let option = config.options[key];\n        if ($.isPlainObject(option)) {\n          if (typeof option.optgroup !== 'undefined') {\n            options.push(option);\n          } else {\n            options.push({\n              label: option.label,\n              value: typeof option.value !== 'undefined' ? option.value : key,\n              disabled:\n                typeof option.disabled !== 'undefined'\n                  ? option.disabled\n                  : false,\n            });\n          }\n        } else {\n          options.push({\n            label: option,\n            value: key,\n          });\n        }\n      }\n      config.options = options;\n    }\n\n    var $optgroup = null;\n\n    for (let i = 0; i < config.options.length; i++) {\n      let option = config.options[i];\n\n      // Starting a new <optgroup>?\n      if (typeof option.optgroup !== 'undefined') {\n        $optgroup = $('<optgroup/>', {\n          label: option.label,\n        }).appendTo($select);\n      } else {\n        $('<option/>', {\n          value: option.value,\n          selected: option.value == config.value,\n          disabled:\n            typeof option.disabled !== 'undefined' ? option.disabled : false,\n          html: option.label,\n        }).appendTo($optgroup || $select);\n      }\n    }\n\n    if (config.toggle) {\n      $select.addClass('fieldtoggle');\n      new Craft.FieldToggle($select);\n    }\n\n    return $container;\n  },\n\n  createSelectField: function (config) {\n    if (!config.id) {\n      config.id = 'select' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createSelect(config), config);\n  },\n\n  createCheckbox: function (config) {\n    var id = config.id || 'checkbox' + Math.floor(Math.random() * 1000000000);\n\n    var $input = $('<input/>', {\n      type: 'checkbox',\n      value: typeof config.value !== 'undefined' ? config.value : '1',\n      id: id,\n      class: 'checkbox',\n      name: config.name,\n      checked: config.checked ? 'checked' : null,\n      autofocus: this.getAutofocusValue(config.autofocus),\n      disabled: this.getDisabledValue(config.disabled),\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $input.addClass('fieldtoggle');\n      new Craft.FieldToggle($input);\n    }\n\n    var $label = $('<label/>', {\n      for: id,\n      html: config.label,\n    });\n\n    // Should we include a hidden input first?\n    if (\n      config.name &&\n      (config.name.length < 3 || config.name.substr(-2) !== '[]')\n    ) {\n      return $([\n        $('<input/>', {\n          type: 'hidden',\n          name: config.name,\n          value: '',\n        })[0],\n        $input[0],\n        $label[0],\n      ]);\n    } else {\n      return $([$input[0], $label[0]]);\n    }\n  },\n\n  createCheckboxField: function (config) {\n    if (!config.id) {\n      config.id = 'checkbox' + Math.floor(Math.random() * 1000000000);\n    }\n\n    var $field = $('<div class=\"field checkboxfield\"/>', {\n      id: `${config.id}-field`,\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n    if (config.instructions) {\n      $field.addClass('has-instructions');\n    }\n\n    this.createCheckbox(config).appendTo($field);\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    return $field;\n  },\n\n  createCheckboxSelect: function (config) {\n    var $container = $('<fieldset class=\"checkbox-select\"/>');\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var allValue, allChecked;\n\n    if (config.showAllOption) {\n      allValue = config.allValue || '*';\n      allChecked = config.values == allValue;\n\n      // Create the \"All\" checkbox\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            id: config.id,\n            class: 'all',\n            label: '<b>' + (config.allLabel || Craft.t('app', 'All')) + '</b>',\n            name: config.name,\n            value: allValue,\n            checked: allChecked,\n            autofocus: config.autofocus,\n          })\n        );\n    } else {\n      allChecked = false;\n    }\n\n    // Create the actual options\n    for (var i = 0; i < config.options.length; i++) {\n      var option = config.options[i];\n\n      if (option.value == allValue) {\n        continue;\n      }\n\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            label: option.label,\n            name: config.name ? config.name + '[]' : null,\n            value: option.value,\n            checked: allChecked || (config.values || []).includes(option.value),\n            disabled: allChecked,\n          })\n        );\n    }\n\n    new Garnish.CheckboxSelect($container);\n\n    return $container;\n  },\n\n  createCheckboxSelectField: function (config) {\n    config.fieldset = true;\n    if (!config.id) {\n      config.id = 'checkboxselect' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCheckboxSelect(config), config);\n  },\n\n  createLightswitch: function (config) {\n    var value = config.value || '1';\n    var indeterminateValue = config.indeterminateValue || '-';\n\n    var $container = $('<button/>', {\n      type: 'button',\n      class: 'lightswitch',\n      'data-value': value,\n      'data-indeterminate-value': indeterminateValue,\n      id: config.id,\n      role: 'checkbox',\n      'aria-checked': config.on\n        ? 'true'\n        : config.indeterminate\n        ? 'mixed'\n        : 'false',\n      'aria-labelledby': config.labelId,\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.on) {\n      $container.addClass('on');\n    } else if (config.indeterminate) {\n      $container.addClass('indeterminate');\n    }\n\n    if (config.small) {\n      $container.addClass('small');\n    }\n\n    if (config.disabled) {\n      $container.addClass('disabled');\n    }\n\n    $(\n      '<div class=\"lightswitch-container\">' +\n        '<div class=\"handle\"></div>' +\n        '</div>'\n    ).appendTo($container);\n\n    if (config.name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: config.name,\n        value: config.on\n          ? value\n          : config.indeterminate\n          ? indeterminateValue\n          : '',\n        disabled: config.disabled,\n      }).appendTo($container);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $container.addClass('fieldtoggle');\n      new Craft.FieldToggle($container);\n    }\n\n    new Craft.LightSwitch($container, {\n      onChange: config.onChange || $.noop,\n    });\n\n    return $container;\n  },\n\n  createLightswitchField: function (config) {\n    if (!config.id) {\n      config.id = 'lightswitch' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createLightswitch(config), config).addClass(\n      'lightswitch-field'\n    );\n  },\n\n  createColorInput: function (config) {\n    const id = config.id || 'color' + Math.floor(Math.random() * 1000000000);\n    const containerId = config.containerId || id + '-container';\n    const name = config.name || null;\n    const value = config.value || null;\n    const small = config.small || false;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      id: containerId,\n      class: 'flex color-container',\n    });\n\n    const $colorPreviewContainer = $('<div/>', {\n      class: 'color static' + (small ? ' small' : ''),\n    }).appendTo($container);\n\n    const $colorPreview = $('<div/>', {\n      class: 'color-preview',\n      style: config.value ? {backgroundColor: config.value} : null,\n    }).appendTo($colorPreviewContainer);\n\n    const $inputContainer = $('<div/>', {\n      class: 'color-input-container',\n    })\n      .append(\n        $('<div/>', {\n          class: 'color-hex-indicator light code',\n          'aria-hidden': 'true',\n          text: '#',\n        })\n      )\n      .appendTo($container);\n\n    const $input = this.createTextInput({\n      id: id,\n      name: name,\n      value: Craft.ltrim(value, '#'),\n      size: 10,\n      class: 'color-input',\n      autofocus: autofocus,\n      disabled: disabled,\n      'aria-label': Craft.t('app', 'Color hex value'),\n    }).appendTo($inputContainer);\n\n    new Craft.ColorInput($container);\n    return $container;\n  },\n\n  createColorField: function (config) {\n    config.fieldset = true;\n    o;\n    if (!config.id) {\n      config.id = 'color' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createColorInput(config), config);\n  },\n\n  createDateInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'date' + Math.floor(Math.random() * 1000000000)) + '-date';\n    const name = config.name || null;\n    const inputName = name ? name + '[date]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'datewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'date' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      value: value\n        ? isMobile\n          ? value.toISOString().split('T')[0]\n          : Craft.formatDate(value)\n        : '',\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"date\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      $input.datetimeinput();\n    } else {\n      $input.datepicker(\n        $.extend(\n          {\n            defaultDate: value || new Date(),\n          },\n          Craft.datepickerOptions\n        )\n      );\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createDateField: function (config) {\n    if (!config.id) {\n      config.id = 'date' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createDateInput(config), config);\n  },\n\n  createDateRangePicker: function (config) {\n    var now = new Date();\n    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n    config = $.extend(\n      {\n        class: '',\n        options: [\n          'today',\n          'thisWeek',\n          'thisMonth',\n          'thisYear',\n          'past7Days',\n          'past30Days',\n          'past90Days',\n          'pastYear',\n        ],\n        onChange: $.noop,\n        selected: null,\n        startDate: null,\n        endDate: null,\n      },\n      config\n    );\n\n    var $menu = $('<div/>', {class: 'menu'});\n    var $ul = $('<ul/>', {class: 'padded'}).appendTo($menu);\n    var $allOption = $('<a/>')\n      .addClass('sel')\n      .text(Craft.t('app', 'All'))\n      .data('handle', 'all');\n\n    $('<li/>').append($allOption).appendTo($ul);\n\n    var option;\n    var selectedOption;\n    for (var i = 0; i < config.options.length; i++) {\n      var handle = config.options[i];\n      switch (handle) {\n        case 'today':\n          option = {\n            label: Craft.t('app', 'Today'),\n            startDate: today,\n            endDate: today,\n          };\n          break;\n        case 'thisWeek':\n          var firstDayOffset = now.getDay() - Craft.datepickerOptions.firstDay;\n          if (firstDayOffset < 0) {\n            firstDayOffset += 7;\n          }\n          option = {\n            label: Craft.t('app', 'This week'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - firstDayOffset\n            ),\n            endDate: today,\n          };\n          break;\n        case 'thisMonth':\n          option = {\n            label: Craft.t('app', 'This month'),\n            startDate: new Date(now.getFullYear(), now.getMonth()),\n            endDate: today,\n          };\n          break;\n        case 'thisYear':\n          option = {\n            label: Craft.t('app', 'This year'),\n            startDate: new Date(now.getFullYear(), 0),\n            endDate: today,\n          };\n          break;\n        case 'past7Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 7}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 7\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past30Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 30}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 30\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past90Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 90}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 90\n            ),\n            endDate: today,\n          };\n          break;\n        case 'pastYear':\n          option = {\n            label: Craft.t('app', 'Past year'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 365\n            ),\n            endDate: today,\n          };\n          break;\n      }\n\n      var $li = $('<li/>');\n      var $a = $('<a/>', {text: option.label})\n        .data('handle', handle)\n        .data('startDate', option.startDate)\n        .data('endDate', option.endDate)\n        .data('startTime', option.startDate ? option.startDate.getTime() : null)\n        .data('endTime', option.endDate ? option.endDate.getTime() : null);\n\n      if (config.selected && handle == config.selected) {\n        selectedOption = $a[0];\n      }\n\n      $li.append($a);\n      $li.appendTo($ul);\n    }\n\n    $('<hr/>').appendTo($menu);\n\n    var $flex = $('<div/>', {class: 'flex flex-nowrap padded'}).appendTo($menu);\n    var $startDate = this.createDateField({label: Craft.t('app', 'From')})\n      .appendTo($flex)\n      .find('input');\n    var $endDate = this.createDateField({label: Craft.t('app', 'To')})\n      .appendTo($flex)\n      .find('input');\n\n    // prevent ESC keypresses in the date inputs from closing the menu\n    var $dateInputs = $startDate.add($endDate);\n    $dateInputs.on('keyup', function (ev) {\n      if (\n        ev.keyCode === Garnish.ESC_KEY &&\n        $(this).data('datepicker') &&\n        $(this).data('datepicker').dpDiv.is(':visible')\n      ) {\n        ev.stopPropagation();\n      }\n    });\n\n    // prevent clicks in the datepicker divs from closing the menu\n    if ($startDate.data('datepicker')) {\n      $startDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n    if ($endDate.data('datepicker')) {\n      $endDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n\n    var menu = new Garnish.Menu($menu, {\n      onOptionSelect: function (option) {\n        var $option = $(option);\n        $btn.text($option.text());\n        menu.setPositionRelativeToAnchor();\n        $menu.find('.sel').removeClass('sel');\n        $option.addClass('sel');\n\n        // Update the start/end dates\n        $startDate.datepicker('setDate', $option.data('startDate'));\n        $endDate.datepicker('setDate', $option.data('endDate'));\n\n        config.onChange(\n          $option.data('startDate') || null,\n          $option.data('endDate') || null,\n          $option.data('handle')\n        );\n      },\n    });\n\n    $dateInputs.on('change', function () {\n      // Do the start & end dates match one of our options?\n      let startDate = $startDate.datepicker('getDate');\n      let endDate = $endDate.datepicker('getDate');\n      let startTime = startDate ? startDate.getTime() : null;\n      let endTime = endDate ? endDate.getTime() : null;\n\n      let $options = $ul.find('a');\n      let $option;\n      let foundOption = false;\n\n      for (let i = 0; i < $options.length; i++) {\n        $option = $options.eq(i);\n        if (\n          startTime === ($option.data('startTime') || null) &&\n          endTime === ($option.data('endTime') || null)\n        ) {\n          menu.selectOption($option[0]);\n          foundOption = true;\n          config.onChange(null, null, $option.data('handle'));\n          break;\n        }\n      }\n\n      if (!foundOption) {\n        $menu.find('.sel').removeClass('sel');\n        $flex.addClass('sel');\n\n        if (!startTime && !endTime) {\n          $btn.text(Craft.t('app', 'All'));\n        } else if (startTime && endTime) {\n          $btn.text($startDate.val() + ' - ' + $endDate.val());\n        } else if (startTime) {\n          $btn.text(Craft.t('app', 'From {date}', {date: $startDate.val()}));\n        } else {\n          $btn.text(Craft.t('app', 'To {date}', {date: $endDate.val()}));\n        }\n        menu.setPositionRelativeToAnchor();\n\n        config.onChange(startDate, endDate, 'custom');\n      }\n    });\n\n    menu.on('hide', function () {\n      $startDate.datepicker('hide');\n      $endDate.datepicker('hide');\n    });\n\n    let btnClasses = 'btn menubtn';\n    if (config.class) {\n      btnClasses = btnClasses + ' ' + config.class;\n    }\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      class: btnClasses,\n      'data-icon': 'date',\n      text: Craft.t('app', 'All'),\n    });\n\n    new Garnish.MenuBtn($btn, menu);\n\n    if (selectedOption) {\n      menu.selectOption(selectedOption);\n    }\n\n    if (config.startDate) {\n      $startDate.datepicker('setDate', config.startDate);\n    }\n\n    if (config.endDate) {\n      $endDate.datepicker('setDate', config.endDate);\n    }\n\n    if (config.startDate || config.endDate) {\n      $dateInputs.trigger('change');\n    }\n\n    return $btn;\n  },\n\n  createTimeInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'time' + Math.floor(Math.random() * 1000000000)) + '-time';\n    const name = config.name || null;\n    const inputName = name ? name + '[time]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'timewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'time' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"time\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      if (value) {\n        $input.val(value.toISOString().split('T')[1]);\n      }\n      $input.datetimeinput();\n    } else {\n      $input.timepicker(Craft.timepickerOptions);\n      if (value) {\n        $input.timepicker(\n          'setTime',\n          value.getHours() * 3600 + value.getMinutes() * 60 + value.getSeconds()\n        );\n      }\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createTimeField: function (config) {\n    if (!config.id) {\n      config.id = 'time' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTimeInput(config), config);\n  },\n\n  createField: function (input, config) {\n    var label =\n        config.label && config.label !== '__blank__' ? config.label : null,\n      siteId = Craft.isMultiSite && config.siteId ? config.siteId : null;\n\n    var $field = $(config.fieldset ? '<fieldset/>' : '<div/>', {\n      class: 'field',\n      id: config.fieldId || (config.id ? config.id + '-field' : null),\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n\n    if (label) {\n      var $heading = $('<div class=\"heading\"/>').appendTo($field);\n\n      var $label = $(config.fieldset ? '<legend/>' : '<label/>', {\n        id:\n          config.labelId ||\n          (config.id\n            ? `${config.id}-${config.fieldset ? 'legend' : 'label'}`\n            : null),\n        class: config.required ? 'required' : null,\n        for: !config.fieldset && config.id,\n        text: label,\n      }).appendTo($heading);\n    }\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    $('<div class=\"input\"/>').append(input).appendTo($field);\n\n    if (config.tip) {\n      const $tip = $('<p class=\"notice has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($tip);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Tip') + ': ')\n        .appendTo($tip);\n      $('<span/>').text(config.tip).appendTo($tip);\n      $tip.appendTo($field);\n    }\n\n    if (config.warning) {\n      const $warning = $('<p class=\"warning has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($warning);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Warning') + ': ')\n        .appendTo($warning);\n      $('<span/>').text(config.warning).appendTo($warning);\n      $warning.appendTo($field);\n    }\n\n    if (config.errors) {\n      this.addErrorsToField($field, config.errors);\n    }\n\n    return $field;\n  },\n\n  createErrorList: function (errors) {\n    var $list = $('<ul class=\"errors\"/>');\n\n    if (errors) {\n      this.addErrorsToList($list, errors);\n    }\n\n    return $list;\n  },\n\n  addErrorsToList: function ($list, errors) {\n    for (var i = 0; i < errors.length; i++) {\n      $('<li/>').text(errors[i]).appendTo($list);\n    }\n  },\n\n  addErrorsToField: function ($field, errors) {\n    if (!errors) {\n      return;\n    }\n\n    $field.addClass('has-errors');\n    $field.children('.input').addClass('errors');\n\n    var $errors = $field.children('ul.errors');\n\n    if (!$errors.length) {\n      $errors = this.createErrorList().appendTo($field);\n    }\n\n    this.addErrorsToList($errors, errors);\n  },\n\n  clearErrorsFromField: function ($field) {\n    $field.removeClass('has-errors');\n    $field.children('.input').removeClass('errors');\n    $field.children('ul.errors').remove();\n  },\n\n  getAutofocusValue: function (autofocus) {\n    return autofocus && !Garnish.isMobileBrowser(true) ? 'autofocus' : null;\n  },\n\n  getDisabledValue: function (disabled) {\n    return disabled ? 'disabled' : null;\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.Uploader = Garnish.Base.extend(\n  {\n    uploader: null,\n    allowedKinds: null,\n    $element: null,\n    settings: null,\n    _rejectedFiles: {},\n    _extensionList: null,\n    _totalFileCounter: 0,\n    _validFileCounter: 0,\n\n    init: function ($element, settings) {\n      this._rejectedFiles = {size: [], type: [], limit: []};\n      this.$element = $element;\n      this.allowedKinds = null;\n      this._extensionList = null;\n      this._totalFileCounter = 0;\n      this._validFileCounter = 0;\n\n      settings = $.extend({}, Craft.Uploader.defaults, settings);\n\n      var events = settings.events;\n      delete settings.events;\n\n      if (settings.allowedKinds && settings.allowedKinds.length) {\n        if (typeof settings.allowedKinds === 'string') {\n          settings.allowedKinds = [settings.allowedKinds];\n        }\n\n        this.allowedKinds = settings.allowedKinds;\n        delete settings.allowedKinds;\n      }\n\n      settings.autoUpload = false;\n\n      this.uploader = this.$element.fileupload(settings);\n      for (var event in events) {\n        if (!events.hasOwnProperty(event)) {\n          continue;\n        }\n\n        this.uploader.on(event, events[event]);\n      }\n\n      this.settings = settings;\n\n      this.uploader.on('fileuploadadd', this.onFileAdd.bind(this));\n    },\n\n    /**\n     * Set uploader parameters.\n     */\n    setParams: function (paramObject) {\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        paramObject[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      this.uploader.fileupload('option', {formData: paramObject});\n    },\n\n    /**\n     * Get the number of uploads in progress.\n     */\n    getInProgress: function () {\n      return this.uploader.fileupload('active');\n    },\n\n    /**\n     * Return true, if this is the last upload.\n     */\n    isLastUpload: function () {\n      // Processing the last file or not processing at all.\n      return this.getInProgress() < 2;\n    },\n\n    /**\n     * Called on file add.\n     */\n    onFileAdd: function (e, data) {\n      e.stopPropagation();\n\n      var validateExtension = false;\n\n      if (this.allowedKinds) {\n        if (!this._extensionList) {\n          this._createExtensionList();\n        }\n\n        validateExtension = true;\n      }\n\n      // Make sure that file API is there before relying on it\n      data.process().done(() => {\n        var file = data.files[0];\n        var pass = true;\n        if (validateExtension) {\n          var matches = file.name.match(/\\.([a-z0-4_]+)$/i);\n          var fileExtension = matches[1];\n          if (\n            $.inArray(fileExtension.toLowerCase(), this._extensionList) === -1\n          ) {\n            pass = false;\n            this._rejectedFiles.type.push('“' + file.name + '”');\n          }\n        }\n\n        if (file.size > this.settings.maxFileSize) {\n          this._rejectedFiles.size.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        // If the validation has passed for this file up to now, check if we're not hitting any limits\n        if (\n          pass &&\n          typeof this.settings.canAddMoreFiles === 'function' &&\n          !this.settings.canAddMoreFiles(this._validFileCounter)\n        ) {\n          this._rejectedFiles.limit.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        if (pass) {\n          this._validFileCounter++;\n          data.submit();\n        }\n\n        if (++this._totalFileCounter === data.originalFiles.length) {\n          this._totalFileCounter = 0;\n          this._validFileCounter = 0;\n          this.processErrorMessages();\n        }\n      });\n\n      return true;\n    },\n\n    /**\n     * Process error messages.\n     */\n    processErrorMessages: function () {\n      var str;\n\n      if (this._rejectedFiles.type.length) {\n        if (this._rejectedFiles.type.length === 1) {\n          str =\n            'The file {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.type.join(', '),\n          kinds: this.allowedKinds.join(', '),\n        });\n        this._rejectedFiles.type = [];\n        alert(str);\n      }\n\n      if (this._rejectedFiles.size.length) {\n        if (this._rejectedFiles.size.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.size.join(', '),\n          size: this.humanFileSize(Craft.maxUploadSize),\n        });\n        this._rejectedFiles.size = [];\n        alert(str);\n      }\n\n      if (this._rejectedFiles.limit.length) {\n        if (this._rejectedFiles.limit.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because the field limit has been reached.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because the field limit has been reached.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.limit.join(', '),\n        });\n        this._rejectedFiles.limit = [];\n        alert(str);\n      }\n    },\n\n    humanFileSize: function (bytes) {\n      var threshold = 1024;\n\n      if (bytes < threshold) {\n        return bytes + ' B';\n      }\n\n      var units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n\n      var u = -1;\n\n      do {\n        bytes = bytes / threshold;\n        ++u;\n      } while (bytes >= threshold);\n\n      return bytes.toFixed(1) + ' ' + units[u];\n    },\n\n    _createExtensionList: function () {\n      this._extensionList = [];\n\n      for (var i = 0; i < this.allowedKinds.length; i++) {\n        var allowedKind = this.allowedKinds[i];\n\n        if (typeof Craft.fileKinds[allowedKind] !== 'undefined') {\n          for (\n            var j = 0;\n            j < Craft.fileKinds[allowedKind].extensions.length;\n            j++\n          ) {\n            var ext = Craft.fileKinds[allowedKind].extensions[j];\n            this._extensionList.push(ext);\n          }\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$element.fileupload('destroy');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      dropZone: null,\n      pasteZone: null,\n      fileInput: null,\n      sequentialUploads: true,\n      maxFileSize: Craft.maxUploadSize,\n      allowedKinds: null,\n      events: {},\n      canAddMoreFiles: null,\n      headers: {Accept: 'application/json;q=0.9,*/*;q=0.8'},\n      paramName: 'assets-upload',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.UriFormatGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace('/<(.*?)>/g', '');\n\n    // Make it lowercase\n    sourceVal = sourceVal.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    sourceVal = Craft.asciiString(sourceVal);\n\n    // Handle must start with a letter and end with a letter/number\n    sourceVal = sourceVal.replace(/^[^a-z]+/, '');\n    sourceVal = sourceVal.replace(/[^a-z0-9]+$/, '');\n\n    // Get the \"words\"\n    var words = Craft.filterArray(sourceVal.split(/[^a-z0-9]+/));\n\n    var uriFormat = words.join(Craft.slugWordSeparator);\n\n    if (uriFormat && this.settings.suffix) {\n      uriFormat += this.settings.suffix;\n    }\n\n    return uriFormat;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * User index class\n */\nCraft.UserIndex = Craft.BaseElementIndex.extend({\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateUrl.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSourceSlug !== 'undefined'\n    ) {\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('slug') === defaultSourceSlug) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateUrl: function () {\n    if (this.settings.context === 'index' && typeof history !== 'undefined') {\n      let uri = 'users';\n      const slug = this.$source.data('slug');\n      if (slug) {\n        uri += `/${slug}`;\n      }\n      history.replaceState({}, '', Craft.getUrl(uri));\n    }\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\User', Craft.UserIndex);\n","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./charts.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"3790022a\", content, true, {});","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./craft.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"80058a3c\", content, true, {});","/**\n * Translates the list format produced by css-loader into something\n * easier to manipulate.\n */\nexport default function listToStyles (parentId, list) {\n  var styles = []\n  var newStyles = {}\n  for (var i = 0; i < list.length; i++) {\n    var item = list[i]\n    var id = item[0]\n    var css = item[1]\n    var media = item[2]\n    var sourceMap = item[3]\n    var part = {\n      id: parentId + ':' + i,\n      css: css,\n      media: media,\n      sourceMap: sourceMap\n    }\n    if (!newStyles[id]) {\n      styles.push(newStyles[id] = { id: id, parts: [part] })\n    } else {\n      newStyles[id].parts.push(part)\n    }\n  }\n  return styles\n}\n","/*\n  MIT License http://www.opensource.org/licenses/mit-license.php\n  Author Tobias Koppers @sokra\n  Modified by Evan You @yyx990803\n*/\n\nimport listToStyles from './listToStyles'\n\nvar hasDocument = typeof document !== 'undefined'\n\nif (typeof DEBUG !== 'undefined' && DEBUG) {\n  if (!hasDocument) {\n    throw new Error(\n    'vue-style-loader cannot be used in a non-browser environment. ' +\n    \"Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.\"\n  ) }\n}\n\n/*\ntype StyleObject = {\n  id: number;\n  parts: Array<StyleObjectPart>\n}\n\ntype StyleObjectPart = {\n  css: string;\n  media: string;\n  sourceMap: ?string\n}\n*/\n\nvar stylesInDom = {/*\n  [id: number]: {\n    id: number,\n    refs: number,\n    parts: Array<(obj?: StyleObjectPart) => void>\n  }\n*/}\n\nvar head = hasDocument && (document.head || document.getElementsByTagName('head')[0])\nvar singletonElement = null\nvar singletonCounter = 0\nvar isProduction = false\nvar noop = function () {}\nvar options = null\nvar ssrIdKey = 'data-vue-ssr-id'\n\n// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>\n// tags it will allow on a page\nvar isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\\b/.test(navigator.userAgent.toLowerCase())\n\nexport default function addStylesClient (parentId, list, _isProduction, _options) {\n  isProduction = _isProduction\n\n  options = _options || {}\n\n  var styles = listToStyles(parentId, list)\n  addStylesToDom(styles)\n\n  return function update (newList) {\n    var mayRemove = []\n    for (var i = 0; i < styles.length; i++) {\n      var item = styles[i]\n      var domStyle = stylesInDom[item.id]\n      domStyle.refs--\n      mayRemove.push(domStyle)\n    }\n    if (newList) {\n      styles = listToStyles(parentId, newList)\n      addStylesToDom(styles)\n    } else {\n      styles = []\n    }\n    for (var i = 0; i < mayRemove.length; i++) {\n      var domStyle = mayRemove[i]\n      if (domStyle.refs === 0) {\n        for (var j = 0; j < domStyle.parts.length; j++) {\n          domStyle.parts[j]()\n        }\n        delete stylesInDom[domStyle.id]\n      }\n    }\n  }\n}\n\nfunction addStylesToDom (styles /* Array<StyleObject> */) {\n  for (var i = 0; i < styles.length; i++) {\n    var item = styles[i]\n    var domStyle = stylesInDom[item.id]\n    if (domStyle) {\n      domStyle.refs++\n      for (var j = 0; j < domStyle.parts.length; j++) {\n        domStyle.parts[j](item.parts[j])\n      }\n      for (; j < item.parts.length; j++) {\n        domStyle.parts.push(addStyle(item.parts[j]))\n      }\n      if (domStyle.parts.length > item.parts.length) {\n        domStyle.parts.length = item.parts.length\n      }\n    } else {\n      var parts = []\n      for (var j = 0; j < item.parts.length; j++) {\n        parts.push(addStyle(item.parts[j]))\n      }\n      stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }\n    }\n  }\n}\n\nfunction createStyleElement () {\n  var styleElement = document.createElement('style')\n  styleElement.type = 'text/css'\n  head.appendChild(styleElement)\n  return styleElement\n}\n\nfunction addStyle (obj /* StyleObjectPart */) {\n  var update, remove\n  var styleElement = document.querySelector('style[' + ssrIdKey + '~=\"' + obj.id + '\"]')\n\n  if (styleElement) {\n    if (isProduction) {\n      // has SSR styles and in production mode.\n      // simply do nothing.\n      return noop\n    } else {\n      // has SSR styles but in dev mode.\n      // for some reason Chrome can't handle source map in server-rendered\n      // style tags - source maps in <style> only works if the style tag is\n      // created and inserted dynamically. So we remove the server rendered\n      // styles and inject new ones.\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  if (isOldIE) {\n    // use singleton mode for IE9.\n    var styleIndex = singletonCounter++\n    styleElement = singletonElement || (singletonElement = createStyleElement())\n    update = applyToSingletonTag.bind(null, styleElement, styleIndex, false)\n    remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true)\n  } else {\n    // use multi-style-tag mode in all other cases\n    styleElement = createStyleElement()\n    update = applyToTag.bind(null, styleElement)\n    remove = function () {\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  update(obj)\n\n  return function updateStyle (newObj /* StyleObjectPart */) {\n    if (newObj) {\n      if (newObj.css === obj.css &&\n          newObj.media === obj.media &&\n          newObj.sourceMap === obj.sourceMap) {\n        return\n      }\n      update(obj = newObj)\n    } else {\n      remove()\n    }\n  }\n}\n\nvar replaceText = (function () {\n  var textStore = []\n\n  return function (index, replacement) {\n    textStore[index] = replacement\n    return textStore.filter(Boolean).join('\\n')\n  }\n})()\n\nfunction applyToSingletonTag (styleElement, index, remove, obj) {\n  var css = remove ? '' : obj.css\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = replaceText(index, css)\n  } else {\n    var cssNode = document.createTextNode(css)\n    var childNodes = styleElement.childNodes\n    if (childNodes[index]) styleElement.removeChild(childNodes[index])\n    if (childNodes.length) {\n      styleElement.insertBefore(cssNode, childNodes[index])\n    } else {\n      styleElement.appendChild(cssNode)\n    }\n  }\n}\n\nfunction applyToTag (styleElement, obj) {\n  var css = obj.css\n  var media = obj.media\n  var sourceMap = obj.sourceMap\n\n  if (media) {\n    styleElement.setAttribute('media', media)\n  }\n  if (options.ssrId) {\n    styleElement.setAttribute(ssrIdKey, obj.id)\n  }\n\n  if (sourceMap) {\n    // https://developer.chrome.com/devtools/docs/javascript-debugging\n    // this makes source maps inside style tags work properly in Chrome\n    css += '\\n/*# sourceURL=' + sourceMap.sources[0] + ' */'\n    // http://stackoverflow.com/a/26603875\n    css += '\\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'\n  }\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = css\n  } else {\n    while (styleElement.firstChild) {\n      styleElement.removeChild(styleElement.firstChild)\n    }\n    styleElement.appendChild(document.createTextNode(css))\n  }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }"],"names":["Craft","AdminTable","Garnish","Base","extend","settings","totalItems","sorter","$noItems","$table","$tbody","$deleteBtns","init","this","setSettings","defaults","allowDeleteAll","minItems","$","noItemsSelector","tableSelector","children","length","sortable","DataTableSorter","onSortChange","reorderItems","bind","find","addListener","updateUI","addRow","row","maxItems","$row","appendTo","$deleteBtn","addItems","add","ids","i","$items","id","attr","idAttribute","push","data","JSON","stringify","postActionRequest","reorderAction","response","textStatus","success","onReorderItems","cp","displayNotice","t","reorderSuccessMessage","displayError","reorderFailMessage","handleDeleteBtnClick","event","target","closest","confirmDeleteItem","deleteItem","name","getItemName","confirm","confirmDeleteMessage","getItemId","deleteAction","handleDeleteItemResponse","removeItems","remove","onDeleteItem","deleteSuccessMessage","deleteFailMessage","escapeHtml","nameAttribute","hide","removeClass","show","addClass","$moveButtons","newItemBtnSelector","noop","AssetEditor","BaseElementEditor","$filenameInput","originalBasename","originalExtension","reloadIndex","element","on","$sidebar","elementIndex","updateElements","input","refreshThumbnail","$element","base","validators","validateExtension","showImageEditor","AssetImageEditor","onSave","load","showImagePreview","startingWidth","startingHeight","PreviewFileModal","selectFilename","selectionStart","_parseFilename","basename","extension","selectionEnd","one","ev","preventDefault","setTimeout","off","oldExt","newExt","originalFilename","val","rtrim","ext","parts","split","pop","join","registerElementEditorClass","Modal","$body","$footer","$imageTools","$buttons","$cancelBtn","$replaceBtn","$saveBtn","$editorContainer","$straighten","$croppingCanvas","$spinnerCanvas","canvas","image","viewport","focalPoint","grid","croppingCanvas","clipper","croppingRectangle","cropperHandles","cropperGrid","croppingShade","imageStraightenAngle","viewportRotation","originalWidth","originalHeight","imageVerticeCoords","zoomRatio","animationInProgress","currentView","assetId","cacheBust","draggingCropper","scalingCropper","draggingFocal","previousMouseX","previousMouseY","shiftKeyHeld","editorHeight","editorWidth","cropperState","scaleFactor","flipData","focalPointState","spinnerInterval","maxImageSize","lastLoadedDimensions","imageIsLoading","mouseMoveEvent","croppingConstraint","constraintOrientation","showingCustomConstraint","renderImage","renderCropper","Date","now","allowDegreeFractions","isImagick","x","y","$container","$bod","type","class","text","allowSavingAsNew","saveImage","removeListener","$shade","getMaxImageSize","loadEditor","browserViewportWidth","$doc","get","documentElement","clientWidth","browserViewportHeight","clientHeight","Math","max","window","devicePixelRatio","html","alert","$tabs","$viewsContainer","$views","innerHeight","innerWidth","_showSpinner","updateSizeAndPosition","fabric","StaticCanvas","width","height","enableRetinaScaling","requestAnimationFrame","renderAll","imageUrl","getActionUrl","size","Image","fromURL","imageObject","set","originX","originY","left","top","getHeight","getWidth","getScaledImageDimensions","_setFittedImageVerticeCoordinates","_repositionEditorElements","focalState","imageDimensions","offsetX","offsetY","focal","focalData","adjustedX","adjustedY","storeFocalPointState","_createFocalPoint","_createViewport","storeCropperState","_addControlListeners","_handleMouseMove","_handleMouseDown","_handleMouseUp","_handleMouseOut","_hideSpinner","first","trigger","_reloadImage","setSrc","css","parent","previousEditorDimensions","setDimensions","currentScaledDimensions","getZoomToFitRatio","previouslyOccupiedArea","_getBoundingRectangle","_repositionCropper","getZoomToCoverRatio","_repositionImage","_repositionViewport","_repositionFocalPoint","_zoomImage","Rect","fill","globalCompositeOperation","sizeFactor","focalX","focalY","deltaX","deltaY","Group","Circle","radius","strokeWidth","stroke","toggleFocalPoint","dimensions","state","currentWidth","ratio","hasOrientationChanged","_","imageRatio","editorRatio","min","round","_handleTabClick","rotateImage","flipImage","straighteningInput","SlideRuleInput","onStart","_showGrid","onChange","slider","straighten","onEnd","_hideGrid","_cleanupFocalPointAfterStraighten","keyCode","SHIFT_KEY","_handleConstraintClick","_handleOrientationClick","_applyCustomConstraint","constraint","currentTarget","$target","siblings","_showCustomConstraint","_hideCustomConstraint","setCroppingConstraint","enforceCroppingConstraint","value","$constraints","$constraint","reverse","filter","click","_getCustomConstraint","w","h","parseFloat","isNaN","_setCustomConstraint","$tab","view","showView","enableSlider","disableSlider","disableCropMode","enableCropMode","zoomFactor","degrees","parseInt","imageZoomRatio","newAngle","angle","scaledImageDimensions","viewportProperties","imageProperties","angleInRadians","PI","newDeltaX","cos","sin","newDeltaY","modifiedDeltaX","modifiedDeltaY","temp","animate","duration","animationDuration","onComplete","cleanAngle","_adjustFocalPointByAngle","_resetFocalPointPosition","axis","editorCenter","setValue","properties","scaleY","scaleX","previousAngle","_adjustEditorElementsOnStraighten","newCenterX","newCenterY","angleDelta","currentZoomRatio","adjustmentRatio","cropperCenterX","cropperCenterY","imageVertices","getImageVerticeCoords","rectangle","_getZoomRatioToFitRectangle","_isCenterInside","opacity","object","containingObject","newFocalX","newFocalY","adjustedFocalX","adjustedFocalY","containingVertices","vertex","rectangleVertices","_getRectangleVertices","verticeIndex","arePointsInsideRectangle","edge","_getEdgeCrossed","rectangleCenter","distanceFromVertexToEdge","abs","sqrt","pow","distanceFromCenterToEdge","$button","hasClass","append","postData","imageRotation","replace","cropData","zoom","end","error","runQueue","scaledWidth","scaledHeight","boundingBox","_getImageBoundingBox","scale","vertScale","horiScale","getCombinedZoomRatio","strokeOptions","gridWidth","gridHeight","xStep","yStep","Line","onFadeOut","destroy","removeAllListeners","_editorModeTransition","cropperData","_showCropper","_hideCropper","targetZoom","inverseZoomFactor","imageOffsetX","imageOffsetY","callback","context","document","getElementById","getContext","start","cW","cH","setInterval","rotation","save","clearRect","translate","rotate","beginPath","moveTo","lineTo","lineWidth","strokeStyle","restore","clearInterval","clipperData","_setupCropperLayer","_redrawCropperElements","backgroundColor","hoverCursor","selection","position","rectangleRatio","rectWidth","rectHeight","lineOptions","gridOptions","pathGroup","Path","cropTextTop","cropTextBackgroundColor","previousImageArea","currentOffset","areaFactor","coordinateSet","a","b","c","d","_isMouseOver","move","handle","_cropperHandleHitTest","pageX","pageY","_handleMouseMoveInternal","_handleFocalDrag","_handleCropperDrag","_handleCropperResize","_setMouseCursor","vertices","dxi","dyi","furthest","furthestDeltas","newX","newY","previousHeight","previousWidth","startingRectangle","_calculateNewCropperSizeByDeltas","cropperDirection","topDelta","leftDelta","change","match","isMobileBrowser","cursor","parentOffset","offset","mouseX","mouseY","lb","rb","tb","bb","topLeft","topRight","bottomRight","bottomLeft","zoomMode","topVerticalSegment","bottomVerticalSegment","rightHorizontalSegment","leftHorizontalSegment","verticalOffset","horizontalOffset","_debug","fabricObj","points","ab","_getVector","bc","scalarAbAb","_getScalarProduct","scalarBcBc","point","ap","bp","scalarAbAp","scalarBcBp","projectsOnAB","projectsOnBC","_getVectorMagnitude","vector","_getAngleBetweenVectors","acos","edgePoints","centerPoint","smallestDiff","edgeCrossed","edgeIndex","toCenter","edgeVector","toVertex","diff","box","proportion","AssetIndex","BaseElementIndex","$includeSubfoldersContainer","$includeSubfoldersCheckbox","showingIncludeSubfoldersCheckbox","$uploadButton","$uploadInput","$progressBar","$folders","uploader","promptHandler","progressBar","_uploadTotalFiles","_uploadFileProgress","_currentUploaderSettings","_assetDrag","_folderDrag","_expandDropTargetFolderTimeout","_tempExpandedFolders","_fileConflictTemplate","choices","title","_folderConflictTemplate","elementType","_initIndexPageMode","$win","$main","modal","_positionProgressBar","initSources","initSource","$source","_createFolderContextMenu","_getSourceLevel","updateDropTargets","deinitSource","contextMenu","parentsUntil","selectable","multiSelect","DragDrop","activeDropTargetClass","helperOpacity","getSelectedElements","has","helper","$file","_getFileDragHelper","dropTargets","$draggee","targets","$sources","eq","hasAttr","onDragStart","_onDragStart","onDropTargetChange","_onDropTargetChange","onDragStop","_onFileDragStop","helperBaseZindex","$draggeeHelper","$helperSidebar","$helperNav","$helperUl","draggedSourceIds","each","key","_getFolderUidFromSourceKey","inArray","_onFolderDragStop","$activeDropTarget","originatingSource","targetFolderId","originalAssetIds","originalAssetId","getElementInfo","setIndexBusy","resetProgressBar","setItemCount","showProgressBar","parameterArray","action","params","folderId","_performBatchRequests","onMoveFinish","responseArray","resetPrompts","conflict","addPrompt","suggestedFilename","prompt","message","setIndexAvailable","hideProgressBar","performAfterMoveActions","sourceSelect","selectItem","_totalVisible","deselectAllElements","_collapseExtraExpandedFolders","getPromptCount","fadeOutHelpers","showBatchPrompts","returnData","newParameterArray","choice","filename","force","apply","returnHelpersToDraggees","folderIds","sort","parentId","requestId","fileMoveList","newSourceKey","transferList","newFolderId","newFolderUid","merge","_performActualFolderMove","folderDeleteList","moveCallback","counter","limit","setInstanceState","refreshSources","_getRootSource","$parent","_getParentSource","_selectSourceByFolderId","$targetSource","_getSourceByKey","$parentSources","parents","$parentSource","selectSource","afterInit","style","addButton","insertBefore","PromptHandler","ProgressBar","options","url","fileInput","dropZone","events","fileuploadstart","_onUploadStart","fileuploadprogressall","_onUploadProgress","fileuploaddone","_onUploadComplete","fileuploadfail","_onUploadFailure","criteria","kind","allowedKinds","Uploader","isIndexBusy","getDefaultSourceKey","defaultSource","defaultSourceParts","volumeSource","toArray","s","subfolderSource","_getChildSources","_expandSource","onSelectSource","sourceKey","setParams","_updateUrl","history","nestedSources","$thisSource","unshift","uri","forEach","$s","replaceState","getUrl","m","startSearching","hideSidebar","floor","random","insertAfter","$search","$subContainer","setSelecetedSourceState","prop","velocity","checked","getSelectedSourceState","marginBottom","stopSearching","getViewParams","includeSubfolders","progress","loaded","total","setProgressPercentage","result","files","doReload","selectElementAfterUpdate","file","isLastUpload","_uploadFollowup","_updateAfterUpload","jqXHR","responseJSON","clearSearch","setSortAttribute","setSortDirection","doFollowup","parameterIndex","followupCallback","incrementProcessedItemCount","updateProgressBar","sourceAssetId","conflictingAssetId","targetFilename","onUpdateElements","_onUpdateElements","getAllElements","newElements","$newElements","removeAllItems","$elements","_onKeyDown","elementSelect","_onElementFocus","SPACE_KEY","shiftKey","openInstance","selfDestruct","$focusedItem","_loadPreview","stopPropagation","item","$outerContainer","$innerContainer","_$firstRowCells","$helperCells","$helperCell","$firstRowCell","$dropTarget","clearTimeout","dropTargetFolder","_hasSubfolders","_isExpanded","_expandFolder","dropTargetFolderId","$excludedSources","_collapseFolder","splice","menuOptions","label","onClick","_createSubfolder","_renameFolder","_deleteFolder","ContextMenu","menuClass","$parentFolder","subfolderName","folderName","_prepareParentForChildren","$subfolder","folderUid","$a","_appendSubfolder","$targetFolder","folder","trim","_cleanUpTree","$label","oldName","newName","sendActionRequest","then","initSourceToggle","$existingChildren","subfolderLabel","folderInserted","$existingChild","before","deinitSourceToggle","scrollTop","windowHeight","finalCallback","activeRequests","parameters","shift","registerElementIndexClass","AssetSelectInput","BaseElementSelectInput","hud","$uploadBtn","arguments","canUpload","_attachUploader","$elementsContainer","createElementEditor","defaultFieldLayoutId","formData","fieldId","sourceElementId","elementId","siteId","$addElementBtn","describedBy","multiple","csrfTokenName","csrfTokenValue","canAddMoreFiles","next","viewMode","$existing","replaceWith","thumbLoader","selectUploadedFile","canAddMoreElements","$newElement","prepend","margin","outerWidth","animateCss","addElements","outerHeight","appendHeadHtml","headHtml","draftEditor","checkForm","slotsTaken","AssetSelectorModal","BaseElementSelectorModal","$selectTransformBtn","_selectedTransform","transforms","createSelectTransformButton","$btnGroup","$primaryButtons","$selectBtn","$menu","$menuList","MenuButton","MenuBtn","onOptionSelect","onSelectTransform","disable","onSelectionChange","$selectedElements","allowTransforms","enable","option","transform","selectImagesWithTransform","transformUrls","imageIdsWithMissingUrls","$item","showFooterSpinner","fetchMissingTransformUrls","hideFooterSpinner","selectElements","info","onSelect","elementInfo","canSelectImageTransforms","registerElementSelectorModalClass","AuthManager","remainingSessionTime","checkRemainingSessionTimer","showLoginModalTimer","decrementLogoutWarningInterval","showingLogoutWarningModal","showingLoginModal","logoutWarningModal","loginModal","$logoutWarningPara","$passwordInput","$passwordSpinner","$loginBtn","$loginErrorPara","submitLoginIfLoggedOut","updateRemainingSessionTime","setCheckRemainingSessionTimer","seconds","checkRemainingSessionTime","extendSession","ajax","dataType","complete","timeout","minSafeSessionTime","showLogoutWarningModal","checkInterval","showLoginModal","submitLogin","hideLogoutWarningModal","hideLoginModal","quickShow","$form","$logoutBtn","$renewSessionBtn","prependTo","autoShow","closeOtherModals","hideOnEsc","hideOnShadeClick","shadeClass","onFadeIn","updateLogoutWarningMessage","decrementLogoutWarning","time","secondsToHumanTimeDuration","quick","quickHide","$inputContainer","$inputsFlexContainer","$passwordContainer","$buttonContainer","$passwordWrapper","PasswordInput","onToggleInput","$newPasswordInput","logout","redirectTo","renewSession","validatePassword","login","clearLoginError","loginName","username","password","showLoginError","shake","deltaNames","initialData","$header","$toolbar","$tabContainer","$editLink","$sidebarBtn","$loadSpinner","$fieldsContainer","$siteSelectContainer","$siteSelect","$siteSpinner","$saveSpinner","slideout","tabManager","showingSidebar","cancelToken","ignoreFailedRequest","initialDeltaValues","isPlainObject","ltr","showSidebar","trapFocusWithin","$siteSelectOuterContainer","$contents","Slideout","containerElement","containerAttributes","method","novalidate","closeOnEsc","closeOnShadeClick","uiLayerManager","registerShortcut","S_KEY","ctrl","saveElement","ESC_KEY","maybeCloseSlideout","onShowHud","onCreateForm","setElementAttribute","attributes","getBaseData","prevalidate","refreshInitialData","Promise","resolve","reject","showLoadSpinner","onBeginLoading","cancel","axios","CancelToken","source","token","includeSites","isMultiSite","showSiteSwitcher","hideLoadSpinner","onEndLoading","updateForm","e","showHeader","hideHeader","switchSite","isDirty","newSiteId","fieldHtml","sites","siteInfo","$option","tabHtml","Tabs","editUrl","sidebarHtml","initUiElements","ElementThumbLoader","hostname","appendFootHtml","footHtml","serialize","setFocusWithin","_closedSidebarStyles","offsetWidth","_openedSidebarStyles","addLayer","removeLayer","isArray","isFunction","call","param","findDeltaData","$title","cpEditUrl","newTitle","elementTypeNames","closeSlideout","onSaveElement","isOpen","close","onHideHud","loadHud","maybeCloseHud","closeHud","reloadForm","initialized","instanceState","sourceStates","sourceStatesStorageKey","searchTimeout","sourceViewModes","sourcesByKey","$visibleSources","$customizeSourcesBtn","customizeSourcesModal","toolbarOffset","searching","searchText","trashed","drafts","$clearSearchBtn","$statusMenuBtn","$statusMenuContainer","statusMenu","status","$siteMenuBtn","siteMenu","$sortMenuBtn","sortMenu","$sortAttributesList","$sortDirectionsList","$scoreSortAttribute","$structureSortAttribute","$viewModeBtnContainer","viewModeBtns","_autoSelectElements","$countSpinner","$countContainer","page","resultSet","totalResults","$exportBtn","actions","actionsHeadHtml","actionsFootHtml","$selectAllContainer","$selectAllCheckbox","showingActionTriggers","exporters","exportersByType","_$detachedToolbarItems","_$triggers","_ignoreFailedRequest","_cancelToken","getDefaultInstanceState","storageKey","getLocalStorage","toolbarSelector","menubtn","menu","_handleStatusChange","$options","_setSite","_handleSiteChange","defaultSiteId","getSiteId","$storedSiteOption","updateElementsIfSearchTextChanged","RETURN_KEY","_handleSortChange","selectDefaultSource","setPage","pageNum","onAfterInit","_createCancelToken","_cancelRequests","getSourceContainer","getSite","_getSourcesInList","Select","multi","allowEmpty","vertical","_handleSourceSelectionChange","getSourceByKey","index","refreshSourcesAction","expandedSources","indexOf","$toggle","_getSourceToggle","removeData","selectedSource","paths","path","getDefaultExpandedSources","addOptions","_updateStructureSortOption","detach","storeInstanceState","setLocalStorage","getSourceState","defaultValue","viewState","storeSortAttributeAndDirection","getSelectedSortAttribute","lastAttr","oldHistory","includes","order","getSelectedSortDirection","orderHistory","location","href","RegExp","pageTrigger","_resetCount","search","batchSize","canHaveDrafts","savedDraftsOnly","draftOf","disabledElementIds","paginated","_isViewPaginated","collapsedElementIds","preservePagination","updateElementsAction","$scrollContainer","_updateView","showActionTriggers","_createTriggers","submitAction","actionParams","selectedElementIds","getSelectedElementIds","_findAction","viewParams","expandPostArray","elementAction","elementIds","download","downloadFromUrl","submitActionsAction","badgeCounts","_updateBadgeCounts","afterAction","actionClass","onAfterAction","hideActionTriggers","updateActionTriggers","totalSelected","getEnabledElements","setStatus","selectOption","getSortAttributeOption","attribute","getSortDirectionOption","dir","getSelectedViewMode","updateSidebarMenuLabel","sortOptions","setStoredSortOptionsForSource","$firstOption","getViewModesForSource","sourceViewMode","$viewModeBtn","className","mode","icon","selectViewMode","doesSourceHaveViewMode","selectSourceByKey","sortAttr","sortDir","getDefaultSort","viewModes","createView","getViewClass","TableElementIndexView","ThumbsElementIndexView","rememberDisabledElementId","forgetDisabledElementId","enableElements","onEnableElements","disableElements","onDisableElements","enableElementsById","makeArray","disableElementsById","getButtonContainer","isShowingSidebar","buttonContainer","createCustomizeSourcesModal","CustomizeSourcesModal","onHide","onSelectSite","elements","$selectedItems","_handleActionTriggerSubmit","getPostData","_handleMenuActionTriggerSubmit","selectedOption","$firstVisibleSource","firstSite","selectNewSource","toString","$heading","$headings","nextUntil","setSiteId","is","_handleSelectionChange","_handleSourceDblClick","_toggleSource","_handleSourceToggleClick","prev","$list","_collapseSource","$childSources","not","_countResults","itemLabel","itemsLabel","last","countLabel","items","$paginationContainer","totalPages","ceil","$prevBtn","$nextBtn","role","tabindex","selectAllElements","checkboxMode","selectElementById","hasOwnProperty","$badge","countElementsAction","count","$btn","triggers","safeMenuActions","destructiveMenuActions","formatInputId","destructive","$menuTrigger","$safeList","_createMenuTriggerList","$destructiveList","$div","_showExportHud","typeOptions","$typeField","ui","createSelectField","$formatField","$typeSelect","formattable","$limitField","createTextField","placeholder","$spinner","HUD","submitting","format","$ul","BaseElementIndexView","$loadingMoreSpinner","$elementContainer","$scroller","loadingMore","_morePending","_handleEnableElements","_handleDisableElements","container","getElementContainer","setTotalVisible","setMorePending","isVerticalList","_handleElementEditing","isTouchCapable","maybeLoadMore","selectElement","selectAll","deselectAll","getTotalVisible","totalVisible","getMorePending","morePending","canLoadMore","loadMore","loadMoreElementsAction","getLoadMoreParams","appendElements","onAppendElements","elementSort","elementEditor","fieldLabel","$addElementBtnContainer","_initialized","normalizedSettings","args","modalStorageKey","getContainer","getFieldLabel","getElementsContainer","getAddElementsBtn","initElementSelect","initElementSort","resetElements","getElements","DragSort","$targetItem","getSelectedItems","ignoreHandleSelector","getElementSortAxis","collapseDraggees","magnetStrength","helperLagBase","resetItemOrder","updateAddElementsBtn","enableAddElementsBtn","disableAddElementsBtn","focusNextLogicalElement","focus","focusLastRemoveBtn","$removeBtns","removeElements","editable","_handleShowElementEditor","removeElement","$nextDeleteBtn","lastElementIndex","onRemoveElements","animateElementAway","right","pause","REMOVE_FX_DURATION","resume","showModal","createModal","createElementSelectorModal","getModalSettings","sources","showSiteMenu","getDisabledElementIds","onModalSelect","onModalHide","triggerElement","modalTitle","modalSettings","allowSelfRelations","slotsLeft","slice","updateDisabledElementsInModal","createNewElement","appendElement","animateElementIntoPlace","onSelectElements","clone","removeText","setElementSize","single","$modalElement","$inputElement","origOffset","destOffset","$helper","zIndex","ADD_FX_DURATION","editorSettings","$sourceToggles","$secondaryButtons","$footerSpinner","$headingId","fullscreen","minGutter","_createElementIndex","updateSelectBtnState","enableSelectBtn","disableSelectBtn","enableCancelBtn","disableCancelBtn","clearMouseUpTimeout","disableElementsOnSelect","hideOnSelect","bodyAction","createElementIndex","Object","assign","indexSettings","touchData","firstTap","secondTap","resizable","onCancel","BaseInputGenerator","listening","startListening","setNewSource","stopListening","onSourceTextChange","updateTarget","onTargetTextChange","activeElement","onFormSubmit","sourceVal","targetVal","generateTargetValue","dispatchEvent","InputEvent","inputType","Event","selectFullValue","CP","authManager","$nav","$navToggle","$globalSidebar","$globalContainer","$mainContainer","$alerts","$crumbs","$breadcrumbList","$breadcrumbItems","$notificationContainer","$primaryForm","$headerContainer","$mainContent","$details","$sidebarContainer","$contentContainer","$edition","$confirmUnloadForms","$deltaForms","$collapsibleTables","isMobile","fixedHeader","breadcrumbListWidth","breadcrumbDisclosureItem","enableQueue","totalJobs","jobInfo","displayedJobInfo","displayedJobInfoUnchanged","trackJobProgressTimeout","jobProgressIcon","checkingForUpdates","forcingRefreshOnUpdatesCheck","includingDetailsOnUpdatesCheck","checkForUpdatesCallbacks","resizeTimeout","$allInstructions","$instructions","updateFixedHeader","ready","handleWindowResize","setSidebarNavAttributes","$errorNotifications","$otherNotifications","delay","notificationDuration","initSpecialForms","initAlerts","shortcuts","redirect","retainScroll","shortcut","submitPrimaryForm","initTabs","scrollY","removeLocalStorage","scrollTo","_handleInputFocus","_handleInputBlur","announcements","hasUnreads","some","unread","contents","group","timestamp","heading","body","onShow","map","serialized","$forms","createForm","submit","confirmUnload","livePreview","inPreviewMode","originalEvent","returnValue","saveShortcut","submitForm","toggleNav","isExpanded","navIsExpanded","disableGlobalSidebarLinks","enableGlobalSidebarLinks","focusableItems","isAlwaysVisible","getComputedStyle","getPropertyValue","toggleSidebar","toggleClass","charAt","menuBtn","undefined","LOCATION_HASH","selectTab","$tabsContainer","$tabsList","$selectedTab","selectedTabIndex","$focusableTab","tab","deselectTab","updateResponsiveTables","handleBreadcrumbVisibility","breadcrumbItemsWrap","orientation","listWidth","getBoundingClientRect","totalItemWidth","finalIndex","visibleItemWidth","shownItems","hiddenItems","disclosureMenu","_i","_$table","_containerWidth","_check","_isCollapsed","headerHeight","displayNotification","$notification","fadedMargin","display","notificationType","fetchAlerts","queueActionRequest","displayAlerts","alerts","$shunnableAlerts","$link","substr","checkForUpdates","forceRefresh","includeDetails","realCallback","_checkForUpdates","updateUtilitiesBadge","callbacks","updateInfo","_getUpdates","_checkForCachedUpdates","cached","onlyIfCached","sendApiRequest","updates","_cacheUpdates","contentType","$utilitiesLink","badgeCount","runQueueAutomatically","trackJobProgress","_trackJobProgressInternal","setJobInfo","jobs","oldInfo","getDisplayedJobInfo","progressLabel","updateJobIcon","statuses","JOB_STATUS_RESERVED","JOB_STATUS_FAILED","JOB_STATUS_WAITING","j","JobProgressIcon","hideFailMode","setDescription","description","setProgress","showFailMode","getCookie","setCookie","maxAge","JOB_STATUS_DONE","$li","$progressLabel","failMode","_$bgCanvas","_$staticCanvas","_$hoverCanvas","_$failCanvas","_staticCtx","_hoverCtx","_canvasSize","_arcPos","_arcRadius","_lineWidth","_arcStartPos","_arcEndPos","_arcStartStepSize","_arcEndStepSize","_arcStep","_arcStepTimeout","_arcAnimateCallback","_progressBar","canAccessQueueManager","$canvasContainer","$labelContainer","_createCanvas","_drawArc","_animateArc","_setArc","color","$canvas","ctx","lineCap","startPos","endPos","arc","closePath","targetStartPos","targetEndPos","_takeNextArcStep","CategoryIndex","editableGroups","$newCategoryBtnGroup","$newCategoryBtn","updateButton","editableCategoryGroups","uid","defaultGroupHandle","selectedSourceHandle","selectedGroup","$menuBtn","_getGroupTriggerHref","_openCreateCategoryModal","getAttribute","menuHtml","site","groupId","newCategoryBtnText","hudTrigger","groupSourceKey","CategorySelectInput","selectedCategoryIds","categoryIds","branchLimit","selectionLabel","$newElementsContainer","filteredElements","$allCategories","_animateCategoryAway","func","charts","DataTable","columns","rows","cellIndex","parseTime","d3","timeParse","Tip","$tip","setContent","setPosition","BaseChart","$chart","chartBaseClass","dataTable","formatLocale","timeFormatLocale","svg","globalSettings","formats","d3Formats","formatLocaleDefinition","d3FormatLocaleDefinition","timeFormatLocaleDefinition","d3TimeFormatLocaleDefinition","select","resize","baseSettings","draw","chartClass","onAfterDrawTicks","tickKey","tick","$tickText","numberFormat","percentFormat","currencyFormat","shortDateFormats","day","month","year","bottom","colors","Area","tip","drawingArea","getChartMargin","translateX","translateY","drawTicks","drawAxes","drawChart","drawTipTriggers","getX","xAxis","axisBottom","tickFormat","getXFormatter","ticks","yAxis","getY","axisLeft","getYFormatter","tickValues","getYTickValues","axisRight","showAxis","tickSizeOuter","gridlines","xLineAxis","tickSize","yLineAxis","line","datum","area","y0","y1","plots","enter","tips","chartMargin","xAxisTickInterval","node","getTotalLength","tipTriggerWidth","$content","$xValue","$yValue","content","values","yTicksMaxWidth","computedTickWidth","formatter","padded","xDomainMin","xDomainMax","xDomain","scaleTime","range","domain","yDomain","getYMaxValue","scaleLinear","utils","getTimeFormatter","getNumberFormatter","maxValue","getDuration","secondsNum","hours","minutes","chartSettings","dataScale","ColorInput","$input","$colorContainer","$colorPreview","$colorInput","createColorInput","handleTextChange","createElement","setAttribute","updateColor","repeat","_browserSupportsColorInputs","doesBrowserSupportColorInputs","rxhtmlTag","jQuery","htmlPrefilter","navHeight","arr","reduce","obj","grouped","thisKey","category","translations","formatMessage","pattern","tokens","_tokenizePattern","_parseToken","pos","depth","chars","open","arg","number","formatNumber","selector","plural","selectorChars","substring","p","formatDate","date","datepicker","datepickerOptions","dateFormat","shortcutText","alt","clientOs","str","escapeRegex","getText","encodeUriComponent","encodeURIComponent","differences","chr","re","setSelectionRange","inputName","baseUrl","anchor","aParams","apos","qpos","pathParam","pathMatch","omitScriptNameInUrls","usePathInfo","scriptName","basePath","endPath","getCpUrl","baseCpUrl","getSiteUrl","baseSiteUrl","actionUrl","getCsrfInput","headers","_actionHeaders","errorThrown","readyState","send","_waitingOnAjax","_ajaxQueue","_postNextActionRequestInQueue","keys","registeredAssetBundles","registeredJsFiles","v","getTime","request","_getApiHeaders","apiHeaders","baseURL","baseApiUrl","apiParams","_apiHeaders","processCraftHeaders","httpProxy","proxy","apiResponse","_processApiHeaders","_loadingApiHeaders","_apiHeaderWaitlist","_rejectApiRequests","clearCachedApiHeaders","XMLHttpRequest","setRequestHeader","responseType","onload","disposition","getResponseHeader","matches","exec","blob","Blob","link","URL","createObjectURL","appendChild","removeChild","stringToArray","oldData","newData","groupedOldParams","_groupParamsByDeltaNames","groupedNewParams","__root__","n","modifiedDeltaNames","concat","withRoot","initialValues","encodeURIComponentExceptEqualChar","o","decodeURIComponent","paramLoop","paramName","serializeParam","subName","expanded","parentElem","chunks","compare","obj1","obj2","sortObjectKeys","Array","getObjectKeys","escapeChars","escaped","ltrim","startsWith","filterArray","filtered","elem","removeFromArray","getLast","uppercaseFirst","toUpperCase","lowercaseFirst","toLowerCase","parseUrl","scheme","host","port","query","hash","isSameHost","requestUrlInfo","urlInfo","showSeconds","secondsInWeek","weeks","days","timeComponents","asciiString","charMap","normalize","char","asciiStr","asciiCharMap","randomString","createErrorList","errors","$existingCss","existingCss","regexp","$existingJs","src","existingJs","infoicon","checkboxselect","fieldtoggle","lightswitch","nicetext","formsubmit","datetime","datetimeinput","_elementIndexClasses","_elementSelectorModalClasses","_elementEditorClasses","systemUid","localStorage","parse","removeItem","cookie","defaultCookieOptions","expires","toUTCString","secure","removeCookie","hasThumb","otherSize","$oldImg","$newImg","sizes","srcset","picturefill","fn","animateLeft","easing","animateRight","$elem","removeAttr","itemSelector","cols","maxCols","minColWidth","fillMode","colClass","snapToGrid","Grid","InfoIcon","CheckboxSelect","FieldToggle","settingName","settingValue","thisSettings","indeterminateValue","LightSwitch","NiceText","$anchor","customTrigger","menuAnchor","$trigger","DisclosureMenu","$wrapper","$inputs","checkValue","hasValue","charsLeftHtml","charsLeft","$elementIndexSourcesContainer","$sourcesContainer","$sourceSettingsContainer","$newHeadingBtn","$footerBtnContainer","$loadingSpinner","sourceSort","updateSourcesOnSave","availableTableAttributes","setContainer","buildModal","addSource","sourceData","$itemLabel","$itemInput","Heading","updateItemLabel","Source","handleNewHeadingBtnClick","scrollContainerToElement","$pendingHeading","$lastSource","$indexSource","getIndexSource","isHeading","appendSource","$extraSources","nextAll","BaseSource","$settingsContainer","isSelected","deselect","createSettings","$settings","headerColHeading","defaultHeaderColHeading","tableAttributes","createTableColumnsField","firstKey","firstLabel","$titleColumnCheckbox","createTableColumnOption","$columnCheckboxes","selectedAttributes","createField","instructions","createCheckbox","disabled","$labelField","$labelInput","handleLabelInputChange","deleteHeading","table","$rows","getHelper","caboose","Y_AXIS","$helperRow","helperClass","$cells","DeleteUserModal","userId","$deleteActionRadios","$deleteSpinner","userSelect","_deleting","idParam","contentSummary","$deleteSubmitBtn","_submitBtnLabel","validateDeleteInputs","withContent","num","validates","handleSubmit","onSubmit","DraftEditor","$revisionBtn","$revisionLabel","$expandSiteStatusesBtn","$statusIcon","$editMetaBtn","metaHud","$nameTextInput","$saveMetaBtn","$siteStatusPane","$globalLightswitch","$siteLightswitches","$addlSiteField","siteIds","newSiteIds","enableAutosave","lastSerializedValue","listeningForChanges","pauseLevel","saving","queue","submittingForm","duplicatedElements","httpStatus","httpError","openingPreview","preview","activatingPreviewToken","activatedPreviewToken","previewTokenQueue","previewLinks","createdProvisionalDraft","autosaveDrafts","siteStatuses","$statusMessage","canEditMultipleSites","previewTargets","enablePreview","$previewBtnContainer","createPreviewLink","createShareMenu","revisionId","serializeForm","isProvisionalDraft","initForProvisionalDraft","draftId","isUnpublishedDraft","initForDraft","canUpdateSource","createDraft","listenForChanges","showStatusHud","BroadcastChannel","onmessage","canonicalId","sourceId","reload","saveDraftAction","statusIcons","stopListeningForChanges","deleteDraftAction","hashedCpEditUrl","provisional","createEditMetaBtn","publishDraftAction","expandSiteStatuses","$enabledForSiteField","_getOtherSupportedSites","_createSiteStatusField","$globalField","createLightswitchField","_showField","siteStatusValues","hasEnabled","hasDisabled","originalEnabledValue","originalSerializedStatus","enabledForSite","_updateGlobalStatus","serializedStatuses","addlSites","_createAddlSiteField","_updateSiteStatuses","$field","overflow","_removeField","allEnabled","allDisabled","turnOn","turnOff","turnIndeterminate","enabled","$lightswitch","$addlSiteSelectContainer","createSelect","$addlSiteSelect","addlSiteInfo","enabledByDefault","bodyHtml","_saveSuccessMessage","_saveFailMessage","hudClass","spinners","statusMessage","getTokenizedPreviewUrl","targetUrl","targetLabel","activatePreviewToken","updatePreviewLinks","updatePreviewLinkHref","isLive","getPreviewTokenParams","previewToken","getPreviewToken","randoParam","asPromise","siteToken","previewUrl","tokenParam","createTokenParams","getPreview","Preview","$statusIcons","openPreview","ensureIsDraftOrRevision","onlyIfChanged","removeActionParams","isPreviewActive","$editor","saveDraft","console","warn","isActive","empty","modifiedFieldNames","preparedData","prepareData","deltaName","_afterSaveRequest","_showFailStatus","docTitle","draftName","revisionMenu","oldId","siteSettings","creator","updatePreviewTargets","checkMetaValues","selectors","modifiedAttributes","$fields","afterUpdate","postMessage","setStatusMessage","deltaCallback","swapDuplicatedElementIds","idsRE","pre","post","newTarget","$previewLink","nextInQueue","showMetaHud","createMetaHud","onMetaHudShow","$hudBody","$nameField","$nameInputContainer","saveMeta","onMetaHudHide","onMetaHudEscape","shakeMetaHud","$hud","handleFormSubmit","autosave","hashedAddAnotherRedirectUrl","DynamicGenerator","EditableTable","baseName","biggestId","$addRowBtn","$tableParent","rowCount","hasMaxRows","hasMinRows","radioCheckboxes","copyDraggeeInputValuesToHelper","updateAllRows","isVisible","initialize","initializeIfVisible","minRows","createRowObj","updateAddRowButton","canAddRow","staticRows","updateRow","canDeleteRow","updateDeleteRowButton","rowId","updateStatusMessage","deleteRow","$tr","onDeleteRow","maxRows","rowIdPrefix","createRow","defaultValues","onAddRow","Row","focusOnPrevRow","tdIndex","blurTd","prevRow","$prevTr","$tds","focusOnNextRow","nextRow","$nextTr","importData","lines","textualColTypes","colId","$cell","col","scope","code","small","createDateInput","createLightswitch","createTimeInput","createTextInput","niceTexts","tds","$textareas","tr","td","$textarea","$checkbox","textareasByColId","onHeightChange","onTextareaHeightChange","radioMode","toggle","applyToggleCheckbox","autopopulate","HandleGenerator","allowNonAlphaStart","onTextareaFocus","onRadioCheckboxChange","checkbox","checkboxColId","neg","checkboxCol","colum","ignoreNextTextareaFocus","handleKeypress","charCode","isCtrlKeyPressed","numericKeyCodes","handlePaste","clipboardData","getData","validateValue","safeValue","tallestTextareaHeight","tdHeight","ElementActionTrigger","maxLevels","newChildUrl","triggerEnabled","activate","updateTrigger","validateSelection","enableTrigger","disableTrigger","valid","batch","handleTriggerActivation","workers","Worker","$thumbs","$thumb","$scrollParent","scrollParent","addToQueue","invisibleThumbs","thumb","active","loadNext","scrollParentOffset","scrollParentHeight","thumbOffset","retryAll","loader","$img","ElevatedSessionForm","inputs","form","getInputPostVal","elevatedSessionManager","fetchingTimeout","stopImmediatePropagation","inputsChanged","$currentInput","requireElevatedSession","ElevatedSessionManager","passwordModal","$submitBtn","$errorPara","minSafeElevatedSessionTimeout","showPasswordModal","$passwordModal","focusPasswordInput","submitPassword","currentPassword","showPasswordError","EntryIndex","publishableSections","$newEntryBtnGroup","$newEntryBtn","section","defaultSectionHandle","selectedSection","_getSectionTriggerHref","_openCreateEntryModal","sectionId","newEntryBtnText","typeId","entryTypes","canPublish","sectionSourceKey","FieldLayoutDesigner","$newTabBtn","$libraryToggle","$selectedLibrary","$fieldLibrary","$uiLibrary","$uiLibraryElements","$fieldSearch","$clearFieldSearchBtn","$fieldGroups","tabGrid","elementDrag","$workspace","$fieldSearchContainer","initTab","elementPlacementInputName","ElementDrag","customizableTabs","tabDrag","TabDrag","customizableUi","$libraryPicker","Listbox","$selectedOption","$matches","$group","$editBtn","onTabOptionSelect","initElement","Element","renameTab","removeTab","$prev","$next","$labelSpan","promptForTabName","getElementPlacementInputName","removeFieldByHandle","removeField","refreshCols","addTab","tabName","elementConfigInputName","designer","$placementInput","$configInput","config","isField","requirable","hasCustomWidth","hasSettings","settingsHtml","isRequired","createSettingsHud","initUi","updatePlacementInput","updateConfigInput","SlidePicker","step","valueLabel","pct","applyHudSettings","serializeArray","updateRequiredClass","required","BaseDrag","Drag","$insertion","showingInsertion","$caboose","findItems","createInsertion","createCaboose","removeCaboose","swapDraggeeWithInsertion","swapInsertionWithDraggee","setMidpoints","getClosestItem","_closestItem","_closestItemMouseDiff","_$item","_midpoint","_mouseDiff","getDist","checkForNewClosestItem","draggeeDisplay","visibility","FX_DURATION","helpers","_showDraggee","onDrag","draggingLibraryElement","draggingField","isDraggeeMandatory","isHoveringOverTab","hitTest","$fieldContainers","$libraryElement","targetPrefix","targetSelector","reverseTargetSelector","_$target","_$reverseTarget","getType","normalizeTargetSelector","findTargets","onToggleChange","nodeName","getToggleVal","boolean","postVal","hideTarget","showTarget","_show","_currentHeight","$t","_targetHeight","totalCols","colGutterDrop","colPctWidth","possibleItemColspans","possibleItemPositionsByColspan","itemPositions","itemColspansByPosition","layouts","layout","itemHeights","leftPadding","_refreshingCols","_refreshColsAfterRefresh","_forceRefreshColsAfterRefresh","handleContainerHeightProxy","setItems","oldHeight","scrollHeight","gutter","itemIndex","tallestItemHeight","colIndex","itemHeight","remainder","itemHeightsByColspan","positionRight","positionLeft","minColspan","maxColspan","colspan","getItemWidthCss","minPosition","maxPosition","colHeights","createLayouts","layoutTotalCols","highestTotalCols","layoutHeights","shortestHeight","shortestLayouts","emptySpaces","emptySpace","colspans","getItemLeftPosCss","positions","isSimpleLayout","positionItems","completeRefreshCols","onRefreshCols","getItemWidth","getItemWidthInPx","getItemLeftPosInPx","prevPositions","prevColspans","prevColHeights","prevEmptySpace","LayoutGenerator","endingCol","affectedColHeights","onItemResize","newHeight","tallestColHeightsByPosition","colHeightsForPosition","tallestColHeight","words","handleCasing","ImageUpload","initImageUpload","containerSelector","uploadAction","postParameters","fileInputSelector","uploadParamName","initButtons","uploadButtonSelector","deleteButtonSelector","refreshImage","onAfterRefreshImage","$icon","previousSibling","nodeType","Node","TEXT_NODE","nodeValue","showHud","showing","closeOtherHUDs","indeterminate","dragger","dragStartMargin","outerContainer","X_AXIS","_onDrag","_onDragStop","muteEvent","changed","prefersReducedMotion","_onSettle","_getOffMargin","_onMouseDown","_onMouseUp","dragging","RIGHT_KEY","LEFT_KEY","_getMargin","mouseDistX","log","selectedOptionIndex","UP_KEY","selectPrev","DOWN_KEY","selectNext","selectedClass","focusClass","LivePreview","$extraFields","$dragHandle","$previewContainer","$iframeContainer","$iframe","$fieldPlaceholder","basePostData","fields","lastPostData","updateIframeInterval","loading","checkAgain","dragStartEditorWidth","_slideInOnIframeLoad","_forceUpdateIframeProxy","_scrollX","_scrollY","_editorWidth","_editorWidthInPx","protocol","previewParams","forceUpdateIframe","extraFields","defaultEditorWidth","moveFieldsBack","editorWidthInPx","inPx","minEditorWidthInPx","exit","$editorHeader","$closeBtn","getIframeWidth","$clone","_getClone","updateIframe","slideIn","createToken","previewAction","updateWidths","$newClone","field","contentWindow","scrollLeft","xhrFields","withCredentials","crossDomain","handleSuccess","handleError","write","onResponse","copyInputValues","$textInput","$showPasswordToggle","showingPassword","passwordInput","initInputFocusEvents","hidePassword","setCurrentInput","updateToggleLabel","showPassword","autocapitalize","togglePassword","onKeyDown","ALT_KEY","onKeyUp","onInputChange","$previewHeader","$targetBtn","$targetMenu","$deviceTypeContainer","$orientationBtn","$refreshBtn","$deviceMask","$devicePreviewContainer","iframeLoaded","$tempInput","activeTarget","currentDeviceType","deviceOrientation","deviceWidth","deviceHeight","deviceMaskDimensions","phone","tablet","iframeHeight","_updateIframeProxy","Pro","switchTarget","_buildDeviceTypeFieldset","_updateRefreshBtn","$radioGroup","$desktopWrapper","$desktopLabel","for","$tabletWrapper","$tabletLabel","$mobileWrapper","$mobileLabel","_activeTarget","_autoRefresh","refresh","previewTarget","_devicePreviewIsActive","updateDevicePreview","_useIframeResizer","previewIframeResizerOptions","resetScroll","sameHost","frameborder","iFrameResize","checkOrigin","scrolling","onInit","iframe","switchDeviceType","$inputWrapper","newDeviceType","switchOrientation","hZoom","wZoom","previewHeight","previewWidth","maskHeight","maskWidth","rotationDeg","marginTop","marginLeft","defaultSettings","_onHide","instance","loadAsset","focusItem","desiredHeight","desiredWidth","containerHeight","containerWidth","_resizeContainer","previewHtml","$innerProgressBar","$progressBarStatus","_itemCount","_processedItemCount","_displaySteps","displaySteps","setProcessedItemCount","fadeTo","incrementItemCount","percentage","$modalContainerDiv","$prompt","$promptApplyToRemainingContainer","$promptApplyToRemainingCheckbox","$promptApplyToRemainingLabel","$pomptChoices","_prompts","_promptBatchCallback","_promptBatchReturnData","_promptBatchNum","_showNextPromptInBatch","remainingInBatch","_showPrompt","_handleBatchPromptSelection","applyToRemaining","choiceData","itemsToGo","_promptCallback","$promptMessage","$promptChoices","$promptButtons","$radioButton","_selectPromptChoice","fadeOut","_cancelPrompt","totalSteps","_min","_max","Number","isInteger","prevAll","triggerEvent","$activeButton","startPositionX","graduationsMin","graduationsMax","slideMin","slideMax","$overlay","$cursor","$graduations","$graduationsUl","_handleResize","_handleTapStart","_handleTapMove","_handleTapEnd","graduationsCalculatedWidth","valueToPosition","touch","startLeft","curX","positionToValue","scaleMin","scaleMax","addModalAttributes","autoOpen","setTriggerElement","_cancelTransitionListeners","addPanel","hideModalBackgroundLayers","removePanel","resetModalBackgroundLayerVisibility","openPanels","panel","updateStyles","totalPanels","SlugGenerator","allowUppercaseInSlug","limitAutoSlugsToAscii","XRegExp","matchChain","slugWordSeparator","Structure","structureDrag","$parents","initToggle","StructureDrag","initNewChildMenus","viewStateKey","$addBtns","onNewChildMenuClick","showMenu","getIndent","level","baseIndent","nestedIndent","addElement","$addBtn","$parentUl","_removeUl","structure","draggeeLevel","$helperLi","$targets","draggeeHeight","$level","cancelDrag","$lis","$closestTarget","closestTargetPos","closestTargetYDiff","closestTargetOffset","closestTargetHeight","targetOffset","targetHeight","targetYMidpoint","targetYDiff","$closestTargetLi","closestTargetLevel","$nextTargetLi","nextTargetLevel","hoveringBetweenRows","draggeeX","targetItemMouseDiffX","$parentLis","$closestParentLi","closestParentLiXDiff","closestParentLevel","$parentLi","parentLiX","parentLiXDiff","parentLevel","onMouseUp","$draggeeParent","moved","$closestSiblings","newLevel","setLevel","structureId","prevId","indent","$childLis","StructureTableSorter","tableView","_basePadding","_helperMargin","_$titleHelperCell","_titleHelperCellOuterWidth","_ancestors","_updateAncestorsFrame","_draggeeLevel","_draggeeLevelDelta","draggingLastElements","_loadingDraggeeLevelDelta","_targetLevel","_targetLevelBounds","_positionChanged","singleHelper","helperSpacingY","findDraggee","$nextRow","nextRowLevel","nextRowLevelDelta","_getAjaxBaseData","delta","drag","canInsertBefore","_getLevelBounds","canInsertAfter","_getAncestors","_setTargetLevelBounds","_updateIndent","onInsertionPointChange","_updateAncestorsBeforeRepaint","levelDiff","padding","_getLevelIndent","$prevRow","prevRowLevel","$spinnerRow","_createSpinnerRowAfter","onPositionChange","_expandElement","onReturnHelpersToDraggees","newDraggeeIndexes","oldDraggeeIndexes","$postDraggeeItems","_minLevel","_maxLevel","forcePositionChange","_mouseDist","realMouseX","mousedownX","_indentationDist","LEVEL_INDENT","_targetLevelMouseDiff","_magnetImpact","MAX_GIVE","_closestLevelMagnetIndent","targetLevel","_level","_$prevRow","cancelAnimationFrame","_updateAncestors","_$ancestor","_newAncestors","HELPER_MARGIN","$selectedSortHeader","structureTableSort","_totalVisiblePostStructureTableDraggee","_morePendingPostStructureTableDraggee","initTableHeaders","_collapseElement","selectedSortAttr","$tableHeaders","selectedSortDir","_handleSelectedSortHeaderClick","_handleUnselectedSortHeaderClick","_isStructureTableDraggingLastElements","positionedAfter","includeTableAttributesForSource","_updateTableAttributes","$nextNextRow","descendantOf","$nextRows","newSortDir","_handleSortHeaderClick","makeTabFocusable","$initialTab","contains","scrollToTab","updateMenuBtn","_getTab","elemScrollOffset","targetScrollLeft","tabWidth","ulWidth","HTMLElement","TagSelectInput","searchMenu","$addTagInput","_ignoreBlur","searchForTags","selectTag","$hoverOption","$nextOption","focusOption","$prevOption","killSearchMenu","excludeIds","tagGroupId","tags","exclude","exactMatch","Menu","attachToElement","targetSiteId","$titleContainer","autocomplete","inputmode","maxlength","autofocus","getAutofocusValue","getDisabledValue","readonly","showCharsLeft","createCopyTextInput","buttonId","execCommand","createCopyTextBtn","copyValue","createCopyTextField","createCopyTextPrompt","createTextarea","createTextareaField","$select","optgroup","$optgroup","selected","reverseToggle","createCheckboxField","createCheckboxSelect","allValue","allChecked","showAllOption","allLabel","createCheckboxSelectField","fieldset","labelId","containerId","$colorPreviewContainer","createColorField","getMonth","toISOString","timezone","defaultDate","hasOuterContainer","createDateField","createDateRangePicker","today","getFullYear","getDate","startDate","endDate","$allOption","firstDayOffset","getDay","firstDay","$flex","$startDate","$endDate","$dateInputs","dpDiv","setPositionRelativeToAnchor","startTime","endTime","foundOption","btnClasses","timepicker","timepickerOptions","getHours","getMinutes","getSeconds","createTimeField","warning","$warning","addErrorsToField","addErrorsToList","$errors","clearErrorsFromField","_rejectedFiles","_extensionList","_totalFileCounter","_validFileCounter","autoUpload","fileupload","onFileAdd","paramObject","getInProgress","_createExtensionList","process","done","pass","fileExtension","maxFileSize","originalFiles","processErrorMessages","kinds","humanFileSize","maxUploadSize","bytes","threshold","u","toFixed","allowedKind","fileKinds","extensions","pasteZone","sequentialUploads","Accept","UriFormatGenerator","uriFormat","suffix","UserIndex","updateUrl","defaultSourceSlug","slug","__esModule","default","module","locals","exports","listToStyles","list","styles","newStyles","part","media","sourceMap","hasDocument","DEBUG","Error","stylesInDom","head","getElementsByTagName","singletonElement","singletonCounter","isProduction","ssrIdKey","isOldIE","navigator","test","userAgent","addStylesClient","_isProduction","_options","addStylesToDom","newList","mayRemove","domStyle","refs","addStyle","createStyleElement","styleElement","update","querySelector","parentNode","styleIndex","applyToSingletonTag","applyToTag","newObj","textStore","replaceText","replacement","Boolean","styleSheet","cssText","cssNode","createTextNode","childNodes","ssrId","btoa","unescape","firstChild","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","definition","defineProperty","enumerable","prototype"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"cp.js","mappings":"mCAKAA,MAAMC,WAAaC,QAAQC,KAAKC,OAC9B,CACEC,SAAU,KACVC,WAAY,KACZC,OAAQ,KAERC,SAAU,KACVC,OAAQ,KACRC,OAAQ,KACRC,YAAa,KAEbC,KAAM,SAAUP,GACdQ,KAAKC,YAAYT,EAAUL,MAAMC,WAAWc,UAEvCF,KAAKR,SAASW,iBACjBH,KAAKR,SAASY,SAAW,GAG3BJ,KAAKL,SAAWU,EAAEL,KAAKR,SAASc,iBAChCN,KAAKJ,OAASS,EAAEL,KAAKR,SAASe,eAC9BP,KAAKH,OAASG,KAAKJ,OAAOY,SAAS,SACnCR,KAAKP,WAAaO,KAAKH,OAAOW,WAAWC,OAErCT,KAAKR,SAASkB,WAChBV,KAAKN,OAAS,IAAIP,MAAMwB,gBAAgBX,KAAKJ,OAAQ,CACnDgB,aAAcZ,KAAKa,aAAaC,KAAKd,SAIzCA,KAAKF,YAAcE,KAAKJ,OAAOmB,KAAK,0BACpCf,KAAKgB,YAAYhB,KAAKF,YAAa,QAAS,wBAE5CE,KAAKiB,YAGPC,OAAQ,SAAUC,GAChB,KAAInB,KAAKR,SAAS4B,UAAYpB,KAAKP,YAAcO,KAAKR,SAAS4B,UAA/D,CAKA,IAAIC,EAAOhB,EAAEc,GAAKG,SAAStB,KAAKH,QAC9B0B,EAAaF,EAAKN,KAAK,WAErBf,KAAKR,SAASkB,UAChBV,KAAKN,OAAO8B,SAAS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V,OAHAyD,EAAoBF,GAAUzD,EAAQA,EAAOE,QAASsD,GAG/CxD,EAAOE,QCpBfsD,EAAoBhzC,EAAI,SAASwvC,GAChC,IAAI4D,EAAS5D,GAAUA,EAAOF,WAC7B,WAAa,OAAOE,EAAgB,SACpC,WAAa,OAAOA,GAErB,OADAwD,EAAoBxyF,EAAE4yF,EAAQ,CAAE/yF,EAAG+yF,IAC5BA,GCLRJ,EAAoBxyF,EAAI,SAASkvF,EAAS2D,GACzC,IAAI,IAAI1pF,KAAO0pF,EACXL,EAAoB1yC,EAAE+yC,EAAY1pF,KAASqpF,EAAoB1yC,EAAEovC,EAAS/lF,IAC5Ek2B,OAAOyzD,eAAe5D,EAAS/lF,EAAK,CAAE4pF,YAAY,EAAMnlG,IAAKilG,EAAW1pF,MCJ3EqpF,EAAoB1yC,EAAI,SAASnH,EAAKznC,GAAQ,OAAOmuB,OAAO2zD,UAAUp9D,eAAexP,KAAKuyB,EAAKznC,I","sources":["webpack:///./js/AdminTable.js","webpack:///./js/AssetEditor.js","webpack:///./js/AssetImageEditor.js","webpack:///./js/AssetIndex.js","webpack:///./js/AssetSelectInput.js","webpack:///./js/AssetSelectorModal.js","webpack:///./js/AuthManager.js","webpack:///./js/BaseElementEditor.js","webpack:///./js/BaseElementIndex.js","webpack:///./js/BaseElementIndexView.js","webpack:///./js/BaseElementSelectInput.js","webpack:///./js/BaseElementSelectorModal.js","webpack:///./js/BaseInputGenerator.js","webpack:///./js/CP.js","webpack:///./js/CategoryIndex.js","webpack:///./js/CategorySelectInput.js","webpack:///./js/Chart.js","webpack:///./js/ColorInput.js","webpack:///./js/Craft.js","webpack:///./js/CustomizeSourcesModal.js","webpack:///./js/DataTableSorter.js","webpack:///./js/DeleteUserModal.js","webpack:///./js/DraftEditor.js","webpack:///./js/DynamicGenerator.js","webpack:///./js/EditableTable.js","webpack:///./js/ElementActionTrigger.js","webpack:///./js/ElementThumbLoader.js","webpack:///./js/ElevatedSessionForm.js","webpack:///./js/ElevatedSessionManager.js","webpack:///./js/EntryIndex.js","webpack:///./js/FieldLayoutDesigner.js","webpack:///./js/FieldToggle.js","webpack:///./js/Grid.js","webpack:///./js/HandleGenerator.js","webpack:///./js/ImageUpload.js","webpack:///./js/InfoIcon.js","webpack:///./js/LightSwitch.js","webpack:///./js/Listbox.js","webpack:///./js/LivePreview.js","webpack:///./js/PasswordInput.js","webpack:///./js/Preview.js","webpack:///./js/PreviewFileModal.js","webpack:///./js/ProgressBar.js","webpack:///./js/PromptHandler.js","webpack:///./js/SlidePicker.js","webpack:///./js/SlideRuleInput.js","webpack:///./js/Slideout.js","webpack:///./js/SlugGenerator.js","webpack:///./js/Structure.js","webpack:///./js/StructureDrag.js","webpack:///./js/StructureTableSorter.js","webpack:///./js/TableElementIndexView.js","webpack:///./js/Tabs.js","webpack:///./js/TagSelectInput.js","webpack:///./js/ThumbsElementIndexView.js","webpack:///./js/UI.js","webpack:///./js/Uploader.js","webpack:///./js/UriFormatGenerator.js","webpack:///./js/UserIndex.js","webpack:///./css/charts.scss?4afb","webpack:///./css/craft.scss?1b58","webpack:///../../../../../node_modules/vue-style-loader/lib/listToStyles.js","webpack:///../../../../../node_modules/vue-style-loader/lib/addStylesClient.js","webpack:///webpack/bootstrap","webpack:///webpack/runtime/compat get default export","webpack:///webpack/runtime/define property getters","webpack:///webpack/runtime/hasOwnProperty shorthand"],"sourcesContent":["/** global: Craft */\n/** global: Garnish */\n/**\n * Admin table class\n */\nCraft.AdminTable = Garnish.Base.extend(\n  {\n    settings: null,\n    totalItems: null,\n    sorter: null,\n\n    $noItems: null,\n    $table: null,\n    $tbody: null,\n    $deleteBtns: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.AdminTable.defaults);\n\n      if (!this.settings.allowDeleteAll) {\n        this.settings.minItems = 1;\n      }\n\n      this.$noItems = $(this.settings.noItemsSelector);\n      this.$table = $(this.settings.tableSelector);\n      this.$tbody = this.$table.children('tbody');\n      this.totalItems = this.$tbody.children().length;\n\n      if (this.settings.sortable) {\n        this.sorter = new Craft.DataTableSorter(this.$table, {\n          onSortChange: this.reorderItems.bind(this),\n        });\n      }\n\n      this.$deleteBtns = this.$table.find('.delete:not(.disabled)');\n      this.addListener(this.$deleteBtns, 'click', 'handleDeleteBtnClick');\n\n      this.updateUI();\n    },\n\n    addRow: function (row) {\n      if (this.settings.maxItems && this.totalItems >= this.settings.maxItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(row).appendTo(this.$tbody),\n        $deleteBtn = $row.find('.delete');\n\n      if (this.settings.sortable) {\n        this.sorter.addItems($row);\n      }\n\n      this.$deleteBtns = this.$deleteBtns.add($deleteBtn);\n\n      this.addListener($deleteBtn, 'click', 'handleDeleteBtnClick');\n      this.totalItems++;\n\n      this.updateUI();\n    },\n\n    reorderItems: function () {\n      if (!this.settings.sortable) {\n        return;\n      }\n\n      // Get the new field order\n      var ids = [];\n\n      for (var i = 0; i < this.sorter.$items.length; i++) {\n        var id = $(this.sorter.$items[i]).attr(this.settings.idAttribute);\n        ids.push(id);\n      }\n\n      // Send it to the server\n      var data = {\n        ids: JSON.stringify(ids),\n      };\n\n      Craft.postActionRequest(\n        this.settings.reorderAction,\n        data,\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            if (response.success) {\n              this.onReorderItems(ids);\n              Craft.cp.displayNotice(\n                Craft.t('app', this.settings.reorderSuccessMessage)\n              );\n            } else {\n              Craft.cp.displayError(\n                Craft.t('app', this.settings.reorderFailMessage)\n              );\n            }\n          }\n        }\n      );\n    },\n\n    handleDeleteBtnClick: function (event) {\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        // Sorry pal.\n        return;\n      }\n\n      var $row = $(event.target).closest('tr');\n\n      if (this.confirmDeleteItem($row)) {\n        this.deleteItem($row);\n      }\n    },\n\n    confirmDeleteItem: function ($row) {\n      var name = this.getItemName($row);\n      return confirm(\n        Craft.t('app', this.settings.confirmDeleteMessage, {name})\n      );\n    },\n\n    deleteItem: function ($row) {\n      var data = {\n        id: this.getItemId($row),\n      };\n\n      Craft.postActionRequest(\n        this.settings.deleteAction,\n        data,\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.handleDeleteItemResponse(response, $row);\n          }\n        }\n      );\n    },\n\n    handleDeleteItemResponse: function (response, $row) {\n      var id = this.getItemId($row),\n        name = this.getItemName($row);\n\n      if (response.success) {\n        if (this.sorter) {\n          this.sorter.removeItems($row);\n        }\n\n        $row.remove();\n        this.totalItems--;\n        this.updateUI();\n        this.onDeleteItem(id);\n\n        Craft.cp.displayNotice(\n          Craft.t('app', this.settings.deleteSuccessMessage, {name})\n        );\n      } else {\n        Craft.cp.displayError(\n          Craft.t('app', this.settings.deleteFailMessage, {name})\n        );\n      }\n    },\n\n    onReorderItems: function (ids) {\n      this.settings.onReorderItems(ids);\n    },\n\n    onDeleteItem: function (id) {\n      this.settings.onDeleteItem(id);\n    },\n\n    getItemId: function ($row) {\n      return $row.attr(this.settings.idAttribute);\n    },\n\n    getItemName: function ($row) {\n      return Craft.escapeHtml($row.attr(this.settings.nameAttribute));\n    },\n\n    updateUI: function () {\n      // Show the \"No Whatever Exists\" message if there aren't any\n      if (this.totalItems === 0) {\n        this.$table.hide();\n        this.$noItems.removeClass('hidden');\n      } else {\n        this.$table.show();\n        this.$noItems.addClass('hidden');\n      }\n\n      // Disable the sort buttons if there's only one row\n      if (this.settings.sortable) {\n        var $moveButtons = this.$table.find('.move');\n\n        if (this.totalItems === 1) {\n          $moveButtons.addClass('disabled');\n        } else {\n          $moveButtons.removeClass('disabled');\n        }\n      }\n\n      // Disable the delete buttons if we've reached the minimum items\n      if (this.settings.minItems && this.totalItems <= this.settings.minItems) {\n        this.$deleteBtns.addClass('disabled');\n      } else {\n        this.$deleteBtns.removeClass('disabled');\n      }\n\n      // Hide the New Whatever button if we've reached the maximum items\n      if (this.settings.newItemBtnSelector) {\n        if (\n          this.settings.maxItems &&\n          this.totalItems >= this.settings.maxItems\n        ) {\n          $(this.settings.newItemBtnSelector).addClass('hidden');\n        } else {\n          $(this.settings.newItemBtnSelector).removeClass('hidden');\n        }\n      }\n    },\n  },\n  {\n    defaults: {\n      tableSelector: null,\n      noItemsSelector: null,\n      newItemBtnSelector: null,\n      idAttribute: 'data-id',\n      nameAttribute: 'data-name',\n      sortable: false,\n      allowDeleteAll: true,\n      minItems: 0,\n      maxItems: null,\n      reorderAction: null,\n      deleteAction: null,\n      reorderSuccessMessage: Craft.t('app', 'New order saved.'),\n      reorderFailMessage: Craft.t('app', 'Couldn’t save new order.'),\n      confirmDeleteMessage: Craft.t(\n        'app',\n        'Are you sure you want to delete “{name}”?'\n      ),\n      deleteSuccessMessage: Craft.t('app', '“{name}” deleted.'),\n      deleteFailMessage: Craft.t('app', 'Couldn’t delete “{name}”.'),\n      onReorderItems: $.noop,\n      onDeleteItem: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset index class\n */\nCraft.AssetEditor = Craft.BaseElementEditor.extend({\n  $filenameInput: null,\n\n  originalBasename: null,\n  originalExtension: null,\n  reloadIndex: false,\n\n  init: function (element, settings) {\n    this.on('updateForm', () => {\n      this.addListener(\n        this.$sidebar.find('.preview-thumb-container .edit-btn'),\n        'click',\n        'showImageEditor'\n      );\n      this.addListener(\n        this.$sidebar.find('.preview-thumb-container .preview-btn'),\n        'click',\n        'showImagePreview'\n      );\n\n      this.$filenameInput = this.$sidebar.find('.filename');\n      this.addListener(this.$filenameInput, 'focus', 'selectFilename');\n    });\n\n    this.on('closeSlideout', () => {\n      if (this.reloadIndex) {\n        if (this.settings.elementIndex) {\n          this.settings.elementIndex.updateElements();\n        } else if (this.settings.input) {\n          this.settings.input.refreshThumbnail(this.$element.data('id'));\n        }\n      }\n    });\n\n    this.base(element, settings);\n\n    this.settings.validators.push(() => this.validateExtension());\n  },\n\n  showImageEditor: function () {\n    new Craft.AssetImageEditor(this.$element.data('id'), {\n      onSave: () => {\n        this.reloadIndex = true;\n        this.load();\n      },\n    });\n  },\n\n  showImagePreview: function () {\n    var settings = {};\n\n    if (this.$element.data('image-width')) {\n      settings.startingWidth = this.$element.data('image-width');\n      settings.startingHeight = this.$element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(this.$element.data('id'), null, settings);\n  },\n\n  selectFilename: function () {\n    if (typeof this.$filenameInput[0].selectionStart === 'undefined') {\n      return;\n    }\n\n    const {basename, extension} = this._parseFilename();\n\n    if (this.originalBasename === null) {\n      this.originalBasename = basename;\n      this.originalExtension = extension;\n    }\n\n    this.$filenameInput[0].selectionStart = 0;\n    this.$filenameInput[0].selectionEnd = basename.length;\n\n    // Prevent the selection from changing by the mouseup event\n    this.$filenameInput.one('mouseup.keepselection', (ev) => {\n      ev.preventDefault();\n    });\n    setTimeout(() => {\n      this.$filenameInput.off('mouseup.keepselection');\n    }, 500);\n  },\n\n  validateExtension: function () {\n    if (this.originalBasename === null) {\n      return true;\n    }\n\n    const {basename, extension} = this._parseFilename();\n\n    if (extension === this.originalExtension) {\n      return true;\n    }\n\n    // No extension?\n    if (!extension) {\n      // If filename changed as well, assume removal of extension a mistake\n      if (this.originalFilename !== basename) {\n        this.$filenameInput.val(\n          `${Craft.rtrim(basename, '.')}.${this.originalExtension}`\n        );\n        return true;\n      }\n\n      // If filename hasn't changed, make sure they want to remove extension\n      return confirm(\n        Craft.t(\n          'app',\n          'Are you sure you want to remove the extension “.{ext}”?',\n          {\n            ext: this.originalExtension,\n          }\n        )\n      );\n    }\n\n    // If the extension has changed, make sure it's intentional\n    return confirm(\n      Craft.t(\n        'app',\n        'Are you sure you want to change the extension from “.{oldExt}” to “.{newExt}”?',\n        {\n          oldExt: this.originalExtension,\n          newExt: extension,\n        }\n      )\n    );\n  },\n\n  _parseFilename: function () {\n    const parts = this.$filenameInput.val().split('.');\n    const extension = parts.length > 1 ? parts.pop() : null;\n    const basename = parts.join('.');\n    return {basename, extension};\n  },\n});\n\n// Register it!\nCraft.registerElementEditorClass('craft\\\\elements\\\\Asset', Craft.AssetEditor);\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Asset image editor class\n */\n\nCraft.AssetImageEditor = Garnish.Modal.extend(\n  {\n    // jQuery objects\n    $body: null,\n    $footer: null,\n    $imageTools: null,\n    $buttons: null,\n    $cancelBtn: null,\n    $replaceBtn: null,\n    $saveBtn: null,\n    $editorContainer: null,\n    $straighten: null,\n    $croppingCanvas: null,\n    $spinnerCanvas: null,\n\n    // FabricJS objects\n    canvas: null,\n    image: null,\n    viewport: null,\n    focalPoint: null,\n    grid: null,\n    croppingCanvas: null,\n    clipper: null,\n    croppingRectangle: null,\n    cropperHandles: null,\n    cropperGrid: null,\n    croppingShade: null,\n\n    // Image state attributes\n    imageStraightenAngle: 0,\n    viewportRotation: 0,\n    originalWidth: 0,\n    originalHeight: 0,\n    imageVerticeCoords: null,\n    zoomRatio: 1,\n\n    // Editor state attributes\n    animationInProgress: false,\n    currentView: '',\n    assetId: null,\n    cacheBust: null,\n    draggingCropper: false,\n    scalingCropper: false,\n    draggingFocal: false,\n    previousMouseX: 0,\n    previousMouseY: 0,\n    shiftKeyHeld: false,\n    editorHeight: 0,\n    editorWidth: 0,\n    cropperState: false,\n    scaleFactor: 1,\n    flipData: {},\n    focalPointState: false,\n    spinnerInterval: null,\n    maxImageSize: null,\n    lastLoadedDimensions: null,\n    imageIsLoading: false,\n    mouseMoveEvent: null,\n    croppingConstraint: false,\n    constraintOrientation: 'landscape',\n    showingCustomConstraint: false,\n\n    // Rendering proxy functions\n    renderImage: null,\n    renderCropper: null,\n\n    init: function (assetId, settings) {\n      this.cacheBust = Date.now();\n\n      this.setSettings(settings, Craft.AssetImageEditor.defaults);\n\n      if (this.settings.allowDegreeFractions === null) {\n        this.settings.allowDegreeFractions = Craft.isImagick;\n      }\n\n      this.assetId = assetId;\n      this.flipData = {x: 0, y: 0};\n\n      // Build the modal\n      this.$container = $(\n        '<form class=\"modal fitted imageeditor\"></form>'\n      ).appendTo(Garnish.$bod);\n      this.$body = $('<div class=\"body\"></div>').appendTo(this.$container);\n      this.$footer = $('<div class=\"footer\"/>').appendTo(this.$container);\n\n      this.base(this.$container, this.settings);\n\n      this.$buttons = $('<div class=\"buttons right\"/>').appendTo(this.$footer);\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn cancel',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$buttons);\n      this.$replaceBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn submit save replace',\n        text: Craft.t('app', 'Save'),\n      }).appendTo(this.$buttons);\n\n      if (this.settings.allowSavingAsNew) {\n        this.$saveBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit save copy',\n          text: Craft.t('app', 'Save as a new asset'),\n        }).appendTo(this.$buttons);\n        this.addListener(this.$saveBtn, 'activate', this.saveImage);\n      }\n\n      this.addListener(this.$replaceBtn, 'activate', this.saveImage);\n      this.addListener(this.$cancelBtn, 'activate', this.hide);\n      this.removeListener(this.$shade, 'click');\n\n      this.maxImageSize = this.getMaxImageSize();\n      Craft.postActionRequest(\n        'assets/image-editor',\n        {assetId},\n        this.loadEditor.bind(this)\n      );\n    },\n\n    /**\n     * Get the max image size that is viewable in the editor currently\n     */\n    getMaxImageSize: function () {\n      var browserViewportWidth =\n        Garnish.$doc.get(0).documentElement.clientWidth;\n      var browserViewportHeight =\n        Garnish.$doc.get(0).documentElement.clientHeight;\n\n      return (\n        Math.max(browserViewportHeight, browserViewportWidth) *\n        (window.devicePixelRatio > 1 ? 2 : 1)\n      );\n    },\n\n    /**\n     * Load the editor markup and start loading components and the image.\n     *\n     * @param data\n     */\n    loadEditor: function (data) {\n      if (!data.html) {\n        alert(Craft.t('app', 'Could not load the image editor.'));\n      }\n\n      this.$body.html(data.html);\n      this.$tabs = $('.tabs li', this.$body);\n      this.$viewsContainer = $('.views', this.$body);\n      this.$views = $('> div', this.$viewsContainer);\n      this.$imageTools = $('.image-container .image-tools', this.$body);\n      this.$editorContainer = $('.image-container .image', this.$body);\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this._showSpinner();\n\n      this.updateSizeAndPosition();\n\n      // Load the canvas on which we'll host our image and set up the proxy render function\n      this.canvas = new fabric.StaticCanvas('image-canvas');\n\n      // Set up the cropping canvas jquery element for tracking all the nice events\n      this.$croppingCanvas = $('#cropping-canvas', this.$editorContainer);\n      this.$croppingCanvas.width(this.editorWidth);\n      this.$croppingCanvas.height(this.editorHeight);\n\n      this.canvas.enableRetinaScaling = true;\n      this.renderImage = () => {\n        Garnish.requestAnimationFrame(this.canvas.renderAll.bind(this.canvas));\n      };\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      // Load image and set up the initial properties\n      fabric.Image.fromURL(imageUrl, (imageObject) => {\n        this.image = imageObject;\n        this.image.set({\n          originX: 'center',\n          originY: 'center',\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        });\n        this.canvas.add(this.image);\n\n        this.originalHeight = this.image.getHeight();\n        this.originalWidth = this.image.getWidth();\n        this.zoomRatio = 1;\n\n        this.lastLoadedDimensions = this.getScaledImageDimensions();\n\n        // Set up the image bounding box, viewport and position everything\n        this._setFittedImageVerticeCoordinates();\n        this._repositionEditorElements();\n\n        // Set up the focal point\n        var focalState = {\n          imageDimensions: this.getScaledImageDimensions(),\n          offsetX: 0,\n          offsetY: 0,\n        };\n\n        var focal = false;\n        if (data.focalPoint) {\n          // Transform the focal point coordinates from relative to absolute\n          var focalData = data.focalPoint;\n\n          // Resolve for the current image dimensions.\n          var adjustedX = focalState.imageDimensions.width * focalData.x;\n          var adjustedY = focalState.imageDimensions.height * focalData.y;\n\n          focalState.offsetX = adjustedX - focalState.imageDimensions.width / 2;\n          focalState.offsetY =\n            adjustedY - focalState.imageDimensions.height / 2;\n\n          focal = true;\n        }\n\n        this.storeFocalPointState(focalState);\n\n        if (focal) {\n          this._createFocalPoint();\n        }\n\n        this._createViewport();\n        this.storeCropperState();\n\n        // Add listeners to buttons\n        this._addControlListeners();\n\n        // Add mouse event listeners\n        this.addListener(\n          this.$croppingCanvas,\n          'mousemove,touchmove',\n          this._handleMouseMove\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mousedown,touchstart',\n          this._handleMouseDown\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseup,touchend',\n          this._handleMouseUp\n        );\n        this.addListener(\n          this.$croppingCanvas,\n          'mouseout,touchcancel',\n          this._handleMouseOut\n        );\n\n        this._hideSpinner();\n\n        // Render it, finally\n        this.renderImage();\n\n        // Make sure verything gets fired for the first tab\n        this.$tabs.first().trigger('click');\n      });\n    },\n\n    /**\n     * Reload the image to better fit the current available image editor viewport.\n     */\n    _reloadImage: function () {\n      if (this.imageIsLoading) {\n        return;\n      }\n\n      this.imageIsLoading = true;\n      this.maxImageSize = this.getMaxImageSize();\n\n      // Load the image from URL\n      var imageUrl = Craft.getActionUrl('assets/edit-image', {\n        assetId: this.assetId,\n        size: this.maxImageSize,\n        cacheBust: this.cacheBust,\n      });\n\n      this.image.setSrc(imageUrl, (imageObject) => {\n        this.originalHeight = imageObject.getHeight();\n        this.originalWidth = imageObject.getWidth();\n        this.lastLoadedDimensions = {\n          width: this.originalHeight,\n          height: this.originalWidth,\n        };\n        this.updateSizeAndPosition();\n        this.renderImage();\n        this.imageIsLoading = false;\n      });\n    },\n\n    /**\n     * Update the modal size and position on browser resize\n     */\n    updateSizeAndPosition: function () {\n      if (!this.$container) {\n        return;\n      }\n\n      // Fullscreen modal\n      var innerWidth = window.innerWidth;\n      var innerHeight = window.innerHeight;\n\n      this.$container.css({\n        width: innerWidth,\n        'min-width': innerWidth,\n        left: 0,\n\n        height: innerHeight,\n        'min-height': innerHeight,\n        top: 0,\n      });\n\n      this.$body.css({\n        height: innerHeight - 62,\n      });\n\n      if (innerWidth < innerHeight) {\n        this.$container.addClass('vertical');\n      } else {\n        this.$container.removeClass('vertical');\n      }\n\n      if (this.$spinnerCanvas) {\n        this.$spinnerCanvas.css({\n          left:\n            this.$spinnerCanvas.parent().width() / 2 -\n            this.$spinnerCanvas.width() / 2 +\n            'px',\n          top:\n            this.$spinnerCanvas.parent().height() / 2 -\n            this.$spinnerCanvas.height() / 2 +\n            'px',\n        });\n      }\n\n      // If image is already loaded, make sure it looks pretty.\n      if (this.$editorContainer && this.image) {\n        this._repositionEditorElements();\n      }\n    },\n\n    /**\n     * Reposition the editor elements to accurately reflect the editor state with current dimensions\n     */\n    _repositionEditorElements: function () {\n      // Remember what the dimensions were before the resize took place\n      var previousEditorDimensions = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      this.editorHeight = this.$editorContainer.innerHeight();\n      this.editorWidth = this.$editorContainer.innerWidth();\n\n      this.canvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      var currentScaledDimensions = this.getScaledImageDimensions();\n\n      // If we're cropping now, we have to reposition the cropper correctly in case\n      // the area for image changes, forcing the image size to change as well.\n      if (this.currentView === 'crop') {\n        this.zoomRatio = this.getZoomToFitRatio(\n          this.getScaledImageDimensions()\n        );\n        var previouslyOccupiedArea = this._getBoundingRectangle(\n          this.imageVerticeCoords\n        );\n        this._setFittedImageVerticeCoordinates();\n        this._repositionCropper(previouslyOccupiedArea);\n      } else {\n        // Otherwise just recalculate the image zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n      }\n\n      // Reposition the image relatively to the previous editor dimensions.\n      this._repositionImage(previousEditorDimensions);\n      this._repositionViewport();\n      this._repositionFocalPoint(previousEditorDimensions);\n      this._zoomImage();\n\n      this.renderImage();\n\n      if (\n        currentScaledDimensions.width / this.lastLoadedDimensions.width > 1.5 ||\n        currentScaledDimensions.height / this.lastLoadedDimensions.height > 1.5\n      ) {\n        this._reloadImage();\n      }\n    },\n\n    /**\n     * Reposition image based on how the editor dimensions have changed.\n     * This ensures keeping the image center offset, if there is any.\n     *\n     * @param previousEditorDimensions\n     */\n    _repositionImage: function (previousEditorDimensions) {\n      this.image.set({\n        left:\n          this.image.left -\n          (previousEditorDimensions.width - this.editorWidth) / 2,\n        top:\n          this.image.top -\n          (previousEditorDimensions.height - this.editorHeight) / 2,\n      });\n    },\n\n    /**\n     * Create the viewport for image editor.\n     */\n    _createViewport: function () {\n      this.viewport = new fabric.Rect({\n        width: this.image.width,\n        height: this.image.height,\n        fill: 'rgba(127,0,0,1)',\n        originX: 'center',\n        originY: 'center',\n        globalCompositeOperation: 'destination-in', // This clips everything outside of the viewport\n        left: this.image.left,\n        top: this.image.top,\n      });\n      this.canvas.add(this.viewport);\n      this.renderImage();\n    },\n\n    /**\n     * Create the focal point.\n     */\n    _createFocalPoint: function () {\n      var focalPointState = this.focalPointState;\n      var sizeFactor =\n        this.getScaledImageDimensions().width /\n        focalPointState.imageDimensions.width;\n\n      var focalX =\n        focalPointState.offsetX *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n      var focalY =\n        focalPointState.offsetY *\n        sizeFactor *\n        this.zoomRatio *\n        this.scaleFactor;\n\n      // Adjust by image margins\n      focalX += this.image.left;\n      focalY += this.image.top;\n\n      var deltaX = 0;\n      var deltaY = 0;\n\n      // When creating a fresh focal point, drop it dead in the center of the viewport, not the image.\n      if (\n        this.viewport &&\n        focalPointState.offsetX === 0 &&\n        focalPointState.offsetY === 0\n      ) {\n        if (this.currentView !== 'crop') {\n          deltaX = this.viewport.left - this.image.left;\n          deltaY = this.viewport.top - this.image.top;\n        } else {\n          // Unless we have a cropper showing, in which case drop it in the middle of the cropper\n          deltaX = this.clipper.left - this.image.left;\n          deltaY = this.clipper.top - this.image.top;\n        }\n\n        // Bump focal to middle of viewport\n        focalX += deltaX;\n        focalY += deltaY;\n\n        // Reflect changes in saved state\n        focalPointState.offsetX +=\n          deltaX / (sizeFactor * this.zoomRatio * this.scaleFactor);\n        focalPointState.offsetY +=\n          deltaY / (sizeFactor * this.zoomRatio * this.scaleFactor);\n      }\n\n      this.focalPoint = new fabric.Group(\n        [\n          new fabric.Circle({\n            radius: 8,\n            fill: 'rgba(0,0,0,0.5)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n          new fabric.Circle({\n            radius: 1,\n            fill: 'rgba(255,255,255,0)',\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,0.8)',\n            left: 0,\n            top: 0,\n            originX: 'center',\n            originY: 'center',\n          }),\n        ],\n        {\n          originX: 'center',\n          originY: 'center',\n          left: focalX,\n          top: focalY,\n        }\n      );\n\n      this.storeFocalPointState(focalPointState);\n      this.canvas.add(this.focalPoint);\n    },\n\n    /**\n     * Toggle focal point\n     */\n    toggleFocalPoint: function () {\n      if (!this.focalPoint) {\n        this._createFocalPoint();\n      } else {\n        this.canvas.remove(this.focalPoint);\n        this.focalPoint = null;\n      }\n\n      this.renderImage();\n    },\n\n    /**\n     * Reposition the viewport to handle editor resizing.\n     */\n    _repositionViewport: function () {\n      if (this.viewport) {\n        var dimensions = {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n        };\n\n        // If we're cropping, nothing exciting happens for the viewport\n        if (this.currentView === 'crop') {\n          dimensions.width = this.editorWidth;\n          dimensions.height = this.editorHeight;\n        } else {\n          // If this is the first initial reposition, no cropper state yet\n          if (this.cropperState) {\n            // Recall the state\n            var state = this.cropperState;\n\n            var scaledImageDimensions = this.getScaledImageDimensions();\n            // Make sure we have the correct current image size\n            var sizeFactor =\n              scaledImageDimensions.width / state.imageDimensions.width;\n\n            // Set the viewport dimensions\n            dimensions.width = state.width * sizeFactor * this.zoomRatio;\n            dimensions.height = state.height * sizeFactor * this.zoomRatio;\n\n            // Adjust the image position to show the correct part of the image in the viewport\n            this.image.set({\n              left: this.editorWidth / 2 - state.offsetX * sizeFactor,\n              top: this.editorHeight / 2 - state.offsetY * sizeFactor,\n            });\n          } else {\n            $.extend(dimensions, this.getScaledImageDimensions());\n          }\n        }\n        this.viewport.set(dimensions);\n      }\n    },\n\n    _repositionFocalPoint: function (previousEditorDimensions) {\n      if (this.focalPoint) {\n        var offsetX = this.focalPoint.left - this.editorWidth / 2;\n        var offsetY = this.focalPoint.top - this.editorHeight / 2;\n\n        var currentWidth = this.image.width;\n        var newWidth = this.getScaledImageDimensions().width * this.zoomRatio;\n        var ratio = newWidth / currentWidth / this.scaleFactor;\n\n        offsetX -= (previousEditorDimensions.width - this.editorWidth) / 2;\n        offsetY -= (previousEditorDimensions.height - this.editorHeight) / 2;\n\n        offsetX *= ratio;\n        offsetY *= ratio;\n\n        this.focalPoint.set({\n          left: this.editorWidth / 2 + offsetX,\n          top: this.editorHeight / 2 + offsetY,\n        });\n      }\n    },\n\n    /**\n     * Return true if the image orientation has changed\n     */\n    hasOrientationChanged: function () {\n      return this.viewportRotation % 180 !== 0;\n    },\n\n    /**\n     * Return the current image dimensions that would be used in the current image area with no straightening or rotation applied.\n     */\n    getScaledImageDimensions: function () {\n      if (typeof this.getScaledImageDimensions._ === 'undefined') {\n        this.getScaledImageDimensions._ = {};\n      }\n\n      this.getScaledImageDimensions._.imageRatio =\n        this.originalHeight / this.originalWidth;\n      this.getScaledImageDimensions._.editorRatio =\n        this.editorHeight / this.editorWidth;\n\n      this.getScaledImageDimensions._.dimensions = {};\n      if (\n        this.getScaledImageDimensions._.imageRatio >\n        this.getScaledImageDimensions._.editorRatio\n      ) {\n        this.getScaledImageDimensions._.dimensions.height = Math.min(\n          this.editorHeight,\n          this.originalHeight\n        );\n        this.getScaledImageDimensions._.dimensions.width = Math.round(\n          this.originalWidth /\n            (this.originalHeight /\n              this.getScaledImageDimensions._.dimensions.height)\n        );\n      } else {\n        this.getScaledImageDimensions._.dimensions.width = Math.min(\n          this.editorWidth,\n          this.originalWidth\n        );\n        this.getScaledImageDimensions._.dimensions.height = Math.round(\n          this.originalHeight *\n            (this.getScaledImageDimensions._.dimensions.width /\n              this.originalWidth)\n        );\n      }\n\n      return this.getScaledImageDimensions._.dimensions;\n    },\n\n    /**\n     * Set the image dimensions to reflect the current zoom ratio.\n     */\n    _zoomImage: function () {\n      if (typeof this._zoomImage._ === 'undefined') {\n        this._zoomImage._ = {};\n      }\n\n      this._zoomImage._.imageDimensions = this.getScaledImageDimensions();\n      this.image.set({\n        width: this._zoomImage._.imageDimensions.width * this.zoomRatio,\n        height: this._zoomImage._.imageDimensions.height * this.zoomRatio,\n      });\n    },\n\n    /**\n     * Set up listeners for the controls.\n     */\n    _addControlListeners: function () {\n      // Tabs\n      this.addListener(this.$tabs, 'click', this._handleTabClick);\n\n      // Focal point\n      this.addListener($('.focal-point'), 'click', this.toggleFocalPoint);\n\n      // Rotate controls\n      this.addListener($('.rotate-left'), 'click', function () {\n        this.rotateImage(-90);\n      });\n      this.addListener($('.rotate-right'), 'click', function () {\n        this.rotateImage(90);\n      });\n      this.addListener($('.flip-vertical'), 'click', function () {\n        this.flipImage('y');\n      });\n      this.addListener($('.flip-horizontal'), 'click', function () {\n        this.flipImage('x');\n      });\n\n      // Straighten slider\n      this.straighteningInput = new Craft.SlideRuleInput('slide-rule', {\n        onStart: () => {\n          this._showGrid();\n        },\n        onChange: (slider) => {\n          this.straighten(slider);\n        },\n        onEnd: () => {\n          this._hideGrid();\n          this._cleanupFocalPointAfterStraighten();\n        },\n      });\n\n      // Cropper scale modifier key\n      this.addListener(Garnish.$doc, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = true;\n        }\n      });\n      this.addListener(Garnish.$doc, 'keyup', function (ev) {\n        if (ev.keyCode === Garnish.SHIFT_KEY) {\n          this.shiftKeyHeld = false;\n        }\n      });\n\n      this.addListener(\n        $('.constraint-buttons .constraint', this.$container),\n        'click',\n        this._handleConstraintClick\n      );\n      this.addListener(\n        $('.orientation input', this.$container),\n        'click',\n        this._handleOrientationClick\n      );\n      this.addListener(\n        $('.constraint-buttons .custom-input input', this.$container),\n        'keyup',\n        this._applyCustomConstraint\n      );\n    },\n\n    /**\n     * Handle a constraint button click.\n     *\n     * @param ev\n     */\n    _handleConstraintClick: function (ev) {\n      var constraint = $(ev.currentTarget).data('constraint');\n      var $target = $(ev.currentTarget);\n      $target.siblings().removeClass('active');\n      $target.addClass('active');\n\n      if (constraint == 'custom') {\n        this._showCustomConstraint();\n        this._applyCustomConstraint();\n        return;\n      }\n\n      this._hideCustomConstraint();\n\n      this.setCroppingConstraint(constraint);\n      this.enforceCroppingConstraint();\n    },\n\n    /**\n     * Handle an orientation switch click.\n     *\n     * @param ev\n     */\n    _handleOrientationClick: function (ev) {\n      if (ev.currentTarget.value === this.constraintOrientation) {\n        return;\n      }\n      this.constraintOrientation = ev.currentTarget.value;\n\n      var $constraints = $('.constraint.flip', this.$container);\n\n      for (var i = 0; i < $constraints.length; i++) {\n        var $constraint = $($constraints[i]);\n        $constraint.data('constraint', 1 / $constraint.data('constraint'));\n        $constraint.html($constraint.html().split(':').reverse().join(':'));\n      }\n\n      $constraints.filter('.active').click();\n    },\n\n    /**\n     * Apply the custom ratio set in the inputs\n     */\n    _applyCustomConstraint: function () {\n      var constraint = this._getCustomConstraint();\n\n      if (constraint.w > 0 && constraint.h > 0) {\n        this.setCroppingConstraint(constraint.w / constraint.h);\n        this.enforceCroppingConstraint();\n      }\n    },\n\n    /**\n     * Get the custom constraint.\n     *\n     * @returns {{w: *, h: *}}\n     */\n    _getCustomConstraint: function () {\n      var w = parseFloat($('.custom-constraint-w').val());\n      var h = parseFloat($('.custom-constraint-h').val());\n      return {\n        w: isNaN(w) ? 0 : w,\n        h: isNaN(h) ? 0 : h,\n      };\n    },\n\n    /**\n     * Set the custom constraint.\n     *\n     * @param w\n     * @param h\n     */\n    _setCustomConstraint: function (w, h) {\n      $('.custom-constraint-w').val(parseFloat(w));\n      $('.custom-constraint-h').val(parseFloat(h));\n    },\n\n    /**\n     * Hide the custom constraint inputs.\n     */\n    _hideCustomConstraint: function () {\n      this.showingCustomConstraint = false;\n      $('.constraint.custom .custom-input', this.$container).addClass('hidden');\n      $('.constraint.custom .custom-label', this.$container).removeClass(\n        'hidden'\n      );\n      $('.orientation', this.$container).removeClass('hidden');\n    },\n\n    /**\n     * Show the custom constraint inputs.\n     */\n    _showCustomConstraint: function () {\n      if (this.showingCustomConstraint) {\n        return;\n      }\n\n      this.showingCustomConstraint = true;\n      $('.constraint.custom .custom-input', this.$container).removeClass(\n        'hidden'\n      );\n      $('.constraint.custom .custom-label', this.$container).addClass('hidden');\n      $('.orientation', this.$container).addClass('hidden');\n    },\n\n    /**\n     * Handle tab click.\n     *\n     * @param ev\n     */\n    _handleTabClick: function (ev) {\n      if (!this.animationInProgress) {\n        var $tab = $(ev.currentTarget);\n        var view = $tab.data('view');\n        this.$tabs.removeClass('selected');\n        $tab.addClass('selected');\n        this.showView(view);\n      }\n    },\n\n    /**\n     * Show a view.\n     *\n     * @param view\n     */\n    showView: function (view) {\n      if (this.currentView === view) {\n        return;\n      }\n\n      this.$views.addClass('hidden');\n      var $view = this.$views.filter('[data-view=\"' + view + '\"]');\n      $view.removeClass('hidden');\n\n      if (view === 'rotate') {\n        this.enableSlider();\n      } else {\n        this.disableSlider();\n      }\n\n      // Now that most likely our editor dimensions have changed, time to reposition stuff\n      this.updateSizeAndPosition();\n\n      // See if we have to enable or disable crop mode as we transition between tabs\n      if (this.currentView === 'crop' && view !== 'crop') {\n        this.disableCropMode();\n      } else if (this.currentView !== 'crop' && view === 'crop') {\n        this.enableCropMode();\n      }\n\n      // Mark the current view\n      this.currentView = view;\n    },\n\n    /**\n     * Store the current cropper state.\n     *\n     * Cropper state is always assumed to be saved at a zoom ratio of 1 to be used\n     * as the basis for recalculating the cropper position and dimensions.\n     *\n     * @param [state]\n     */\n    storeCropperState: function (state) {\n      if (typeof this.storeCropperState._ === 'undefined') {\n        this.storeCropperState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.cropperState = state;\n      } else if (this.clipper) {\n        this.storeCropperState._.zoomFactor = 1 / this.zoomRatio;\n\n        this.cropperState = {\n          offsetX:\n            (this.clipper.left - this.image.left) *\n            this.storeCropperState._.zoomFactor,\n          offsetY:\n            (this.clipper.top - this.image.top) *\n            this.storeCropperState._.zoomFactor,\n          height: this.clipper.height * this.storeCropperState._.zoomFactor,\n          width: this.clipper.width * this.storeCropperState._.zoomFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      } else {\n        this.storeCropperState._.dimensions = this.getScaledImageDimensions();\n        this.cropperState = {\n          offsetX: 0,\n          offsetY: 0,\n          height: this.storeCropperState._.dimensions.height,\n          width: this.storeCropperState._.dimensions.width,\n          imageDimensions: this.storeCropperState._.dimensions,\n        };\n      }\n    },\n\n    /**\n     * Store focal point coordinates in a manner that is not tied to zoom ratio and rotation.\n     */\n    storeFocalPointState: function (state) {\n      if (typeof this.storeFocalPointState._ === 'undefined') {\n        this.storeFocalPointState._ = {};\n      }\n\n      // If we're asked to store a specific state.\n      if (state) {\n        this.focalPointState = state;\n      } else if (this.focalPoint) {\n        this.storeFocalPointState._.zoomFactor = 1 / this.zoomRatio;\n        this.focalPointState = {\n          offsetX:\n            ((this.focalPoint.left - this.image.left) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          offsetY:\n            ((this.focalPoint.top - this.image.top) *\n              this.storeFocalPointState._.zoomFactor) /\n            this.scaleFactor,\n          imageDimensions: this.getScaledImageDimensions(),\n        };\n      }\n    },\n\n    /**\n     * Rotate the image along with the viewport.\n     *\n     * @param degrees\n     */\n    rotateImage: function (degrees) {\n      if (!this.animationInProgress) {\n        // We're not that kind of an establishment, sir.\n        if (degrees !== 90 && degrees !== -90) {\n          return false;\n        }\n\n        this.animationInProgress = true;\n        this.viewportRotation += degrees;\n\n        // Normalize the viewport rotation angle so it's between 0 and 359\n        this.viewportRotation = parseInt(\n          (this.viewportRotation + 360) % 360,\n          10\n        );\n\n        var newAngle = this.image.angle + degrees;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var imageZoomRatio;\n\n        if (this.hasOrientationChanged()) {\n          imageZoomRatio = this.getZoomToCoverRatio({\n            height: scaledImageDimensions.width,\n            width: scaledImageDimensions.height,\n          });\n        } else {\n          imageZoomRatio = this.getZoomToCoverRatio(scaledImageDimensions);\n        }\n\n        // In cases when for some reason we've already zoomed in on the image,\n        // use existing zoom.\n        if (this.zoomRatio > imageZoomRatio) {\n          imageZoomRatio = this.zoomRatio;\n        }\n\n        var viewportProperties = {\n          angle: degrees === 90 ? '+=90' : '-=90',\n        };\n\n        var imageProperties = {\n          angle: newAngle,\n          width: scaledImageDimensions.width * imageZoomRatio,\n          height: scaledImageDimensions.height * imageZoomRatio,\n        };\n\n        var scaleFactor = 1;\n        if (this.scaleFactor < 1) {\n          scaleFactor = 1 / this.scaleFactor;\n          this.scaleFactor = 1;\n        } else {\n          if (this.viewport.width > this.editorHeight) {\n            scaleFactor = this.editorHeight / this.viewport.width;\n          } else if (this.viewport.height > this.editorWidth) {\n            scaleFactor = this.editorWidth / this.viewport.height;\n          }\n          this.scaleFactor = scaleFactor;\n        }\n\n        if (scaleFactor < 1) {\n          imageProperties.width *= scaleFactor;\n          imageProperties.height *= scaleFactor;\n        }\n\n        var state = this.cropperState;\n\n        // Make sure we reposition the image as well to focus on the same image area\n        var deltaX = state.offsetX;\n        var deltaY = state.offsetY;\n        var angleInRadians = degrees * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        var newDeltaX =\n          deltaX * Math.cos(angleInRadians) - deltaY * Math.sin(angleInRadians);\n        var newDeltaY =\n          deltaX * Math.sin(angleInRadians) + deltaY * Math.cos(angleInRadians);\n\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        var modifiedDeltaX =\n          newDeltaX * sizeFactor * this.zoomRatio * this.scaleFactor;\n        var modifiedDeltaY =\n          newDeltaY * sizeFactor * this.zoomRatio * this.scaleFactor;\n\n        imageProperties.left = this.editorWidth / 2 - modifiedDeltaX;\n        imageProperties.top = this.editorHeight / 2 - modifiedDeltaY;\n\n        state.offsetX = newDeltaX;\n        state.offsetY = newDeltaY;\n\n        var temp = state.width;\n        state.width = state.height;\n        state.height = temp;\n\n        this.storeCropperState(state);\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        }\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            // If we're zooming the image in or out, better do the same to viewport\n            var temp = this.viewport.height * scaleFactor;\n            this.viewport.height = this.viewport.width * scaleFactor;\n            this.viewport.width = temp;\n            this.viewport.set({angle: 0});\n          },\n        });\n\n        // Animate the rotation and dimension change\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            var cleanAngle = parseFloat((this.image.angle + 360) % 360);\n            this.image.set({angle: cleanAngle});\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              this._adjustFocalPointByAngle(degrees);\n              this.straighten(this.straighteningInput);\n              this.canvas.add(this.focalPoint);\n            } else {\n              this._resetFocalPointPosition();\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Flip an image along an axis.\n     *\n     * @param axis\n     */\n    flipImage: function (axis) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        if (this.hasOrientationChanged()) {\n          axis = axis === 'y' ? 'x' : 'y';\n        }\n\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n        } else {\n          this._resetFocalPointPosition();\n        }\n\n        var editorCenter = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n        this.straighteningInput.setValue(-this.imageStraightenAngle);\n        this.imageStraightenAngle = -this.imageStraightenAngle;\n        var properties = {\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        };\n\n        var deltaY, deltaX;\n        var cropperState = this.cropperState;\n        var focalPointState = this.focalPointState;\n\n        // Reposition the image, viewport, and stored cropper and focal point states.\n        if (\n          (axis === 'y' && this.hasOrientationChanged()) ||\n          (axis !== 'y' && !this.hasOrientationChanged())\n        ) {\n          cropperState.offsetX = -cropperState.offsetX;\n          focalPointState.offsetX = -focalPointState.offsetX;\n          deltaX = this.image.left - editorCenter.x;\n          properties.left = editorCenter.x - deltaX;\n        } else {\n          cropperState.offsetY = -cropperState.offsetY;\n          focalPointState.offsetY = -focalPointState.offsetY;\n          deltaY = this.image.top - editorCenter.y;\n          properties.top = editorCenter.y - deltaY;\n        }\n\n        if (axis === 'y') {\n          properties.scaleY = this.image.scaleY * -1;\n          this.flipData.y = 1 - this.flipData.y;\n        } else {\n          properties.scaleX = this.image.scaleX * -1;\n          this.flipData.x = 1 - this.flipData.x;\n        }\n\n        this.storeCropperState(cropperState);\n        this.storeFocalPointState(focalPointState);\n\n        this.image.animate(properties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            this.animationInProgress = false;\n            if (this.focalPoint) {\n              // Well this is handy\n              this._adjustFocalPointByAngle(0);\n              this.canvas.add(this.focalPoint);\n            }\n          },\n        });\n      }\n    },\n\n    /**\n     * Perform the straightening with input slider.\n     *\n     * @param {Craft.SlideRuleInput} slider\n     */\n    straighten: function (slider) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        var previousAngle = this.image.angle;\n\n        this.imageStraightenAngle =\n          (this.settings.allowDegreeFractions\n            ? parseFloat(slider.value)\n            : Math.round(parseFloat(slider.value))) % 360;\n\n        // Straighten the image\n        this.image.set({\n          angle: this.viewportRotation + this.imageStraightenAngle,\n        });\n\n        // Set the new zoom ratio\n        this.zoomRatio =\n          this.getZoomToCoverRatio(this.getScaledImageDimensions()) *\n          this.scaleFactor;\n        this._zoomImage();\n\n        if (this.cropperState) {\n          this._adjustEditorElementsOnStraighten(previousAngle);\n        }\n\n        this.renderImage();\n\n        this.animationInProgress = false;\n      }\n    },\n\n    /**\n     * Adjust the cropped viewport when straightening the image to correct for\n     * bumping into edges, keeping focus on the cropped area center and to\n     * maintain the illusion that the image is being straightened relative to the viewport center.\n     *\n     * @param {integer} previousAngle integer the previous image angle before straightening\n     */\n    _adjustEditorElementsOnStraighten: function (previousAngle) {\n      var scaledImageDimensions = this.getScaledImageDimensions();\n      var angleDelta = this.image.angle - previousAngle;\n      var state = this.cropperState;\n\n      var currentZoomRatio = this.zoomRatio;\n      var adjustmentRatio = 1;\n\n      var deltaX, deltaY, newCenterX, newCenterY, sizeFactor;\n\n      do {\n        // Get the cropper center coordinates\n        var cropperCenterX = state.offsetX;\n        var cropperCenterY = state.offsetY;\n        var angleInRadians = angleDelta * (Math.PI / 180);\n\n        // Calculate how the cropper would need to move in a circle to maintain\n        // the focus on the same region if the image was rotated with zoom intact.\n        newCenterX =\n          cropperCenterX * Math.cos(angleInRadians) -\n          cropperCenterY * Math.sin(angleInRadians);\n        newCenterY =\n          cropperCenterX * Math.sin(angleInRadians) +\n          cropperCenterY * Math.cos(angleInRadians);\n\n        sizeFactor = scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Figure out the final image offset to keep the viewport focused where we need it\n        deltaX = newCenterX * currentZoomRatio * sizeFactor;\n        deltaY = newCenterY * currentZoomRatio * sizeFactor;\n\n        // If the image would creep in the viewport, figure out how to math around it.\n        var imageVertices = this.getImageVerticeCoords(currentZoomRatio);\n        var rectangle = {\n          width: this.viewport.width,\n          height: this.viewport.height,\n          left: this.editorWidth / 2 - this.viewport.width / 2 + deltaX,\n          top: this.editorHeight / 2 - this.viewport.height / 2 + deltaY,\n        };\n        adjustmentRatio = this._getZoomRatioToFitRectangle(\n          rectangle,\n          imageVertices\n        );\n        currentZoomRatio = currentZoomRatio * adjustmentRatio;\n\n        // If we had to make adjustments, do the calculations again\n      } while (adjustmentRatio !== 1);\n\n      // Reposition the image correctly\n      this.image.set({\n        left: this.editorWidth / 2 - deltaX,\n        top: this.editorHeight / 2 - deltaY,\n      });\n\n      // Finally, store the new cropper state to reflect the rotation change.\n      state.offsetX = newCenterX;\n      state.offsetY = newCenterY;\n      state.width = this.viewport.width / currentZoomRatio / sizeFactor;\n      state.height = this.viewport.height / currentZoomRatio / sizeFactor;\n\n      this.storeCropperState(state);\n\n      // Zoom the image in and we're done.\n      this.zoomRatio = currentZoomRatio;\n\n      if (this.focalPoint) {\n        this._adjustFocalPointByAngle(angleDelta);\n\n        if (!this._isCenterInside(this.focalPoint, this.viewport)) {\n          this.focalPoint.set({opacity: 0});\n        } else {\n          this.focalPoint.set({opacity: 1});\n        }\n      } else if (angleDelta !== 0) {\n        this._resetFocalPointPosition();\n      }\n\n      this._zoomImage();\n    },\n\n    /**\n     * If focal point is active and outside of viewport after straightening, reset it.\n     */\n    _cleanupFocalPointAfterStraighten: function () {\n      if (\n        this.focalPoint &&\n        !this._isCenterInside(this.focalPoint, this.viewport)\n      ) {\n        this.focalPoint.set({opacity: 1});\n        var state = this.focalPointState;\n        state.offsetX = 0;\n        state.offsetY = 0;\n        this.storeFocalPointState(state);\n        this.toggleFocalPoint();\n      }\n    },\n\n    /**\n     * Reset focal point to the middle of image.\n     */\n    _resetFocalPointPosition: function () {\n      var state = this.focalPointState;\n      state.offsetX = 0;\n      state.offsetY = 0;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Returns true if a center of an object is inside another rectangle shaped object that is not rotated.\n     *\n     * @param object\n     * @param containingObject\n     *\n     * @returns {boolean}\n     */\n    _isCenterInside: function (object, containingObject) {\n      return (\n        object.left > containingObject.left - containingObject.width / 2 &&\n        object.top > containingObject.top - containingObject.height / 2 &&\n        object.left < containingObject.left + containingObject.width / 2 &&\n        object.top < containingObject.top + containingObject.height / 2\n      );\n    },\n\n    /**\n     * Adjust the focal point by an angle in degrees.\n     * @param angle\n     */\n    _adjustFocalPointByAngle: function (angle) {\n      var angleInRadians = angle * (Math.PI / 180);\n      var state = this.focalPointState;\n\n      var focalX = state.offsetX;\n      var focalY = state.offsetY;\n\n      // Calculate how the focal point would need to move in a circle to keep on the same spot\n      // on the image if it was rotated with zoom intact.\n      var newFocalX =\n        focalX * Math.cos(angleInRadians) - focalY * Math.sin(angleInRadians);\n      var newFocalY =\n        focalX * Math.sin(angleInRadians) + focalY * Math.cos(angleInRadians);\n      var sizeFactor =\n        this.getScaledImageDimensions().width / state.imageDimensions.width;\n\n      var adjustedFocalX = newFocalX * sizeFactor * this.zoomRatio;\n      var adjustedFocalY = newFocalY * sizeFactor * this.zoomRatio;\n\n      this.focalPoint.left = this.image.left + adjustedFocalX;\n      this.focalPoint.top = this.image.top + adjustedFocalY;\n\n      state.offsetX = newFocalX;\n      state.offsetY = newFocalY;\n      this.storeFocalPointState(state);\n    },\n\n    /**\n     * Get the zoom ratio required to fit a rectangle within another rectangle, that is defined by vertices.\n     * If the rectangle fits, 1 will be returned.\n     *\n     * @param rectangle\n     * @param containingVertices\n     */\n    _getZoomRatioToFitRectangle: function (rectangle, containingVertices) {\n      var rectangleVertices = this._getRectangleVertices(rectangle);\n      var vertex;\n\n      // Check if any of the viewport vertices end up out of bounds\n      for (\n        var verticeIndex = 0;\n        verticeIndex < rectangleVertices.length;\n        verticeIndex++\n      ) {\n        vertex = rectangleVertices[verticeIndex];\n\n        if (!this.arePointsInsideRectangle([vertex], containingVertices)) {\n          break;\n        }\n\n        vertex = false;\n      }\n\n      // If there's no vertex set after loop, it means that all of them are inside the image rectangle\n      var adjustmentRatio;\n\n      if (!vertex) {\n        adjustmentRatio = 1;\n      } else {\n        // Find out which edge got crossed by the vertex\n        var edge = this._getEdgeCrossed(containingVertices, vertex);\n\n        var rectangleCenter = {\n          x: rectangle.left + rectangle.width / 2,\n          y: rectangle.top + rectangle.height / 2,\n        };\n\n        // Calculate how much further that edge needs to be.\n        // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points\n        var distanceFromVertexToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * vertex.x -\n              (edge[1].x - edge[0].x) * vertex.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n        var distanceFromCenterToEdge =\n          Math.abs(\n            (edge[1].y - edge[0].y) * rectangleCenter.x -\n              (edge[1].x - edge[0].x) * rectangleCenter.y +\n              edge[1].x * edge[0].y -\n              edge[1].y * edge[0].x\n          ) /\n          Math.sqrt(\n            Math.pow(edge[1].y - edge[0].y, 2) +\n              Math.pow(edge[1].x - edge[0].x, 2)\n          );\n\n        // Adjust the zoom ratio\n        adjustmentRatio =\n          (distanceFromVertexToEdge + distanceFromCenterToEdge) /\n          distanceFromCenterToEdge;\n      }\n\n      return adjustmentRatio;\n    },\n\n    /**\n     * Save the image.\n     *\n     * @param ev\n     */\n    saveImage: function (ev) {\n      var $button = $(ev.currentTarget);\n      if ($button.hasClass('disabled')) {\n        return false;\n      }\n\n      $('.btn', this.$buttons).addClass('disabled');\n      this.$buttons.append('<div class=\"spinner\"></div>');\n\n      var postData = {\n        assetId: this.assetId,\n        viewportRotation: this.viewportRotation,\n        imageRotation: this.imageStraightenAngle,\n        replace: $button.hasClass('replace') ? 1 : 0,\n      };\n\n      if (this.cropperState) {\n        var cropData = {};\n\n        cropData.height = this.cropperState.height;\n        cropData.width = this.cropperState.width;\n        cropData.offsetX = this.cropperState.offsetX;\n        cropData.offsetY = this.cropperState.offsetY;\n\n        postData.imageDimensions = this.cropperState.imageDimensions;\n\n        postData.cropData = cropData;\n      } else {\n        postData.imageDimensions = this.getScaledImageDimensions();\n      }\n\n      if (this.focalPoint) {\n        postData.focalPoint = this.focalPointState;\n      }\n\n      postData.flipData = this.flipData;\n      postData.zoom = this.zoomRatio;\n\n      Craft.postActionRequest('assets/save-image', postData, (data) => {\n        this.$buttons\n          .find('.btn')\n          .removeClass('disabled')\n          .end()\n          .find('.spinner')\n          .remove();\n\n        if (data.error) {\n          alert(data.error);\n          return;\n        }\n\n        this.onSave();\n        this.hide();\n        Craft.cp.runQueue();\n      });\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to cover a viewport by given dimensions.\n     *\n     * @param dimensions\n     */\n    getZoomToCoverRatio: function (dimensions) {\n      // Convert the angle to radians\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      // Calculate the dimensions of the scaled image using the magic of math\n      var scaledWidth =\n        Math.sin(angleInRadians) * dimensions.height +\n        Math.cos(angleInRadians) * dimensions.width;\n      var scaledHeight =\n        Math.sin(angleInRadians) * dimensions.width +\n        Math.cos(angleInRadians) * dimensions.height;\n\n      // Calculate the ratio\n      return Math.max(\n        scaledWidth / dimensions.width,\n        scaledHeight / dimensions.height\n      );\n    },\n\n    /**\n     * Return image zoom ratio depending on the straighten angle to fit inside a viewport by given dimensions.\n     *\n     * @param dimensions\n     */\n    getZoomToFitRatio: function (dimensions) {\n      // Get the bounding box for a rotated image\n      var boundingBox = this._getImageBoundingBox(dimensions);\n\n      // Scale the bounding box to fit\n      var scale = 1;\n      if (\n        boundingBox.height > this.editorHeight ||\n        boundingBox.width > this.editorWidth\n      ) {\n        var vertScale = this.editorHeight / boundingBox.height;\n        var horiScale = this.editorWidth / boundingBox.width;\n        scale = Math.min(horiScale, vertScale);\n      }\n\n      return scale;\n    },\n\n    /**\n     * Return the combined zoom ratio to fit a rectangle inside image that's been zoomed to fit.\n     */\n    getCombinedZoomRatio: function (dimensions) {\n      return (\n        this.getZoomToCoverRatio(dimensions) /\n        this.getZoomToFitRatio(dimensions)\n      );\n    },\n\n    /**\n     * Draw the grid.\n     *\n     * @private\n     */\n    _showGrid: function () {\n      if (!this.grid) {\n        var strokeOptions = {\n          strokeWidth: 1,\n          stroke: 'rgba(255,255,255,0.5)',\n        };\n\n        var lineCount = 8;\n        var gridWidth = this.viewport.width;\n        var gridHeight = this.viewport.height;\n        var xStep = gridWidth / (lineCount + 1);\n        var yStep = gridHeight / (lineCount + 1);\n\n        var grid = [\n          new fabric.Rect({\n            strokeWidth: 2,\n            stroke: 'rgba(255,255,255,1)',\n            originX: 'center',\n            originY: 'center',\n            width: gridWidth,\n            height: gridHeight,\n            left: gridWidth / 2,\n            top: gridHeight / 2,\n            fill: 'rgba(255,255,255,0)',\n          }),\n        ];\n\n        var i;\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line(\n              [i * xStep, 0, i * xStep, gridHeight],\n              strokeOptions\n            )\n          );\n        }\n        for (i = 1; i <= lineCount; i++) {\n          grid.push(\n            new fabric.Line([0, i * yStep, gridWidth, i * yStep], strokeOptions)\n          );\n        }\n\n        this.grid = new fabric.Group(grid, {\n          left: this.editorWidth / 2,\n          top: this.editorHeight / 2,\n          originX: 'center',\n          originY: 'center',\n          angle: this.viewport.angle,\n        });\n\n        this.canvas.add(this.grid);\n        this.renderImage();\n      }\n    },\n\n    /**\n     * Hide the grid\n     */\n    _hideGrid: function () {\n      this.canvas.remove(this.grid);\n      this.grid = null;\n      this.renderImage();\n    },\n\n    /**\n     * Remove all the events when hiding the editor.\n     */\n    onFadeOut: function () {\n      this.destroy();\n    },\n\n    /**\n     * Make sure underlying content is not scrolled by accident.\n     */\n    show: function () {\n      this.base();\n      Garnish.$bod.addClass('no-scroll');\n    },\n\n    /**\n     * Allow the content to scroll.\n     */\n    hide: function () {\n      this.removeAllListeners();\n      this.straighteningInput.removeAllListeners();\n      Garnish.$bod.removeClass('no-scroll');\n      this.base();\n    },\n\n    /**\n     * onSave callback.\n     */\n    onSave: function () {\n      this.settings.onSave();\n      this.trigger('save');\n    },\n\n    /**\n     * Enable the rotation slider.\n     */\n    enableSlider: function () {\n      this.$imageTools.removeClass('hidden');\n    },\n\n    /**\n     * Disable the rotation slider.\n     */\n    disableSlider: function () {\n      this.$imageTools.addClass('hidden');\n    },\n\n    /**\n     * Switch to crop mode.\n     */\n    enableCropMode: function () {\n      var imageDimensions = this.getScaledImageDimensions();\n      this.zoomRatio = this.getZoomToFitRatio(imageDimensions);\n\n      var viewportProperties = {\n        width: this.editorWidth,\n        height: this.editorHeight,\n      };\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var callback = () => {\n        this._setFittedImageVerticeCoordinates();\n\n        // Restore cropper\n        var state = this.cropperState;\n        var scaledImageDimensions = this.getScaledImageDimensions();\n        var sizeFactor =\n          scaledImageDimensions.width / state.imageDimensions.width;\n\n        // Restore based on the stored information\n        var cropperData = {\n          left: this.image.left + state.offsetX * sizeFactor * this.zoomRatio,\n          top: this.image.top + state.offsetY * sizeFactor * this.zoomRatio,\n          width: state.width * sizeFactor * this.zoomRatio,\n          height: state.height * sizeFactor * this.zoomRatio,\n        };\n\n        this._showCropper(cropperData);\n\n        if (this.focalPoint) {\n          sizeFactor =\n            scaledImageDimensions.width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * Switch out of crop mode.\n     */\n    disableCropMode: function () {\n      var viewportProperties = {};\n\n      this._hideCropper();\n      var imageDimensions = this.getScaledImageDimensions();\n      var targetZoom =\n        this.getZoomToCoverRatio(imageDimensions) * this.scaleFactor;\n      var inverseZoomFactor = targetZoom / this.zoomRatio;\n      this.zoomRatio = targetZoom;\n\n      var imageProperties = {\n        width: imageDimensions.width * this.zoomRatio,\n        height: imageDimensions.height * this.zoomRatio,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      };\n\n      var offsetX = this.clipper.left - this.image.left;\n      var offsetY = this.clipper.top - this.image.top;\n\n      var imageOffsetX = offsetX * inverseZoomFactor;\n      var imageOffsetY = offsetY * inverseZoomFactor;\n      imageProperties.left = this.editorWidth / 2 - imageOffsetX;\n      imageProperties.top = this.editorHeight / 2 - imageOffsetY;\n\n      // Calculate the cropper dimensions after all the zooming\n      viewportProperties.height = this.clipper.height * inverseZoomFactor;\n      viewportProperties.width = this.clipper.width * inverseZoomFactor;\n\n      if (\n        !this.focalPoint ||\n        (this.focalPoint &&\n          !this._isCenterInside(this.focalPoint, this.clipper))\n      ) {\n        if (this.focalPoint) {\n          this.toggleFocalPoint();\n        }\n\n        this._resetFocalPointPosition();\n      }\n\n      var callback = () => {\n        // Reposition focal point correctly\n        if (this.focalPoint) {\n          var sizeFactor =\n            this.getScaledImageDimensions().width /\n            this.focalPointState.imageDimensions.width;\n          this.focalPoint.left =\n            this.image.left +\n            this.focalPointState.offsetX * sizeFactor * this.zoomRatio;\n          this.focalPoint.top =\n            this.image.top +\n            this.focalPointState.offsetY * sizeFactor * this.zoomRatio;\n          this.canvas.add(this.focalPoint);\n        }\n      };\n\n      this._editorModeTransition(callback, imageProperties, viewportProperties);\n    },\n\n    /**\n     * Transition between cropping end editor modes\n     *\n     * @param callback\n     * @param imageProperties\n     * @param viewportProperties\n     * @private\n     */\n    _editorModeTransition: function (\n      callback,\n      imageProperties,\n      viewportProperties\n    ) {\n      if (!this.animationInProgress) {\n        this.animationInProgress = true;\n\n        // Without this it looks semi-broken during animation\n        if (this.focalPoint) {\n          this.canvas.remove(this.focalPoint);\n          this.renderImage();\n        }\n\n        this.image.animate(imageProperties, {\n          onChange: this.canvas.renderAll.bind(this.canvas),\n          duration: this.settings.animationDuration,\n          onComplete: () => {\n            callback();\n            this.animationInProgress = false;\n            this.renderImage();\n          },\n        });\n\n        this.viewport.animate(viewportProperties, {\n          duration: this.settings.animationDuration,\n        });\n      }\n    },\n\n    _showSpinner: function () {\n      this.$spinnerCanvas = $('<canvas id=\"spinner-canvas\"></canvas>').appendTo(\n        $('.image', this.$container)\n      );\n      var canvas = document.getElementById('spinner-canvas');\n      var context = canvas.getContext('2d');\n      var start = new Date();\n      var lines = 16,\n        cW = context.canvas.width,\n        cH = context.canvas.height;\n\n      var draw = function () {\n        var rotation = parseInt(((new Date() - start) / 1000) * lines) / lines;\n        context.save();\n        context.clearRect(0, 0, cW, cH);\n        context.translate(cW / 2, cH / 2);\n        context.rotate(Math.PI * 2 * rotation);\n        for (var i = 0; i < lines; i++) {\n          context.beginPath();\n          context.rotate((Math.PI * 2) / lines);\n          context.moveTo(cW / 10, 0);\n          context.lineTo(cW / 4, 0);\n          context.lineWidth = cW / 30;\n          context.strokeStyle = 'rgba(255,255,255,' + i / lines + ')';\n          context.stroke();\n        }\n        context.restore();\n      };\n      this.spinnerInterval = window.setInterval(draw, 1000 / 30);\n    },\n\n    _hideSpinner: function () {\n      window.clearInterval(this.spinnerInterval);\n      this.$spinnerCanvas.remove();\n      this.$spinnerCanvas = null;\n    },\n\n    /**\n     * Show the cropper.\n     *\n     * @param clipperData\n     */\n    _showCropper: function (clipperData) {\n      this._setupCropperLayer(clipperData);\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Hide the cropper.\n     */\n    _hideCropper: function () {\n      if (this.clipper) {\n        this.croppingCanvas.remove(this.clipper);\n        this.croppingCanvas.remove(this.croppingShade);\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n\n        this.croppingCanvas = null;\n        this.renderCropper = null;\n      }\n    },\n\n    /**\n     * Draw the cropper.\n     *\n     * @param clipperData\n     */\n    _setupCropperLayer: function (clipperData) {\n      // Set up the canvas for cropper\n      this.croppingCanvas = new fabric.StaticCanvas('cropping-canvas', {\n        backgroundColor: 'rgba(0,0,0,0)',\n        hoverCursor: 'default',\n        selection: false,\n      });\n\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      this.renderCropper = () =>\n        Garnish.requestAnimationFrame(\n          this.croppingCanvas.renderAll.bind(this.croppingCanvas)\n        );\n\n      $('#cropping-canvas', this.$editorContainer).css({\n        position: 'absolute',\n        top: 0,\n        left: 0,\n      });\n\n      this.croppingShade = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: this.editorWidth,\n        height: this.editorHeight,\n        fill: 'rgba(0,0,0,0.7)',\n      });\n\n      // Calculate the cropping rectangle size\n      var imageDimensions = this.getScaledImageDimensions();\n      var rectangleRatio =\n        this.imageStraightenAngle === 0\n          ? 1\n          : this.getCombinedZoomRatio(imageDimensions) * 1.2;\n      var rectWidth = imageDimensions.width / rectangleRatio;\n      var rectHeight = imageDimensions.height / rectangleRatio;\n\n      if (this.hasOrientationChanged()) {\n        var temp = rectHeight;\n        rectHeight = rectWidth;\n        rectWidth = temp;\n      }\n\n      // Set up the cropping viewport rectangle\n      this.clipper = new fabric.Rect({\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n        originX: 'center',\n        originY: 'center',\n        width: rectWidth,\n        height: rectHeight,\n        stroke: 'black',\n        fill: 'rgba(128,0,0,1)',\n        strokeWidth: 0,\n      });\n\n      // Set from clipper data\n      if (clipperData) {\n        this.clipper.set(clipperData);\n      }\n\n      this.clipper.globalCompositeOperation = 'destination-out';\n      this.croppingCanvas.add(this.croppingShade);\n      this.croppingCanvas.add(this.clipper);\n    },\n\n    /**\n     * Redraw the cropper boundaries\n     */\n    _redrawCropperElements: function () {\n      if (typeof this._redrawCropperElements._ === 'undefined') {\n        this._redrawCropperElements._ = {};\n      }\n\n      if (this.cropperHandles) {\n        this.croppingCanvas.remove(this.cropperHandles);\n        this.croppingCanvas.remove(this.cropperGrid);\n        this.croppingCanvas.remove(this.croppingRectangle);\n      }\n      this._redrawCropperElements._.lineOptions = {\n        strokeWidth: 4,\n        stroke: 'rgb(255,255,255)',\n        fill: false,\n      };\n\n      this._redrawCropperElements._.gridOptions = {\n        strokeWidth: 2,\n        stroke: 'rgba(255,255,255,0.5)',\n      };\n\n      // Draw the handles\n      this._redrawCropperElements._.pathGroup = [\n        new fabric.Path(\n          'M 0,10 L 0,0 L 10,0',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width - 8) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',0 L ' +\n            (this.clipper.width + 4) +\n            ',10',\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M ' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height - 8) +\n            ' L' +\n            (this.clipper.width + 4) +\n            ',' +\n            (this.clipper.height + 4) +\n            ' L ' +\n            (this.clipper.width - 8) +\n            ',' +\n            (this.clipper.height + 4),\n          this._redrawCropperElements._.lineOptions\n        ),\n        new fabric.Path(\n          'M 10,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height + 4) +\n            ' L 0,' +\n            (this.clipper.height - 8),\n          this._redrawCropperElements._.lineOptions\n        ),\n      ];\n\n      this.cropperHandles = new fabric.Group(\n        this._redrawCropperElements._.pathGroup,\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      // Don't forget the rectangle\n      this.croppingRectangle = new fabric.Rect({\n        left: this.clipper.left,\n        top: this.clipper.top,\n        width: this.clipper.width,\n        height: this.clipper.height,\n        fill: 'rgba(0,0,0,0)',\n        stroke: 'rgba(255,255,255,0.8)',\n        strokeWidth: 2,\n        originX: 'center',\n        originY: 'center',\n      });\n\n      this.cropperGrid = new fabric.Group(\n        [\n          new fabric.Line(\n            [\n              this.clipper.width * 0.33,\n              0,\n              this.clipper.width * 0.33,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              this.clipper.width * 0.66,\n              0,\n              this.clipper.width * 0.66,\n              this.clipper.height,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.33,\n              this.clipper.width,\n              this.clipper.height * 0.33,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n          new fabric.Line(\n            [\n              0,\n              this.clipper.height * 0.66,\n              this.clipper.width,\n              this.clipper.height * 0.66,\n            ],\n            this._redrawCropperElements._.gridOptions\n          ),\n        ],\n        {\n          left: this.clipper.left,\n          top: this.clipper.top,\n          originX: 'center',\n          originY: 'center',\n        }\n      );\n\n      this._redrawCropperElements._.cropTextTop =\n        this.croppingRectangle.top + this.clipper.height / 2 + 12;\n      this._redrawCropperElements._.cropTextBackgroundColor = 'rgba(0,0,0,0)';\n\n      if (\n        this._redrawCropperElements._.cropTextTop + 12 >\n        this.editorHeight - 2\n      ) {\n        this._redrawCropperElements._.cropTextTop -= 24;\n        this._redrawCropperElements._.cropTextBackgroundColor =\n          'rgba(0,0,0,0.5)';\n      }\n\n      this.croppingCanvas.add(this.cropperHandles);\n      this.croppingCanvas.add(this.cropperGrid);\n      this.croppingCanvas.add(this.croppingRectangle);\n    },\n\n    /**\n     * Reposition the cropper when the image editor dimensions change.\n     *\n     * @param previousImageArea\n     */\n    _repositionCropper: function (previousImageArea) {\n      if (!this.croppingCanvas) {\n        return;\n      }\n\n      // Get the current clipper offset relative to center\n      var currentOffset = {\n        x: this.clipper.left - this.croppingCanvas.width / 2,\n        y: this.clipper.top - this.croppingCanvas.height / 2,\n      };\n\n      // Resize the cropping canvas\n      this.croppingCanvas.setDimensions({\n        width: this.editorWidth,\n        height: this.editorHeight,\n      });\n\n      // Check by what factor will the new final bounding box be different\n      var currentArea = this._getBoundingRectangle(this.imageVerticeCoords);\n      var areaFactor = currentArea.width / previousImageArea.width;\n\n      // Adjust the cropper size to scale along with the bounding box\n      this.clipper.width = Math.round(this.clipper.width * areaFactor);\n      this.clipper.height = Math.round(this.clipper.height * areaFactor);\n\n      // Adjust the coordinates: re-position clipper in relation to the new center to adjust\n      // for editor size changes and then multiply by the size factor to adjust for image size changes\n      this.clipper.left = this.editorWidth / 2 + currentOffset.x * areaFactor;\n      this.clipper.top = this.editorHeight / 2 + currentOffset.y * areaFactor;\n\n      // Resize the cropping shade\n      this.croppingShade.set({\n        width: this.editorWidth,\n        height: this.editorHeight,\n        left: this.editorWidth / 2,\n        top: this.editorHeight / 2,\n      });\n\n      this._redrawCropperElements();\n      this.renderCropper();\n    },\n\n    /**\n     * Get the dimensions of a bounding rectangle by a set of four coordinates.\n     *\n     * @param coordinateSet\n     */\n    _getBoundingRectangle: function (coordinateSet) {\n      return {\n        width:\n          Math.max(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ) -\n          Math.min(\n            coordinateSet.a.x,\n            coordinateSet.b.x,\n            coordinateSet.c.x,\n            coordinateSet.d.x\n          ),\n        height:\n          Math.max(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ) -\n          Math.min(\n            coordinateSet.a.y,\n            coordinateSet.b.y,\n            coordinateSet.c.y,\n            coordinateSet.d.y\n          ),\n      };\n    },\n\n    /**\n     * Handle the mouse being clicked.\n     *\n     * @param ev\n     */\n    _handleMouseDown: function (ev) {\n      // Focal before resize before dragging\n      var focal = this.focalPoint && this._isMouseOver(ev, this.focalPoint);\n      var move = this.croppingCanvas && this._isMouseOver(ev, this.clipper);\n      var handle = this.croppingCanvas && this._cropperHandleHitTest(ev);\n\n      if (handle || move || focal) {\n        this.previousMouseX = ev.pageX;\n        this.previousMouseY = ev.pageY;\n\n        if (focal) {\n          this.draggingFocal = true;\n        } else if (handle) {\n          this.scalingCropper = handle;\n        } else if (move) {\n          this.draggingCropper = true;\n        }\n      }\n    },\n\n    /**\n     * Handle the mouse being moved.\n     *\n     * @param ev\n     */\n    _handleMouseMove: function (ev) {\n      if (this.mouseMoveEvent !== null) {\n        Garnish.requestAnimationFrame(this._handleMouseMoveInternal.bind(this));\n      }\n      this.mouseMoveEvent = ev;\n    },\n\n    _handleMouseMoveInternal: function () {\n      if (this.mouseMoveEvent === null) {\n        return;\n      }\n\n      if (this.focalPoint && this.draggingFocal) {\n        this._handleFocalDrag(this.mouseMoveEvent);\n        this.storeFocalPointState();\n        this.renderImage();\n      } else if (this.draggingCropper || this.scalingCropper) {\n        if (this.draggingCropper) {\n          this._handleCropperDrag(this.mouseMoveEvent);\n        } else {\n          this._handleCropperResize(this.mouseMoveEvent);\n        }\n\n        this._redrawCropperElements();\n\n        this.storeCropperState();\n        this.renderCropper();\n      } else {\n        this._setMouseCursor(this.mouseMoveEvent);\n      }\n\n      this.previousMouseX = this.mouseMoveEvent.pageX;\n      this.previousMouseY = this.mouseMoveEvent.pageY;\n\n      this.mouseMoveEvent = null;\n    },\n\n    /**\n     * Handle mouse being released.\n     *\n     * @param ev\n     */\n    _handleMouseUp: function (ev) {\n      this.draggingCropper = false;\n      this.scalingCropper = false;\n      this.draggingFocal = false;\n    },\n\n    /**\n     * Handle mouse out\n     *\n     * @param ev\n     */\n    _handleMouseOut: function (ev) {\n      this._handleMouseUp(ev);\n      this.mouseMoveEvent = ev;\n      this._handleMouseMoveInternal();\n    },\n\n    /**\n     * Handle cropper being dragged.\n     *\n     * @param ev\n     */\n    _handleCropperDrag: function (ev) {\n      if (typeof this._handleCropperDrag._ === 'undefined') {\n        this._handleCropperDrag._ = {};\n      }\n\n      this._handleCropperDrag._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (\n        this._handleCropperDrag._.deltaX === 0 &&\n        this._handleCropperDrag._.deltaY === 0\n      ) {\n        return false;\n      }\n\n      this._handleCropperDrag._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperDrag._.vertices = this._getRectangleVertices(\n        this._handleCropperDrag._.rectangle,\n        this._handleCropperDrag._.deltaX,\n        this._handleCropperDrag._.deltaY\n      );\n\n      // If this would drag it outside of the image\n      if (\n        !this.arePointsInsideRectangle(\n          this._handleCropperDrag._.vertices,\n          this.imageVerticeCoords\n        )\n      ) {\n        // Try to find the furthest point in the same general direction where we can drag it\n\n        // Delta iterator setup\n        this._handleCropperDrag._.dxi = 0;\n        this._handleCropperDrag._.dyi = 0;\n        this._handleCropperDrag._.xStep =\n          this._handleCropperDrag._.deltaX > 0 ? -1 : 1;\n        this._handleCropperDrag._.yStep =\n          this._handleCropperDrag._.deltaY > 0 ? -1 : 1;\n\n        // The furthest we can move\n        this._handleCropperDrag._.furthest = 0;\n        this._handleCropperDrag._.furthestDeltas = {};\n\n        // Loop through every combination of dragging it not so far\n        for (\n          this._handleCropperDrag._.dxi = Math.min(\n            Math.abs(this._handleCropperDrag._.deltaX),\n            10\n          );\n          this._handleCropperDrag._.dxi >= 0;\n          this._handleCropperDrag._.dxi--\n        ) {\n          for (\n            this._handleCropperDrag._.dyi = Math.min(\n              Math.abs(this._handleCropperDrag._.deltaY),\n              10\n            );\n            this._handleCropperDrag._.dyi >= 0;\n            this._handleCropperDrag._.dyi--\n          ) {\n            this._handleCropperDrag._.vertices = this._getRectangleVertices(\n              this._handleCropperDrag._.rectangle,\n              this._handleCropperDrag._.dxi *\n                (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n              this._handleCropperDrag._.dyi *\n                (this._handleCropperDrag._.deltaY > 0 ? 1 : -1)\n            );\n\n            if (\n              this.arePointsInsideRectangle(\n                this._handleCropperDrag._.vertices,\n                this.imageVerticeCoords\n              )\n            ) {\n              if (\n                this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi >\n                this._handleCropperDrag._.furthest\n              ) {\n                this._handleCropperDrag._.furthest =\n                  this._handleCropperDrag._.dxi + this._handleCropperDrag._.dyi;\n                this._handleCropperDrag._.furthestDeltas = {\n                  x:\n                    this._handleCropperDrag._.dxi *\n                    (this._handleCropperDrag._.deltaX > 0 ? 1 : -1),\n                  y:\n                    this._handleCropperDrag._.dyi *\n                    (this._handleCropperDrag._.deltaY > 0 ? 1 : -1),\n                };\n              }\n            }\n          }\n        }\n\n        // REALLY can't drag along the cursor movement\n        if (this._handleCropperDrag._.furthest == 0) {\n          return;\n        } else {\n          this._handleCropperDrag._.deltaX =\n            this._handleCropperDrag._.furthestDeltas.x;\n          this._handleCropperDrag._.deltaY =\n            this._handleCropperDrag._.furthestDeltas.y;\n        }\n      }\n\n      this.clipper.set({\n        left: this.clipper.left + this._handleCropperDrag._.deltaX,\n        top: this.clipper.top + this._handleCropperDrag._.deltaY,\n      });\n    },\n\n    /**\n     * Handle focal point being dragged.\n     *\n     * @param ev\n     */\n    _handleFocalDrag: function (ev) {\n      if (typeof this._handleFocalDrag._ === 'undefined') {\n        this._handleFocalDrag._ = {};\n      }\n\n      if (this.focalPoint) {\n        this._handleFocalDrag._.deltaX = ev.pageX - this.previousMouseX;\n        this._handleFocalDrag._.deltaY = ev.pageY - this.previousMouseY;\n\n        if (\n          this._handleFocalDrag._.deltaX === 0 &&\n          this._handleFocalDrag._.deltaY === 0\n        ) {\n          return;\n        }\n\n        this._handleFocalDrag._.newX =\n          this.focalPoint.left + this._handleFocalDrag._.deltaX;\n        this._handleFocalDrag._.newY =\n          this.focalPoint.top + this._handleFocalDrag._.deltaY;\n\n        // Just make sure that the focal point stays inside the image\n        if (this.currentView === 'crop') {\n          if (\n            !this.arePointsInsideRectangle(\n              [\n                {\n                  x: this._handleFocalDrag._.newX,\n                  y: this._handleFocalDrag._.newY,\n                },\n              ],\n              this.imageVerticeCoords\n            )\n          ) {\n            return;\n          }\n        } else {\n          if (\n            !(\n              this.viewport.left -\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX <\n                0 &&\n              this.viewport.left +\n                this.viewport.width / 2 -\n                this._handleFocalDrag._.newX >\n                0 &&\n              this.viewport.top -\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY <\n                0 &&\n              this.viewport.top +\n                this.viewport.height / 2 -\n                this._handleFocalDrag._.newY >\n                0\n            )\n          ) {\n            return;\n          }\n        }\n\n        this.focalPoint.set({\n          left: this.focalPoint.left + this._handleFocalDrag._.deltaX,\n          top: this.focalPoint.top + this._handleFocalDrag._.deltaY,\n        });\n      }\n    },\n\n    /**\n     * Set the cropping constraint\n     * @param constraint\n     */\n    setCroppingConstraint: function (constraint) {\n      // In case this caused the sidebar width to change.\n      this.updateSizeAndPosition();\n\n      switch (constraint) {\n        case 'none':\n          this.croppingConstraint = false;\n          break;\n\n        case 'original':\n          this.croppingConstraint = this.originalWidth / this.originalHeight;\n          break;\n\n        case 'current':\n          this.croppingConstraint = this.clipper.width / this.clipper.height;\n          break;\n\n        case 'custom':\n          break;\n        default:\n          this.croppingConstraint = parseFloat(constraint);\n\n          break;\n      }\n    },\n\n    /**\n     * Enforce the cropping constraint\n     */\n    enforceCroppingConstraint: function () {\n      if (typeof this.enforceCroppingConstraint._ === 'undefined') {\n        this.enforceCroppingConstraint._ = {};\n      }\n\n      if (this.animationInProgress || !this.croppingConstraint) {\n        return;\n      }\n\n      this.animationInProgress = true;\n\n      // Mock the clipping rectangle for collision tests\n      this.enforceCroppingConstraint._.rectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      // If wider than it should be\n      if (this.clipper.width > this.clipper.height * this.croppingConstraint) {\n        this.enforceCroppingConstraint._.previousHeight =\n          this.enforceCroppingConstraint._.rectangle.height;\n\n        // Make it taller!\n        this.enforceCroppingConstraint._.rectangle.height =\n          this.clipper.width / this.croppingConstraint;\n\n        // Getting really awkward having to convert between 0;0 being center or top-left corner.\n        this.enforceCroppingConstraint._.rectangle.top -=\n          (this.enforceCroppingConstraint._.rectangle.height -\n            this.enforceCroppingConstraint._.previousHeight) /\n          2;\n\n        // If the clipper would end up out of bounds, make it narrower instead.\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.clipper.height * this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.enforceCroppingConstraint._.rectangle.width /\n            this.croppingConstraint;\n        }\n      } else {\n        // Follow the same pattern, if taller than it should be.\n        this.enforceCroppingConstraint._.previousWidth =\n          this.enforceCroppingConstraint._.rectangle.width;\n        this.enforceCroppingConstraint._.rectangle.width =\n          this.clipper.height * this.croppingConstraint;\n        this.enforceCroppingConstraint._.rectangle.left -=\n          (this.enforceCroppingConstraint._.rectangle.width -\n            this.enforceCroppingConstraint._.previousWidth) /\n          2;\n\n        if (\n          !this.arePointsInsideRectangle(\n            this._getRectangleVertices(\n              this.enforceCroppingConstraint._.rectangle\n            ),\n            this.imageVerticeCoords\n          )\n        ) {\n          this.enforceCroppingConstraint._.rectangle.height =\n            this.clipper.width / this.croppingConstraint;\n          this.enforceCroppingConstraint._.rectangle.width =\n            this.enforceCroppingConstraint._.rectangle.height *\n            this.croppingConstraint;\n        }\n      }\n\n      this.enforceCroppingConstraint._.properties = {\n        height: this.enforceCroppingConstraint._.rectangle.height,\n        width: this.enforceCroppingConstraint._.rectangle.width,\n      };\n\n      // Make sure to redraw cropper handles and gridlines when resizing\n      this.clipper.animate(this.enforceCroppingConstraint._.properties, {\n        onChange: () => {\n          this._redrawCropperElements();\n          this.croppingCanvas.renderAll();\n        },\n        duration: this.settings.animationDuration,\n        onComplete: () => {\n          this._redrawCropperElements();\n          this.animationInProgress = false;\n          this.renderCropper();\n          this.storeCropperState();\n        },\n      });\n    },\n\n    /**\n     * Handle cropper being resized.\n     *\n     * @param ev\n     */\n    _handleCropperResize: function (ev) {\n      if (typeof this._handleCropperResize._ === 'undefined') {\n        this._handleCropperResize._ = {};\n      }\n\n      // Size deltas\n      this._handleCropperResize._.deltaX = ev.pageX - this.previousMouseX;\n      this._handleCropperResize._.deltaY = ev.pageY - this.previousMouseY;\n\n      if (this.scalingCropper === 'b' || this.scalingCropper === 't') {\n        this._handleCropperResize._.deltaX = 0;\n      }\n\n      if (this.scalingCropper === 'l' || this.scalingCropper === 'r') {\n        this._handleCropperResize._.deltaY = 0;\n      }\n\n      if (\n        this._handleCropperResize._.deltaX === 0 &&\n        this._handleCropperResize._.deltaY === 0\n      ) {\n        return;\n      }\n\n      // Translate from center-center origin to absolute coords\n      this._handleCropperResize._.startingRectangle = {\n        left: this.clipper.left - this.clipper.width / 2,\n        top: this.clipper.top - this.clipper.height / 2,\n        width: this.clipper.width,\n        height: this.clipper.height,\n      };\n\n      this._handleCropperResize._.rectangle =\n        this._calculateNewCropperSizeByDeltas(\n          this._handleCropperResize._.startingRectangle,\n          this._handleCropperResize._.deltaX,\n          this._handleCropperResize._.deltaY,\n          this.scalingCropper\n        );\n\n      if (\n        this._handleCropperResize._.rectangle.height < 30 ||\n        this._handleCropperResize._.rectangle.width < 30\n      ) {\n        return;\n      }\n\n      if (\n        !this.arePointsInsideRectangle(\n          this._getRectangleVertices(this._handleCropperResize._.rectangle),\n          this.imageVerticeCoords\n        )\n      ) {\n        return;\n      }\n\n      // Translate back to center-center origin.\n      this.clipper.set({\n        top:\n          this._handleCropperResize._.rectangle.top +\n          this._handleCropperResize._.rectangle.height / 2,\n        left:\n          this._handleCropperResize._.rectangle.left +\n          this._handleCropperResize._.rectangle.width / 2,\n        width: this._handleCropperResize._.rectangle.width,\n        height: this._handleCropperResize._.rectangle.height,\n      });\n\n      this._redrawCropperElements();\n    },\n\n    _calculateNewCropperSizeByDeltas: function (\n      startingRectangle,\n      deltaX,\n      deltaY,\n      cropperDirection\n    ) {\n      if (typeof this._calculateNewCropperSizeByDeltas._ === 'undefined') {\n        this._calculateNewCropperSizeByDeltas._ = {};\n      }\n\n      // Center deltas\n      this._calculateNewCropperSizeByDeltas._.topDelta = 0;\n      this._calculateNewCropperSizeByDeltas._.leftDelta = 0;\n\n      this._calculateNewCropperSizeByDeltas._.rectangle = startingRectangle;\n      this._calculateNewCropperSizeByDeltas._.deltaX = deltaX;\n      this._calculateNewCropperSizeByDeltas._.deltaY = deltaY;\n\n      // Lock the aspect ratio if needed\n      if (this.croppingConstraint) {\n        this._calculateNewCropperSizeByDeltas._.change = 0;\n\n        // Take into account the mouse direction and figure out the \"real\" change in cropper size\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.change =\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.change =\n              -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? -this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'br':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.change =\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaY) >\n              Math.abs(this._calculateNewCropperSizeByDeltas._.deltaX)\n                ? this._calculateNewCropperSizeByDeltas._.deltaY\n                : -this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n\n        if (this.croppingConstraint > 1) {\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.deltaX /\n            this.croppingConstraint;\n        } else {\n          this._calculateNewCropperSizeByDeltas._.deltaY =\n            this._calculateNewCropperSizeByDeltas._.change;\n          this._calculateNewCropperSizeByDeltas._.deltaX =\n            this._calculateNewCropperSizeByDeltas._.deltaY *\n            this.croppingConstraint;\n        }\n\n        this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n          this._calculateNewCropperSizeByDeltas._.deltaY;\n        this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n          this._calculateNewCropperSizeByDeltas._.deltaX;\n\n        // Make the cropper compress/expand relative to the correct edge to make it feel \"right\"\n        switch (cropperDirection) {\n          case 't':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'b':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n              -this._calculateNewCropperSizeByDeltas._.deltaX / 2;\n            break;\n          case 'r':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n              -this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            break;\n          case 'l':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY / 2;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'tr':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            break;\n          case 'tl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.top -=\n              this._calculateNewCropperSizeByDeltas._.deltaY;\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n          case 'bl':\n            this._calculateNewCropperSizeByDeltas._.rectangle.left -=\n              this._calculateNewCropperSizeByDeltas._.deltaX;\n            break;\n        }\n      } else {\n        // Lock the aspect ratio\n        if (\n          this.shiftKeyHeld &&\n          (cropperDirection === 'tl' ||\n            cropperDirection === 'tr' ||\n            cropperDirection === 'bl' ||\n            cropperDirection === 'br')\n        ) {\n          this._calculateNewCropperSizeByDeltas._.ratio;\n          if (Math.abs(deltaX) > Math.abs(deltaY)) {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaY =\n              this._calculateNewCropperSizeByDeltas._.deltaX /\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaY *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          } else {\n            this._calculateNewCropperSizeByDeltas._.ratio =\n              startingRectangle.width / startingRectangle.height;\n            this._calculateNewCropperSizeByDeltas._.deltaX =\n              this._calculateNewCropperSizeByDeltas._.deltaY *\n              this._calculateNewCropperSizeByDeltas._.ratio;\n            this._calculateNewCropperSizeByDeltas._.deltaX *=\n              cropperDirection === 'tr' || cropperDirection === 'bl' ? -1 : 1;\n          }\n        }\n\n        if (cropperDirection.match(/t/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.top +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n          this._calculateNewCropperSizeByDeltas._.rectangle.height -=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/b/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.height +=\n            this._calculateNewCropperSizeByDeltas._.deltaY;\n        }\n        if (cropperDirection.match(/r/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.width +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n        if (cropperDirection.match(/l/)) {\n          this._calculateNewCropperSizeByDeltas._.rectangle.left +=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n          this._calculateNewCropperSizeByDeltas._.rectangle.width -=\n            this._calculateNewCropperSizeByDeltas._.deltaX;\n        }\n      }\n\n      this._calculateNewCropperSizeByDeltas._.rectangle.top =\n        this._calculateNewCropperSizeByDeltas._.rectangle.top;\n      this._calculateNewCropperSizeByDeltas._.rectangle.left =\n        this._calculateNewCropperSizeByDeltas._.rectangle.left;\n      this._calculateNewCropperSizeByDeltas._.rectangle.width =\n        this._calculateNewCropperSizeByDeltas._.rectangle.width;\n      this._calculateNewCropperSizeByDeltas._.rectangle.height =\n        this._calculateNewCropperSizeByDeltas._.rectangle.height;\n\n      return this._calculateNewCropperSizeByDeltas._.rectangle;\n    },\n\n    /**\n     * Set mouse cursor by it's position over cropper.\n     *\n     * @param ev\n     */\n    _setMouseCursor: function (ev) {\n      if (typeof this._setMouseCursor._ === 'undefined') {\n        this._setMouseCursor._ = {};\n      }\n\n      if (Garnish.isMobileBrowser(true)) {\n        return;\n      }\n      this._setMouseCursor._.cursor = 'default';\n      this._setMouseCursor._.handle =\n        this.croppingCanvas && this._cropperHandleHitTest(ev);\n      if (this.focalPoint && this._isMouseOver(ev, this.focalPoint)) {\n        this._setMouseCursor._.cursor = 'pointer';\n      } else if (this._setMouseCursor._.handle) {\n        if (\n          this._setMouseCursor._.handle === 't' ||\n          this._setMouseCursor._.handle === 'b'\n        ) {\n          this._setMouseCursor._.cursor = 'ns-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'l' ||\n          this._setMouseCursor._.handle === 'r'\n        ) {\n          this._setMouseCursor._.cursor = 'ew-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'tl' ||\n          this._setMouseCursor._.handle === 'br'\n        ) {\n          this._setMouseCursor._.cursor = 'nwse-resize';\n        } else if (\n          this._setMouseCursor._.handle === 'bl' ||\n          this._setMouseCursor._.handle === 'tr'\n        ) {\n          this._setMouseCursor._.cursor = 'nesw-resize';\n        }\n      } else if (this.croppingCanvas && this._isMouseOver(ev, this.clipper)) {\n        this._setMouseCursor._.cursor = 'move';\n      }\n\n      $('.body').css('cursor', this._setMouseCursor._.cursor);\n    },\n\n    /**\n     * Test whether the mouse cursor is on any cropper handles.\n     *\n     * @param ev\n     */\n    _cropperHandleHitTest: function (ev) {\n      if (typeof this._cropperHandleHitTest._ === 'undefined') {\n        this._cropperHandleHitTest._ = {};\n      }\n\n      this._cropperHandleHitTest._.parentOffset = this.$croppingCanvas.offset();\n      this._cropperHandleHitTest._.mouseX =\n        ev.pageX - this._cropperHandleHitTest._.parentOffset.left;\n      this._cropperHandleHitTest._.mouseY =\n        ev.pageY - this._cropperHandleHitTest._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._cropperHandleHitTest._.lb =\n        this.clipper.left - this.clipper.width / 2;\n      this._cropperHandleHitTest._.rb =\n        this._cropperHandleHitTest._.lb + this.clipper.width;\n      this._cropperHandleHitTest._.tb =\n        this.clipper.top - this.clipper.height / 2;\n      this._cropperHandleHitTest._.bb =\n        this._cropperHandleHitTest._.tb + this.clipper.height;\n\n      // Left side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tl';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 3 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'bl';\n        }\n      }\n      // Right side top/bottom\n      if (\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 13 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 3\n      ) {\n        if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.tb + 10 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.tb - 3\n        ) {\n          return 'tr';\n        } else if (\n          this._cropperHandleHitTest._.mouseY <\n            this._cropperHandleHitTest._.bb + 2 &&\n          this._cropperHandleHitTest._.mouseY >\n            this._cropperHandleHitTest._.bb - 10\n        ) {\n          return 'br';\n        }\n      }\n\n      // Left or right\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.lb + 3 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb - 3 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'l';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb + 1 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.rb - 5 &&\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb - 10 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb + 10\n      ) {\n        return 'r';\n      }\n\n      // Top or bottom\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.tb + 4 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.tb - 2 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 't';\n      }\n      if (\n        this._cropperHandleHitTest._.mouseY <\n          this._cropperHandleHitTest._.bb + 2 &&\n        this._cropperHandleHitTest._.mouseY >\n          this._cropperHandleHitTest._.bb - 4 &&\n        this._cropperHandleHitTest._.mouseX >\n          this._cropperHandleHitTest._.lb + 10 &&\n        this._cropperHandleHitTest._.mouseX <\n          this._cropperHandleHitTest._.rb - 10\n      ) {\n        return 'b';\n      }\n\n      return false;\n    },\n\n    /**\n     * Test whether the mouse cursor is on a fabricJS object.\n     *\n     * @param object\n     * @param event\n     *\n     * @return boolean\n     */\n\n    _isMouseOver: function (event, object) {\n      if (typeof this._isMouseOver._ === 'undefined') {\n        this._isMouseOver._ = {};\n      }\n\n      this._isMouseOver._.parentOffset = this.$croppingCanvas.offset();\n      this._isMouseOver._.mouseX =\n        event.pageX - this._isMouseOver._.parentOffset.left;\n      this._isMouseOver._.mouseY =\n        event.pageY - this._isMouseOver._.parentOffset.top;\n\n      // Compensate for center origin coordinate-wise\n      this._isMouseOver._.lb = object.left - object.width / 2;\n      this._isMouseOver._.rb = this._isMouseOver._.lb + object.width;\n      this._isMouseOver._.tb = object.top - object.height / 2;\n      this._isMouseOver._.bb = this._isMouseOver._.tb + object.height;\n\n      return (\n        this._isMouseOver._.mouseX >= this._isMouseOver._.lb &&\n        this._isMouseOver._.mouseX <= this._isMouseOver._.rb &&\n        this._isMouseOver._.mouseY >= this._isMouseOver._.tb &&\n        this._isMouseOver._.mouseY <= this._isMouseOver._.bb\n      );\n    },\n\n    /**\n     * Get vertices of a rectangle defined by left,top,height and width properties.\n     * Optionally it's possible to provide offsetX and offsetY values.\n     * Left and top properties of rectangle reference the top-left corner.\n     *\n     * @param rectangle\n     * @param [offsetX]\n     * @param [offsetY]\n     */\n    _getRectangleVertices: function (rectangle, offsetX, offsetY) {\n      if (typeof this._getRectangleVertices._ === 'undefined') {\n        this._getRectangleVertices._ = {};\n      }\n\n      if (typeof offsetX === 'undefined') {\n        offsetX = 0;\n      }\n      if (typeof offsetY === 'undefined') {\n        offsetY = 0;\n      }\n\n      this._getRectangleVertices._.topLeft = {\n        x: rectangle.left + offsetX,\n        y: rectangle.top + offsetY,\n      };\n\n      this._getRectangleVertices._.topRight = {\n        x: this._getRectangleVertices._.topLeft.x + rectangle.width,\n        y: this._getRectangleVertices._.topLeft.y,\n      };\n      this._getRectangleVertices._.bottomRight = {\n        x: this._getRectangleVertices._.topRight.x,\n        y: this._getRectangleVertices._.topRight.y + rectangle.height,\n      };\n      this._getRectangleVertices._.bottomLeft = {\n        x: this._getRectangleVertices._.topLeft.x,\n        y: this._getRectangleVertices._.bottomRight.y,\n      };\n\n      return [\n        this._getRectangleVertices._.topLeft,\n        this._getRectangleVertices._.topRight,\n        this._getRectangleVertices._.bottomRight,\n        this._getRectangleVertices._.bottomLeft,\n      ];\n    },\n\n    /**\n     * Set image vertice coordinates for an image that's been zoomed to fit.\n     */\n    _setFittedImageVerticeCoordinates: function () {\n      this.imageVerticeCoords = this.getImageVerticeCoords('fit');\n    },\n\n    /**\n     * Get image vertice coords by a zoom mode and taking into account the straightening angle.\n     * The zoomMode can be either \"cover\", \"fit\" or a discrete float value.\n     *\n     * @param zoomMode\n     */\n    getImageVerticeCoords: function (zoomMode) {\n      var angleInRadians =\n        -1 *\n        ((this.hasOrientationChanged() ? 90 : 0) + this.imageStraightenAngle) *\n        (Math.PI / 180);\n\n      var imageDimensions = this.getScaledImageDimensions();\n\n      var ratio;\n\n      if (typeof zoomMode === 'number') {\n        ratio = zoomMode;\n      } else if (zoomMode === 'cover') {\n        ratio = this.getZoomToCoverRatio(imageDimensions);\n      } else {\n        ratio = this.getZoomToFitRatio(imageDimensions);\n      }\n\n      // Get the dimensions of the scaled image\n      var scaledHeight = imageDimensions.height * ratio;\n      var scaledWidth = imageDimensions.width * ratio;\n\n      // Calculate the segments of the containing box for the image.\n      // When referring to top/bottom or right/left segments, these are on the\n      // right-side and bottom projection of the containing box for the zoomed out image.\n      var topVerticalSegment = Math.cos(angleInRadians) * scaledHeight;\n      var bottomVerticalSegment = Math.sin(angleInRadians) * scaledWidth;\n      var rightHorizontalSegment = Math.cos(angleInRadians) * scaledWidth;\n      var leftHorizontalSegment = Math.sin(angleInRadians) * scaledHeight;\n\n      // Calculate the offsets from editor box for the image-containing box\n      var verticalOffset =\n        (this.editorHeight - (topVerticalSegment + bottomVerticalSegment)) / 2;\n      var horizontalOffset =\n        (this.editorWidth - (leftHorizontalSegment + rightHorizontalSegment)) /\n        2;\n\n      // Finally, calculate the image vertice coordinates\n      return {\n        a: {\n          x: horizontalOffset + rightHorizontalSegment,\n          y: verticalOffset,\n        },\n        b: {\n          x: this.editorWidth - horizontalOffset,\n          y: verticalOffset + topVerticalSegment,\n        },\n        c: {\n          x: horizontalOffset + leftHorizontalSegment,\n          y: this.editorHeight - verticalOffset,\n        },\n        d: {\n          x: horizontalOffset,\n          y: verticalOffset + bottomVerticalSegment,\n        },\n      };\n    },\n\n    /**\n     * Debug stuff by continuously rendering a fabric object on canvas.\n     *\n     * @param fabricObj\n     */\n    _debug: function (fabricObj) {\n      this.canvas.remove(this.debugger);\n      this.debugger = fabricObj;\n      this.canvas.add(this.debugger);\n    },\n\n    /**\n     * Given an array of points in the form of {x: int, y:int} and a rectangle in the form of\n     * {a:{x:int, y:int}, b:{x:int, y:int}, c:{x:int, y:int}} (the fourth vertice is unnecessary)\n     * return true if the point is in the rectangle.\n     *\n     * Adapted from: http://stackoverflow.com/a/2763387/2040791\n     *\n     * @param points\n     * @param rectangle\n     */\n    arePointsInsideRectangle: function (points, rectangle) {\n      if (typeof this.arePointsInsideRectangle._ === 'undefined') {\n        this.arePointsInsideRectangle._ = {};\n      }\n\n      // Pre-calculate the vectors and scalar products for two rectangle edges\n      this.arePointsInsideRectangle._.ab = this._getVector(\n        rectangle.a,\n        rectangle.b\n      );\n      this.arePointsInsideRectangle._.bc = this._getVector(\n        rectangle.b,\n        rectangle.c\n      );\n      this.arePointsInsideRectangle._.scalarAbAb = this._getScalarProduct(\n        this.arePointsInsideRectangle._.ab,\n        this.arePointsInsideRectangle._.ab\n      );\n      this.arePointsInsideRectangle._.scalarBcBc = this._getScalarProduct(\n        this.arePointsInsideRectangle._.bc,\n        this.arePointsInsideRectangle._.bc\n      );\n\n      for (\n        this.arePointsInsideRectangle._.i = 0;\n        this.arePointsInsideRectangle._.i < points.length;\n        this.arePointsInsideRectangle._.i++\n      ) {\n        this.arePointsInsideRectangle._.point =\n          points[this.arePointsInsideRectangle._.i];\n\n        // Calculate the vectors for two rectangle sides and for\n        // the vector from vertices a and b to the point P\n        this.arePointsInsideRectangle._.ap = this._getVector(\n          rectangle.a,\n          this.arePointsInsideRectangle._.point\n        );\n        this.arePointsInsideRectangle._.bp = this._getVector(\n          rectangle.b,\n          this.arePointsInsideRectangle._.point\n        );\n\n        // Calculate scalar or dot products for some vector combinations\n        this.arePointsInsideRectangle._.scalarAbAp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.ab,\n          this.arePointsInsideRectangle._.ap\n        );\n        this.arePointsInsideRectangle._.scalarBcBp = this._getScalarProduct(\n          this.arePointsInsideRectangle._.bc,\n          this.arePointsInsideRectangle._.bp\n        );\n\n        this.arePointsInsideRectangle._.projectsOnAB =\n          0 <= this.arePointsInsideRectangle._.scalarAbAp &&\n          this.arePointsInsideRectangle._.scalarAbAp <=\n            this.arePointsInsideRectangle._.scalarAbAb;\n        this.arePointsInsideRectangle._.projectsOnBC =\n          0 <= this.arePointsInsideRectangle._.scalarBcBp &&\n          this.arePointsInsideRectangle._.scalarBcBp <=\n            this.arePointsInsideRectangle._.scalarBcBc;\n\n        if (\n          !(\n            this.arePointsInsideRectangle._.projectsOnAB &&\n            this.arePointsInsideRectangle._.projectsOnBC\n          )\n        ) {\n          return false;\n        }\n      }\n\n      return true;\n    },\n\n    /**\n     * Returns an object representing the vector between points a and b.\n     *\n     * @param a\n     * @param b\n     */\n    _getVector: function (a, b) {\n      return {x: b.x - a.x, y: b.y - a.y};\n    },\n\n    /**\n     * Returns the scalar product of two vectors\n     *\n     * @param a\n     * @param b\n     */\n    _getScalarProduct: function (a, b) {\n      return a.x * b.x + a.y * b.y;\n    },\n\n    /**\n     * Returns the magnitude of a vector_redrawCropperElements\n     * .\n     *\n     * @param vector\n     */\n    _getVectorMagnitude: function (vector) {\n      return Math.sqrt(vector.x * vector.x + vector.y * vector.y);\n    },\n\n    /**\n     * Returns the angle between two vectors in degrees with two decimal points\n     *\n     * @param a\n     * @param b\n     */\n    _getAngleBetweenVectors: function (a, b) {\n      return (\n        Math.round(\n          ((Math.acos(\n            Math.min(\n              1,\n              this._getScalarProduct(a, b) /\n                (this._getVectorMagnitude(a) * this._getVectorMagnitude(b))\n            )\n          ) *\n            180) /\n            Math.PI) *\n            100\n        ) / 100\n      );\n    },\n\n    /**\n     * Return the rectangle edge crossed by an imaginary line drawn from editor center to a vertex\n     *\n     * @param rectangle\n     * @param vertex\n     *\n     * @returns {*}\n     */\n    _getEdgeCrossed: function (rectangle, vertex) {\n      // Determine over which edge the vertex is\n      var edgePoints = [\n        [rectangle.a, rectangle.b],\n        [rectangle.b, rectangle.c],\n        [rectangle.c, rectangle.d],\n        [rectangle.d, rectangle.a],\n      ];\n\n      var centerPoint = {x: this.editorWidth / 2, y: this.editorHeight / 2};\n      var smallestDiff = 180;\n      var edgeCrossed = null;\n\n      // Test each edge\n      for (var edgeIndex = 0; edgeIndex < edgePoints.length; edgeIndex++) {\n        var edge = edgePoints[edgeIndex];\n        var toCenter = this._getVector(edge[0], centerPoint);\n        var edgeVector = this._getVector(edge[0], edge[1]);\n        var toVertex = this._getVector(edge[0], vertex);\n\n        // If the angle between toCenter/toVertex is the sum of\n        // angles between edgeVector/toCenter and edgeVector/toVertex, it means that\n        // the edgeVector is between the other two meaning that this is the offending vertex.\n        // To avoid the rounding errors, we'll take the closest match\n        var diff = Math.abs(\n          this._getAngleBetweenVectors(toCenter, toVertex) -\n            (this._getAngleBetweenVectors(toCenter, edgeVector) +\n              this._getAngleBetweenVectors(edgeVector, toVertex))\n        );\n\n        if (diff < smallestDiff) {\n          smallestDiff = diff;\n          edgeCrossed = edge;\n        }\n      }\n\n      return edgeCrossed;\n    },\n\n    /**\n     * Get the image bounding box by image scaled dimensions, taking ingo account the straightening angle.\n     *\n     * @param dimensions\n     */\n    _getImageBoundingBox: function (dimensions) {\n      var box = {};\n\n      var angleInRadians =\n        Math.abs(this.imageStraightenAngle) * (Math.PI / 180);\n\n      var proportion = dimensions.height / dimensions.width;\n      box.height =\n        dimensions.width *\n        (Math.sin(angleInRadians) + Math.cos(angleInRadians) * proportion);\n      box.width =\n        dimensions.width *\n        (Math.cos(angleInRadians) + Math.sin(angleInRadians) * proportion);\n\n      if (this.hasOrientationChanged()) {\n        var temp = box.width;\n        box.width = box.height;\n        box.height = temp;\n      }\n\n      return box;\n    },\n  },\n  {\n    defaults: {\n      animationDuration: 100,\n      allowSavingAsNew: true,\n      onSave: $.noop,\n      allowDegreeFractions: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset index class\n */\nCraft.AssetIndex = Craft.BaseElementIndex.extend({\n  $includeSubfoldersContainer: null,\n  $includeSubfoldersCheckbox: null,\n  showingIncludeSubfoldersCheckbox: false,\n\n  $uploadButton: null,\n  $uploadInput: null,\n  $progressBar: null,\n  $folders: null,\n\n  uploader: null,\n  promptHandler: null,\n  progressBar: null,\n\n  _uploadTotalFiles: 0,\n  _uploadFileProgress: {},\n  _currentUploaderSettings: {},\n\n  _assetDrag: null,\n  _folderDrag: null,\n  _expandDropTargetFolderTimeout: null,\n  _tempExpandedFolders: [],\n\n  _fileConflictTemplate: {\n    choices: [\n      {value: 'keepBoth', title: Craft.t('app', 'Keep both')},\n      {value: 'replace', title: Craft.t('app', 'Replace it')},\n    ],\n  },\n  _folderConflictTemplate: {\n    choices: [\n      {\n        value: 'replace',\n        title: Craft.t(\n          'app',\n          'Replace the folder (all existing files will be deleted)'\n        ),\n      },\n      {\n        value: 'merge',\n        title: Craft.t(\n          'app',\n          'Merge the folder (any conflicting files will be replaced)'\n        ),\n      },\n    ],\n  },\n\n  init: function (elementType, $container, settings) {\n    this.base(elementType, $container, settings);\n\n    if (this.settings.context === 'index') {\n      if (!this._folderDrag) {\n        this._initIndexPageMode();\n      }\n\n      this.addListener(Garnish.$win, 'resize,scroll', '_positionProgressBar');\n    } else {\n      this.addListener(this.$main, 'scroll', '_positionProgressBar');\n\n      if (this.settings.modal) {\n        this.settings.modal.on(\n          'updateSizeAndPosition',\n          this._positionProgressBar.bind(this)\n        );\n      }\n    }\n  },\n\n  initSources: function () {\n    if (this.settings.context === 'index' && !this._folderDrag) {\n      this._initIndexPageMode();\n    }\n\n    return this.base();\n  },\n\n  initSource: function ($source) {\n    this.base($source);\n\n    this._createFolderContextMenu($source);\n\n    if (this.settings.context === 'index') {\n      if (this._folderDrag && this._getSourceLevel($source) > 1) {\n        if ($source.data('folder-id')) {\n          this._folderDrag.addItems($source.parent());\n        }\n      }\n\n      if (this._assetDrag) {\n        this._assetDrag.updateDropTargets();\n      }\n    }\n  },\n\n  deinitSource: function ($source) {\n    this.base($source);\n\n    // Does this source have a context menu?\n    var contextMenu = $source.data('contextmenu');\n\n    if (contextMenu) {\n      contextMenu.destroy();\n    }\n\n    if (this.settings.context === 'index') {\n      if (this._folderDrag && this._getSourceLevel($source) > 1) {\n        this._folderDrag.removeItems($source.parent());\n      }\n\n      if (this._assetDrag) {\n        this._assetDrag.updateDropTargets();\n      }\n    }\n  },\n\n  _getSourceLevel: function ($source) {\n    return $source.parentsUntil('nav', 'ul').length;\n  },\n\n  /**\n   * Initialize the index page-specific features\n   */\n  _initIndexPageMode: function () {\n    if (this._folderDrag) {\n      return;\n    }\n\n    // Make the elements selectable\n    this.settings.selectable = true;\n    this.settings.multiSelect = true;\n\n    // Asset dragging\n    // ---------------------------------------------------------------------\n\n    this._assetDrag = new Garnish.DragDrop({\n      activeDropTargetClass: 'sel',\n      helperOpacity: 0.75,\n      filter: () =>\n        this.view.getSelectedElements().has('div.element[data-movable]'),\n      helper: ($file) => this._getFileDragHelper($file),\n      dropTargets: () => {\n        // Which data attribute should we be checking?\n        var attr;\n        if (\n          this._assetDrag.$draggee &&\n          this._assetDrag.$draggee.has('.element[data-peer-file]').length\n        ) {\n          attr = 'data-can-move-peer-files-to';\n        } else {\n          attr = 'data-can-move-to';\n        }\n\n        var targets = [];\n\n        for (var i = 0; i < this.$sources.length; i++) {\n          // Make sure it's a volume folder\n          var $source = this.$sources.eq(i);\n          if (Garnish.hasAttr($source, attr)) {\n            targets.push($source);\n          }\n        }\n\n        return targets;\n      },\n\n      onDragStart: this._onDragStart.bind(this),\n      onDropTargetChange: this._onDropTargetChange.bind(this),\n      onDragStop: this._onFileDragStop.bind(this),\n      helperBaseZindex: 800,\n    });\n\n    // Folder dragging\n    // ---------------------------------------------------------------------\n\n    this._folderDrag = new Garnish.DragDrop({\n      activeDropTargetClass: 'sel',\n      helperOpacity: 0.75,\n\n      helper: ($draggeeHelper) => {\n        var $helperSidebar = $('<div class=\"sidebar drag-helper\"/>'),\n          $helperNav = $('<nav/>').appendTo($helperSidebar),\n          $helperUl = $('<ul/>').appendTo($helperNav);\n\n        $draggeeHelper.appendTo($helperUl).removeClass('expanded');\n        $draggeeHelper.children('a').addClass('sel');\n\n        // Match the style\n        $draggeeHelper.css({\n          'padding-top': this._folderDrag.$draggee.css('padding-top'),\n          'padding-right': this._folderDrag.$draggee.css('padding-right'),\n          'padding-bottom': this._folderDrag.$draggee.css('padding-bottom'),\n          'padding-left': this._folderDrag.$draggee.css('padding-left'),\n        });\n\n        return $helperSidebar;\n      },\n\n      dropTargets: () => {\n        var targets = [];\n\n        // Tag the dragged folder and it's subfolders\n        var draggedSourceIds = [];\n        this._folderDrag.$draggee.find('a[data-key]').each(function () {\n          draggedSourceIds.push($(this).data('key'));\n        });\n\n        for (var i = 0; i < this.$sources.length; i++) {\n          // Make sure it's a volume folder and not one of the dragged folders\n          var $source = this.$sources.eq(i),\n            key = $source.data('key');\n\n          if (!this._getFolderUidFromSourceKey(key)) {\n            continue;\n          }\n\n          if (!Craft.inArray(key, draggedSourceIds)) {\n            targets.push($source);\n          }\n        }\n\n        return targets;\n      },\n\n      onDragStart: this._onDragStart.bind(this),\n      onDropTargetChange: this._onDropTargetChange.bind(this),\n      onDragStop: this._onFolderDragStop.bind(this),\n    });\n  },\n\n  /**\n   * On file drag stop\n   */\n  _onFileDragStop: function () {\n    if (\n      this._assetDrag.$activeDropTarget &&\n      this._assetDrag.$activeDropTarget[0] !== this.$source[0]\n    ) {\n      // Keep it selected\n      var originatingSource = this.$source;\n\n      var targetFolderId = this._assetDrag.$activeDropTarget.data('folder-id'),\n        originalAssetIds = [];\n\n      // For each file, prepare array data.\n      for (var i = 0; i < this._assetDrag.$draggee.length; i++) {\n        var originalAssetId = Craft.getElementInfo(\n          this._assetDrag.$draggee[i]\n        ).id;\n\n        originalAssetIds.push(originalAssetId);\n      }\n\n      // Are any files actually getting moved?\n      if (originalAssetIds.length) {\n        this.setIndexBusy();\n\n        this._positionProgressBar();\n        this.progressBar.resetProgressBar();\n        this.progressBar.setItemCount(originalAssetIds.length);\n        this.progressBar.showProgressBar();\n\n        // For each file to move a separate request\n        var parameterArray = [];\n        for (i = 0; i < originalAssetIds.length; i++) {\n          parameterArray.push({\n            action: 'assets/move-asset',\n            params: {\n              assetId: originalAssetIds[i],\n              folderId: targetFolderId,\n            },\n          });\n        }\n\n        // Define the callback for when all file moves are complete\n        var onMoveFinish = (responseArray) => {\n          this.promptHandler.resetPrompts();\n\n          // Loop trough all the responses\n          for (var i = 0; i < responseArray.length; i++) {\n            var response = responseArray[i];\n\n            // Push prompt into prompt array\n            if (response.conflict) {\n              this.promptHandler.addPrompt({\n                assetId: response.assetId,\n                suggestedFilename: response.suggestedFilename,\n                prompt: {\n                  message: response.conflict,\n                  choices: this._fileConflictTemplate.choices,\n                },\n              });\n            }\n\n            if (response.error) {\n              alert(response.error);\n            }\n          }\n\n          this.setIndexAvailable();\n          this.progressBar.hideProgressBar();\n          var reloadIndex = false;\n\n          var performAfterMoveActions = function () {\n            // Select original source\n            this.sourceSelect.selectItem(originatingSource);\n\n            // Make sure we use the correct offset when fetching the next page\n            this._totalVisible -= this._assetDrag.$draggee.length;\n\n            // And remove the elements that have been moved away\n            for (var i = 0; i < originalAssetIds.length; i++) {\n              $('[data-id=' + originalAssetIds[i] + ']').remove();\n            }\n\n            this.view.deselectAllElements();\n            this._collapseExtraExpandedFolders(targetFolderId);\n\n            if (reloadIndex) {\n              this.updateElements();\n            }\n          };\n\n          if (this.promptHandler.getPromptCount()) {\n            // Define callback for completing all prompts\n            var promptCallback = (returnData) => {\n              var newParameterArray = [];\n\n              // Loop trough all returned data and prepare a new request array\n              for (var i = 0; i < returnData.length; i++) {\n                if (returnData[i].choice === 'cancel') {\n                  reloadIndex = true;\n                  continue;\n                }\n\n                if (returnData[i].choice === 'keepBoth') {\n                  newParameterArray.push({\n                    action: 'assets/move-asset',\n                    params: {\n                      folderId: targetFolderId,\n                      assetId: returnData[i].assetId,\n                      filename: returnData[i].suggestedFilename,\n                    },\n                  });\n                }\n\n                if (returnData[i].choice === 'replace') {\n                  newParameterArray.push({\n                    action: 'assets/move-asset',\n                    params: {\n                      folderId: targetFolderId,\n                      assetId: returnData[i].assetId,\n                      force: true,\n                    },\n                  });\n                }\n              }\n\n              // Nothing to do, carry on\n              if (newParameterArray.length === 0) {\n                performAfterMoveActions.apply(this);\n              } else {\n                // Start working\n                this.setIndexBusy();\n                this.progressBar.resetProgressBar();\n                this.progressBar.setItemCount(\n                  this.promptHandler.getPromptCount()\n                );\n                this.progressBar.showProgressBar();\n\n                // Move conflicting files again with resolutions now\n                this._performBatchRequests(newParameterArray, onMoveFinish);\n              }\n            };\n\n            this._assetDrag.fadeOutHelpers();\n            this.promptHandler.showBatchPrompts(promptCallback);\n          } else {\n            performAfterMoveActions.apply(this);\n            this._assetDrag.fadeOutHelpers();\n          }\n        };\n\n        // Initiate the file move with the built array, index of 0 and callback to use when done\n        this._performBatchRequests(parameterArray, onMoveFinish);\n\n        // Skip returning dragees\n        return;\n      }\n    } else {\n      // Add the .sel class back on the selected source\n      this.$source.addClass('sel');\n\n      this._collapseExtraExpandedFolders();\n    }\n\n    this._assetDrag.returnHelpersToDraggees();\n  },\n\n  /**\n   * On folder drag stop\n   */\n  _onFolderDragStop: function () {\n    // Only move if we have a valid target and we're not trying to move into our direct parent\n    if (\n      this._folderDrag.$activeDropTarget &&\n      this._folderDrag.$activeDropTarget\n        .siblings('ul')\n        .children('li')\n        .filter(this._folderDrag.$draggee).length === 0\n    ) {\n      var targetFolderId = this._folderDrag.$activeDropTarget.data('folder-id');\n\n      this._collapseExtraExpandedFolders(targetFolderId);\n\n      // Get the old folder IDs, and sort them so that we're moving the most-nested folders first\n      var folderIds = [];\n\n      for (var i = 0; i < this._folderDrag.$draggee.length; i++) {\n        var $a = this._folderDrag.$draggee.eq(i).children('a'),\n          folderId = $a.data('folder-id');\n\n        // Make sure it's not already in the target folder and use this single folder Id.\n        if (folderId != targetFolderId) {\n          folderIds.push(folderId);\n          break;\n        }\n      }\n\n      if (folderIds.length) {\n        folderIds.sort();\n        folderIds.reverse();\n\n        this.setIndexBusy();\n        this._positionProgressBar();\n        this.progressBar.resetProgressBar();\n        this.progressBar.setItemCount(folderIds.length);\n        this.progressBar.showProgressBar();\n\n        var parameterArray = [];\n\n        for (i = 0; i < folderIds.length; i++) {\n          parameterArray.push({\n            action: 'assets/move-folder',\n            params: {\n              folderId: folderIds[i],\n              parentId: targetFolderId,\n            },\n          });\n        }\n\n        // Increment, so to avoid displaying folder files that are being moved\n        this.requestId++;\n\n        /*\n                 Here's the rundown:\n                 1) Send all the folders being moved\n                 2) Get results:\n                 a) For all conflicting, receive prompts and resolve them to get:\n                 b) For all valid move operations: by now server has created the needed folders\n                 in target destination. Server returns an array of file move operations\n                 c) server also returns a list of all the folder id changes\n                 d) and the data-id of node to be removed, in case of conflict\n                 e) and a list of folders to delete after the move\n                 3) From data in 2) build a large file move operation array\n                 4) Create a request loop based on this, so we can display progress bar\n                 5) when done, delete all the folders and perform other maintenance\n                 6) Champagne\n                 */\n\n        // This will hold the final list of files to move\n        var fileMoveList = [];\n\n        var newSourceKey = '';\n\n        var onMoveFinish = (responseArray) => {\n          this.promptHandler.resetPrompts();\n\n          // Loop trough all the responses\n          for (var i = 0; i < responseArray.length; i++) {\n            var data = responseArray[i];\n\n            // If successful and have data, then update\n            if (data.success) {\n              if (data.transferList) {\n                fileMoveList = data.transferList;\n              }\n\n              if (data.newFolderId) {\n                newSourceKey =\n                  this._folderDrag.$activeDropTarget.data('key') +\n                  '/folder:' +\n                  data.newFolderUid;\n              }\n            }\n\n            // Push prompt into prompt array\n            if (data.conflict) {\n              data.prompt = {\n                message: data.conflict,\n                choices: this._folderConflictTemplate.choices,\n              };\n\n              this.promptHandler.addPrompt(data);\n            }\n\n            if (data.error) {\n              alert(data.error);\n            }\n          }\n\n          if (this.promptHandler.getPromptCount()) {\n            // Define callback for completing all prompts\n            var promptCallback = (returnData) => {\n              this.promptHandler.resetPrompts();\n\n              var newParameterArray = [];\n\n              var params = {};\n              // Loop trough all returned data and prepare a new request array\n              for (var i = 0; i < returnData.length; i++) {\n                if (returnData[i].choice === 'cancel') {\n                  continue;\n                }\n\n                if (returnData[i].choice === 'replace') {\n                  params.force = true;\n                }\n\n                if (returnData[i].choice === 'merge') {\n                  params.merge = true;\n                }\n\n                params.folderId = data.folderId;\n                params.parentId = data.parentId;\n\n                newParameterArray.push({\n                  action: 'assets/move-folder',\n                  params: params,\n                });\n              }\n\n              // Start working on them lists, baby\n              if (newParameterArray.length === 0) {\n                this._performActualFolderMove(\n                  fileMoveList,\n                  folderIds,\n                  newSourceKey\n                );\n              } else {\n                // Start working\n                this.setIndexBusy();\n                this.progressBar.resetProgressBar();\n                this.progressBar.setItemCount(\n                  this.promptHandler.getPromptCount()\n                );\n                this.progressBar.showProgressBar();\n\n                this._performBatchRequests(newParameterArray, onMoveFinish);\n              }\n            };\n\n            this.promptHandler.showBatchPrompts(promptCallback);\n\n            this.setIndexAvailable();\n            this.progressBar.hideProgressBar();\n          } else {\n            this._performActualFolderMove(\n              fileMoveList,\n              folderIds,\n              newSourceKey\n            );\n          }\n        };\n\n        // Initiate the folder move with the built array, index of 0 and callback to use when done\n        this._performBatchRequests(parameterArray, onMoveFinish);\n\n        // Skip returning dragees until we get the Ajax response\n        return;\n      }\n    } else {\n      // Add the .sel class back on the selected source\n      this.$source.addClass('sel');\n\n      this._collapseExtraExpandedFolders();\n    }\n\n    this._folderDrag.returnHelpersToDraggees();\n  },\n\n  /**\n   * Really move the folder. Like really. For real.\n   */\n  _performActualFolderMove: function (\n    fileMoveList,\n    folderDeleteList,\n    newSourceKey\n  ) {\n    this.setIndexBusy();\n    this.progressBar.resetProgressBar();\n    this.progressBar.setItemCount(1);\n    this.progressBar.showProgressBar();\n\n    var moveCallback = (folderDeleteList) => {\n      // Delete the old folders\n      var counter = 0;\n      var limit = folderDeleteList.length;\n      for (var i = 0; i < folderDeleteList.length; i++) {\n        // When all folders are deleted, reload the sources.\n        Craft.postActionRequest(\n          'assets/delete-folder',\n          {folderId: folderDeleteList[i]},\n          () => {\n            if (++counter === limit) {\n              this.setIndexAvailable();\n              this.progressBar.hideProgressBar();\n              this._folderDrag.returnHelpersToDraggees();\n              this.setInstanceState('selectedSource', newSourceKey);\n              this.refreshSources();\n            }\n          }\n        );\n      }\n    };\n\n    if (fileMoveList.length > 0) {\n      var parameterArray = [];\n\n      for (var i = 0; i < fileMoveList.length; i++) {\n        parameterArray.push({\n          action: 'assets/move-asset',\n          params: fileMoveList[i],\n        });\n      }\n      this._performBatchRequests(parameterArray, function () {\n        moveCallback(folderDeleteList);\n      });\n    } else {\n      moveCallback(folderDeleteList);\n    }\n  },\n\n  /**\n   * Returns the root level source for a source.\n   *\n   * @param $source\n   * @returns {*}\n   * @private\n   */\n  _getRootSource: function ($source) {\n    var $parent;\n    while (($parent = this._getParentSource($source)) && $parent.length) {\n      $source = $parent;\n    }\n    return $source;\n  },\n\n  /**\n   * Get parent source for a source.\n   *\n   * @param $source\n   * @returns {*}\n   * @private\n   */\n  _getParentSource: function ($source) {\n    if (this._getSourceLevel($source) > 1) {\n      return $source.parent().parent().siblings('a');\n    }\n  },\n\n  _selectSourceByFolderId: function (targetFolderId) {\n    var $targetSource = this._getSourceByKey(targetFolderId);\n\n    // Make sure that all the parent sources are expanded and this source is visible.\n    var $parentSources = $targetSource.parent().parents('li');\n\n    for (var i = 0; i < $parentSources.length; i++) {\n      var $parentSource = $($parentSources[i]);\n\n      if (!$parentSource.hasClass('expanded')) {\n        $parentSource.children('.toggle').trigger('click');\n      }\n    }\n\n    this.selectSource($targetSource);\n    this.updateElements();\n  },\n\n  /**\n   * Initialize the uploader.\n   *\n   * @private\n   */\n  afterInit: function () {\n    if (!this.$uploadButton) {\n      this.$uploadButton = $('<button/>', {\n        type: 'button',\n        class: 'btn submit',\n        'data-icon': 'upload',\n        style: 'position: relative; overflow: hidden;',\n        text: Craft.t('app', 'Upload files'),\n      });\n      this.addButton(this.$uploadButton);\n\n      this.$uploadInput = $(\n        '<input type=\"file\" multiple=\"multiple\" name=\"assets-upload\" />'\n      )\n        .hide()\n        .insertBefore(this.$uploadButton);\n    }\n\n    this.promptHandler = new Craft.PromptHandler();\n    this.progressBar = new Craft.ProgressBar(this.$main, true);\n\n    var options = {\n      url: Craft.getActionUrl('assets/upload'),\n      fileInput: this.$uploadInput,\n      dropZone: this.$container,\n    };\n\n    options.events = {\n      fileuploadstart: this._onUploadStart.bind(this),\n      fileuploadprogressall: this._onUploadProgress.bind(this),\n      fileuploaddone: this._onUploadComplete.bind(this),\n      fileuploadfail: this._onUploadFailure.bind(this),\n    };\n\n    if (\n      this.settings.criteria &&\n      typeof this.settings.criteria.kind !== 'undefined'\n    ) {\n      options.allowedKinds = this.settings.criteria.kind;\n    }\n\n    this._currentUploaderSettings = options;\n\n    this.uploader = new Craft.Uploader(this.$uploadButton, options);\n\n    this.$uploadButton.on('click', () => {\n      if (this.$uploadButton.hasClass('disabled')) {\n        return;\n      }\n      if (!this.isIndexBusy) {\n        this.$uploadButton\n          .parent()\n          .find('input[name=assets-upload]')\n          .trigger('click');\n      }\n    });\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific volume in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof window.defaultSource !== 'undefined'\n    ) {\n      let defaultSourceParts = window.defaultSource.split('/');\n      let volumeSource = this.$sources.toArray().find((s) => {\n        return $(s).data('volume-handle') === defaultSourceParts[0];\n      });\n      if (volumeSource) {\n        let $source = $(volumeSource);\n\n        for (let i = 1; i < defaultSourceParts.length; i++) {\n          // does $source have a subfolder with this path name?\n          let subfolderSource = this._getChildSources($source)\n            .toArray()\n            .find((s) => {\n              return $('> .label', s).text() === defaultSourceParts[i];\n            });\n          if (!subfolderSource) {\n            break;\n          }\n          this._expandSource($source);\n          $source = $(subfolderSource);\n        }\n\n        return $source.data('key');\n      }\n    }\n\n    return this.base();\n  },\n\n  onSelectSource: function () {\n    var $source = this._getSourceByKey(this.sourceKey);\n    var folderId = $source.data('folder-id');\n\n    if (folderId && Garnish.hasAttr(this.$source, 'data-can-upload')) {\n      this.uploader.setParams({\n        folderId: this.$source.attr('data-folder-id'),\n      });\n      this.$uploadButton.removeClass('disabled');\n    } else {\n      this.$uploadButton.addClass('disabled');\n    }\n\n    // Update the URL if we're on the Assets index\n    if ($source.length && this.settings.context === 'index') {\n      this._updateUrl($source);\n    }\n\n    this.base();\n  },\n\n  _updateUrl: function ($source) {\n    if (typeof history === 'undefined') {\n      return;\n    }\n\n    // Find all the subfolder sources. At the end, $thisSource will be the root volume source\n    let nestedSources = [];\n    let $thisSource = $source;\n    let $parent;\n    while (($parent = this._getParentSource($thisSource)) && $parent.length) {\n      nestedSources.unshift($thisSource);\n      $thisSource = $parent;\n    }\n\n    let uri = 'assets';\n    if ($thisSource.data('volume-handle')) {\n      uri += '/' + $thisSource.data('volume-handle');\n      nestedSources.forEach(($s) => {\n        uri += '/' + $s.children('.label').text();\n      });\n    }\n\n    history.replaceState({}, '', Craft.getUrl(uri));\n  },\n\n  _getFolderUidFromSourceKey: function (sourceKey) {\n    var m = sourceKey.match(/\\bfolder:([0-9a-f\\-]+)$/);\n\n    return m ? m[1] : null;\n  },\n\n  startSearching: function () {\n    // Does this source have subfolders?\n    if (!this.settings.hideSidebar && this.$source.siblings('ul').length) {\n      if (this.$includeSubfoldersContainer === null) {\n        var id = 'includeSubfolders-' + Math.floor(Math.random() * 1000000000);\n\n        this.$includeSubfoldersContainer = $(\n          '<div style=\"margin-bottom: -25px; opacity: 0;\"/>'\n        ).insertAfter(this.$search);\n        var $subContainer = $('<div style=\"padding-top: 5px;\"/>').appendTo(\n          this.$includeSubfoldersContainer\n        );\n        this.$includeSubfoldersCheckbox = $(\n          '<input type=\"checkbox\" id=\"' + id + '\" class=\"checkbox\"/>'\n        ).appendTo($subContainer);\n        $('<label class=\"light smalltext\" for=\"' + id + '\"/>')\n          .text(' ' + Craft.t('app', 'Search in subfolders'))\n          .appendTo($subContainer);\n\n        this.addListener(\n          this.$includeSubfoldersCheckbox,\n          'change',\n          function () {\n            this.setSelecetedSourceState(\n              'includeSubfolders',\n              this.$includeSubfoldersCheckbox.prop('checked')\n            );\n            this.updateElements();\n          }\n        );\n      } else {\n        this.$includeSubfoldersContainer.velocity('stop');\n      }\n\n      var checked = this.getSelectedSourceState('includeSubfolders', false);\n      this.$includeSubfoldersCheckbox.prop('checked', checked);\n\n      this.$includeSubfoldersContainer.velocity(\n        {\n          marginBottom: 0,\n          opacity: 1,\n        },\n        'fast'\n      );\n\n      this.showingIncludeSubfoldersCheckbox = true;\n    }\n\n    this.base();\n  },\n\n  stopSearching: function () {\n    if (this.showingIncludeSubfoldersCheckbox) {\n      this.$includeSubfoldersContainer.velocity('stop');\n\n      this.$includeSubfoldersContainer.velocity(\n        {\n          marginBottom: -25,\n          opacity: 0,\n        },\n        'fast'\n      );\n\n      this.showingIncludeSubfoldersCheckbox = false;\n    }\n\n    this.base();\n  },\n\n  getViewParams: function () {\n    var data = this.base();\n\n    if (\n      this.showingIncludeSubfoldersCheckbox &&\n      this.$includeSubfoldersCheckbox.prop('checked')\n    ) {\n      data.criteria.includeSubfolders = true;\n    }\n\n    return data;\n  },\n\n  /**\n   * React on upload submit.\n   *\n   * @private\n   */\n  _onUploadStart: function () {\n    this.setIndexBusy();\n\n    // Initial values\n    this._positionProgressBar();\n    this.progressBar.resetProgressBar();\n    this.progressBar.showProgressBar();\n\n    this.promptHandler.resetPrompts();\n  },\n\n  /**\n   * Update uploaded byte count.\n   */\n  _onUploadProgress: function (event, data) {\n    var progress = parseInt((data.loaded / data.total) * 100, 10);\n    this.progressBar.setProgressPercentage(progress);\n  },\n\n  /**\n   * On Upload Complete.\n   */\n  _onUploadComplete: function (event, data) {\n    var response = data.result;\n    var filename = data.files[0].name;\n\n    var doReload = true;\n\n    if (response.success || response.conflict) {\n      // Add the uploaded file to the selected ones, if appropriate\n      this.selectElementAfterUpdate(response.assetId);\n\n      // If there is a prompt, add it to the queue\n      if (response.conflict) {\n        response.prompt = {\n          message: Craft.t('app', response.conflict, {file: response.filename}),\n          choices: this._fileConflictTemplate.choices,\n        };\n\n        this.promptHandler.addPrompt(response);\n      }\n\n      Craft.cp.runQueue();\n    } else {\n      if (response.error) {\n        alert(\n          Craft.t('app', 'Upload failed. The error message was: “{error}”', {\n            error: response.error,\n          })\n        );\n      } else {\n        alert(Craft.t('app', 'Upload failed for {filename}.', {filename}));\n      }\n\n      doReload = false;\n    }\n\n    // For the last file, display prompts, if any. If not - just update the element view.\n    if (this.uploader.isLastUpload()) {\n      this.progressBar.hideProgressBar();\n      this.setIndexAvailable();\n\n      if (this.promptHandler.getPromptCount()) {\n        this.promptHandler.showBatchPrompts(this._uploadFollowup.bind(this));\n      } else {\n        if (doReload) {\n          this._updateAfterUpload();\n        }\n      }\n    }\n  },\n\n  /**\n   * On Upload Failure.\n   */\n  _onUploadFailure: function (event, data) {\n    if (data.jqXHR.responseJSON.error) {\n      alert(data.jqXHR.responseJSON.error);\n      this.progressBar.hideProgressBar();\n      this.setIndexAvailable();\n    }\n  },\n\n  /**\n   * Update the elements after an upload, setting sort to dateModified descending, if not using index.\n   *\n   * @private\n   */\n  _updateAfterUpload: function () {\n    if (this.settings.context !== 'index') {\n      this.clearSearch();\n      this.setSortAttribute('dateCreated');\n      this.setSortDirection('desc');\n    }\n    this.updateElements();\n  },\n\n  /**\n   * Follow up to an upload that triggered at least one conflict resolution prompt.\n   *\n   * @param returnData\n   * @private\n   */\n  _uploadFollowup: function (returnData) {\n    this.setIndexBusy();\n    this.progressBar.resetProgressBar();\n\n    this.promptHandler.resetPrompts();\n\n    var finalCallback = () => {\n      this.progressBar.hideProgressBar();\n      this.setIndexAvailable();\n      this._updateAfterUpload();\n    };\n\n    this.progressBar.setItemCount(returnData.length);\n\n    var doFollowup = (parameterArray, parameterIndex, callback) => {\n      var postData = {};\n      var action = null;\n\n      var followupCallback = (data, textStatus) => {\n        if (textStatus === 'success' && data.assetId) {\n          this.selectElementAfterUpdate(data.assetId);\n        } else if (data.error) {\n          alert(data.error);\n        }\n        parameterIndex++;\n        this.progressBar.incrementProcessedItemCount(1);\n        this.progressBar.updateProgressBar();\n\n        if (parameterIndex === parameterArray.length) {\n          callback();\n        } else {\n          doFollowup(parameterArray, parameterIndex, callback);\n        }\n      };\n\n      if (parameterArray[parameterIndex].choice === 'replace') {\n        action = 'assets/replace-file';\n        postData.sourceAssetId = parameterArray[parameterIndex].assetId;\n\n        if (parameterArray[parameterIndex].conflictingAssetId) {\n          postData.assetId = parameterArray[parameterIndex].conflictingAssetId;\n        } else {\n          postData.targetFilename = parameterArray[parameterIndex].filename;\n        }\n      } else if (parameterArray[parameterIndex].choice === 'cancel') {\n        action = 'assets/delete-asset';\n        postData.assetId = parameterArray[parameterIndex].assetId;\n      }\n\n      if (!action) {\n        // We don't really need to do another request, so let's pretend that already happened\n        followupCallback(\n          {assetId: parameterArray[parameterIndex].assetId},\n          'success'\n        );\n      } else {\n        Craft.postActionRequest(action, postData, followupCallback);\n      }\n    };\n\n    this.progressBar.showProgressBar();\n    doFollowup(returnData, 0, finalCallback);\n  },\n\n  /**\n   * Perform actions after updating elements\n   * @private\n   */\n  onUpdateElements: function () {\n    this._onUpdateElements(false, this.view.getAllElements());\n    this.view.on('appendElements', (ev) => {\n      this._onUpdateElements(true, ev.newElements);\n    });\n\n    this.base();\n  },\n\n  /**\n   * Do the after-update initializations\n   * @private\n   */\n  _onUpdateElements: function (append, $newElements) {\n    if (this.settings.context === 'index') {\n      if (!append) {\n        this._assetDrag.removeAllItems();\n      }\n\n      this._assetDrag.addItems($newElements.has('div.element[data-movable]'));\n    }\n\n    this.base(append, $newElements);\n\n    this.removeListener(this.$elements, 'keydown');\n    this.addListener(this.$elements, 'keydown', this._onKeyDown.bind(this));\n    this.view.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n  },\n\n  /**\n   * Handle a keypress\n   * @private\n   */\n  _onKeyDown: function (ev) {\n    if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n      if (Craft.PreviewFileModal.openInstance) {\n        Craft.PreviewFileModal.openInstance.selfDestruct();\n      } else {\n        var $element = this.view.elementSelect.$focusedItem.find('.element');\n\n        if ($element.length) {\n          this._loadPreview($element);\n        }\n      }\n\n      ev.stopPropagation();\n      return false;\n    }\n  },\n\n  /**\n   * Handle element being focused\n   * @private\n   */\n  _onElementFocus: function (ev) {\n    var $element = $(ev.item).find('.element');\n\n    if (Craft.PreviewFileModal.openInstance && $element.length) {\n      this._loadPreview($element);\n    }\n  },\n\n  /**\n   * Load the preview for an Asset element\n   * @private\n   */\n  _loadPreview: function ($element) {\n    var settings = {};\n\n    if ($element.data('image-width')) {\n      settings.startingWidth = $element.data('image-width');\n      settings.startingHeight = $element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(\n      $element.data('id'),\n      this.view.elementSelect,\n      settings\n    );\n  },\n\n  /**\n   * On Drag Start\n   */\n  _onDragStart: function () {\n    this._tempExpandedFolders = [];\n  },\n\n  /**\n   * Get File Drag Helper\n   */\n  _getFileDragHelper: function ($element) {\n    var currentView = this.getSelectedSourceState('mode');\n    var $outerContainer;\n    var $innerContainer;\n\n    switch (currentView) {\n      case 'table': {\n        $outerContainer = $(\n          '<div class=\"elements datatablesorthelper\"/>'\n        ).appendTo(Garnish.$bod);\n        $innerContainer = $('<div class=\"tableview\"/>').appendTo(\n          $outerContainer\n        );\n        var $table = $('<table class=\"data\"/>').appendTo($innerContainer);\n        var $tbody = $('<tbody/>').appendTo($table);\n\n        $element.appendTo($tbody);\n\n        // Copy the column widths\n        this._$firstRowCells = this.view.$table\n          .children('tbody')\n          .children('tr:first')\n          .children();\n        var $helperCells = $element.children();\n\n        for (var i = 0; i < $helperCells.length; i++) {\n          // Hard-set the cell widths\n          var $helperCell = $($helperCells[i]);\n\n          // Skip the checkbox cell\n          if ($helperCell.hasClass('checkbox-cell')) {\n            $helperCell.remove();\n            $outerContainer.css('margin-' + Craft.left, 19); // 26 - 7\n            continue;\n          }\n\n          var $firstRowCell = $(this._$firstRowCells[i]),\n            width = $firstRowCell.width();\n\n          $firstRowCell.width(width);\n          $helperCell.width(width);\n        }\n\n        return $outerContainer;\n      }\n      case 'thumbs': {\n        $outerContainer = $('<div class=\"elements thumbviewhelper\"/>').appendTo(\n          Garnish.$bod\n        );\n        $innerContainer = $('<ul class=\"thumbsview\"/>').appendTo(\n          $outerContainer\n        );\n\n        $element.appendTo($innerContainer);\n\n        return $outerContainer;\n      }\n    }\n\n    return $();\n  },\n\n  /**\n   * On Drop Target Change\n   */\n  _onDropTargetChange: function ($dropTarget) {\n    clearTimeout(this._expandDropTargetFolderTimeout);\n\n    if ($dropTarget) {\n      var folderId = $dropTarget.data('folder-id');\n\n      if (folderId) {\n        this.dropTargetFolder = this._getSourceByKey(folderId);\n\n        if (\n          this._hasSubfolders(this.dropTargetFolder) &&\n          !this._isExpanded(this.dropTargetFolder)\n        ) {\n          this._expandDropTargetFolderTimeout = setTimeout(\n            this._expandFolder.bind(this),\n            500\n          );\n        }\n      } else {\n        this.dropTargetFolder = null;\n      }\n    }\n\n    if ($dropTarget && $dropTarget[0] !== this.$source[0]) {\n      // Temporarily remove the .sel class on the active source\n      this.$source.removeClass('sel');\n    } else {\n      this.$source.addClass('sel');\n    }\n  },\n\n  /**\n   * Collapse Extra Expanded Folders\n   */\n  _collapseExtraExpandedFolders: function (dropTargetFolderId) {\n    clearTimeout(this._expandDropTargetFolderTimeout);\n\n    // If a source ID is passed in, exclude its parents\n    var $excludedSources;\n\n    if (dropTargetFolderId) {\n      $excludedSources = this._getSourceByKey(dropTargetFolderId)\n        .parents('li')\n        .children('a');\n    }\n\n    for (var i = this._tempExpandedFolders.length - 1; i >= 0; i--) {\n      var $source = this._tempExpandedFolders[i];\n\n      // Check the parent list, if a source id is passed in\n      if (\n        typeof $excludedSources === 'undefined' ||\n        $excludedSources.filter('[data-key=\"' + $source.data('key') + '\"]')\n          .length === 0\n      ) {\n        this._collapseFolder($source);\n        this._tempExpandedFolders.splice(i, 1);\n      }\n    }\n  },\n\n  _getSourceByKey: function (key) {\n    return this.$sources.filter('[data-key$=\"' + key + '\"]');\n  },\n\n  _hasSubfolders: function ($source) {\n    return $source.siblings('ul').find('li').length;\n  },\n\n  _isExpanded: function ($source) {\n    return $source.parent('li').hasClass('expanded');\n  },\n\n  _expandFolder: function () {\n    // Collapse any temp-expanded drop targets that aren't parents of this one\n    this._collapseExtraExpandedFolders(this.dropTargetFolder.data('folder-id'));\n\n    this.dropTargetFolder.siblings('.toggle').trigger('click');\n\n    // Keep a record of that\n    this._tempExpandedFolders.push(this.dropTargetFolder);\n  },\n\n  _collapseFolder: function ($source) {\n    if ($source.parent().hasClass('expanded')) {\n      $source.siblings('.toggle').trigger('click');\n    }\n  },\n\n  _createFolderContextMenu: function ($source) {\n    // Make sure it's a volume folder\n    if (!this._getFolderUidFromSourceKey($source.data('key'))) {\n      return;\n    }\n\n    var menuOptions = [\n      {\n        label: Craft.t('app', 'New subfolder'),\n        onClick: () => {\n          this._createSubfolder($source);\n        },\n      },\n    ];\n\n    // For all folders that are not top folders\n    if (\n      this.settings.context === 'index' &&\n      this._getSourceLevel($source) > 1\n    ) {\n      menuOptions.push({\n        label: Craft.t('app', 'Rename folder'),\n        onClick: () => {\n          this._renameFolder($source);\n        },\n      });\n      menuOptions.push({\n        label: Craft.t('app', 'Delete folder'),\n        onClick: () => {\n          this._deleteFolder($source);\n        },\n      });\n    }\n\n    new Garnish.ContextMenu($source, menuOptions, {menuClass: 'menu'});\n  },\n\n  _createSubfolder: function ($parentFolder) {\n    var subfolderName = prompt(Craft.t('app', 'Enter the name of the folder'));\n\n    if (subfolderName) {\n      var params = {\n        parentId: $parentFolder.data('folder-id'),\n        folderName: subfolderName,\n      };\n\n      this.setIndexBusy();\n\n      Craft.postActionRequest(\n        'assets/create-folder',\n        params,\n        (data, textStatus) => {\n          this.setIndexAvailable();\n\n          if (textStatus === 'success' && data.success) {\n            this._prepareParentForChildren($parentFolder);\n\n            var $subfolder = $(\n              '<li>' +\n                '<a data-key=\"' +\n                $parentFolder.data('key') +\n                '/folder:' +\n                data.folderUid +\n                '\"' +\n                (Garnish.hasAttr($parentFolder, 'data-has-thumbs')\n                  ? ' data-has-thumbs'\n                  : '') +\n                ' data-folder-id=\"' +\n                data.folderId +\n                '\"' +\n                (Garnish.hasAttr($parentFolder, 'data-can-upload')\n                  ? ' data-can-upload'\n                  : '') +\n                (Garnish.hasAttr($parentFolder, 'data-can-move-to')\n                  ? ' data-can-move-to'\n                  : '') +\n                (Garnish.hasAttr($parentFolder, 'data-can-move-peer-files-to')\n                  ? ' data-can-move-peer-files-to'\n                  : '') +\n                '>' +\n                data.folderName +\n                '</a>' +\n                '</li>'\n            );\n\n            var $a = $subfolder.children('a:first');\n            this._appendSubfolder($parentFolder, $subfolder);\n            this.initSource($a);\n          }\n\n          if (textStatus === 'success' && data.error) {\n            alert(data.error);\n          }\n        }\n      );\n    }\n  },\n\n  _deleteFolder: function ($targetFolder) {\n    if (\n      confirm(\n        Craft.t('app', 'Really delete folder “{folder}”?', {\n          folder: $.trim($targetFolder.text()),\n        })\n      )\n    ) {\n      var params = {\n        folderId: $targetFolder.data('folder-id'),\n      };\n\n      this.setIndexBusy();\n\n      Craft.postActionRequest(\n        'assets/delete-folder',\n        params,\n        (data, textStatus) => {\n          this.setIndexAvailable();\n\n          if (textStatus === 'success' && data.success) {\n            var $parentFolder = this._getParentSource($targetFolder);\n\n            // Remove folder and any trace from its parent, if needed\n            this.deinitSource($targetFolder);\n\n            $targetFolder.parent().remove();\n            this._cleanUpTree($parentFolder);\n          }\n\n          if (textStatus === 'success' && data.error) {\n            alert(data.error);\n          }\n        }\n      );\n    }\n  },\n\n  /**\n   * Rename\n   */\n  _renameFolder: function ($source) {\n    const $label = $source.children('.label');\n    const oldName = Craft.trim($label.text());\n    const newName = prompt(Craft.t('app', 'Rename folder'), oldName);\n\n    if (!newName || newName === oldName) {\n      return;\n    }\n\n    this.setIndexBusy();\n\n    Craft.sendActionRequest('POST', 'assets/rename-folder', {\n      data: {\n        folderId: $source.data('folder-id'),\n        newName: newName,\n      },\n    })\n      .then((response) => {\n        if (response.data.success) {\n          $label.text(response.data.newName);\n\n          // Is this the selected source?\n          if ($source.data('key') === this.$source.data('key')) {\n            this.updateElements();\n\n            // Update the URL if we're on the Assets index\n            if (this.settings.context === 'index') {\n              this._updateUrl($source);\n            }\n          }\n        } else if (response.data.error) {\n          alert(response.data.error);\n        }\n      })\n      .finally(() => {\n        this.setIndexAvailable();\n      });\n  },\n\n  /**\n   * Prepare a source folder for children folder.\n   *\n   * @param $parentFolder\n   * @private\n   */\n  _prepareParentForChildren: function ($parentFolder) {\n    if (!this._hasSubfolders($parentFolder)) {\n      $parentFolder\n        .parent()\n        .addClass('expanded')\n        .append('<div class=\"toggle\"></div><ul></ul>');\n      this.initSourceToggle($parentFolder);\n    }\n  },\n\n  /**\n   * Appends a subfolder to the parent folder at the correct spot.\n   *\n   * @param $parentFolder\n   * @param $subfolder\n   * @private\n   */\n  _appendSubfolder: function ($parentFolder, $subfolder) {\n    var $subfolderList = $parentFolder.siblings('ul'),\n      $existingChildren = $subfolderList.children('li'),\n      subfolderLabel = $.trim($subfolder.children('a:first').text()),\n      folderInserted = false;\n\n    for (var i = 0; i < $existingChildren.length; i++) {\n      var $existingChild = $($existingChildren[i]);\n\n      if ($.trim($existingChild.children('a:first').text()) > subfolderLabel) {\n        $existingChild.before($subfolder);\n        folderInserted = true;\n        break;\n      }\n    }\n\n    if (!folderInserted) {\n      $parentFolder.siblings('ul').append($subfolder);\n    }\n  },\n\n  _cleanUpTree: function ($parentFolder) {\n    if (\n      $parentFolder !== null &&\n      $parentFolder.siblings('ul').children('li').length === 0\n    ) {\n      this.deinitSourceToggle($parentFolder);\n      $parentFolder.siblings('ul').remove();\n      $parentFolder.siblings('.toggle').remove();\n      $parentFolder.parent().removeClass('expanded');\n    }\n  },\n\n  _positionProgressBar: function () {\n    if (!this.progressBar) {\n      this.progressBar = new Craft.ProgressBar(this.$main, true);\n    }\n\n    var $container = $(),\n      scrollTop = 0,\n      offset = 0;\n\n    if (this.settings.context === 'index') {\n      $container = this.progressBar.$progressBar.closest('#content');\n      scrollTop = Garnish.$win.scrollTop();\n    } else {\n      $container = this.progressBar.$progressBar.closest('.main');\n      scrollTop = this.$main.scrollTop();\n    }\n\n    var containerTop = $container.offset().top;\n    var diff = scrollTop - containerTop;\n    var windowHeight = Garnish.$win.height();\n\n    if ($container.height() > windowHeight) {\n      offset = windowHeight / 2 - 6 + diff;\n    } else {\n      offset = $container.height() / 2 - 6;\n    }\n\n    if (this.settings.context !== 'index') {\n      offset = scrollTop + ($container.height() / 2 - 6);\n    }\n\n    this.progressBar.$progressBar.css({\n      top: offset,\n    });\n  },\n\n  _performBatchRequests: function (parameterArray, finalCallback) {\n    const responseArray = [];\n    let activeRequests = parameterArray.length;\n\n    while (parameterArray.length) {\n      const parameters = parameterArray.shift();\n      Craft.sendActionRequest('POST', parameters.action, {\n        data: parameters.params,\n      })\n        .then((response) => {\n          responseArray.push(response.data);\n        })\n        .finally(() => {\n          this.progressBar.incrementProcessedItemCount(1);\n          this.progressBar.updateProgressBar();\n\n          // Was that the last one?\n          if (--activeRequests === 0) {\n            // If assets were just merged we should get the reference tags updated right away\n            Craft.cp.runQueue();\n            finalCallback(responseArray);\n          }\n        });\n    }\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Asset', Craft.AssetIndex);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset Select input\n */\nCraft.AssetSelectInput = Craft.BaseElementSelectInput.extend({\n  requestId: 0,\n  hud: null,\n  $uploadBtn: null,\n  uploader: null,\n  progressBar: null,\n\n  init: function () {\n    this.base.apply(this, arguments);\n\n    if (this.settings.canUpload) {\n      this._attachUploader();\n    }\n\n    this.addListener(\n      this.$elementsContainer,\n      'keydown',\n      this._onKeyDown.bind(this)\n    );\n    this.elementSelect.on('focusItem', this._onElementFocus.bind(this));\n  },\n\n  /**\n   * Handle a keypress\n   * @private\n   */\n  _onKeyDown: function (ev) {\n    if (ev.keyCode === Garnish.SPACE_KEY && ev.shiftKey) {\n      if (Craft.PreviewFileModal.openInstance) {\n        Craft.PreviewFileModal.openInstance.selfDestruct();\n      } else {\n        var $element = this.elementSelect.$focusedItem;\n\n        if ($element.length) {\n          this._loadPreview($element);\n        }\n      }\n\n      ev.stopPropagation();\n\n      return false;\n    }\n  },\n\n  /**\n   * Handle element being focused\n   * @private\n   */\n  _onElementFocus: function (ev) {\n    var $element = $(ev.item);\n\n    if (Craft.PreviewFileModal.openInstance && $element.length) {\n      this._loadPreview($element);\n    }\n  },\n\n  /**\n   * Load the preview for an Asset element\n   * @private\n   */\n  _loadPreview: function ($element) {\n    var settings = {};\n\n    if ($element.data('image-width')) {\n      settings.startingWidth = $element.data('image-width');\n      settings.startingHeight = $element.data('image-height');\n    }\n\n    new Craft.PreviewFileModal(\n      $element.data('id'),\n      this.elementSelect,\n      settings\n    );\n  },\n\n  /**\n   * Create the element editor\n   */\n  createElementEditor: function ($element) {\n    return this.base($element, {\n      params: {\n        defaultFieldLayoutId: this.settings.defaultFieldLayoutId,\n      },\n      input: this,\n    });\n  },\n\n  /**\n   * Attach the uploader with drag event handler\n   */\n  _attachUploader: function () {\n    this.progressBar = new Craft.ProgressBar(\n      $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n    );\n\n    var options = {\n      url: Craft.getActionUrl('assets/upload'),\n      dropZone: this.$container,\n      formData: {\n        fieldId: this.settings.fieldId,\n      },\n    };\n\n    if (this.settings.sourceElementId) {\n      options.formData.elementId = this.settings.sourceElementId;\n    }\n\n    if (this.settings.criteria.siteId) {\n      options.formData.siteId = this.settings.criteria.siteId;\n    }\n\n    if (this.$addElementBtn) {\n      this.$uploadBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn dashed',\n        'data-icon': 'upload',\n        'aria-label':\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n        'aria-describedby': this.settings.describedBy,\n        text:\n          this.settings.limit == 1\n            ? Craft.t('app', 'Upload a file')\n            : Craft.t('app', 'Upload files'),\n      }).insertAfter(this.$addElementBtn);\n      options.fileInput = $('<input/>', {\n        type: 'file',\n        class: 'hidden',\n        multiple: this.settings.limit != 1,\n      }).insertAfter(this.$uploadBtn);\n\n      // Trigger a window resize in case the field is inside an element editor HUD\n      Garnish.$win.trigger('resize');\n    }\n\n    // If CSRF protection isn't enabled, these won't be defined.\n    if (\n      typeof Craft.csrfTokenName !== 'undefined' &&\n      typeof Craft.csrfTokenValue !== 'undefined'\n    ) {\n      // Add the CSRF token\n      options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n    }\n\n    if (typeof this.settings.criteria.kind !== 'undefined') {\n      options.allowedKinds = this.settings.criteria.kind;\n    }\n\n    options.canAddMoreFiles = this.canAddMoreFiles.bind(this);\n\n    options.events = {};\n    options.events.fileuploadstart = this._onUploadStart.bind(this);\n    options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n    options.events.fileuploaddone = this._onUploadComplete.bind(this);\n    options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n    this.uploader = new Craft.Uploader(this.$container, options);\n\n    if (this.$uploadBtn) {\n      this.$uploadBtn.on('click', (ev) => {\n        // We can't store a reference to the file input, because it gets replaced with a new input\n        // each time a new file is uploaded - see https://stackoverflow.com/a/25034721/1688568\n        this.$uploadBtn.next('input[type=file]').trigger('click');\n      });\n    }\n  },\n\n  refreshThumbnail: function (elementId) {\n    var parameters = {\n      elementId: elementId,\n      siteId: this.settings.criteria.siteId,\n      size: this.settings.viewMode,\n    };\n\n    Craft.postActionRequest('elements/get-element-html', parameters, (data) => {\n      if (data.error) {\n        alert(data.error);\n      } else {\n        var $existing = this.$elements.filter('[data-id=\"' + elementId + '\"]');\n        $existing\n          .find('.elementthumb')\n          .replaceWith($(data.html).find('.elementthumb'));\n        this.thumbLoader.load($existing);\n      }\n    });\n  },\n\n  /**\n   * Add the freshly uploaded file to the input field.\n   */\n  selectUploadedFile: function (element) {\n    // Check if we're able to add new elements\n    if (!this.canAddMoreElements()) {\n      return;\n    }\n\n    var $newElement = element.$element;\n\n    // Make a couple tweaks\n    $newElement.addClass('removable');\n    $newElement.prepend(\n      '<input type=\"hidden\" name=\"' +\n        this.settings.name +\n        '[]\" value=\"' +\n        element.id +\n        '\">' +\n        '<a class=\"delete icon\" title=\"' +\n        Craft.t('app', 'Remove') +\n        '\"></a>'\n    );\n\n    $newElement.appendTo(this.$elementsContainer);\n\n    var margin = -($newElement.outerWidth() + 10);\n\n    this.$addElementBtn.css('margin-' + Craft.left, margin + 'px');\n\n    var animateCss = {};\n    animateCss['margin-' + Craft.left] = 0;\n    this.$addElementBtn.velocity(animateCss, 'fast');\n\n    this.addElements($newElement);\n\n    delete this.modal;\n  },\n\n  /**\n   * On upload start.\n   */\n  _onUploadStart: function () {\n    this.progressBar.$progressBar.css({\n      top: Math.round(this.$container.outerHeight() / 2) - 6,\n    });\n\n    this.$container.addClass('uploading');\n    this.progressBar.resetProgressBar();\n    this.progressBar.showProgressBar();\n  },\n\n  /**\n   * On upload progress.\n   */\n  _onUploadProgress: function (event, data) {\n    var progress = parseInt((data.loaded / data.total) * 100, 10);\n    this.progressBar.setProgressPercentage(progress);\n  },\n\n  /**\n   * On a file being uploaded.\n   */\n  _onUploadComplete: function (event, data) {\n    if (data.result.error) {\n      alert(data.result.error);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    } else {\n      var parameters = {\n        elementId: data.result.assetId,\n        siteId: this.settings.criteria.siteId,\n        size: this.settings.viewMode,\n      };\n\n      Craft.postActionRequest(\n        'elements/get-element-html',\n        parameters,\n        (data) => {\n          if (data.error) {\n            alert(data.error);\n          } else {\n            var html = $(data.html);\n            Craft.appendHeadHtml(data.headHtml);\n            this.selectUploadedFile(Craft.getElementInfo(html));\n          }\n\n          // Last file\n          if (this.uploader.isLastUpload()) {\n            this.progressBar.hideProgressBar();\n            this.$container.removeClass('uploading');\n\n            if (window.draftEditor) {\n              window.draftEditor.checkForm();\n            }\n          }\n        }\n      );\n\n      Craft.cp.runQueue();\n    }\n  },\n\n  /**\n   * On Upload Failure.\n   */\n  _onUploadFailure: function (event, data) {\n    if (data.jqXHR.responseJSON.error) {\n      alert(data.jqXHR.responseJSON.error);\n      this.progressBar.hideProgressBar();\n      this.$container.removeClass('uploading');\n    }\n  },\n\n  /**\n   * We have to take into account files about to be added as well\n   */\n  canAddMoreFiles: function (slotsTaken) {\n    return (\n      !this.settings.limit ||\n      this.$elements.length + slotsTaken < this.settings.limit\n    );\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Asset selector modal class\n */\nCraft.AssetSelectorModal = Craft.BaseElementSelectorModal.extend(\n  {\n    $selectTransformBtn: null,\n    _selectedTransform: null,\n\n    init: function (elementType, settings) {\n      settings = $.extend({}, Craft.AssetSelectorModal.defaults, settings);\n\n      this.base(elementType, settings);\n\n      if (settings.transforms.length) {\n        this.createSelectTransformButton(settings.transforms);\n      }\n    },\n\n    createSelectTransformButton: function (transforms) {\n      if (!transforms || !transforms.length) {\n        return;\n      }\n\n      var $btnGroup = $('<div class=\"btngroup\"/>').appendTo(\n        this.$primaryButtons\n      );\n      this.$selectBtn.appendTo($btnGroup);\n\n      this.$selectTransformBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn menubtn disabled',\n        text: Craft.t('app', 'Select transform'),\n      }).appendTo($btnGroup);\n\n      var $menu = $('<div class=\"menu\" data-align=\"right\"></div>').insertAfter(\n          this.$selectTransformBtn\n        ),\n        $menuList = $('<ul></ul>').appendTo($menu);\n\n      for (var i = 0; i < transforms.length; i++) {\n        $(\n          '<li><a data-transform=\"' +\n            transforms[i].handle +\n            '\">' +\n            transforms[i].name +\n            '</a></li>'\n        ).appendTo($menuList);\n      }\n\n      var MenuButton = new Garnish.MenuBtn(this.$selectTransformBtn, {\n        onOptionSelect: this.onSelectTransform.bind(this),\n      });\n      MenuButton.disable();\n\n      this.$selectTransformBtn.data('menuButton', MenuButton);\n    },\n\n    onSelectionChange: function (ev) {\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        allowTransforms = false;\n\n      if ($selectedElements.length && this.settings.transforms.length) {\n        allowTransforms = true;\n\n        for (var i = 0; i < $selectedElements.length; i++) {\n          if (!$('.element.hasthumb:first', $selectedElements[i]).length) {\n            break;\n          }\n        }\n      }\n\n      var MenuBtn = null;\n\n      if (this.$selectTransformBtn) {\n        MenuBtn = this.$selectTransformBtn.data('menuButton');\n      }\n\n      if (allowTransforms) {\n        if (MenuBtn) {\n          MenuBtn.enable();\n        }\n\n        this.$selectTransformBtn.removeClass('disabled');\n      } else if (this.$selectTransformBtn) {\n        if (MenuBtn) {\n          MenuBtn.disable();\n        }\n\n        this.$selectTransformBtn.addClass('disabled');\n      }\n\n      this.base();\n    },\n\n    onSelectTransform: function (option) {\n      var transform = $(option).data('transform');\n      this.selectImagesWithTransform(transform);\n    },\n\n    selectImagesWithTransform: function (transform) {\n      // First we must get any missing transform URLs\n      if (\n        typeof Craft.AssetSelectorModal.transformUrls[transform] === 'undefined'\n      ) {\n        Craft.AssetSelectorModal.transformUrls[transform] = {};\n      }\n\n      var $selectedElements = this.elementIndex.getSelectedElements(),\n        imageIdsWithMissingUrls = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $item = $($selectedElements[i]),\n          elementId = Craft.getElementInfo($item).id;\n\n        if (\n          typeof Craft.AssetSelectorModal.transformUrls[transform][\n            elementId\n          ] === 'undefined'\n        ) {\n          imageIdsWithMissingUrls.push(elementId);\n        }\n      }\n\n      if (imageIdsWithMissingUrls.length) {\n        this.showFooterSpinner();\n\n        this.fetchMissingTransformUrls(\n          imageIdsWithMissingUrls,\n          transform,\n          () => {\n            this.hideFooterSpinner();\n            this.selectImagesWithTransform(transform);\n          }\n        );\n      } else {\n        this._selectedTransform = transform;\n        this.selectElements();\n        this._selectedTransform = null;\n      }\n    },\n\n    fetchMissingTransformUrls: function (\n      imageIdsWithMissingUrls,\n      transform,\n      callback\n    ) {\n      var elementId = imageIdsWithMissingUrls.pop();\n\n      var data = {\n        assetId: elementId,\n        handle: transform,\n      };\n\n      Craft.postActionRequest(\n        'assets/generate-transform',\n        data,\n        (response, textStatus) => {\n          Craft.AssetSelectorModal.transformUrls[transform][elementId] = false;\n\n          if (textStatus === 'success') {\n            if (response.url) {\n              Craft.AssetSelectorModal.transformUrls[transform][elementId] =\n                response.url;\n            }\n          }\n\n          // More to load?\n          if (imageIdsWithMissingUrls.length) {\n            this.fetchMissingTransformUrls(\n              imageIdsWithMissingUrls,\n              transform,\n              callback\n            );\n          } else {\n            callback();\n          }\n        }\n      );\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = this.base($selectedElements);\n\n      if (this._selectedTransform) {\n        for (var i = 0; i < info.length; i++) {\n          var elementId = info[i].id;\n\n          if (\n            typeof Craft.AssetSelectorModal.transformUrls[\n              this._selectedTransform\n            ][elementId] !== 'undefined' &&\n            Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n              elementId\n            ] !== false\n          ) {\n            info[i].url =\n              Craft.AssetSelectorModal.transformUrls[this._selectedTransform][\n                elementId\n              ];\n          }\n        }\n      }\n\n      return info;\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo, this._selectedTransform);\n    },\n  },\n  {\n    defaults: {\n      canSelectImageTransforms: false,\n      transforms: [],\n    },\n\n    transformUrls: {},\n  }\n);\n\n// Register it!\nCraft.registerElementSelectorModalClass(\n  'craft\\\\elements\\\\Asset',\n  Craft.AssetSelectorModal\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * AuthManager class\n */\nCraft.AuthManager = Garnish.Base.extend(\n  {\n    remainingSessionTime: null,\n    checkRemainingSessionTimer: null,\n    showLoginModalTimer: null,\n    decrementLogoutWarningInterval: null,\n\n    showingLogoutWarningModal: false,\n    showingLoginModal: false,\n\n    logoutWarningModal: null,\n    loginModal: null,\n\n    $logoutWarningPara: null,\n    $passwordInput: null,\n    $passwordSpinner: null,\n    $loginBtn: null,\n    $loginErrorPara: null,\n\n    submitLoginIfLoggedOut: false,\n\n    /**\n     * Init\n     */\n    init: function () {\n      this.updateRemainingSessionTime(Craft.remainingSessionTime);\n    },\n\n    /**\n     * Sets a timer for the next time to check the auth timeout.\n     */\n    setCheckRemainingSessionTimer: function (seconds) {\n      if (this.checkRemainingSessionTimer) {\n        clearTimeout(this.checkRemainingSessionTimer);\n      }\n\n      this.checkRemainingSessionTimer = setTimeout(\n        this.checkRemainingSessionTime.bind(this),\n        seconds * 1000\n      );\n    },\n\n    /**\n     * Pings the server to see how many seconds are left on the current user session, and handles the response.\n     */\n    checkRemainingSessionTime: function (extendSession) {\n      $.ajax({\n        url: Craft.getActionUrl(\n          'users/session-info',\n          extendSession ? null : 'dontExtendSession=1'\n        ),\n        type: 'GET',\n        dataType: 'json',\n        complete: (jqXHR, textStatus) => {\n          if (textStatus === 'success') {\n            if (\n              typeof jqXHR.responseJSON.csrfTokenValue !== 'undefined' &&\n              typeof Craft.csrfTokenValue !== 'undefined'\n            ) {\n              Craft.csrfTokenValue = jqXHR.responseJSON.csrfTokenValue;\n            }\n\n            this.updateRemainingSessionTime(jqXHR.responseJSON.timeout);\n            this.submitLoginIfLoggedOut = false;\n          } else {\n            this.updateRemainingSessionTime(-1);\n          }\n        },\n      });\n    },\n\n    /**\n     * Updates our record of the auth timeout, and handles it.\n     */\n    updateRemainingSessionTime: function (remainingSessionTime) {\n      this.remainingSessionTime = parseInt(remainingSessionTime);\n\n      // Are we within the warning window?\n      if (\n        this.remainingSessionTime !== -1 &&\n        this.remainingSessionTime < Craft.AuthManager.minSafeSessionTime\n      ) {\n        // Is there still time to renew the session?\n        if (this.remainingSessionTime) {\n          if (!this.showingLogoutWarningModal) {\n            // Show the warning modal\n            this.showLogoutWarningModal();\n          }\n\n          // Will the session expire before the next checkup?\n          if (this.remainingSessionTime < Craft.AuthManager.checkInterval) {\n            if (this.showLoginModalTimer) {\n              clearTimeout(this.showLoginModalTimer);\n            }\n\n            this.showLoginModalTimer = setTimeout(\n              this.showLoginModal.bind(this),\n              this.remainingSessionTime * 1000\n            );\n          }\n        } else {\n          if (this.showingLoginModal) {\n            if (this.submitLoginIfLoggedOut) {\n              this.submitLogin();\n            }\n          } else {\n            // Show the login modal\n            this.showLoginModal();\n          }\n        }\n\n        this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n      } else {\n        // Everything's good!\n        this.hideLogoutWarningModal();\n        this.hideLoginModal();\n\n        // Will be be within the minSafeSessionTime before the next update?\n        if (\n          this.remainingSessionTime !== -1 &&\n          this.remainingSessionTime <\n            Craft.AuthManager.minSafeSessionTime +\n              Craft.AuthManager.checkInterval\n        ) {\n          this.setCheckRemainingSessionTimer(\n            this.remainingSessionTime - Craft.AuthManager.minSafeSessionTime + 1\n          );\n        } else {\n          this.setCheckRemainingSessionTimer(Craft.AuthManager.checkInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the logout warning modal.\n     */\n    showLogoutWarningModal: function () {\n      var quickShow;\n\n      if (this.showingLoginModal) {\n        this.hideLoginModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLogoutWarningModal = true;\n\n      if (!this.logoutWarningModal) {\n        let $form = $(\n          '<form id=\"logoutwarningmodal\" class=\"modal alert fitted\"/>'\n        );\n        let $body = $('<div class=\"body\"/>').appendTo($form);\n        let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n        let $logoutBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Log out now'),\n        }).appendTo($buttons);\n        let $renewSessionBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit',\n          text: Craft.t('app', 'Keep me logged in'),\n        }).appendTo($buttons);\n\n        this.$logoutWarningPara = $('<p/>').prependTo($body);\n\n        this.logoutWarningModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark logoutwarningmodalshade',\n          onFadeIn: function () {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the renew button\n              setTimeout(function () {\n                $renewSessionBtn.trigger('focus');\n              }, 100);\n            }\n          },\n        });\n\n        this.addListener($logoutBtn, 'activate', 'logout');\n        this.addListener($form, 'submit', 'renewSession');\n      }\n\n      if (quickShow) {\n        this.logoutWarningModal.quickShow();\n      } else {\n        this.logoutWarningModal.show();\n      }\n\n      this.updateLogoutWarningMessage();\n\n      this.decrementLogoutWarningInterval = setInterval(\n        this.decrementLogoutWarning.bind(this),\n        1000\n      );\n    },\n\n    /**\n     * Updates the logout warning message indicating that the session is about to expire.\n     */\n    updateLogoutWarningMessage: function () {\n      this.$logoutWarningPara.text(\n        Craft.t('app', 'Your session will expire in {time}.', {\n          time: Craft.secondsToHumanTimeDuration(this.remainingSessionTime),\n        })\n      );\n\n      this.logoutWarningModal.updateSizeAndPosition();\n    },\n\n    decrementLogoutWarning: function () {\n      if (this.remainingSessionTime > 0) {\n        this.remainingSessionTime--;\n        this.updateLogoutWarningMessage();\n      }\n\n      if (this.remainingSessionTime === 0) {\n        clearInterval(this.decrementLogoutWarningInterval);\n      }\n    },\n\n    /**\n     * Hides the logout warning modal.\n     */\n    hideLogoutWarningModal: function (quick) {\n      this.showingLogoutWarningModal = false;\n\n      if (this.logoutWarningModal) {\n        if (quick) {\n          this.logoutWarningModal.quickHide();\n        } else {\n          this.logoutWarningModal.hide();\n        }\n\n        if (this.decrementLogoutWarningInterval) {\n          clearInterval(this.decrementLogoutWarningInterval);\n        }\n      }\n    },\n\n    /**\n     * Shows the login modal.\n     */\n    showLoginModal: function () {\n      var quickShow;\n\n      if (this.showingLogoutWarningModal) {\n        this.hideLogoutWarningModal(true);\n        quickShow = true;\n      } else {\n        quickShow = false;\n      }\n\n      this.showingLoginModal = true;\n\n      if (!this.loginModal) {\n        var $form = $('<form id=\"loginmodal\" class=\"modal alert fitted\"/>'),\n          $body = $(\n            '<div class=\"body\"><h2>' +\n              Craft.t('app', 'Your session has ended.') +\n              '</h2><p>' +\n              Craft.t('app', 'Enter your password to log back in.') +\n              '</p></div>'\n          ).appendTo($form),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<div/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\"/>'\n        ).appendTo($passwordWrapper);\n        this.$passwordSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n          $inputContainer\n        );\n        this.$loginBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit disabled',\n          text: Craft.t('app', 'Login'),\n        }).appendTo($buttonContainer);\n        this.$loginErrorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.loginModal = new Garnish.Modal($form, {\n          autoShow: false,\n          closeOtherModals: false,\n          hideOnEsc: false,\n          hideOnShadeClick: false,\n          shadeClass: 'modal-shade dark loginmodalshade',\n          onFadeIn: () => {\n            if (!Garnish.isMobileBrowser(true)) {\n              // Auto-focus the password input\n              setTimeout(() => {\n                this.$passwordInput.trigger('focus');\n              }, 100);\n            }\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($form, 'submit', 'login');\n      }\n\n      if (quickShow) {\n        this.loginModal.quickShow();\n      } else {\n        this.loginModal.show();\n      }\n    },\n\n    /**\n     * Hides the login modal.\n     */\n    hideLoginModal: function (quick) {\n      this.showingLoginModal = false;\n\n      if (this.loginModal) {\n        if (quick) {\n          this.loginModal.quickHide();\n        } else {\n          this.loginModal.hide();\n        }\n      }\n    },\n\n    logout: function () {\n      $.get({\n        url: Craft.getActionUrl('users/logout'),\n        dataType: 'json',\n        success: () => {\n          Craft.redirectTo('');\n        },\n      });\n    },\n\n    renewSession: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      this.hideLogoutWarningModal();\n      this.checkRemainingSessionTime(true);\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$loginBtn.removeClass('disabled');\n        return true;\n      } else {\n        this.$loginBtn.addClass('disabled');\n        return false;\n      }\n    },\n\n    login: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (this.validatePassword()) {\n        this.$passwordSpinner.removeClass('hidden');\n        this.clearLoginError();\n\n        if (typeof Craft.csrfTokenValue !== 'undefined') {\n          // Check the auth status one last time before sending this off,\n          // in case the user has already logged back in from another window/tab\n          this.submitLoginIfLoggedOut = true;\n          this.checkRemainingSessionTime();\n        } else {\n          this.submitLogin();\n        }\n      }\n    },\n\n    submitLogin: function () {\n      var data = {\n        loginName: Craft.username,\n        password: this.$passwordInput.val(),\n      };\n\n      Craft.postActionRequest('users/login', data, (response, textStatus) => {\n        this.$passwordSpinner.addClass('hidden');\n\n        if (textStatus === 'success') {\n          if (response.success) {\n            this.hideLoginModal();\n            this.checkRemainingSessionTime();\n          } else {\n            this.showLoginError(response.error);\n            Garnish.shake(this.loginModal.$container);\n\n            if (!Garnish.isMobileBrowser(true)) {\n              this.$passwordInput.trigger('focus');\n            }\n          }\n        } else {\n          this.showLoginError();\n        }\n      });\n    },\n\n    showLoginError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$loginErrorPara.text(error);\n      this.loginModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showLoginError('');\n    },\n  },\n  {\n    checkInterval: 60,\n    minSafeSessionTime: 120,\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element editor\n */\nCraft.BaseElementEditor = Garnish.Base.extend(\n  {\n    $element: null,\n    elementId: null,\n    siteId: null,\n    deltaNames: null,\n    initialData: null,\n\n    $header: null,\n    $toolbar: null,\n    $tabContainer: null,\n    $editLink: null,\n    $sidebarBtn: null,\n    $loadSpinner: null,\n\n    $body: null,\n    $fieldsContainer: null,\n\n    $sidebar: null,\n\n    $footer: null,\n    $siteSelectContainer: null,\n    $siteSelect: null,\n    $siteSpinner: null,\n    $cancelBtn: null,\n    $saveBtn: null,\n    $saveSpinner: null,\n\n    slideout: null,\n    tabManager: null,\n    showingSidebar: false,\n\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    initialDeltaValues: null,\n\n    init: function (element, settings) {\n      // Param mapping\n      if (typeof settings === 'undefined' && $.isPlainObject(element)) {\n        // (settings)\n        settings = element;\n        element = null;\n      }\n\n      this.$element = $(element);\n      this.setSettings(settings, Craft.BaseElementEditor.defaults);\n\n      // Header\n      this.$header = $('<header/>', {class: 'pane-header'});\n      this.$toolbar = $('<div/>', {class: 'ee-toolbar'}).appendTo(this.$header);\n      this.$tabContainer = $('<div/>', {class: 'pane-tabs'}).appendTo(\n        this.$toolbar\n      );\n      this.$loadSpinner = $('<div/>', {\n        class: 'spinner',\n        title: Craft.t('app', 'Loading'),\n        'aria-label': Craft.t('app', 'Loading'),\n      }).appendTo(this.$toolbar);\n      this.$editLink = $('<a/>', {\n        target: '_blank',\n        class: 'btn hidden',\n        title: Craft.t('app', 'Open the full edit page in a new tab'),\n        'aria-label': Craft.t('app', 'Open the full edit page in a new tab'),\n        'data-icon': 'external',\n      }).appendTo(this.$toolbar);\n      this.$sidebarBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn hidden sidebar-btn',\n        title: Craft.t('app', 'Show sidebar'),\n        'aria-label': Craft.t('app', 'Show sidebar'),\n        'data-icon': `sidebar-${Garnish.ltr ? 'right' : 'left'}`,\n      }).appendTo(this.$toolbar);\n\n      this.addListener(this.$sidebarBtn, 'click', (ev) => {\n        ev.preventDefault();\n        if (!this.showingSidebar) {\n          this.showSidebar();\n        } else {\n          this.hideSidebar();\n        }\n      });\n\n      // Body\n      this.$body = $('<div/>', {class: 'ee-body'});\n\n      // Fields\n      this.$fieldsContainer = $('<div/>', {class: 'fields'}).appendTo(\n        this.$body\n      );\n\n      // Sidebar\n      this.$sidebar = $('<div/>', {class: 'ee-sidebar hidden'}).appendTo(\n        this.$body\n      );\n      Craft.trapFocusWithin(this.$sidebar);\n\n      // Footer\n      this.$footer = $('<div/>', {class: 'ee-footer hidden'});\n      const $siteSelectOuterContainer = $('<div/>', {\n        class: 'ee-site-select',\n      }).appendTo(this.$footer);\n      this.$siteSelectContainer = $('<div/>', {\n        class: 'select hidden',\n      }).appendTo($siteSelectOuterContainer);\n      this.$siteSelect = $('<select/>').appendTo(this.$siteSelectContainer);\n      this.$siteSpinner = $('<div/>', {class: 'spinner hidden'}).appendTo(\n        $siteSelectOuterContainer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$footer);\n      this.$saveBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit',\n        text: Craft.t('app', 'Save'),\n      }).appendTo(this.$footer);\n      this.$saveSpinner = $('<div/>', {class: 'spinner hidden'}).appendTo(\n        this.$footer\n      );\n\n      let $contents = this.$header.add(this.$body).add(this.$footer);\n\n      // Create the slideout\n      this.slideout = new Craft.Slideout($contents, {\n        containerElement: 'form',\n        containerAttributes: {\n          action: '',\n          method: 'post',\n          novalidate: '',\n          class: 'element-editor',\n        },\n        closeOnEsc: false,\n        closeOnShadeClick: false,\n      });\n      this.slideout.$container.data('elementEditor', this);\n      this.slideout.on('beforeClose', () => {\n        this.hideSidebar();\n      });\n      this.slideout.on('close', () => {\n        this.trigger('closeSlideout');\n        this.destroy();\n      });\n\n      // Register shortcuts & events\n      Garnish.uiLayerManager.registerShortcut(\n        {\n          keyCode: Garnish.S_KEY,\n          ctrl: true,\n        },\n        () => {\n          this.saveElement();\n        }\n      );\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.maybeCloseSlideout();\n      });\n      this.addListener(this.$cancelBtn, 'click', () => {\n        this.maybeCloseSlideout();\n      });\n      this.addListener(this.slideout.$shade, 'click', () => {\n        this.maybeCloseSlideout();\n      });\n      this.addListener(this.slideout.$container, 'click', (ev) => {\n        const $target = $(event.target);\n\n        if (\n          this.showingSidebar &&\n          !$target.closest(this.$sidebarBtn).length &&\n          !$target.closest(this.$sidebar).length\n        ) {\n          this.hideSidebar();\n        }\n      });\n      this.addListener(this.slideout.$container, 'submit', (ev) => {\n        ev.preventDefault();\n        this.saveElement();\n      });\n      this.addListener(this.$siteSelect, 'change', 'switchSite');\n\n      this.load().then(() => {\n        this.onShowHud();\n        this.onCreateForm(this.$body);\n      });\n    },\n\n    setElementAttribute: function (name, value) {\n      if (!this.settings.attributes) {\n        this.settings.attributes = {};\n      }\n\n      if (value === null) {\n        delete this.settings.attributes[name];\n      } else {\n        this.settings.attributes[name] = value;\n      }\n    },\n\n    getBaseData: function () {\n      const data = $.extend({}, this.settings.params);\n\n      if (this.settings.siteId) {\n        data.siteId = this.settings.siteId;\n      } else if (this.$element && this.$element.data('site-id')) {\n        data.siteId = this.$element.data('site-id');\n      }\n\n      if (this.settings.elementId) {\n        data.elementId = this.settings.elementId;\n      } else if (this.$element && this.$element.data('id')) {\n        data.elementId = this.$element.data('id');\n      }\n\n      if (this.settings.elementType) {\n        data.elementType = this.settings.elementType;\n      }\n\n      if (this.settings.attributes) {\n        data.attributes = this.settings.attributes;\n      }\n\n      if (this.settings.prevalidate) {\n        data.prevalidate = 1;\n      }\n\n      return data;\n    },\n\n    /**\n     * @param {object} [data={}]\n     * @param {boolean} [refreshInitialData=true]\n     * @returns {Promise}\n     */\n    load: function (data, refreshInitialData) {\n      return new Promise((resolve, reject) => {\n        this.trigger('beforeLoad');\n        // todo: remove this in Craft 4\n        this.trigger('beginLoading');\n        this.showLoadSpinner();\n        this.onBeginLoading();\n\n        if (this.cancelToken) {\n          this.ignoreFailedRequest = true;\n          this.cancelToken.cancel();\n        }\n\n        this.cancelToken = axios.CancelToken.source();\n\n        Craft.sendActionRequest('POST', 'elements/get-editor-html', {\n          cancelToken: this.cancelToken.token,\n          data: $.extend(this.getBaseData(), data || {}, {\n            includeSites: Craft.isMultiSite && this.settings.showSiteSwitcher,\n          }),\n        })\n          .then((response) => {\n            this.hideLoadSpinner();\n            this.trigger('load');\n            // todo: remove this in Craft 4\n            this.trigger('endLoading');\n            this.onEndLoading();\n            this.cancelToken = null;\n            if (this.initialDeltaValues === null) {\n              this.initialDeltaValues = response.data.initialDeltaValues;\n            }\n            this.updateForm(response.data, refreshInitialData);\n            this.cancelToken = null;\n            resolve();\n          })\n          .catch((e) => {\n            this.hideLoadSpinner();\n            this.onEndLoading();\n            this.cancelToken = null;\n            if (!this.ignoreFailedRequest) {\n              Craft.cp.displayError();\n              reject(e);\n            }\n            this.ignoreFailedRequest = false;\n          });\n      });\n    },\n\n    showHeader: function () {\n      this.$header.removeClass('hidden');\n    },\n\n    hideHeader: function () {\n      this.$header.addClass('hidden');\n    },\n\n    showLoadSpinner: function () {\n      this.showHeader();\n      this.$loadSpinner.removeClass('hidden');\n    },\n\n    hideLoadSpinner: function () {\n      this.$loadSpinner.addClass('hidden');\n    },\n\n    switchSite: function () {\n      if (\n        this.isDirty() &&\n        !confirm(\n          Craft.t(\n            'app',\n            'Switching sites will lose unsaved changes. Are you sure you want to switch sites?'\n          )\n        )\n      ) {\n        this.$siteSelect.val(this.siteId);\n        return;\n      }\n\n      const newSiteId = this.$siteSelect.val();\n\n      if (newSiteId == this.siteId) {\n        return;\n      }\n\n      this.$siteSpinner.removeClass('hidden');\n\n      this.load({siteId: newSiteId})\n        .then(() => {\n          this.$siteSpinner.addClass('hidden');\n        })\n        .catch(() => {\n          this.$siteSpinner.addClass('hidden');\n          // Reset the site select\n          this.$siteSelect.val(this.siteId);\n        });\n    },\n\n    /**\n     * @param {object} data\n     * @param {boolean} [refreshInitialData=true]\n     */\n    updateForm: function (data, refreshInitialData) {\n      // Cleanup\n      if (this.tabManager) {\n        this.$tabContainer.html('');\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n      refreshInitialData = refreshInitialData !== false;\n\n      this.siteId = data.siteId;\n      this.$fieldsContainer.html(data.fieldHtml);\n\n      let showHeader = false;\n\n      if (data.sites && data.sites.length > 1) {\n        showHeader = true;\n        this.$siteSelectContainer.removeClass('hidden');\n        this.$siteSelect.html('');\n\n        for (let i = 0; i < data.sites.length; i++) {\n          const siteInfo = data.sites[i];\n          const $option = $('<option/>', {\n            value: siteInfo.id,\n            text: siteInfo.name,\n          }).appendTo(this.$siteSelect);\n          if (siteInfo.id == data.siteId) {\n            $option.attr('selected', 'selected');\n          }\n        }\n      } else {\n        this.$siteSelectContainer.addClass('hidden');\n      }\n\n      if (data.tabHtml) {\n        showHeader = true;\n        this.$tabContainer.replaceWith((this.$tabContainer = $(data.tabHtml)));\n        this.tabManager = new Craft.Tabs(this.$tabContainer);\n        this.tabManager.on('deselectTab', (ev) => {\n          $(ev.$tab.attr('href')).addClass('hidden');\n        });\n        this.tabManager.on('selectTab', (ev) => {\n          $(ev.$tab.attr('href')).removeClass('hidden');\n          Garnish.$win.trigger('resize');\n          this.$body.trigger('scroll');\n        });\n      }\n\n      if (data.editUrl) {\n        showHeader = true;\n        this.$editLink.removeClass('hidden').attr('href', data.editUrl);\n      } else if (this.$editLink) {\n        this.$editLink.addClass('hidden');\n      }\n\n      if (data.sidebarHtml) {\n        showHeader = true;\n        this.$sidebarBtn.removeClass('hidden');\n        this.$sidebar.html(data.sidebarHtml);\n        Craft.initUiElements(this.$sidebar);\n        new Craft.ElementThumbLoader().load($(this.$sidebar));\n\n        // Open outbound links in new windows\n        this.$sidebar.find('a').each(function () {\n          if (\n            this.hostname.length &&\n            typeof $(this).attr('target') === 'undefined'\n          ) {\n            $(this).attr('target', '_blank');\n          }\n        });\n      } else if (this.$sidebarBtn) {\n        this.$sidebarBtn.addClass('hidden');\n        this.$sidebar.addClass('hidden');\n      }\n\n      if (showHeader) {\n        this.showHeader();\n      } else {\n        this.hideHeader();\n      }\n\n      this.$footer.removeClass('hidden');\n\n      if (refreshInitialData) {\n        this.deltaNames = data.deltaNames;\n      }\n\n      Garnish.requestAnimationFrame(() => {\n        Craft.appendHeadHtml(data.headHtml);\n        Craft.appendFootHtml(data.footHtml);\n        Craft.initUiElements(this.$fieldsContainer);\n\n        if (refreshInitialData) {\n          this.initialData = this.slideout.$container.serialize();\n        }\n\n        if (!Garnish.isMobileBrowser()) {\n          Craft.setFocusWithin(this.$fieldsContainer);\n        }\n\n        this.trigger('updateForm');\n      });\n    },\n\n    showSidebar: function () {\n      if (this.showingSidebar) {\n        return;\n      }\n\n      this.$body.scrollTop(0).addClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.element-editor')\n        .css(this._closedSidebarStyles())\n        .removeClass('hidden');\n\n      // Hack to force CSS animations\n      this.$sidebar[0].offsetWidth;\n\n      this.$sidebar.css(this._openedSidebarStyles());\n\n      if (!Garnish.isMobileBrowser()) {\n        this.$sidebar.one('transitionend.element-editor', () => {\n          Craft.setFocusWithin(this.$sidebar);\n        });\n      }\n\n      this.$sidebarBtn.addClass('active').attr({\n        title: Craft.t('app', 'Hide sidebar'),\n        'aria-label': Craft.t('app', 'Hide sidebar'),\n      });\n\n      Garnish.$win.trigger('resize');\n      this.$sidebar.trigger('scroll');\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.hideSidebar();\n      });\n\n      this.showingSidebar = true;\n    },\n\n    hideSidebar: function () {\n      if (!this.showingSidebar) {\n        return;\n      }\n\n      this.$body.removeClass('no-scroll');\n\n      this.$sidebar\n        .off('transitionend.element-editor')\n        .css(this._closedSidebarStyles())\n        .one('transitionend.element-editor', () => {\n          this.$sidebar.addClass('hidden');\n        });\n\n      this.$sidebarBtn.removeClass('active').attr({\n        title: Craft.t('app', 'Show sidebar'),\n        'aria-label': Craft.t('app', 'Show sidebar'),\n      });\n\n      Garnish.uiLayerManager.removeLayer();\n\n      this.showingSidebar = false;\n    },\n\n    _openedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '0',\n      };\n    },\n\n    _closedSidebarStyles: function () {\n      return {\n        [Garnish.ltr ? 'right' : 'left']: '-350px',\n      };\n    },\n\n    saveElement: function () {\n      const validators = this.settings.validators;\n\n      if ($.isArray(validators)) {\n        for (let i = 0; i < validators.length; i++) {\n          if ($.isFunction(validators[i]) && !validators[i].call()) {\n            return false;\n          }\n        }\n      }\n\n      this.$saveSpinner.removeClass('hidden');\n\n      let data =\n        $.param(this.getBaseData()) +\n        '&' +\n        this.slideout.$container.serialize();\n      data = Craft.findDeltaData(\n        this.initialData,\n        data,\n        this.deltaNames,\n        null,\n        this.initialDeltaValues\n      );\n\n      Craft.postActionRequest(\n        'elements/save-element',\n        data,\n        (response, textStatus) => {\n          this.$saveSpinner.addClass('hidden');\n\n          if (textStatus === 'success') {\n            if (response.success) {\n              if (\n                this.$element &&\n                this.siteId == this.$element.data('site-id')\n              ) {\n                // Update the label\n                const $title = this.$element.find('.title');\n                const $a = $title.find('a');\n\n                if ($a.length && response.cpEditUrl) {\n                  $a.attr('href', response.cpEditUrl);\n                  $a.text(response.newTitle);\n                } else {\n                  $title.text(response.newTitle);\n                }\n              }\n\n              if (\n                this.settings.elementType &&\n                Craft.elementTypeNames[this.settings.elementType]\n              ) {\n                Craft.cp.displayNotice(\n                  Craft.t('app', '{type} saved.', {\n                    type: Craft.elementTypeNames[this.settings.elementType][0],\n                  })\n                );\n              }\n\n              this.closeSlideout();\n              this.trigger('saveElement', {\n                response: response,\n              });\n              this.onSaveElement(response);\n              this.settings.onSaveElement(response);\n\n              // There may be a new background job that needs to be run\n              Craft.cp.runQueue();\n            } else {\n              this.updateForm(response, false);\n              Garnish.shake(this.slideout.$container);\n            }\n          }\n        }\n      );\n    },\n\n    isDirty: function () {\n      return (\n        this.initialData !== null &&\n        this.slideout.$container.serialize() !== this.initialData\n      );\n    },\n\n    maybeCloseSlideout: function () {\n      if (!this.slideout.isOpen) {\n        return;\n      }\n\n      if (\n        !this.isDirty() ||\n        confirm(\n          Craft.t(\n            'app',\n            'Are you sure you want to close the editor? Any changes will be lost.'\n          )\n        )\n      ) {\n        this.closeSlideout();\n      }\n    },\n\n    closeSlideout: function () {\n      this.slideout.close();\n      this.onHideHud();\n\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n    },\n\n    destroy: function () {\n      this.slideout.destroy();\n      delete this.slideout;\n      this.base();\n    },\n\n    // Deprecated Methods\n    // -------------------------------------------------------------------------\n\n    /** @deprecated in 3.7.0 */\n    loadHud: function () {\n      this.load();\n    },\n    /** @deprecated in 3.7.0 */\n    maybeCloseHud: function () {\n      this.maybeCloseSlideout();\n    },\n    /** @deprecated in 3.7.0 */\n    closeHud: function () {\n      this.closeSlideout();\n    },\n    /** @deprecated */\n    reloadForm: function (data, callback) {\n      this.load(data)\n        .then(() => {\n          callback('success');\n        })\n        .catch(() => {\n          callback('error');\n        });\n    },\n    /** @deprecated in 3.7.0 */\n    onBeginLoading: function () {\n      this.settings.onBeginLoading();\n    },\n    /** @deprecated in 3.7.0 */\n    onEndLoading: function () {\n      this.settings.onEndLoading();\n    },\n    /** @deprecated in 3.7.0 */\n    onSaveElement: function (response) {},\n    /** @deprecated in 3.7.0 */\n    onCreateForm: function ($form) {\n      this.settings.onCreateForm($form);\n    },\n    /** @deprecated in 3.7.0 */\n    onShowHud: function () {\n      this.trigger('showHud');\n      this.settings.onShowHud();\n    },\n    /** @deprecated in 3.7.0 */\n    onHideHud: function () {\n      this.trigger('hideHud');\n      this.settings.onHideHud();\n    },\n  },\n  {\n    defaults: {\n      showSiteSwitcher: true,\n      elementId: null,\n      elementType: null,\n      siteId: null,\n      attributes: null,\n      params: null,\n      prevalidate: false,\n      elementIndex: null,\n      onSaveElement: $.noop,\n      validators: [],\n\n      /** @deprecated in 3.7.0 */\n      onShowHud: $.noop,\n      /** @deprecated in 3.7.0 */\n      onHideHud: $.noop,\n      /** @deprecated in 3.7.0 */\n      onBeginLoading: $.noop,\n      /** @deprecated in 3.7.0 */\n      onEndLoading: $.noop,\n      /** @deprecated in 3.7.0 */\n      onCreateForm: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element index class\n */\nCraft.BaseElementIndex = Garnish.Base.extend(\n  {\n    initialized: false,\n    elementType: null,\n\n    instanceState: null,\n    sourceStates: null,\n    sourceStatesStorageKey: null,\n\n    searchTimeout: null,\n    sourceSelect: null,\n\n    $container: null,\n    $main: null,\n    isIndexBusy: false,\n\n    $sidebar: null,\n    showingSidebar: null,\n    sourceKey: null,\n    sourceViewModes: null,\n    $source: null,\n    sourcesByKey: null,\n    $visibleSources: null,\n\n    $customizeSourcesBtn: null,\n    customizeSourcesModal: null,\n\n    $toolbar: null,\n    toolbarOffset: null,\n\n    $search: null,\n    searching: false,\n    searchText: null,\n    trashed: false,\n    drafts: false,\n    $clearSearchBtn: null,\n\n    $statusMenuBtn: null,\n    $statusMenuContainer: null,\n    statusMenu: null,\n    status: null,\n\n    $siteMenuBtn: null,\n    siteMenu: null,\n    siteId: null,\n\n    $sortMenuBtn: null,\n    sortMenu: null,\n    $sortAttributesList: null,\n    $sortDirectionsList: null,\n    $scoreSortAttribute: null,\n    $structureSortAttribute: null,\n\n    $elements: null,\n    $viewModeBtnContainer: null,\n    viewModeBtns: null,\n    viewMode: null,\n    view: null,\n    _autoSelectElements: null,\n    $countSpinner: null,\n    $countContainer: null,\n    page: 1,\n    resultSet: null,\n    totalResults: null,\n    $exportBtn: null,\n\n    actions: null,\n    actionsHeadHtml: null,\n    actionsFootHtml: null,\n    $selectAllContainer: null,\n    $selectAllCheckbox: null,\n    showingActionTriggers: false,\n    exporters: null,\n    exportersByType: null,\n    _$detachedToolbarItems: null,\n    _$triggers: null,\n\n    _ignoreFailedRequest: false,\n    _cancelToken: null,\n\n    /**\n     * Constructor\n     */\n    init: function (elementType, $container, settings) {\n      this.elementType = elementType;\n      this.$container = $container;\n      this.setSettings(settings, Craft.BaseElementIndex.defaults);\n\n      // Set the state objects\n      // ---------------------------------------------------------------------\n\n      this.instanceState = this.getDefaultInstanceState();\n\n      this.sourceStates = {};\n\n      // Instance states (selected source) are stored by a custom storage key defined in the settings\n      if (this.settings.storageKey) {\n        $.extend(\n          this.instanceState,\n          Craft.getLocalStorage(this.settings.storageKey),\n          {}\n        );\n      }\n\n      // Source states (view mode, etc.) are stored by the element type and context\n      this.sourceStatesStorageKey =\n        'BaseElementIndex.' + this.elementType + '.' + this.settings.context;\n      $.extend(\n        this.sourceStates,\n        Craft.getLocalStorage(this.sourceStatesStorageKey, {})\n      );\n\n      // Find the DOM elements\n      // ---------------------------------------------------------------------\n\n      this.$main = this.$container.find('.main');\n      this.$toolbar = this.$container.find(this.settings.toolbarSelector);\n      this.$statusMenuBtn = this.$toolbar.find('.statusmenubtn:first');\n      this.$statusMenuContainer = this.$statusMenuBtn.parent();\n      this.$siteMenuBtn = this.$container.find('.sitemenubtn:first');\n      this.$sortMenuBtn = this.$toolbar.find('.sortmenubtn:first');\n      this.$search = this.$toolbar.find('.search:first input:first');\n      this.$clearSearchBtn = this.$toolbar.find('.search:first > .clear');\n      this.$sidebar = this.$container.find('.sidebar:first');\n      this.$customizeSourcesBtn = this.$sidebar.find('.customize-sources');\n      this.$elements = this.$container.find('.elements:first');\n      this.$countSpinner = this.$container.find('#count-spinner');\n      this.$countContainer = this.$container.find('#count-container');\n      this.$exportBtn = this.$container.find('#export-btn');\n\n      // Hide sidebar if needed\n      if (this.settings.hideSidebar) {\n        this.$sidebar.hide();\n        $('.body, .content', this.$container).removeClass('has-sidebar');\n      }\n\n      // Initialize the sources\n      // ---------------------------------------------------------------------\n\n      if (!this.initSources()) {\n        return;\n      }\n\n      // Customize button\n      if (this.$customizeSourcesBtn.length) {\n        this.addListener(\n          this.$customizeSourcesBtn,\n          'click',\n          'createCustomizeSourcesModal'\n        );\n      }\n\n      // Initialize the status menu\n      // ---------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        this.statusMenu = this.$statusMenuBtn.menubtn().data('menubtn').menu;\n        this.statusMenu.on('optionselect', this._handleStatusChange.bind(this));\n      }\n\n      // Initialize the site menu\n      // ---------------------------------------------------------------------\n\n      // Is there a site menu?\n      if (this.$siteMenuBtn.length) {\n        this.siteMenu = this.$siteMenuBtn.menubtn().data('menubtn').menu;\n\n        // Figure out the initial site\n        var $option = this.siteMenu.$options.filter('.sel:first');\n\n        if (!$option.length) {\n          $option = this.siteMenu.$options.first();\n        }\n\n        if ($option.length) {\n          this._setSite($option.data('site-id'));\n        } else {\n          // No site options -- they must not have any site permissions\n          this.settings.criteria = {id: '0'};\n        }\n\n        this.siteMenu.on('optionselect', this._handleSiteChange.bind(this));\n\n        if (this.siteId) {\n          // Should we be using a different default site?\n          var defaultSiteId =\n            this.settings.defaultSiteId || Craft.cp.getSiteId();\n\n          if (defaultSiteId && defaultSiteId != this.siteId) {\n            // Is that one available here?\n            var $storedSiteOption = this.siteMenu.$options.filter(\n              '[data-site-id=\"' + defaultSiteId + '\"]:first'\n            );\n\n            if ($storedSiteOption.length) {\n              // Todo: switch this to siteMenu.selectOption($storedSiteOption) once Menu is updated to support that\n              $storedSiteOption.trigger('click');\n            }\n          }\n        }\n      } else if (\n        this.settings.criteria &&\n        this.settings.criteria.siteId &&\n        this.settings.criteria.siteId !== '*'\n      ) {\n        this._setSite(this.settings.criteria.siteId);\n      } else {\n        this._setSite(Craft.siteId);\n      }\n\n      // Don't let the criteria override the selected site\n      if (this.settings.criteria && this.settings.criteria.siteId) {\n        delete this.settings.criteria.siteId;\n      }\n\n      // Initialize the search input\n      // ---------------------------------------------------------------------\n\n      // Automatically update the elements after new search text has been sitting for a 1/2 second\n      this.addListener(this.$search, 'input', () => {\n        if (!this.searching && this.$search.val()) {\n          this.startSearching();\n        } else if (this.searching && !this.$search.val()) {\n          this.stopSearching();\n        }\n\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(\n          this.updateElementsIfSearchTextChanged.bind(this),\n          500\n        );\n      });\n\n      // Update the elements when the Return key is pressed\n      this.addListener(this.$search, 'keypress', (ev) => {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n\n          if (this.searchTimeout) {\n            clearTimeout(this.searchTimeout);\n          }\n\n          this.updateElementsIfSearchTextChanged();\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearSearchBtn, 'click', () => {\n        this.clearSearch(true);\n\n        if (!Garnish.isMobileBrowser(true)) {\n          this.$search.trigger('focus');\n        }\n      });\n\n      // Auto-focus the Search box\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$search.trigger('focus');\n      }\n\n      // Initialize the sort menu\n      // ---------------------------------------------------------------------\n\n      // Is there a sort menu?\n      if (this.$sortMenuBtn.length) {\n        this.sortMenu = this.$sortMenuBtn.menubtn().data('menubtn').menu;\n        this.$sortAttributesList =\n          this.sortMenu.$container.children('.sort-attributes');\n        this.$sortDirectionsList =\n          this.sortMenu.$container.children('.sort-directions');\n\n        this.sortMenu.on('optionselect', this._handleSortChange.bind(this));\n      }\n\n      // Initialize the Export button\n      // ---------------------------------------------------------------------\n\n      this.addListener(this.$exportBtn, 'click', '_showExportHud');\n\n      // Let everyone know that the UI is initialized\n      // ---------------------------------------------------------------------\n\n      this.initialized = true;\n      this.afterInit();\n\n      // Select the initial source\n      // ---------------------------------------------------------------------\n\n      this.selectDefaultSource();\n\n      // Load the first batch of elements!\n      // ---------------------------------------------------------------------\n\n      // Default to whatever page is in the URL\n      this.setPage(Craft.pageNum);\n\n      this.updateElements(true);\n    },\n\n    afterInit: function () {\n      this.onAfterInit();\n    },\n\n    _createCancelToken: function () {\n      this._cancelToken = axios.CancelToken.source();\n      return this._cancelToken.token;\n    },\n\n    _cancelRequests: function () {\n      if (this._cancelToken) {\n        this._ignoreFailedRequest = true;\n        this._cancelToken.cancel();\n        Garnish.requestAnimationFrame(() => {\n          this._ignoreFailedRequest = false;\n        });\n      }\n    },\n\n    getSourceContainer: function () {\n      return this.$sidebar.find('nav > ul');\n    },\n\n    get $sources() {\n      if (!this.sourceSelect) {\n        return undefined;\n      }\n\n      return this.sourceSelect.$items;\n    },\n\n    getSite: function () {\n      if (!this.siteId) {\n        return undefined;\n      }\n      return Craft.sites.find((s) => s.id == this.siteId);\n    },\n\n    initSources: function () {\n      var $sources = this._getSourcesInList(this.getSourceContainer());\n\n      // No source, no party.\n      if ($sources.length === 0) {\n        return false;\n      }\n\n      // The source selector\n      if (!this.sourceSelect) {\n        this.sourceSelect = new Garnish.Select(this.$sidebar.find('nav'), {\n          multi: false,\n          allowEmpty: false,\n          vertical: true,\n          onSelectionChange: this._handleSourceSelectionChange.bind(this),\n        });\n      }\n\n      this.sourcesByKey = {};\n\n      for (let i = 0; i < $sources.length; i++) {\n        this.initSource($($sources[i]));\n      }\n\n      return true;\n    },\n\n    selectDefaultSource: function () {\n      var sourceKey = this.getDefaultSourceKey(),\n        $source;\n\n      if (sourceKey) {\n        $source = this.getSourceByKey(sourceKey);\n\n        // Make sure it's visible\n        if (this.$visibleSources.index($source) === -1) {\n          $source = null;\n        }\n      }\n\n      if (!sourceKey || !$source) {\n        // Select the first source by default\n        $source = this.$visibleSources.first();\n      }\n\n      return this.selectSource($source);\n    },\n\n    refreshSources: function () {\n      this.sourceSelect.removeAllItems();\n\n      this.setIndexBusy();\n\n      Craft.sendActionRequest('POST', this.settings.refreshSourcesAction, {\n        data: {\n          context: this.settings.context,\n          elementType: this.elementType,\n        },\n      })\n        .then((response) => {\n          this.setIndexAvailable();\n          this.getSourceContainer().replaceWith(response.data.html);\n          this.initSources();\n          this.selectDefaultSource();\n        })\n        .catch(() => {\n          this.setIndexAvailable();\n          if (!this._ignoreFailedRequest) {\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          }\n        });\n    },\n\n    initSource: function ($source) {\n      this.sourceSelect.addItems($source);\n      this.initSourceToggle($source);\n      this.sourcesByKey[$source.data('key')] = $source;\n\n      if (\n        $source.data('hasNestedSources') &&\n        this.instanceState.expandedSources.indexOf($source.data('key')) !== -1\n      ) {\n        this._expandSource($source);\n      }\n    },\n\n    initSourceToggle: function ($source) {\n      // Remove handlers for the same thing. Just in case.\n      this.deinitSourceToggle($source);\n\n      var $toggle = this._getSourceToggle($source);\n\n      if ($toggle.length) {\n        this.addListener($source, 'dblclick', '_handleSourceDblClick');\n        this.addListener($toggle, 'click', '_handleSourceToggleClick');\n        $source.data('hasNestedSources', true);\n      } else {\n        $source.data('hasNestedSources', false);\n      }\n    },\n\n    deinitSource: function ($source) {\n      this.sourceSelect.removeItems($source);\n      this.deinitSourceToggle($source);\n      delete this.sourcesByKey[$source.data('key')];\n    },\n\n    deinitSourceToggle: function ($source) {\n      if ($source.data('hasNestedSources')) {\n        this.removeListener($source, 'dblclick');\n        this.removeListener(this._getSourceToggle($source), 'click');\n      }\n\n      $source.removeData('hasNestedSources');\n    },\n\n    getDefaultInstanceState: function () {\n      return {\n        selectedSource: null,\n        expandedSources: [],\n      };\n    },\n\n    getDefaultSourceKey: function () {\n      if (this.settings.defaultSource) {\n        var paths = this.settings.defaultSource.split('/'),\n          path = '';\n\n        // Expand the tree\n        for (var i = 0; i < paths.length; i++) {\n          path += paths[i];\n          var $source = this.getSourceByKey(path);\n\n          // If the folder can't be found, then just go to the stored instance source.\n          if (!$source) {\n            return this.instanceState.selectedSource;\n          }\n\n          this._expandSource($source);\n          path += '/';\n        }\n\n        // Just make sure that the modal is aware of the newly expanded sources, too.\n        this._setSite(this.siteId);\n\n        return this.settings.defaultSource;\n      }\n\n      return this.instanceState.selectedSource;\n    },\n\n    getDefaultExpandedSources: function () {\n      return this.instanceState.expandedSources;\n    },\n\n    startSearching: function () {\n      // Show the clear button and add/select the Score sort option\n      this.$clearSearchBtn.removeClass('hidden');\n\n      if (!this.$scoreSortAttribute) {\n        this.$scoreSortAttribute = $(\n          '<li><a data-attr=\"score\">' + Craft.t('app', 'Score') + '</a></li>'\n        );\n        this.sortMenu.addOptions(this.$scoreSortAttribute.children());\n      }\n\n      this.$scoreSortAttribute.prependTo(this.$sortAttributesList);\n\n      this.searching = true;\n\n      this._updateStructureSortOption();\n      this.setSortAttribute('score');\n    },\n\n    clearSearch: function (updateElements) {\n      if (!this.searching) {\n        return;\n      }\n\n      this.$search.val('');\n\n      if (this.searchTimeout) {\n        clearTimeout(this.searchTimeout);\n      }\n\n      this.stopSearching();\n\n      if (updateElements) {\n        this.updateElementsIfSearchTextChanged();\n      } else {\n        this.searchText = null;\n      }\n    },\n\n    stopSearching: function () {\n      // Hide the clear button and Score sort option\n      this.$clearSearchBtn.addClass('hidden');\n\n      this.$scoreSortAttribute.detach();\n\n      this.searching = false;\n\n      this._updateStructureSortOption();\n    },\n\n    setInstanceState: function (key, value) {\n      if (typeof key === 'object') {\n        $.extend(this.instanceState, key);\n      } else {\n        this.instanceState[key] = value;\n      }\n\n      this.storeInstanceState();\n    },\n\n    storeInstanceState: function () {\n      if (this.settings.storageKey) {\n        Craft.setLocalStorage(this.settings.storageKey, this.instanceState);\n      }\n    },\n\n    getSourceState: function (source, key, defaultValue) {\n      if (typeof this.sourceStates[source] === 'undefined') {\n        // Set it now so any modifications to it by whoever's calling this will be stored.\n        this.sourceStates[source] = {};\n      }\n\n      if (typeof key === 'undefined') {\n        return this.sourceStates[source];\n      } else if (typeof this.sourceStates[source][key] !== 'undefined') {\n        return this.sourceStates[source][key];\n      } else {\n        return typeof defaultValue !== 'undefined' ? defaultValue : null;\n      }\n    },\n\n    getSelectedSourceState: function (key, defaultValue) {\n      return this.getSourceState(\n        this.instanceState.selectedSource,\n        key,\n        defaultValue\n      );\n    },\n\n    setSelecetedSourceState: function (key, value) {\n      var viewState = this.getSelectedSourceState();\n\n      if (typeof key === 'object') {\n        $.extend(viewState, key);\n      } else {\n        viewState[key] = value;\n      }\n\n      this.sourceStates[this.instanceState.selectedSource] = viewState;\n\n      // Store it in localStorage too\n      Craft.setLocalStorage(this.sourceStatesStorageKey, this.sourceStates);\n    },\n\n    storeSortAttributeAndDirection: function () {\n      const attr = this.getSelectedSortAttribute();\n\n      if (attr !== 'score') {\n        const history = [];\n\n        if (attr) {\n          // Remember the previous choices\n          const attributes = [attr];\n\n          // Only include the most last attribute if it changed\n          const lastAttr = this.getSelectedSourceState('order');\n          if (lastAttr && lastAttr !== attr) {\n            history.push([lastAttr, this.getSelectedSourceState('sort')]);\n            attributes.push(lastAttr);\n          }\n\n          const oldHistory = this.getSelectedSourceState('orderHistory', []);\n          for (let i = 0; i < oldHistory.length; i++) {\n            const [a] = oldHistory[i];\n            if (a && !attributes.includes(a)) {\n              history.push(oldHistory[i]);\n              attributes.push(a);\n            } else {\n              break;\n            }\n          }\n        }\n\n        this.setSelecetedSourceState({\n          order: attr,\n          sort: this.getSelectedSortDirection(),\n          orderHistory: history,\n        });\n      }\n    },\n\n    /**\n     * Sets the page number.\n     */\n    setPage: function (page) {\n      if (this.settings.context !== 'index') {\n        return;\n      }\n\n      page = Math.max(page, 1);\n      this.page = page;\n\n      // Update the URL\n      var url = document.location.href\n        .replace(/\\?.*$/, '')\n        .replace(\n          new RegExp(\n            '/' +\n              Craft.pageTrigger.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') +\n              '\\\\d+$'\n          ),\n          ''\n        )\n        .replace(/\\/+$/, '');\n\n      if (this.page !== 1) {\n        if (Craft.pageTrigger[0] !== '?') {\n          url += '/';\n        }\n        url += Craft.pageTrigger + this.page;\n      }\n\n      history.replaceState({}, '', url);\n    },\n\n    _resetCount: function () {\n      this.resultSet = null;\n      this.totalResults = null;\n    },\n\n    /**\n     * Returns the data that should be passed to the elementIndex/getElements controller action\n     * when loading elements.\n     */\n    getViewParams: function () {\n      var criteria = {\n        siteId: this.siteId,\n        search: this.searchText,\n        offset: this.settings.batchSize * (this.page - 1),\n        limit: this.settings.batchSize,\n      };\n\n      // Only set drafts/draftOf/trashed params when needed, so we don't potentially override a source's criteria\n      if (\n        this.settings.canHaveDrafts &&\n        (this.drafts || (this.settings.context === 'index' && !this.status))\n      ) {\n        criteria.drafts = this.drafts || null;\n        criteria.savedDraftsOnly = true;\n        if (!this.drafts) {\n          criteria.draftOf = false;\n        }\n      }\n      if (this.trashed) {\n        criteria.trashed = true;\n      }\n\n      if (!Garnish.hasAttr(this.$source, 'data-override-status')) {\n        criteria.status = this.status;\n      }\n\n      $.extend(criteria, this.settings.criteria);\n\n      var params = {\n        context: this.settings.context,\n        elementType: this.elementType,\n        source: this.instanceState.selectedSource,\n        criteria: criteria,\n        disabledElementIds: this.settings.disabledElementIds,\n        viewState: $.extend({}, this.getSelectedSourceState()),\n        paginated: this._isViewPaginated() ? 1 : 0,\n      };\n\n      // Possible that the order/sort isn't entirely accurate if we're sorting by Score\n      params.viewState.order = this.getSelectedSortAttribute();\n      params.viewState.sort = this.getSelectedSortDirection();\n\n      if (this.getSelectedSortAttribute() === 'structure') {\n        if (typeof this.instanceState.collapsedElementIds === 'undefined') {\n          this.instanceState.collapsedElementIds = [];\n        }\n        params.collapsedElementIds = this.instanceState.collapsedElementIds;\n      }\n\n      // Give plugins a chance to hook in here\n      this.trigger('registerViewParams', {\n        params: params,\n      });\n\n      return params;\n    },\n\n    updateElements: function (preservePagination) {\n      // Ignore if we're not fully initialized yet\n      if (!this.initialized) {\n        return;\n      }\n\n      // Cancel any ongoing requests\n      this._cancelRequests();\n\n      this.setIndexBusy();\n\n      // Kill the old view class\n      if (this.view) {\n        this.view.destroy();\n        delete this.view;\n      }\n\n      if (preservePagination !== true) {\n        this.setPage(1);\n        this._resetCount();\n      }\n\n      var params = this.getViewParams();\n\n      Craft.sendActionRequest('POST', this.settings.updateElementsAction, {\n        data: params,\n        cancelToken: this._createCancelToken(),\n      })\n        .then((response) => {\n          this.setIndexAvailable();\n          (this.settings.context === 'index'\n            ? Garnish.$scrollContainer\n            : this.$main\n          ).scrollTop(0);\n          this._updateView(params, response.data);\n        })\n        .catch((e) => {\n          this.setIndexAvailable();\n          if (!this._ignoreFailedRequest) {\n            Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n          }\n        });\n    },\n\n    updateElementsIfSearchTextChanged: function () {\n      if (\n        this.searchText !==\n        (this.searchText = this.searching ? this.$search.val() : null)\n      ) {\n        this.updateElements();\n      }\n    },\n\n    showActionTriggers: function () {\n      // Ignore if they're already shown\n      if (this.showingActionTriggers) {\n        return;\n      }\n\n      // Hard-code the min toolbar height in case it was taller than the actions toolbar\n      // (prevents the elements from jumping if this ends up being a double-click)\n      this.$toolbar.css('min-height', this.$toolbar.height());\n\n      // Hide any toolbar inputs\n      this._$detachedToolbarItems = this.$toolbar.children();\n      this._$detachedToolbarItems.detach();\n\n      if (!this._$triggers) {\n        this._createTriggers();\n      } else {\n        this._$triggers.appendTo(this.$toolbar);\n      }\n\n      this.showingActionTriggers = true;\n    },\n\n    submitAction: function (action, actionParams) {\n      // Make sure something's selected\n      var selectedElementIds = this.view.getSelectedElementIds(),\n        totalSelected = selectedElementIds.length;\n\n      if (totalSelected === 0) {\n        return;\n      }\n\n      if (typeof action === 'string') {\n        action = this._findAction(action);\n      }\n\n      if (action.confirm && !confirm(action.confirm)) {\n        return;\n      }\n\n      // Cancel any ongoing requests\n      this._cancelRequests();\n\n      // Get ready to submit\n      var viewParams = this.getViewParams();\n\n      actionParams = actionParams ? Craft.expandPostArray(actionParams) : {};\n      var params = $.extend(viewParams, action.settings || {}, actionParams, {\n        elementAction: action.type,\n        elementIds: selectedElementIds,\n      });\n\n      // Do it\n      this.setIndexBusy();\n      this._autoSelectElements = selectedElementIds;\n\n      if (action.download) {\n        if (Craft.csrfTokenName) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl(this.settings.submitActionsAction),\n          params\n        )\n          .then((response) => {\n            this.setIndexAvailable();\n          })\n          .catch((e) => {\n            this.setIndexAvailable();\n          });\n      } else {\n        Craft.sendActionRequest('POST', this.settings.submitActionsAction, {\n          data: params,\n          cancelToken: this._createCancelToken(),\n        })\n          .then((response) => {\n            this.setIndexAvailable();\n            if (response.data.success) {\n              // Update the count text too\n              this._resetCount();\n              this._updateView(viewParams, response.data);\n\n              if (typeof response.data.badgeCounts !== 'undefined') {\n                this._updateBadgeCounts(response.data.badgeCounts);\n              }\n\n              if (response.data.message) {\n                Craft.cp.displayNotice(response.data.message);\n              }\n\n              this.afterAction(action, params);\n            } else {\n              Craft.cp.displayError(response.data.message);\n            }\n          })\n          .catch(() => {\n            this.setIndexAvailable();\n          });\n      }\n    },\n\n    _findAction: function (actionClass) {\n      for (var i = 0; i < this.actions.length; i++) {\n        if (this.actions[i].type === actionClass) {\n          return this.actions[i];\n        }\n      }\n      throw `Invalid element action: ${actionClass}`;\n    },\n\n    afterAction: function (action, params) {\n      // There may be a new background job that needs to be run\n      Craft.cp.runQueue();\n\n      this.onAfterAction(action, params);\n    },\n\n    hideActionTriggers: function () {\n      // Ignore if there aren't any\n      if (!this.showingActionTriggers) {\n        return;\n      }\n\n      this._$detachedToolbarItems.appendTo(this.$toolbar);\n      this._$triggers.detach();\n      // this._$detachedToolbarItems.removeClass('hidden');\n\n      // Unset the min toolbar height\n      this.$toolbar.css('min-height', '');\n\n      this.showingActionTriggers = false;\n    },\n\n    updateActionTriggers: function () {\n      // Do we have an action UI to update?\n      if (this.actions) {\n        var totalSelected = this.view.getSelectedElements().length;\n\n        if (totalSelected !== 0) {\n          if (totalSelected === this.view.getEnabledElements().length) {\n            this.$selectAllCheckbox.removeClass('indeterminate');\n            this.$selectAllCheckbox.addClass('checked');\n            this.$selectAllContainer.attr('aria-checked', 'true');\n          } else {\n            this.$selectAllCheckbox.addClass('indeterminate');\n            this.$selectAllCheckbox.removeClass('checked');\n            this.$selectAllContainer.attr('aria-checked', 'mixed');\n          }\n\n          this.showActionTriggers();\n        } else {\n          this.$selectAllCheckbox.removeClass('indeterminate checked');\n          this.$selectAllContainer.attr('aria-checked', 'false');\n          this.hideActionTriggers();\n        }\n      }\n    },\n\n    getSelectedElements: function () {\n      return this.view ? this.view.getSelectedElements() : $();\n    },\n\n    getSelectedElementIds: function () {\n      return this.view ? this.view.getSelectedElementIds() : [];\n    },\n\n    setStatus: function (status) {\n      // Find the option (and make sure it actually exists)\n      var $option = this.statusMenu.$options.filter(\n        'a[data-status=\"' + status + '\"]:first'\n      );\n\n      if ($option.length) {\n        this.statusMenu.selectOption($option[0]);\n      }\n    },\n\n    getSortAttributeOption: function (attr) {\n      return this.$sortAttributesList.find('a[data-attr=\"' + attr + '\"]:first');\n    },\n\n    getSelectedSortAttribute: function () {\n      return this.$sortAttributesList.find('a.sel:first').data('attr');\n    },\n\n    setSortAttribute: function (attr) {\n      // Find the option (and make sure it actually exists)\n      var $option = this.getSortAttributeOption(attr);\n\n      if ($option.length) {\n        this.$sortAttributesList.find('a.sel').removeClass('sel');\n        $option.addClass('sel');\n\n        var label = $option.text();\n        this.$sortMenuBtn.attr(\n          'title',\n          Craft.t('app', 'Sort by {attribute}', {attribute: label})\n        );\n        this.$sortMenuBtn.text(label);\n\n        if (attr === 'score') {\n          this.setSortDirection('desc');\n        } else {\n          this.setSortDirection($option.data('default-dir') || 'asc');\n        }\n\n        if (attr === 'structure') {\n          this.$sortDirectionsList.find('a').addClass('disabled');\n        } else {\n          this.$sortDirectionsList.find('a').removeClass('disabled');\n        }\n      }\n    },\n\n    getSortDirectionOption: function (dir) {\n      return this.$sortDirectionsList.find('a[data-dir=' + dir + ']:first');\n    },\n\n    getSelectedSortDirection: function () {\n      return this.$sortDirectionsList.find('a.sel:first').data('dir');\n    },\n\n    getSelectedViewMode: function () {\n      return this.getSelectedSourceState('mode') || 'table';\n    },\n\n    setSortDirection: function (dir) {\n      if (dir !== 'desc') {\n        dir = 'asc';\n      }\n\n      this.$sortMenuBtn.attr('data-icon', dir);\n      this.$sortDirectionsList.find('a.sel').removeClass('sel');\n      this.getSortDirectionOption(dir).addClass('sel');\n    },\n\n    getSourceByKey: function (key) {\n      if (typeof this.sourcesByKey[key] === 'undefined') {\n        return null;\n      }\n\n      return this.sourcesByKey[key];\n    },\n\n    selectSource: function ($source) {\n      if (!$source || !$source.length) {\n        return false;\n      }\n\n      if (\n        this.$source &&\n        this.$source[0] &&\n        this.$source[0] === $source[0] &&\n        $source.data('key') === this.sourceKey\n      ) {\n        return false;\n      }\n\n      // Hide action triggers if they're currently being shown\n      this.hideActionTriggers();\n\n      this.$source = $source;\n      this.sourceKey = $source.data('key');\n      this.setInstanceState('selectedSource', this.sourceKey);\n      this.sourceSelect.selectItem($source);\n\n      Craft.cp.updateSidebarMenuLabel();\n\n      if (this.searching) {\n        // Clear the search value without causing it to update elements\n        this.searchText = null;\n        this.$search.val('');\n        this.stopSearching();\n      }\n\n      // Sort menu\n      // ----------------------------------------------------------------------\n\n      // Remove any existing custom sort options from the menu\n      this.$sortAttributesList.children('li[data-extra]').remove();\n\n      // Does this source have any custom sort options?\n      let $topSource = this.$source.closest('nav > ul > li').children('a');\n      let sortOptions = $topSource.data('sort-options');\n      if (sortOptions) {\n        for (let i = 0; i < sortOptions.length; i++) {\n          let $option = $('<li/>', {\n            'data-extra': true,\n          })\n            .append(\n              $('<a/>', {\n                text: sortOptions[i][0],\n                'data-attr': sortOptions[i][1],\n              })\n            )\n            .appendTo(this.$sortAttributesList);\n          this.sortMenu.addOptions($option.children());\n        }\n      }\n\n      // Does this source have a structure?\n      if (Garnish.hasAttr(this.$source, 'data-has-structure')) {\n        if (!this.$structureSortAttribute) {\n          this.$structureSortAttribute = $(\n            '<li><a data-attr=\"structure\">' +\n              Craft.t('app', 'Structure') +\n              '</a></li>'\n          );\n          this.sortMenu.addOptions(this.$structureSortAttribute.children());\n        }\n\n        this.$structureSortAttribute.prependTo(this.$sortAttributesList);\n      } else if (this.$structureSortAttribute) {\n        this.$structureSortAttribute.removeClass('sel').detach();\n      }\n\n      this.setStoredSortOptionsForSource();\n\n      // Status menu\n      // ----------------------------------------------------------------------\n\n      if (this.$statusMenuBtn.length) {\n        if (Garnish.hasAttr(this.$source, 'data-override-status')) {\n          this.$statusMenuContainer.addClass('hidden');\n        } else {\n          this.$statusMenuContainer.removeClass('hidden');\n        }\n\n        if (this.trashed) {\n          // Swap to the initial status\n          var $firstOption = this.statusMenu.$options.first();\n          this.setStatus($firstOption.data('status'));\n        }\n      }\n\n      // View mode buttons\n      // ----------------------------------------------------------------------\n\n      // Clear out any previous view mode data\n      if (this.$viewModeBtnContainer) {\n        this.$viewModeBtnContainer.remove();\n      }\n\n      this.viewModeBtns = {};\n      this.viewMode = null;\n\n      // Get the new list of view modes\n      this.sourceViewModes = this.getViewModesForSource();\n\n      // Create the buttons if there's more than one mode available to this source\n      if (this.sourceViewModes.length > 1) {\n        this.$viewModeBtnContainer = $('<div class=\"btngroup\"/>').appendTo(\n          this.$toolbar\n        );\n\n        for (var i = 0; i < this.sourceViewModes.length; i++) {\n          let sourceViewMode = this.sourceViewModes[i];\n\n          let $viewModeBtn = $('<button/>', {\n            type: 'button',\n            class:\n              'btn' +\n              (typeof sourceViewMode.className !== 'undefined'\n                ? ` ${sourceViewMode.className}`\n                : ''),\n            'data-view': sourceViewMode.mode,\n            'data-icon': sourceViewMode.icon,\n            'aria-label': sourceViewMode.title,\n            title: sourceViewMode.title,\n          }).appendTo(this.$viewModeBtnContainer);\n\n          this.viewModeBtns[sourceViewMode.mode] = $viewModeBtn;\n\n          this.addListener(\n            $viewModeBtn,\n            'click',\n            {mode: sourceViewMode.mode},\n            function (ev) {\n              this.selectViewMode(ev.data.mode);\n              this.updateElements();\n            }\n          );\n        }\n      }\n\n      // Figure out which mode we should start with\n      var viewMode = this.getSelectedViewMode();\n\n      if (!viewMode || !this.doesSourceHaveViewMode(viewMode)) {\n        // Try to keep using the current view mode\n        if (this.viewMode && this.doesSourceHaveViewMode(this.viewMode)) {\n          viewMode = this.viewMode;\n        }\n        // Just use the first one\n        else {\n          viewMode = this.sourceViewModes[0].mode;\n        }\n      }\n\n      this.selectViewMode(viewMode);\n\n      this.onSelectSource();\n\n      return true;\n    },\n\n    selectSourceByKey: function (key) {\n      var $source = this.getSourceByKey(key);\n\n      if ($source) {\n        return this.selectSource($source);\n      } else {\n        return false;\n      }\n    },\n\n    setStoredSortOptionsForSource: function () {\n      var sortAttr = this.getSelectedSourceState('order'),\n        sortDir = this.getSelectedSourceState('sort');\n\n      if (!sortAttr || !sortDir) {\n        // Get the default\n        sortAttr = this.getDefaultSort();\n\n        if (Garnish.isArray(sortAttr)) {\n          sortDir = sortAttr[1];\n          sortAttr = sortAttr[0];\n        }\n      }\n\n      if (sortDir !== 'asc' && sortDir !== 'desc') {\n        sortDir = 'asc';\n      }\n\n      this.setSortAttribute(sortAttr);\n      this.setSortDirection(sortDir);\n    },\n\n    getDefaultSort: function () {\n      // Does the source specify what to do?\n      if (this.$source && Garnish.hasAttr(this.$source, 'data-default-sort')) {\n        return this.$source.attr('data-default-sort').split(':');\n      } else {\n        // Default to whatever's first\n        return [this.$sortAttributesList.find('a:first').data('attr'), 'asc'];\n      }\n    },\n\n    getViewModesForSource: function () {\n      var viewModes = [\n        {\n          mode: 'table',\n          title: Craft.t('app', 'Display in a table'),\n          icon: 'list',\n        },\n      ];\n\n      if (this.$source && Garnish.hasAttr(this.$source, 'data-has-thumbs')) {\n        viewModes.push({\n          mode: 'thumbs',\n          title: Craft.t('app', 'Display as thumbnails'),\n          icon: 'grid',\n        });\n      }\n\n      return viewModes;\n    },\n\n    doesSourceHaveViewMode: function (viewMode) {\n      for (var i = 0; i < this.sourceViewModes.length; i++) {\n        if (this.sourceViewModes[i].mode === viewMode) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    selectViewMode: function (viewMode, force) {\n      // Make sure that the current source supports it\n      if (!force && !this.doesSourceHaveViewMode(viewMode)) {\n        viewMode = this.sourceViewModes[0].mode;\n      }\n\n      // Has anything changed?\n      if (viewMode === this.viewMode) {\n        return;\n      }\n\n      // Deselect the previous view mode\n      if (\n        this.viewMode &&\n        typeof this.viewModeBtns[this.viewMode] !== 'undefined'\n      ) {\n        this.viewModeBtns[this.viewMode].removeClass('active');\n      }\n\n      this.viewMode = viewMode;\n      this.setSelecetedSourceState('mode', this.viewMode);\n\n      if (typeof this.viewModeBtns[this.viewMode] !== 'undefined') {\n        this.viewModeBtns[this.viewMode].addClass('active');\n      }\n    },\n\n    createView: function (mode, settings) {\n      var viewClass = this.getViewClass(mode);\n      return new viewClass(this, this.$elements, settings);\n    },\n\n    getViewClass: function (mode) {\n      switch (mode) {\n        case 'table':\n          return Craft.TableElementIndexView;\n        case 'thumbs':\n          return Craft.ThumbsElementIndexView;\n        default:\n          throw `View mode \"${mode}\" not supported.`;\n      }\n    },\n\n    rememberDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index === -1) {\n        this.settings.disabledElementIds.push(id);\n      }\n    },\n\n    forgetDisabledElementId: function (id) {\n      var index = $.inArray(id, this.settings.disabledElementIds);\n\n      if (index !== -1) {\n        this.settings.disabledElementIds.splice(index, 1);\n      }\n    },\n\n    enableElements: function ($elements) {\n      $elements\n        .removeClass('disabled')\n        .parents('.disabled')\n        .removeClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.forgetDisabledElementId(id);\n      }\n\n      this.onEnableElements($elements);\n    },\n\n    disableElements: function ($elements) {\n      $elements.removeClass('sel').addClass('disabled');\n\n      for (var i = 0; i < $elements.length; i++) {\n        var id = $($elements[i]).data('id');\n        this.rememberDisabledElementId(id);\n      }\n\n      this.onDisableElements($elements);\n    },\n\n    getElementById: function (id) {\n      return this.view.getElementById(id);\n    },\n\n    enableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.enableElements($element);\n        } else {\n          this.forgetDisabledElementId(id);\n        }\n      }\n    },\n\n    disableElementsById: function (ids) {\n      ids = $.makeArray(ids);\n\n      for (var i = 0; i < ids.length; i++) {\n        var id = ids[i],\n          $element = this.getElementById(id);\n\n        if ($element && $element.length) {\n          this.disableElements($element);\n        } else {\n          this.rememberDisabledElementId(id);\n        }\n      }\n    },\n\n    selectElementAfterUpdate: function (id) {\n      if (this._autoSelectElements === null) {\n        this._autoSelectElements = [];\n      }\n\n      this._autoSelectElements.push(id);\n    },\n\n    addButton: function ($button) {\n      this.getButtonContainer().append($button);\n    },\n\n    isShowingSidebar: function () {\n      if (this.showingSidebar === null) {\n        this.showingSidebar =\n          this.$sidebar.length && !this.$sidebar.hasClass('hidden');\n      }\n\n      return this.showingSidebar;\n    },\n\n    getButtonContainer: function () {\n      // Is there a predesignated place where buttons should go?\n      if (this.settings.buttonContainer) {\n        return $(this.settings.buttonContainer);\n      } else {\n        var $container = $('#action-button');\n\n        if (!$container.length) {\n          $container = $('<div id=\"action-button\"/>').appendTo($('#header'));\n        }\n\n        return $container;\n      }\n    },\n\n    setIndexBusy: function () {\n      this.$elements.addClass('busy');\n      this.isIndexBusy = true;\n    },\n\n    setIndexAvailable: function () {\n      this.$elements.removeClass('busy');\n      this.isIndexBusy = false;\n    },\n\n    createCustomizeSourcesModal: function () {\n      // Recreate it each time\n      var modal = new Craft.CustomizeSourcesModal(this, {\n        onHide: function () {\n          modal.destroy();\n        },\n      });\n\n      return modal;\n    },\n\n    disable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.disable();\n      }\n\n      if (this.view) {\n        this.view.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.sourceSelect) {\n        this.sourceSelect.enable();\n      }\n\n      if (this.view) {\n        this.view.enable();\n      }\n\n      this.base();\n    },\n\n    onAfterInit: function () {\n      this.settings.onAfterInit();\n      this.trigger('afterInit');\n    },\n\n    onSelectSource: function () {\n      this.settings.onSelectSource(this.sourceKey);\n      this.trigger('selectSource', {sourceKey: this.sourceKey});\n    },\n\n    onSelectSite: function () {\n      this.settings.onSelectSite(this.siteId);\n      this.trigger('selectSite', {siteId: this.siteId});\n    },\n\n    onUpdateElements: function () {\n      this.settings.onUpdateElements();\n      this.trigger('updateElements');\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n    },\n\n    onEnableElements: function ($elements) {\n      this.settings.onEnableElements($elements);\n      this.trigger('enableElements', {elements: $elements});\n    },\n\n    onDisableElements: function ($elements) {\n      this.settings.onDisableElements($elements);\n      this.trigger('disableElements', {elements: $elements});\n    },\n\n    onAfterAction: function (action, params) {\n      this.settings.onAfterAction(action, params);\n      this.trigger('afterAction', {action: action, params: params});\n    },\n\n    // UI state handlers\n    // -------------------------------------------------------------------------\n\n    _handleSourceSelectionChange: function () {\n      // If the selected source was just removed (maybe because its parent was collapsed),\n      // there won't be a selected source\n      if (!this.sourceSelect.totalSelected) {\n        this.sourceSelect.selectItem(this.$visibleSources.first());\n        return;\n      }\n\n      if (this.selectSource(this.sourceSelect.$selectedItems)) {\n        this.updateElements();\n      }\n    },\n\n    _handleActionTriggerSubmit: function (ev) {\n      ev.preventDefault();\n\n      var $form = $(ev.currentTarget);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($form.hasClass('disabled') || $form.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($form.data('action'), Garnish.getPostData($form));\n    },\n\n    _handleMenuActionTriggerSubmit: function (ev) {\n      var $option = $(ev.option);\n\n      // Make sure Craft.ElementActionTrigger isn't overriding this\n      if ($option.hasClass('disabled') || $option.data('custom-handler')) {\n        return;\n      }\n\n      this.submitAction($option.data('action'));\n    },\n\n    _handleStatusChange: function (ev) {\n      this.statusMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$statusMenuBtn.html($option.html());\n\n      this.trashed = false;\n      this.drafts = false;\n      this.status = null;\n\n      if (Garnish.hasAttr($option, 'data-trashed')) {\n        this.trashed = true;\n      } else if (Garnish.hasAttr($option, 'data-drafts')) {\n        this.drafts = true;\n      } else {\n        this.status = $option.data('status');\n      }\n\n      this._updateStructureSortOption();\n      this.updateElements();\n    },\n\n    _handleSiteChange: function (ev) {\n      this.siteMenu.$options.removeClass('sel');\n      var $option = $(ev.selectedOption).addClass('sel');\n      this.$siteMenuBtn.html($option.html());\n      this._setSite($option.data('site-id'));\n      this.onSelectSite();\n    },\n\n    _setSite: function (siteId) {\n      let firstSite = this.siteId === null;\n      this.siteId = siteId;\n      this.$visibleSources = $();\n\n      // Hide any sources that aren't available for this site\n      var $firstVisibleSource;\n      var $source;\n      // Select a new source automatically if a site is already selected, but we don't have a selected source\n      // (or if the currently selected source ends up not supporting the new site)\n      var selectNewSource =\n        !firstSite && (!this.$source || !this.$source.length);\n\n      for (var i = 0; i < this.$sources.length; i++) {\n        $source = this.$sources.eq(i);\n        if (\n          typeof $source.data('sites') === 'undefined' ||\n          $source\n            .data('sites')\n            .toString()\n            .split(',')\n            .indexOf(siteId.toString()) !== -1\n        ) {\n          $source.parent().removeClass('hidden');\n          this.$visibleSources = this.$visibleSources.add($source);\n          if (!$firstVisibleSource) {\n            $firstVisibleSource = $source;\n          }\n        } else {\n          $source.parent().addClass('hidden');\n\n          // Is this the currently selected source?\n          if (this.$source && this.$source.get(0) == $source.get(0)) {\n            selectNewSource = true;\n          }\n        }\n      }\n\n      if (this.initialized && selectNewSource) {\n        this.selectSource($firstVisibleSource);\n      }\n\n      // Hide any empty-nester headings\n      var $headings = this.getSourceContainer().children('.heading');\n      var $heading;\n\n      for (i = 0; i < $headings.length; i++) {\n        $heading = $headings.eq(i);\n        if ($heading.nextUntil('.heading', ':not(.hidden)').length !== 0) {\n          $heading.removeClass('hidden');\n        } else {\n          $heading.addClass('hidden');\n        }\n      }\n\n      if (this.initialized) {\n        if (this.settings.context === 'index') {\n          // Remember this site for later\n          Craft.cp.setSiteId(siteId);\n        }\n\n        // Update the elements\n        this.updateElements();\n      }\n    },\n\n    _handleSortChange: function (ev) {\n      var $option = $(ev.selectedOption);\n\n      if ($option.hasClass('disabled') || $option.hasClass('sel')) {\n        return;\n      }\n\n      // Is this an attribute or a direction?\n      if ($option.parent().parent().is(this.$sortAttributesList)) {\n        this.setSortAttribute($option.data('attr'));\n      } else {\n        this.setSortDirection($option.data('dir'));\n      }\n\n      this.storeSortAttributeAndDirection();\n      this.updateElements();\n    },\n\n    _handleSelectionChange: function () {\n      this.updateActionTriggers();\n      this.onSelectionChange();\n    },\n\n    _handleSourceDblClick: function (ev) {\n      this._toggleSource($(ev.currentTarget));\n      ev.stopPropagation();\n    },\n\n    _handleSourceToggleClick: function (ev) {\n      this._toggleSource($(ev.currentTarget).prev('a'));\n      ev.stopPropagation();\n    },\n\n    _updateStructureSortOption: function () {\n      var $option = this.getSortAttributeOption('structure');\n\n      if (!$option.length) {\n        return;\n      }\n\n      if (this.trashed || this.drafts || this.searching) {\n        $option.addClass('disabled');\n        if (this.getSelectedSortAttribute() === 'structure') {\n          // Temporarily set the sort to the first option\n          var $firstOption = this.$sortAttributesList.find(\n            'a:not(.disabled):first'\n          );\n          this.setSortAttribute($firstOption.data('attr'));\n          this.setSortDirection('asc');\n        }\n      } else {\n        $option.removeClass('disabled');\n        this.setStoredSortOptionsForSource();\n      }\n    },\n\n    // Source managemnet\n    // -------------------------------------------------------------------------\n\n    _getSourcesInList: function ($list) {\n      return $list.children('li').children('a');\n    },\n\n    _getChildSources: function ($source) {\n      var $list = $source.siblings('ul');\n      return this._getSourcesInList($list);\n    },\n\n    _getSourceToggle: function ($source) {\n      return $source.siblings('.toggle');\n    },\n\n    _toggleSource: function ($source) {\n      if ($source.parent('li').hasClass('expanded')) {\n        this._collapseSource($source);\n      } else {\n        this._expandSource($source);\n      }\n    },\n\n    _expandSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'true',\n        'aria-label': Craft.t('app', 'Hide nested sources'),\n      });\n      $source.parent('li').addClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.initSource($($childSources[i]));\n        if (this.$visibleSources) {\n          this.$visibleSources = this.$visibleSources.add($childSources[i]);\n        }\n      }\n\n      var key = $source.data('key');\n      if (this.instanceState.expandedSources.indexOf(key) === -1) {\n        this.instanceState.expandedSources.push(key);\n        this.storeInstanceState();\n      }\n    },\n\n    _collapseSource: function ($source) {\n      $source.next('.toggle').attr({\n        'aria-expanded': 'false',\n        'aria-label': Craft.t('app', 'Show nested sources'),\n      });\n      $source.parent('li').removeClass('expanded');\n\n      var $childSources = this._getChildSources($source);\n      for (let i = 0; i < $childSources.length; i++) {\n        this.deinitSource($($childSources[i]));\n        this.$visibleSources = this.$visibleSources.not($childSources[i]);\n      }\n\n      var i = this.instanceState.expandedSources.indexOf($source.data('key'));\n      if (i !== -1) {\n        this.instanceState.expandedSources.splice(i, 1);\n        this.storeInstanceState();\n      }\n    },\n\n    // View\n    // -------------------------------------------------------------------------\n\n    _isViewPaginated: function () {\n      return (\n        this.settings.context === 'index' &&\n        this.getSelectedSortAttribute() !== 'structure'\n      );\n    },\n\n    _updateView: function (params, response) {\n      // Cleanup\n      // -------------------------------------------------------------\n\n      // Get rid of the old action triggers regardless of whether the new batch has actions or not\n      if (this.actions) {\n        this.hideActionTriggers();\n        this.actions =\n          this.actionsHeadHtml =\n          this.actionsFootHtml =\n          this._$triggers =\n            null;\n      }\n\n      // Update the count text\n      // -------------------------------------------------------------\n\n      if (this.$countContainer.length) {\n        this.$countSpinner.removeClass('hidden');\n        this.$countContainer.html('');\n\n        this._countResults()\n          .then((total) => {\n            this.$countSpinner.addClass('hidden');\n\n            let itemLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][2]\n              : 'element';\n            let itemsLabel = Craft.elementTypeNames[this.elementType]\n              ? Craft.elementTypeNames[this.elementType][3]\n              : 'elements';\n\n            if (!this._isViewPaginated()) {\n              let countLabel = Craft.t(\n                'app',\n                '{total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n              this.$countContainer.text(countLabel);\n            } else {\n              let first = Math.min(\n                this.settings.batchSize * (this.page - 1) + 1,\n                total\n              );\n              let last = Math.min(first + (this.settings.batchSize - 1), total);\n              let countLabel = Craft.t(\n                'app',\n                '{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}',\n                {\n                  first: first,\n                  last: last,\n                  total: total,\n                  item: itemLabel,\n                  items: itemsLabel,\n                }\n              );\n\n              let $paginationContainer = $(\n                '<div class=\"flex pagination\"/>'\n              ).appendTo(this.$countContainer);\n              let totalPages = Math.max(\n                Math.ceil(total / this.settings.batchSize),\n                1\n              );\n\n              let $prevBtn = $('<div/>', {\n                class:\n                  'page-link prev-page' + (this.page > 1 ? '' : ' disabled'),\n                title: Craft.t('app', 'Previous Page'),\n              }).appendTo($paginationContainer);\n              let $nextBtn = $('<div/>', {\n                class:\n                  'page-link next-page' +\n                  (this.page < totalPages ? '' : ' disabled'),\n                title: Craft.t('app', 'Next Page'),\n              }).appendTo($paginationContainer);\n\n              $('<div/>', {\n                class: 'page-info',\n                text: countLabel,\n              }).appendTo($paginationContainer);\n\n              if (this.page > 1) {\n                this.addListener($prevBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page - 1);\n                  this.updateElements(true);\n                });\n              }\n\n              if (this.page < totalPages) {\n                this.addListener($nextBtn, 'click', function () {\n                  this.removeListener($prevBtn, 'click');\n                  this.removeListener($nextBtn, 'click');\n                  this.setPage(this.page + 1);\n                  this.updateElements(true);\n                });\n              }\n            }\n          })\n          .catch(() => {\n            this.$countSpinner.addClass('hidden');\n          });\n      }\n\n      // Update the view with the new container + elements HTML\n      // -------------------------------------------------------------\n\n      this.$elements.html(response.html);\n      Craft.appendHeadHtml(response.headHtml);\n      Craft.appendFootHtml(response.footHtml);\n\n      // Batch actions setup\n      // -------------------------------------------------------------\n\n      this.$selectAllContainer = this.$elements.find(\n        '.selectallcontainer:first'\n      );\n\n      if (response.actions && response.actions.length) {\n        if (this.$selectAllContainer.length) {\n          this.actions = response.actions;\n          this.actionsHeadHtml = response.actionsHeadHtml;\n          this.actionsFootHtml = response.actionsFootHtml;\n\n          // Create the select all checkbox\n          this.$selectAllCheckbox = $('<div class=\"checkbox\"/>').prependTo(\n            this.$selectAllContainer\n          );\n\n          this.$selectAllContainer.attr({\n            role: 'checkbox',\n            tabindex: '0',\n            'aria-checked': 'false',\n            'aria-label': Craft.t('app', 'Select all'),\n          });\n\n          this.addListener(this.$selectAllContainer, 'click', function () {\n            if (this.view.getSelectedElements().length === 0) {\n              this.view.selectAllElements();\n            } else {\n              this.view.deselectAllElements();\n            }\n          });\n\n          this.addListener(this.$selectAllContainer, 'keydown', function (ev) {\n            if (ev.keyCode === Garnish.SPACE_KEY) {\n              ev.preventDefault();\n\n              $(ev.currentTarget).trigger('click');\n            }\n          });\n        }\n      } else {\n        if (!this.$selectAllContainer.siblings().length) {\n          this.$selectAllContainer.parent('.header').remove();\n        }\n        this.$selectAllContainer.remove();\n      }\n\n      // Exporters setup\n      // -------------------------------------------------------------\n\n      this.exporters = response.exporters;\n      this.exportersByType = Craft.index(this.exporters || [], (e) => e.type);\n\n      if (this.exporters && this.exporters.length) {\n        this.$exportBtn.removeClass('hidden');\n      } else {\n        this.$exportBtn.addClass('hidden');\n      }\n\n      // Create the view\n      // -------------------------------------------------------------\n\n      // Should we make the view selectable?\n      var selectable = this.actions || this.settings.selectable;\n\n      this.view = this.createView(this.getSelectedViewMode(), {\n        context: this.settings.context,\n        batchSize:\n          this.settings.context !== 'index' ||\n          this.getSelectedSortAttribute() === 'structure'\n            ? this.settings.batchSize\n            : null,\n        params: params,\n        selectable: selectable,\n        multiSelect: this.actions || this.settings.multiSelect,\n        checkboxMode: !!this.actions,\n        onSelectionChange: this._handleSelectionChange.bind(this),\n      });\n\n      // Auto-select elements\n      // -------------------------------------------------------------\n\n      if (this._autoSelectElements) {\n        if (selectable) {\n          for (var i = 0; i < this._autoSelectElements.length; i++) {\n            this.view.selectElementById(this._autoSelectElements[i]);\n          }\n        }\n\n        this._autoSelectElements = null;\n      }\n\n      // Trigger the event\n      // -------------------------------------------------------------\n\n      this.onUpdateElements();\n    },\n\n    _updateBadgeCounts: function (badgeCounts) {\n      for (let sourceKey in badgeCounts) {\n        if (badgeCounts.hasOwnProperty(sourceKey)) {\n          const $source = this.getSourceByKey(sourceKey);\n          if ($source) {\n            let $badge = $source.children('.badge');\n            if (badgeCounts[sourceKey] !== null) {\n              if (!$badge.length) {\n                $badge = $('<span class=\"badge\"/>').appendTo($source);\n              }\n              $badge.text(badgeCounts[sourceKey]);\n            } else if ($badge) {\n              $badge.remove();\n            }\n          }\n        }\n      }\n    },\n\n    _countResults: function () {\n      return new Promise((resolve, reject) => {\n        if (this.totalResults !== null) {\n          resolve(this.totalResults);\n        } else {\n          var params = this.getViewParams();\n          delete params.criteria.offset;\n          delete params.criteria.limit;\n\n          // Make sure we've got an active result set ID\n          if (this.resultSet === null) {\n            this.resultSet = Math.floor(Math.random() * 100000000);\n          }\n          params.resultSet = this.resultSet;\n\n          Craft.sendActionRequest('POST', this.settings.countElementsAction, {\n            data: params,\n            cancelToken: this._createCancelToken(),\n          })\n            .then((response) => {\n              if (response.data.resultSet == this.resultSet) {\n                this.totalResults = response.data.count;\n                resolve(response.data.count);\n              } else {\n                reject();\n              }\n            })\n            .catch(reject);\n        }\n      });\n    },\n\n    _createTriggers: function () {\n      var triggers = [],\n        safeMenuActions = [],\n        destructiveMenuActions = [];\n\n      var i;\n\n      for (i = 0; i < this.actions.length; i++) {\n        var action = this.actions[i];\n\n        if (action.trigger) {\n          var $form = $(\n            '<form id=\"' +\n              Craft.formatInputId(action.type) +\n              '-actiontrigger\"/>'\n          )\n            .data('action', action)\n            .append(action.trigger);\n\n          this.addListener($form, 'submit', '_handleActionTriggerSubmit');\n          triggers.push($form);\n        } else {\n          if (!action.destructive) {\n            safeMenuActions.push(action);\n          } else {\n            destructiveMenuActions.push(action);\n          }\n        }\n      }\n\n      var $btn;\n\n      if (safeMenuActions.length || destructiveMenuActions.length) {\n        var $menuTrigger = $('<form/>');\n\n        $btn = $('<button/>', {\n          type: 'button',\n          class: 'btn menubtn',\n          'data-icon': 'settings',\n          title: Craft.t('app', 'Actions'),\n        }).appendTo($menuTrigger);\n\n        var $menu = $('<ul class=\"menu\"/>').appendTo($menuTrigger),\n          $safeList = this._createMenuTriggerList(safeMenuActions, false),\n          $destructiveList = this._createMenuTriggerList(\n            destructiveMenuActions,\n            true\n          );\n\n        if ($safeList) {\n          $safeList.appendTo($menu);\n        }\n\n        if ($safeList && $destructiveList) {\n          $('<hr/>').appendTo($menu);\n        }\n\n        if ($destructiveList) {\n          $destructiveList.appendTo($menu);\n        }\n\n        triggers.push($menuTrigger);\n      }\n\n      this._$triggers = $();\n\n      for (i = 0; i < triggers.length; i++) {\n        var $div = $('<div/>').append(triggers[i]);\n        this._$triggers = this._$triggers.add($div);\n      }\n\n      this._$triggers.appendTo(this.$toolbar);\n      Craft.appendHeadHtml(this.actionsHeadHtml);\n      Craft.appendFootHtml(this.actionsFootHtml);\n\n      Craft.initUiElements(this._$triggers);\n\n      if ($btn) {\n        $btn\n          .data('menubtn')\n          .on('optionSelect', this._handleMenuActionTriggerSubmit.bind(this));\n      }\n    },\n\n    _showExportHud: function () {\n      this.$exportBtn.addClass('active');\n\n      var $form = $('<form/>', {\n        class: 'export-form',\n      });\n\n      var typeOptions = [];\n      for (var i = 0; i < this.exporters.length; i++) {\n        typeOptions.push({\n          label: this.exporters[i].name,\n          value: this.exporters[i].type,\n        });\n      }\n      var $typeField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Export Type'),\n          options: typeOptions,\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      var $formatField = Craft.ui\n        .createSelectField({\n          label: Craft.t('app', 'Format'),\n          options: [\n            {label: 'CSV', value: 'csv'},\n            {label: 'JSON', value: 'json'},\n            {label: 'XML', value: 'xml'},\n          ],\n          class: 'fullwidth',\n        })\n        .appendTo($form);\n\n      let $typeSelect = $typeField.find('select');\n      this.addListener($typeSelect, 'change', () => {\n        let type = $typeSelect.val();\n        if (this.exportersByType[type].formattable) {\n          $formatField.removeClass('hidden');\n        } else {\n          $formatField.addClass('hidden');\n        }\n      });\n      $typeSelect.trigger('change');\n\n      // Only show the Limit field if there aren't any selected elements\n      var selectedElementIds = this.view.getSelectedElementIds();\n\n      if (!selectedElementIds.length) {\n        var $limitField = Craft.ui\n          .createTextField({\n            label: Craft.t('app', 'Limit'),\n            placeholder: Craft.t('app', 'No limit'),\n            type: 'number',\n            min: 1,\n          })\n          .appendTo($form);\n      }\n\n      $('<button/>', {\n        type: 'submit',\n        class: 'btn submit fullwidth',\n        text: Craft.t('app', 'Export'),\n      }).appendTo($form);\n\n      var $spinner = $('<div/>', {\n        class: 'spinner hidden',\n      }).appendTo($form);\n\n      var hud = new Garnish.HUD(this.$exportBtn, $form);\n\n      hud.on('hide', () => {\n        this.$exportBtn.removeClass('active');\n      });\n\n      var submitting = false;\n\n      this.addListener($form, 'submit', function (ev) {\n        ev.preventDefault();\n        if (submitting) {\n          return;\n        }\n\n        submitting = true;\n        $spinner.removeClass('hidden');\n\n        var params = this.getViewParams();\n        delete params.criteria.offset;\n        delete params.criteria.limit;\n        delete params.collapsedElementIds;\n\n        params.type = $typeField.find('select').val();\n        params.format = $formatField.find('select').val();\n\n        if (selectedElementIds.length) {\n          params.criteria.id = selectedElementIds;\n        } else {\n          var limit = parseInt($limitField.find('input').val());\n          if (limit && !isNaN(limit)) {\n            params.criteria.limit = limit;\n          }\n        }\n\n        if (Craft.csrfTokenValue) {\n          params[Craft.csrfTokenName] = Craft.csrfTokenValue;\n        }\n\n        Craft.downloadFromUrl(\n          'POST',\n          Craft.getActionUrl('element-indexes/export'),\n          params\n        )\n          .then(function () {\n            submitting = false;\n            $spinner.addClass('hidden');\n          })\n          .catch(function () {\n            submitting = false;\n            $spinner.addClass('hidden');\n            if (!this._ignoreFailedRequest) {\n              Craft.cp.displayError(Craft.t('app', 'A server error occurred.'));\n            }\n          });\n      });\n    },\n\n    _createMenuTriggerList: function (actions, destructive) {\n      if (actions && actions.length) {\n        var $ul = $('<ul/>');\n\n        for (var i = 0; i < actions.length; i++) {\n          $('<li/>')\n            .append(\n              $('<a/>', {\n                id: Craft.formatInputId(actions[i].type) + '-actiontrigger',\n                class: destructive ? 'error' : null,\n                data: {\n                  action: actions[i],\n                },\n                text: actions[i].name,\n              })\n            )\n            .appendTo($ul);\n        }\n\n        return $ul;\n      }\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      modal: null,\n      storageKey: null,\n      criteria: null,\n      batchSize: 100,\n      disabledElementIds: [],\n      selectable: false,\n      multiSelect: false,\n      buttonContainer: null,\n      hideSidebar: false,\n      toolbarSelector: '.toolbar:first',\n      refreshSourcesAction: 'element-indexes/get-source-tree-html',\n      updateElementsAction: 'element-indexes/get-elements',\n      countElementsAction: 'element-indexes/count-elements',\n      submitActionsAction: 'element-indexes/perform-action',\n      defaultSiteId: null,\n      defaultSource: null,\n      canHaveDrafts: false,\n\n      onAfterInit: $.noop,\n      onSelectSource: $.noop,\n      onSelectSite: $.noop,\n      onUpdateElements: $.noop,\n      onSelectionChange: $.noop,\n      onEnableElements: $.noop,\n      onDisableElements: $.noop,\n      onAfterAction: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.BaseElementIndexView = Garnish.Base.extend(\n  {\n    $container: null,\n    $loadingMoreSpinner: null,\n    $elementContainer: null,\n    $scroller: null,\n\n    elementIndex: null,\n    thumbLoader: null,\n    elementSelect: null,\n\n    loadingMore: false,\n\n    _totalVisible: null,\n    _morePending: null,\n    _handleEnableElements: null,\n    _handleDisableElements: null,\n\n    init: function (elementIndex, container, settings) {\n      this.elementIndex = elementIndex;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.BaseElementIndexView.defaults);\n\n      // Create a \"loading-more\" spinner\n      this.$loadingMoreSpinner = $(\n        '<div class=\"centeralign hidden\">' +\n          '<div class=\"spinner loadingmore\"></div>' +\n          '</div>'\n      ).insertAfter(this.$container);\n\n      // Get the actual elements container and its child elements\n      this.$elementContainer = this.getElementContainer();\n      var $elements = this.$elementContainer.children();\n\n      this.setTotalVisible($elements.length);\n      this.setMorePending(\n        this.settings.batchSize && $elements.length == this.settings.batchSize\n      );\n\n      // Instantiate the thumb loader\n      this.thumbLoader = new Craft.ElementThumbLoader();\n      this.thumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select(\n          this.$elementContainer,\n          $elements.filter(':not(.disabled)'),\n          {\n            multi: this.settings.multiSelect,\n            vertical: this.isVerticalList(),\n            handle:\n              this.settings.context === 'index'\n                ? '.checkbox, .element:first'\n                : null,\n            filter: ':not(a):not(.toggle)',\n            checkboxMode: this.settings.checkboxMode,\n            onSelectionChange: this.onSelectionChange.bind(this),\n          }\n        );\n\n        this._handleEnableElements = (ev) => {\n          this.elementSelect.addItems(ev.elements);\n        };\n\n        this._handleDisableElements = (ev) => {\n          this.elementSelect.removeItems(ev.elements);\n        };\n\n        this.elementIndex.on('enableElements', this._handleEnableElements);\n        this.elementIndex.on('disableElements', this._handleDisableElements);\n      }\n\n      // Enable inline element editing if this is an index page\n      if (this.settings.context === 'index') {\n        this._handleElementEditing = (ev) => {\n          var $target = $(ev.target);\n\n          if ($target.prop('nodeName') === 'A') {\n            // Let the link do its thing\n            return;\n          }\n\n          var $element;\n\n          if ($target.hasClass('element')) {\n            $element = $target;\n          } else {\n            $element = $target.closest('.element');\n\n            if (!$element.length) {\n              return;\n            }\n          }\n\n          if (Garnish.hasAttr($element, 'data-editable')) {\n            this.createElementEditor($element);\n          }\n        };\n\n        if (!this.elementIndex.trashed) {\n          this.addListener(\n            this.$elementContainer,\n            'dblclick',\n            this._handleElementEditing\n          );\n          if ($.isTouchCapable()) {\n            this.addListener(\n              this.$elementContainer,\n              'taphold',\n              this._handleElementEditing\n            );\n          }\n        }\n      }\n\n      // Give sub-classes a chance to do post-initialization stuff here\n      this.afterInit();\n\n      // Set up lazy-loading\n      if (this.settings.batchSize) {\n        if (this.settings.context === 'index') {\n          this.$scroller = Garnish.$scrollContainer;\n        } else {\n          this.$scroller = this.elementIndex.$main;\n        }\n\n        this.$scroller.scrollTop(0);\n        this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n        this.maybeLoadMore();\n      }\n    },\n\n    getElementContainer: function () {\n      throw 'Classes that extend Craft.BaseElementIndexView must supply a getElementContainer() method.';\n    },\n\n    afterInit: function () {},\n\n    getAllElements: function () {\n      return this.$elementContainer.children();\n    },\n\n    getEnabledElements: function () {\n      return this.$elementContainer.children(':not(.disabled)');\n    },\n\n    getElementById: function (id) {\n      var $element = this.$elementContainer.children(\n        '[data-id=\"' + id + '\"]:first'\n      );\n\n      if ($element.length) {\n        return $element;\n      } else {\n        return null;\n      }\n    },\n\n    getSelectedElements: function () {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      return this.elementSelect.$selectedItems;\n    },\n\n    getSelectedElementIds: function () {\n      let $selectedElements;\n      try {\n        $selectedElements = this.getSelectedElements();\n      } catch (e) {}\n\n      let ids = [];\n      if ($selectedElements) {\n        for (var i = 0; i < $selectedElements.length; i++) {\n          ids.push($selectedElements.eq(i).data('id'));\n        }\n      }\n      return ids;\n    },\n\n    selectElement: function ($element) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      this.elementSelect.selectItem($element, true);\n      return true;\n    },\n\n    selectElementById: function (id) {\n      if (!this.elementSelect) {\n        throw 'This view is not selectable.';\n      }\n\n      var $element = this.getElementById(id);\n\n      if ($element) {\n        this.elementSelect.selectItem($element, true);\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    selectAllElements: function () {\n      this.elementSelect.selectAll();\n    },\n\n    deselectAllElements: function () {\n      this.elementSelect.deselectAll();\n    },\n\n    isVerticalList: function () {\n      return false;\n    },\n\n    getTotalVisible: function () {\n      return this._totalVisible;\n    },\n\n    setTotalVisible: function (totalVisible) {\n      this._totalVisible = totalVisible;\n    },\n\n    getMorePending: function () {\n      return this._morePending;\n    },\n\n    setMorePending: function (morePending) {\n      this._morePending = morePending;\n    },\n\n    /**\n     * Checks if the user has reached the bottom of the scroll area, and if so, loads the next batch of elemets.\n     */\n    maybeLoadMore: function () {\n      if (this.canLoadMore()) {\n        this.loadMore();\n      }\n    },\n\n    /**\n     * Returns whether the user has reached the bottom of the scroll area.\n     */\n    canLoadMore: function () {\n      if (!this.getMorePending() || !this.settings.batchSize) {\n        return false;\n      }\n\n      // Check if the user has reached the bottom of the scroll area\n      var containerHeight;\n\n      if (this.$scroller[0] === Garnish.$win[0]) {\n        var winHeight = Garnish.$win.innerHeight(),\n          winScrollTop = Garnish.$win.scrollTop(),\n          containerOffset = this.$container.offset().top;\n        containerHeight = this.$container.height();\n\n        return winHeight + winScrollTop >= containerOffset + containerHeight;\n      } else {\n        var containerScrollHeight = this.$scroller.prop('scrollHeight'),\n          containerScrollTop = this.$scroller.scrollTop();\n        containerHeight = this.$scroller.outerHeight();\n\n        return (\n          containerScrollHeight - containerScrollTop <= containerHeight + 15\n        );\n      }\n    },\n\n    /**\n     * Loads the next batch of elements.\n     */\n    loadMore: function () {\n      if (\n        !this.getMorePending() ||\n        this.loadingMore ||\n        !this.settings.batchSize\n      ) {\n        return;\n      }\n\n      this.loadingMore = true;\n      this.$loadingMoreSpinner.removeClass('hidden');\n      this.removeListener(this.$scroller, 'scroll');\n\n      Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n        data: this.getLoadMoreParams(),\n      })\n        .then((response) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n\n          let $newElements = $(response.data.html);\n\n          this.appendElements($newElements);\n          Craft.appendHeadHtml(response.data.headHtml);\n          Craft.appendFootHtml(response.data.footHtml);\n\n          if (this.elementSelect) {\n            this.elementSelect.addItems($newElements.filter(':not(.disabled)'));\n            this.elementIndex.updateActionTriggers();\n          }\n\n          this.setTotalVisible(this.getTotalVisible() + $newElements.length);\n          this.setMorePending($newElements.length == this.settings.batchSize);\n\n          // Is there room to load more right now?\n          this.addListener(this.$scroller, 'scroll', 'maybeLoadMore');\n          this.maybeLoadMore();\n        })\n        .catch((e) => {\n          this.loadingMore = false;\n          this.$loadingMoreSpinner.addClass('hidden');\n        });\n    },\n\n    getLoadMoreParams: function () {\n      // Use the same params that were passed when initializing this view\n      var params = $.extend(true, {}, this.settings.params);\n      params.criteria.offset = this.getTotalVisible();\n      return params;\n    },\n\n    appendElements: function ($newElements) {\n      $newElements.appendTo(this.$elementContainer);\n      this.thumbLoader.load($newElements);\n      this.onAppendElements($newElements);\n    },\n\n    onAppendElements: function ($newElements) {\n      this.settings.onAppendElements($newElements);\n      this.trigger('appendElements', {\n        newElements: $newElements,\n      });\n    },\n\n    onSelectionChange: function () {\n      this.settings.onSelectionChange();\n      this.trigger('selectionChange');\n    },\n\n    createElementEditor: function ($element) {\n      Craft.createElementEditor($element.data('type'), $element, {\n        elementIndex: this.elementIndex,\n      });\n    },\n\n    disable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.disable();\n      }\n    },\n\n    enable: function () {\n      if (this.elementSelect) {\n        this.elementSelect.enable();\n      }\n    },\n\n    destroy: function () {\n      // Remove the \"loading-more\" spinner, since we added that outside of the view container\n      this.$loadingMoreSpinner.remove();\n\n      // Kill the thumb loader\n      this.thumbLoader.destroy();\n      delete this.thumbLoader;\n\n      // Delete the element select\n      if (this.elementSelect) {\n        this.elementIndex.off('enableElements', this._handleEnableElements);\n        this.elementIndex.off('disableElements', this._handleDisableElements);\n\n        this.elementSelect.destroy();\n        delete this.elementSelect;\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      context: 'index',\n      batchSize: null,\n      params: null,\n      selectable: false,\n      multiSelect: false,\n      checkboxMode: false,\n      loadMoreElementsAction: 'element-indexes/get-more-elements',\n      onAppendElements: $.noop,\n      onSelectionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Select input\n */\nCraft.BaseElementSelectInput = Garnish.Base.extend(\n  {\n    thumbLoader: null,\n    elementSelect: null,\n    elementSort: null,\n    modal: null,\n    elementEditor: null,\n\n    fieldLabel: null,\n\n    $container: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addElementBtn: null,\n    $addElementBtnContainer: null,\n\n    _initialized: false,\n\n    init: function (settings) {\n      // Normalize the settings and set them\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = [\n            'id',\n            'name',\n            'elementType',\n            'sources',\n            'criteria',\n            'sourceElementId',\n            'limit',\n            'modalStorageKey',\n            'fieldId',\n          ];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.setSettings(settings, Craft.BaseElementSelectInput.defaults);\n\n      // Apply the storage key prefix\n      if (this.settings.modalStorageKey) {\n        this.modalStorageKey =\n          'BaseElementSelectInput.' + this.settings.modalStorageKey;\n      }\n\n      // No reason for this to be sortable if we're only allowing 1 selection\n      if (this.settings.limit == 1) {\n        this.settings.sortable = false;\n      }\n\n      this.$container = this.getContainer();\n      this.fieldLabel = this.getFieldLabel();\n\n      // Store a reference to this class\n      this.$container.data('elementSelect', this);\n\n      this.$elementsContainer = this.getElementsContainer();\n\n      this.$addElementBtn = this.getAddElementsBtn();\n      if (this.$addElementBtn) {\n        this.$addElementBtnContainer = this.$addElementBtn.parent('.flex');\n        if (!this.$addElementBtnContainer.length) {\n          this.$addElementBtnContainer = null;\n        }\n      }\n\n      this.thumbLoader = new Craft.ElementThumbLoader();\n\n      this.initElementSelect();\n      this.initElementSort();\n      this.resetElements();\n\n      if (this.$addElementBtn) {\n        this.addListener(this.$addElementBtn, 'activate', 'showModal');\n      }\n\n      Garnish.requestAnimationFrame(() => {\n        this._initialized = true;\n      });\n    },\n\n    get totalSelected() {\n      return this.$elements.length;\n    },\n\n    getContainer: function () {\n      return $('#' + this.settings.id);\n    },\n\n    getFieldLabel: function () {\n      if (!this.$container) return;\n\n      const $fieldset = this.$container.closest('fieldset');\n      return $fieldset.find('legend').first().data('label');\n    },\n\n    getElementsContainer: function () {\n      return this.$container.children('.elements');\n    },\n\n    getElements: function () {\n      return this.$elementsContainer.children();\n    },\n\n    getAddElementsBtn: function () {\n      return this.$container.find('.btn.add:first');\n    },\n\n    initElementSelect: function () {\n      if (this.settings.selectable) {\n        this.elementSelect = new Garnish.Select({\n          multi: this.settings.sortable,\n          filter: ':not(.delete)',\n        });\n      }\n    },\n\n    initElementSort: function () {\n      if (this.settings.sortable) {\n        this.elementSort = new Garnish.DragSort({\n          container: this.$elementsContainer,\n          filter: this.settings.selectable\n            ? () => {\n                // Only return all the selected items if the target item is selected\n                if (this.elementSort.$targetItem.hasClass('sel')) {\n                  return this.elementSelect.getSelectedItems();\n                } else {\n                  return this.elementSort.$targetItem;\n                }\n              }\n            : null,\n          ignoreHandleSelector: '.delete',\n          axis: this.getElementSortAxis(),\n          collapseDraggees: true,\n          magnetStrength: 4,\n          helperLagBase: 1.5,\n          onSortChange: this.settings.selectable\n            ? () => {\n                this.elementSelect.resetItemOrder();\n              }\n            : null,\n        });\n      }\n    },\n\n    getElementSortAxis: function () {\n      return this.settings.viewMode === 'list' ? 'y' : null;\n    },\n\n    canAddMoreElements: function () {\n      return (\n        !this.settings.limit || this.$elements.length < this.settings.limit\n      );\n    },\n\n    updateAddElementsBtn: function () {\n      if (this.canAddMoreElements()) {\n        this.enableAddElementsBtn();\n      } else {\n        this.disableAddElementsBtn();\n      }\n    },\n\n    disableAddElementsBtn: function () {\n      let $btn = this.$addElementBtnContainer || this.$addElementBtn;\n      if ($btn) {\n        $btn.addClass('hidden');\n      }\n    },\n\n    enableAddElementsBtn: function () {\n      let $btn = this.$addElementBtnContainer || this.$addElementBtn;\n      if ($btn) {\n        $btn.removeClass('hidden');\n      }\n    },\n\n    focusNextLogicalElement: function () {\n      if (this.canAddMoreElements()) {\n        // If can add more elements, focus ADD button\n        let $btn = this.$addElementBtn;\n\n        if ($btn) {\n          $btn.get(0).focus();\n        }\n      } else {\n        // If can't add more elements, focus on the final remove\n        this.focusLastRemoveBtn();\n      }\n    },\n\n    focusLastRemoveBtn: function () {\n      const $removeBtns = this.$container.find('.delete');\n\n      if (!$removeBtns.length) return;\n\n      $removeBtns.last()[0].focus();\n    },\n\n    resetElements: function () {\n      if (this.$elements !== null) {\n        this.removeElements(this.$elements);\n      } else {\n        this.$elements = $();\n      }\n\n      this.addElements(this.getElements());\n    },\n\n    addElements: function ($elements) {\n      this.thumbLoader.load($elements);\n\n      if (this.settings.selectable) {\n        this.elementSelect.addItems($elements);\n      }\n\n      if (this.settings.sortable) {\n        this.elementSort.addItems($elements);\n      }\n\n      if (this.settings.editable) {\n        this._handleShowElementEditor = (ev) => {\n          var $element = $(ev.currentTarget);\n          if (\n            Garnish.hasAttr($element, 'data-editable') &&\n            !$element.hasClass('disabled') &&\n            !$element.hasClass('loading')\n          ) {\n            this.elementEditor = this.createElementEditor($element);\n          }\n        };\n\n        this.addListener($elements, 'dblclick', this._handleShowElementEditor);\n\n        if ($.isTouchCapable()) {\n          this.addListener($elements, 'taphold', this._handleShowElementEditor);\n        }\n      }\n\n      $elements.find('.delete').on('click dblclick', (ev) => {\n        this.removeElement($(ev.currentTarget).closest('.element'));\n        // Prevent this from acting as one of a double-click\n        ev.stopPropagation();\n      });\n\n      this.$elements = this.$elements.add($elements);\n      this.updateAddElementsBtn();\n    },\n\n    createElementEditor: function ($element, settings) {\n      if (!settings) {\n        settings = {};\n      }\n      settings.prevalidate = this.settings.prevalidate;\n      return Craft.createElementEditor(\n        this.settings.elementType,\n        $element,\n        settings\n      );\n    },\n\n    removeElements: function ($elements) {\n      if (this.settings.selectable) {\n        this.elementSelect.removeItems($elements);\n      }\n\n      if (this.modal) {\n        var ids = [];\n\n        for (var i = 0; i < $elements.length; i++) {\n          var id = $elements.eq(i).data('id');\n\n          if (id) {\n            ids.push(id);\n          }\n        }\n\n        if (ids.length) {\n          this.modal.elementIndex.enableElementsById(ids);\n        }\n      }\n\n      // Disable the hidden input in case the form is submitted before this element gets removed from the DOM\n      $elements.children('input').prop('disabled', true);\n\n      // Move the focus to the next element in the list, if there is one\n      let $nextDeleteBtn;\n      if (this.settings.selectable) {\n        const lastElementIndex = this.$elements.index($elements.last());\n        $nextDeleteBtn = this.$elements\n          .eq(lastElementIndex + 1)\n          .find('.delete');\n      }\n      if ($nextDeleteBtn.length) {\n        $nextDeleteBtn.focus();\n      } else {\n        this.focusNextLogicalElement();\n      }\n\n      this.$elements = this.$elements.not($elements);\n      this.updateAddElementsBtn();\n\n      this.onRemoveElements();\n    },\n\n    removeElement: function ($element) {\n      this.removeElements($element);\n      this.animateElementAway($element, () => {\n        $element.remove();\n      });\n    },\n\n    animateElementAway: function ($element, callback) {\n      $element.css('z-index', 0);\n\n      var animateCss = {\n        opacity: -1,\n      };\n      animateCss['margin-' + Craft.left] = -(\n        $element.outerWidth() + parseInt($element.css('margin-' + Craft.right))\n      );\n\n      if (this.settings.viewMode === 'list' || this.$elements.length === 0) {\n        animateCss['margin-bottom'] = -(\n          $element.outerHeight() + parseInt($element.css('margin-bottom'))\n        );\n      }\n\n      // Pause the draft editor\n      if (window.draftEditor) {\n        window.draftEditor.pause();\n      }\n\n      $element.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.REMOVE_FX_DURATION,\n        () => {\n          if (callback) {\n            callback();\n          }\n\n          // Resume the draft editor\n          if (window.draftEditor) {\n            window.draftEditor.resume();\n          }\n        }\n      );\n    },\n\n    showModal: function () {\n      // Make sure we haven't reached the limit\n      if (!this.canAddMoreElements()) {\n        return;\n      }\n\n      if (!this.modal) {\n        this.modal = this.createModal();\n      } else {\n        this.modal.show();\n      }\n    },\n\n    createModal: function () {\n      return Craft.createElementSelectorModal(\n        this.settings.elementType,\n        this.getModalSettings()\n      );\n    },\n\n    getModalSettings: function () {\n      return $.extend(\n        {\n          closeOtherModals: false,\n          storageKey: this.modalStorageKey,\n          sources: this.settings.sources,\n          criteria: this.settings.criteria,\n          multiSelect: this.settings.limit != 1,\n          showSiteMenu: this.settings.showSiteMenu,\n          disabledElementIds: this.getDisabledElementIds(),\n          onSelect: this.onModalSelect.bind(this),\n          onHide: this.onModalHide.bind(this),\n          triggerElement: this.$addElementBtn,\n          modalTitle: Craft.t('app', 'Select {element}', {\n            element: this.fieldLabel,\n          }),\n        },\n        this.settings.modalSettings\n      );\n    },\n\n    getSelectedElementIds: function () {\n      var ids = [];\n\n      for (var i = 0; i < this.$elements.length; i++) {\n        ids.push(this.$elements.eq(i).data('id'));\n      }\n\n      return ids;\n    },\n\n    getDisabledElementIds: function () {\n      var ids = this.getSelectedElementIds();\n\n      if (!this.settings.allowSelfRelations && this.settings.sourceElementId) {\n        ids.push(this.settings.sourceElementId);\n      }\n\n      if (this.settings.disabledElementIds) {\n        ids.push(...this.settings.disabledElementIds);\n      }\n\n      return ids;\n    },\n\n    onModalSelect: function (elements) {\n      if (this.settings.limit) {\n        // Cut off any excess elements\n        var slotsLeft = this.settings.limit - this.$elements.length;\n\n        if (elements.length > slotsLeft) {\n          elements = elements.slice(0, slotsLeft);\n        }\n      }\n\n      this.selectElements(elements);\n      this.updateDisabledElementsInModal();\n    },\n\n    onModalHide: function () {\n      // If can add more elements, do default behavior of focus on \"Add\" button\n      if (this.canAddMoreElements()) return;\n\n      setTimeout(() => {\n        this.focusNextLogicalElement();\n      }, 200);\n    },\n\n    selectElements: function (elements) {\n      for (let i = 0; i < elements.length; i++) {\n        let elementInfo = elements[i],\n          $element = this.createNewElement(elementInfo);\n\n        this.appendElement($element);\n        this.addElements($element);\n        this.animateElementIntoPlace(elementInfo.$element, $element);\n\n        // Override the element reference with the new one\n        elementInfo.$element = $element;\n      }\n\n      this.onSelectElements(elements);\n    },\n\n    createNewElement: function (elementInfo) {\n      var $element = elementInfo.$element.clone();\n      var removeText = Craft.t('app', 'Remove {label}', {\n        label: Craft.escapeHtml(elementInfo.label),\n      });\n      // Make a couple tweaks\n      Craft.setElementSize(\n        $element,\n        this.settings.viewMode === 'large' ? 'large' : 'small'\n      );\n      $element.addClass('removable');\n      $element.prepend(\n        `<input type=\"hidden\" name=\"${this.settings.name}${\n          this.settings.single ? '' : '[]'\n        }\" value=\"${elementInfo.id}\">` +\n          '<button type=\"button\" class=\"delete icon\" title=\"' +\n          Craft.t('app', 'Remove') +\n          '\" aria-label=\"' +\n          removeText +\n          '\"></button>'\n      );\n\n      return $element;\n    },\n\n    appendElement: function ($element) {\n      $element.appendTo(this.$elementsContainer);\n    },\n\n    animateElementIntoPlace: function ($modalElement, $inputElement) {\n      var origOffset = $modalElement.offset(),\n        destOffset = $inputElement.offset(),\n        $helper = $inputElement.clone().appendTo(Garnish.$bod);\n\n      $inputElement.css('visibility', 'hidden');\n\n      $helper.css({\n        position: 'absolute',\n        zIndex: 10000,\n        top: origOffset.top,\n        left: origOffset.left,\n      });\n\n      var animateCss = {\n        top: destOffset.top,\n        left: destOffset.left,\n      };\n\n      $helper.velocity(\n        animateCss,\n        Craft.BaseElementSelectInput.ADD_FX_DURATION,\n        function () {\n          $helper.remove();\n          $inputElement.css('visibility', 'visible');\n        }\n      );\n    },\n\n    updateDisabledElementsInModal: function () {\n      if (this.modal.elementIndex) {\n        this.modal.elementIndex.disableElementsById(\n          this.getDisabledElementIds()\n        );\n      }\n    },\n\n    getElementById: function (id) {\n      for (var i = 0; i < this.$elements.length; i++) {\n        var $element = this.$elements.eq(i);\n\n        if ($element.data('id') == id) {\n          return $element;\n        }\n      }\n    },\n\n    onSelectElements: function (elements) {\n      this.trigger('selectElements', {elements});\n      this.settings.onSelectElements(elements);\n\n      if (window.draftEditor) {\n        window.draftEditor.checkForm();\n      }\n    },\n\n    onRemoveElements: function () {\n      this.trigger('removeElements');\n      this.settings.onRemoveElements();\n    },\n  },\n  {\n    ADD_FX_DURATION: 200,\n    REMOVE_FX_DURATION: 200,\n\n    defaults: {\n      id: null,\n      name: null,\n      fieldId: null,\n      elementType: null,\n      sources: null,\n      criteria: {},\n      allowSelfRelations: false,\n      sourceElementId: null,\n      disabledElementIds: null,\n      viewMode: 'list',\n      single: false,\n      limit: null,\n      showSiteMenu: false,\n      modalStorageKey: null,\n      modalSettings: {},\n      onSelectElements: $.noop,\n      onRemoveElements: $.noop,\n      sortable: true,\n      selectable: true,\n      editable: true,\n      prevalidate: false,\n      editorSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element selector modal class\n */\nCraft.BaseElementSelectorModal = Garnish.Modal.extend(\n  {\n    elementType: null,\n    elementIndex: null,\n\n    $body: null,\n    $selectBtn: null,\n    $sidebar: null,\n    $sources: null,\n    $sourceToggles: null,\n    $main: null,\n    $search: null,\n    $elements: null,\n    $tbody: null,\n    $primaryButtons: null,\n    $secondaryButtons: null,\n    $cancelBtn: null,\n    $footerSpinner: null,\n\n    init: function (elementType, settings) {\n      this.elementType = elementType;\n      this.setSettings(settings, Craft.BaseElementSelectorModal.defaults);\n      var $headingId = 'elementSelectorModalHeading-' + Date.now();\n\n      // Build the modal\n      var $container = $(\n          '<div class=\"modal elementselectormodal\" aria-labelledby=\"' +\n            $headingId +\n            '\"></div>'\n        ).appendTo(Garnish.$bod),\n        $heading = $(\n          '<h2 id=\"' +\n            $headingId +\n            '\" class=\"visually-hidden\">' +\n            this.settings.modalTitle +\n            '</h2>'\n        ).appendTo($container),\n        $body = $(\n          '<div class=\"body\"><div class=\"spinner big\"></div></div>'\n        ).appendTo($container),\n        $footer = $('<div class=\"footer\"/>').appendTo($container);\n\n      if (this.settings.fullscreen) {\n        $container.addClass('fullscreen');\n        this.settings.minGutter = 0;\n      }\n\n      this.base($container, this.settings);\n\n      this.$footerSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n        $footer\n      );\n      this.$secondaryButtons = $(\n        '<div class=\"buttons left secondary-buttons\"/>'\n      ).appendTo($footer);\n      this.$primaryButtons = $('<div class=\"buttons right\"/>').appendTo(\n        $footer\n      );\n      this.$cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo(this.$primaryButtons);\n      this.$selectBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn disabled submit',\n        text: Craft.t('app', 'Select'),\n      }).appendTo(this.$primaryButtons);\n\n      this.$body = $body;\n\n      this.addListener(this.$cancelBtn, 'activate', 'cancel');\n      this.addListener(this.$selectBtn, 'activate', 'selectElements');\n    },\n\n    onFadeIn: function () {\n      if (!this.elementIndex) {\n        this._createElementIndex();\n      } else {\n        // Auto-focus the Search box\n        if (!Garnish.isMobileBrowser(true)) {\n          this.elementIndex.$search.trigger('focus');\n        }\n      }\n\n      this.base();\n    },\n\n    onSelectionChange: function () {\n      this.updateSelectBtnState();\n    },\n\n    updateSelectBtnState: function () {\n      if (this.$selectBtn) {\n        if (this.elementIndex.getSelectedElements().length) {\n          this.enableSelectBtn();\n        } else {\n          this.disableSelectBtn();\n        }\n      }\n    },\n\n    enableSelectBtn: function () {\n      this.$selectBtn.removeClass('disabled');\n    },\n\n    disableSelectBtn: function () {\n      this.$selectBtn.addClass('disabled');\n    },\n\n    enableCancelBtn: function () {\n      this.$cancelBtn.removeClass('disabled');\n    },\n\n    disableCancelBtn: function () {\n      this.$cancelBtn.addClass('disabled');\n    },\n\n    showFooterSpinner: function () {\n      this.$footerSpinner.removeClass('hidden');\n    },\n\n    hideFooterSpinner: function () {\n      this.$footerSpinner.addClass('hidden');\n    },\n\n    cancel: function () {\n      if (!this.$cancelBtn.hasClass('disabled')) {\n        this.hide();\n      }\n    },\n\n    selectElements: function () {\n      if (this.elementIndex && this.elementIndex.getSelectedElements().length) {\n        // TODO: This code shouldn't know about views' elementSelect objects\n        this.elementIndex.view.elementSelect.clearMouseUpTimeout();\n\n        var $selectedElements = this.elementIndex.getSelectedElements(),\n          elementInfo = this.getElementInfo($selectedElements);\n\n        this.onSelect(elementInfo);\n\n        if (this.settings.disableElementsOnSelect) {\n          this.elementIndex.disableElements(\n            this.elementIndex.getSelectedElements()\n          );\n        }\n\n        if (this.settings.hideOnSelect) {\n          this.hide();\n        }\n      }\n    },\n\n    getElementInfo: function ($selectedElements) {\n      var info = [];\n\n      for (var i = 0; i < $selectedElements.length; i++) {\n        var $element = $($selectedElements[i]);\n        var elementInfo = Craft.getElementInfo($element);\n\n        info.push(elementInfo);\n      }\n\n      return info;\n    },\n\n    show: function () {\n      this.updateSelectBtnState();\n      this.base();\n    },\n\n    onSelect: function (elementInfo) {\n      this.settings.onSelect(elementInfo);\n    },\n\n    disable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.disable();\n      }\n\n      this.base();\n    },\n\n    enable: function () {\n      if (this.elementIndex) {\n        this.elementIndex.enable();\n      }\n\n      this.base();\n    },\n\n    _createElementIndex: function () {\n      // Get the modal body HTML based on the settings\n      var data = {\n        context: 'modal',\n        elementType: this.elementType,\n        sources: this.settings.sources,\n      };\n\n      if (\n        this.settings.showSiteMenu !== null &&\n        this.settings.showSiteMenu !== 'auto'\n      ) {\n        data.showSiteMenu = this.settings.showSiteMenu ? '1' : '0';\n      }\n\n      Craft.postActionRequest(\n        this.settings.bodyAction,\n        data,\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.$body.html(response.html);\n\n            if (this.$body.has('.sidebar:not(.hidden)').length) {\n              this.$body.addClass('has-sidebar');\n            }\n\n            // Initialize the element index\n            this.elementIndex = Craft.createElementIndex(\n              this.elementType,\n              this.$body,\n              Object.assign(\n                {\n                  context: 'modal',\n                  modal: this,\n                  storageKey: this.settings.storageKey,\n                  criteria: this.settings.criteria,\n                  disabledElementIds: this.settings.disabledElementIds,\n                  selectable: true,\n                  multiSelect: this.settings.multiSelect,\n                  buttonContainer: this.$secondaryButtons,\n                  onSelectionChange: this.onSelectionChange.bind(this),\n                  hideSidebar: this.settings.hideSidebar,\n                  defaultSiteId: this.settings.defaultSiteId,\n                  defaultSource: this.settings.defaultSource,\n                },\n                this.settings.indexSettings\n              )\n            );\n\n            // Double-clicking or double-tapping should select the elements\n            this.addListener(\n              this.elementIndex.$elements,\n              'doubletap',\n              function (ev, touchData) {\n                // Make sure the touch targets are the same\n                // (they may be different if Command/Ctrl/Shift-clicking on multiple elements quickly)\n                if (touchData.firstTap.target === touchData.secondTap.target) {\n                  this.selectElements();\n                }\n              }\n            );\n          }\n        }\n      );\n    },\n  },\n  {\n    defaults: {\n      fullscreen: false,\n      resizable: true,\n      storageKey: null,\n      sources: null,\n      criteria: null,\n      multiSelect: false,\n      showSiteMenu: null,\n      disabledElementIds: [],\n      disableElementsOnSelect: false,\n      hideOnSelect: true,\n      modalTitle: Craft.t('app', 'Select element'),\n      onCancel: $.noop,\n      onSelect: $.noop,\n      hideSidebar: false,\n      defaultSiteId: null,\n      defaultSource: null,\n      bodyAction: 'elements/get-modal-body',\n      indexSettings: {},\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Input Generator\n */\nCraft.BaseInputGenerator = Garnish.Base.extend({\n  $source: null,\n  $target: null,\n  $form: null,\n  settings: null,\n\n  listening: null,\n  timeout: null,\n\n  init: function (source, target, settings) {\n    this.$source = $(source);\n    this.$target = $(target);\n    this.$form = this.$source.closest('form');\n\n    this.setSettings(settings);\n\n    this.startListening();\n  },\n\n  setNewSource: function (source) {\n    var listening = this.listening;\n    this.stopListening();\n\n    this.$source = $(source);\n\n    if (listening) {\n      this.startListening();\n    }\n  },\n\n  startListening: function () {\n    if (this.listening) {\n      return;\n    }\n\n    this.listening = true;\n\n    this.addListener(this.$source, 'input', 'onSourceTextChange');\n    this.addListener(this.$target, 'input', 'onTargetTextChange');\n    this.addListener(this.$form, 'submit', 'onFormSubmit');\n  },\n\n  stopListening: function () {\n    if (!this.listening) {\n      return;\n    }\n\n    this.listening = false;\n\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.removeAllListeners(this.$source);\n    this.removeAllListeners(this.$target);\n    this.removeAllListeners(this.$form);\n  },\n\n  onSourceTextChange: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.timeout = setTimeout(this.updateTarget.bind(this), 250);\n  },\n\n  onTargetTextChange: function () {\n    if (this.$target.get(0) === document.activeElement) {\n      this.stopListening();\n    }\n  },\n\n  onFormSubmit: function () {\n    if (this.timeout) {\n      clearTimeout(this.timeout);\n    }\n\n    this.updateTarget();\n  },\n\n  updateTarget: function () {\n    if (!this.$target.is(':visible')) {\n      return;\n    }\n\n    var sourceVal = this.$source.val();\n\n    if (typeof sourceVal === 'undefined') {\n      // The source input may not exist anymore\n      return;\n    }\n\n    var targetVal = this.generateTargetValue(sourceVal);\n\n    this.$target.val(targetVal);\n\n    for (let i = 0; i < this.$target.length; i++) {\n      this.$target[i].dispatchEvent(\n        new InputEvent('input', {\n          inputType: 'insertText',\n        })\n      );\n      this.$target[i].dispatchEvent(new Event('input'));\n    }\n\n    // If the target already has focus, select its whole value to mimic\n    // the behavior if the value had already been generated and they just tabbed in\n    if (this.$target.is(':focus')) {\n      Craft.selectFullValue(this.$target);\n    }\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return sourceVal;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * CP class\n */\nCraft.CP = Garnish.Base.extend(\n  {\n    authManager: null,\n\n    $nav: null,\n    $navToggle: null,\n    $globalSidebar: null,\n    $globalContainer: null,\n    $mainContainer: null,\n    $alerts: null,\n    $crumbs: null,\n    $breadcrumbList: null,\n    $breadcrumbItems: null,\n    $notificationContainer: null,\n    $main: null,\n    $primaryForm: null,\n    $headerContainer: null,\n    $header: null,\n    $mainContent: null,\n    $details: null,\n    $sidebarContainer: null,\n    $sidebar: null,\n    $contentContainer: null,\n    $edition: null,\n\n    $confirmUnloadForms: null,\n    $deltaForms: null,\n    $collapsibleTables: null,\n\n    isMobile: null,\n    fixedHeader: false,\n\n    breadcrumbListWidth: 0,\n    breadcrumbDisclosureItem: `<li class=\"breadcrumb-toggle-wrapper\" data-disclosure-item><button data-disclosure-trigger aria-controls=\"breadcrumb-disclosure\" aria-haspopup=\"true\">${Craft.t(\n      'app',\n      'More…'\n    )}</button><div id=\"breadcrumb-disclosure\" class=\"menu menu--disclosure\" data-disclosure-menu><ul></ul></div></li>`,\n\n    tabManager: null,\n\n    enableQueue: true,\n    totalJobs: 0,\n    jobInfo: null,\n    displayedJobInfo: null,\n    displayedJobInfoUnchanged: 1,\n    trackJobProgressTimeout: null,\n    jobProgressIcon: null,\n\n    checkingForUpdates: false,\n    forcingRefreshOnUpdatesCheck: false,\n    includingDetailsOnUpdatesCheck: false,\n    checkForUpdatesCallbacks: null,\n\n    resizeTimeout: null,\n\n    init: function () {\n      // Is this session going to expire?\n      if (Craft.remainingSessionTime !== 0) {\n        this.authManager = new Craft.AuthManager();\n      }\n\n      // Find all the key elements\n      this.$nav = $('#nav');\n      this.$navToggle = $('#nav-toggle');\n      this.$globalSidebar = $('#global-sidebar');\n      this.$globalContainer = $('#global-container');\n      this.$mainContainer = $('#main-container');\n      this.$alerts = $('#alerts');\n      this.$crumbs = $('#crumbs');\n      this.$breadcrumbList = $('.breadcrumb-list');\n      this.$breadcrumbItems = $('.breadcrumb-list li');\n      this.$notificationContainer = $('#notifications');\n      this.$main = $('#main');\n      this.$primaryForm = $('#main-form');\n      this.$headerContainer = $('#header-container');\n      this.$header = $('#header');\n      this.$mainContent = $('#main-content');\n      this.$details = $('#details');\n      this.$sidebarContainer = $('#sidebar-container');\n      this.$sidebar = $('#sidebar');\n      this.$contentContainer = $('#content-container');\n      this.$collapsibleTables = $('table.collapsible');\n\n      this.isMobile = Garnish.isMobileBrowser();\n\n      this.updateSidebarMenuLabel();\n\n      // Swap any instruction text with info icons\n      let $allInstructions = this.$details.find(\n        '.meta > .field > .instructions'\n      );\n\n      for (let i = 0; i < $allInstructions.length; i++) {\n        let $instructions = $allInstructions.eq(i);\n        let $label = $instructions.siblings('.heading').children('label');\n        $('<span/>', {\n          class: 'info',\n          html: $instructions.children().html(),\n        }).appendTo($label);\n        $instructions.remove();\n      }\n\n      if (!this.isMobile && this.$header.length) {\n        this.addListener(Garnish.$win, 'scroll', 'updateFixedHeader');\n        this.updateFixedHeader();\n      }\n\n      Garnish.$doc.ready(() => {\n        // Update responsive tables on window resize\n        this.addListener(Garnish.$win, 'resize', (ev) => {\n          // Ignore element resizes\n          if (ev.target === window) {\n            this.handleWindowResize();\n\n            clearTimeout(this.resizeTimeout);\n            var cp = this;\n            this.resizeTimeout = setTimeout(function () {\n              cp.setSidebarNavAttributes();\n            }, 100);\n          }\n        });\n        this.handleWindowResize();\n        this.setSidebarNavAttributes();\n\n        // Fade the notification out two seconds after page load\n        var $errorNotifications =\n            this.$notificationContainer.children('.error'),\n          $otherNotifications =\n            this.$notificationContainer.children(':not(.error)');\n\n        $errorNotifications\n          .delay(Craft.CP.notificationDuration * 2)\n          .velocity('fadeOut');\n        $otherNotifications\n          .delay(Craft.CP.notificationDuration)\n          .velocity('fadeOut');\n\n        // Wait a frame before initializing any confirm-unload forms,\n        // so other JS that runs on ready() has a chance to initialize\n        Garnish.requestAnimationFrame(this.initSpecialForms.bind(this));\n      });\n\n      // Alerts\n      if (this.$alerts.length) {\n        this.initAlerts();\n      }\n\n      // Toggles\n      this.addListener(this.$navToggle, 'click', 'toggleNav');\n      this.addListener($('#sidebar-toggle'), 'click', 'toggleSidebar');\n\n      // Does this page have a primary form?\n      if (!this.$primaryForm.length) {\n        this.$primaryForm = $('form[data-saveshortcut]:first');\n      }\n\n      // Does the primary form support the save shortcut?\n      if (\n        this.$primaryForm.length &&\n        Garnish.hasAttr(this.$primaryForm, 'data-saveshortcut')\n      ) {\n        let shortcuts = [];\n        let actions = this.$primaryForm.data('actions');\n        if (typeof actions === 'undefined') {\n          shortcuts.push([\n            {\n              keyCode: Garnish.S_KEY,\n              ctrl: true,\n            },\n            {\n              redirect: this.$primaryForm.data('saveshortcut-redirect'),\n              retainScroll: Garnish.hasAttr(\n                this.$primaryForm,\n                'saveshortcut-scroll'\n              ),\n            },\n          ]);\n        } else {\n          for (let i = 0; i < actions.length; i++) {\n            let action = actions[i];\n            if (!action.shortcut) {\n              continue;\n            }\n            shortcuts.push([\n              {\n                keyCode: Garnish.S_KEY,\n                ctrl: true,\n                shift: !!action.shift,\n              },\n              {\n                action: action.action,\n                redirect: action.redirect,\n                confirm: action.confirm,\n                params: action.params,\n                data: action.data,\n                retainScroll: action.retainScroll,\n              },\n            ]);\n          }\n        }\n        for (let i = 0; i < shortcuts.length; i++) {\n          Garnish.uiLayerManager.registerShortcut(shortcuts[i][0], () => {\n            this.submitPrimaryForm(shortcuts[i][1]);\n          });\n        }\n      }\n\n      this.initTabs();\n\n      // Should we match the previous scroll position?\n      let scrollY = Craft.getLocalStorage('scrollY');\n      if (typeof scrollY !== 'undefined') {\n        Craft.removeLocalStorage('scrollY');\n        Garnish.$doc.ready(() => {\n          Garnish.requestAnimationFrame(() => {\n            window.scrollTo(0, scrollY);\n          });\n        });\n      }\n\n      if ($.isTouchCapable()) {\n        this.$mainContainer.on(\n          'focus',\n          'input, textarea, .focusable-input',\n          this._handleInputFocus.bind(this)\n        );\n        this.$mainContainer.on(\n          'blur',\n          'input, textarea, .focusable-input',\n          this._handleInputBlur.bind(this)\n        );\n      }\n\n      // Announcements HUD\n      if (Craft.announcements.length) {\n        let $btn = $('#announcements-btn').removeClass('hidden');\n        const hasUnreads = Craft.announcements.some((a) => a.unread);\n        if (hasUnreads) {\n          $btn.addClass('unread');\n        }\n        let hud;\n        this.addListener($btn, 'click', () => {\n          if (!hud) {\n            let contents = '';\n            Craft.group(Craft.announcements, 'timestamp').forEach(\n              ([announcements, timestamp]) => {\n                announcements.forEach((a, i) => {\n                  contents +=\n                    `<div class=\"announcement ${a.unread ? 'unread' : ''}\">` +\n                    (i === 0\n                      ? `<div class=\"timestamp\">${a.timestamp}</div>`\n                      : '') +\n                    `<h2>${a.heading}</h2>` +\n                    `<p>${a.body}</p>` +\n                    '</div>';\n                });\n              }\n            );\n            hud = new Garnish.HUD(\n              $btn,\n              `<div id=\"announcements\">${contents}</div>`,\n              {\n                onShow: () => {\n                  $btn.addClass('active');\n                },\n                onHide: () => {\n                  $btn.removeClass('active');\n                },\n              }\n            );\n\n            // Open outbound links in new windows\n            $('a', hud.$main).each(function () {\n              if (\n                this.hostname.length &&\n                this.hostname !== location.hostname &&\n                typeof $(this).attr('target') === 'undefined'\n              ) {\n                $(this).attr('rel', 'noopener').attr('target', '_blank');\n              }\n            });\n\n            if (hasUnreads) {\n              $btn.removeClass('unread');\n              Craft.sendActionRequest(\n                'POST',\n                'users/mark-announcements-as-read',\n                {\n                  data: {\n                    ids: Craft.announcements.map((a) => a.id),\n                  },\n                }\n              );\n            }\n          } else {\n            hud.show();\n          }\n        });\n      }\n    },\n\n    initSpecialForms: function () {\n      // Look for forms that we should watch for changes on\n      this.$confirmUnloadForms = $('form[data-confirm-unload]');\n      this.$deltaForms = $('form[data-delta]');\n\n      if (!this.$confirmUnloadForms.length) {\n        return;\n      }\n\n      var $forms = this.$confirmUnloadForms.add(this.$deltaForms);\n      var $form, serialized;\n\n      for (var i = 0; i < $forms.length; i++) {\n        $form = $forms.eq(i);\n        if (!$form.data('initialSerializedValue')) {\n          if (typeof $form.data('serializer') === 'function') {\n            serialized = $form.data('serializer')();\n          } else {\n            serialized = $form.serialize();\n          }\n          $form.data('initialSerializedValue', serialized);\n        }\n        this.addListener($form, 'submit', function (ev) {\n          if (Garnish.hasAttr($form, 'data-confirm-unload')) {\n            this.removeListener(Garnish.$win, 'beforeunload');\n          }\n          if (Garnish.hasAttr($form, 'data-delta')) {\n            ev.preventDefault();\n            var serialized;\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            var data = Craft.findDeltaData(\n              $form.data('initialSerializedValue'),\n              serialized,\n              Craft.deltaNames\n            );\n            Craft.createForm(data).appendTo(Garnish.$bod).submit();\n          }\n        });\n      }\n\n      this.addListener(Garnish.$win, 'beforeunload', function (ev) {\n        var confirmUnload = false;\n        var $form, serialized;\n        if (\n          typeof Craft.livePreview !== 'undefined' &&\n          Craft.livePreview.inPreviewMode\n        ) {\n          confirmUnload = true;\n        } else {\n          for (var i = 0; i < this.$confirmUnloadForms.length; i++) {\n            $form = this.$confirmUnloadForms.eq(i);\n            if (typeof $form.data('serializer') === 'function') {\n              serialized = $form.data('serializer')();\n            } else {\n              serialized = $form.serialize();\n            }\n            if ($form.data('initialSerializedValue') !== serialized) {\n              confirmUnload = true;\n              break;\n            }\n          }\n        }\n\n        if (confirmUnload) {\n          var message = Craft.t(\n            'app',\n            'Any changes will be lost if you leave this page.'\n          );\n\n          if (ev) {\n            ev.originalEvent.returnValue = message;\n          } else {\n            window.event.returnValue = message;\n          }\n\n          return message;\n        }\n      });\n    },\n\n    _handleInputFocus: function () {\n      this.updateFixedHeader();\n    },\n\n    _handleInputBlur: function () {\n      this.updateFixedHeader();\n    },\n\n    /**\n     * Submits a form.\n     * @param {Object} [options]\n     * @param {string} [options.action] The `action` param value override\n     * @param {string} [options.redirect] The `redirect` param value override\n     * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n     * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n     * @param {Object} [options.data] Additional data to be passed to the submit event\n     * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n     */\n    submitPrimaryForm: function (options) {\n      // Give other stuff on the page a chance to prepare\n      this.trigger('beforeSaveShortcut');\n\n      if (typeof options !== 'object' || !$.isPlainObject(options)) {\n        options = {};\n      }\n\n      if (!options.redirect) {\n        options.redirect = this.$primaryForm.data('saveshortcut-redirect');\n      }\n\n      if (!options.data) {\n        options.data = {};\n      }\n      options.data.saveShortcut = true;\n\n      Craft.submitForm(this.$primaryForm, options);\n    },\n\n    updateSidebarMenuLabel: function () {\n      var $item = this.$sidebar.find('a.sel:first');\n      var $label = $item.children('.label');\n      $('#selected-sidebar-item-label').text(\n        $label.length ? $label.text() : $item.text()\n      );\n      Garnish.$bod.removeClass('showing-sidebar');\n    },\n\n    toggleNav: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (isExpanded) {\n        this.disableGlobalSidebarLinks();\n        this.$navToggle.focus();\n        this.$navToggle.attr('aria-expanded', 'false');\n        Garnish.$bod.removeClass('showing-nav');\n      } else {\n        this.enableGlobalSidebarLinks();\n        this.$globalSidebar.find(':focusable')[0].focus();\n        this.$navToggle.attr('aria-expanded', 'true');\n        Garnish.$bod.addClass('showing-nav');\n      }\n    },\n\n    enableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '0');\n      });\n    },\n\n    disableGlobalSidebarLinks: function () {\n      const focusableItems = this.$globalSidebar.find(':focusable');\n\n      $(focusableItems).each(function () {\n        $(this).attr('tabindex', '-1');\n      });\n    },\n\n    setSidebarNavAttributes: function () {\n      const isExpanded = this.navIsExpanded();\n\n      if (isExpanded === null) return;\n\n      if (!isExpanded) {\n        this.disableGlobalSidebarLinks();\n      } else {\n        this.enableGlobalSidebarLinks();\n      }\n    },\n\n    navIsExpanded: function () {\n      if (!this.$globalSidebar[0]) return null;\n\n      const isAlwaysVisible = getComputedStyle(this.$globalSidebar[0])\n        .getPropertyValue('--is-always-visible')\n        .trim();\n\n      return (\n        this.$navToggle.attr('aria-expanded') === 'true' ||\n        isAlwaysVisible === 'true'\n      );\n    },\n\n    toggleSidebar: function () {\n      Garnish.$bod.toggleClass('showing-sidebar');\n    },\n\n    initTabs: function () {\n      if (this.tabManager) {\n        this.tabManager.destroy();\n        this.tabManager = null;\n      }\n\n      const $tabs = $('#tabs');\n      if (!$tabs.length) {\n        return;\n      }\n\n      this.tabManager = new Craft.Tabs($tabs);\n\n      this.tabManager.on('selectTab', (ev) => {\n        const href = ev.$tab.attr('href');\n\n        // Show its content area\n        if (href.charAt(0) === '#') {\n          $(href).removeClass('hidden');\n        }\n\n        // Trigger a resize event to update any UI components that are listening for it\n        Garnish.$win.trigger('resize');\n\n        // Fixes Redactor fixed toolbars on previously hidden panes\n        Garnish.$doc.trigger('scroll');\n\n        // If there is a revision menu, set its links to this tab ID\n        if (href && href.charAt(0) === '#') {\n          const menuBtn = $('#context-btn').menubtn().data('menubtn');\n          if (menuBtn) {\n            for (let i = 0; i < menuBtn.menu.$options.length; i++) {\n              let a = menuBtn.menu.$options[i];\n              if (a.href) {\n                a.href = a.href.match(/^[^#]*/)[0] + href;\n              }\n            }\n          }\n        }\n\n        if (typeof history !== 'undefined') {\n          // Delay changing the hash so it doesn't cause the browser to jump on page load\n          Garnish.requestAnimationFrame(() => {\n            history.replaceState(undefined, undefined, href);\n          });\n        }\n      });\n\n      this.tabManager.on('deselectTab', (ev) => {\n        if (ev.$tab.attr('href').charAt(0) === '#') {\n          // Hide its content area\n          $(ev.$tab.attr('href')).addClass('hidden');\n        }\n      });\n\n      if (window.LOCATION_HASH) {\n        const $tab = this.tabManager.$tabs.filter(\n          `[href=\"#${window.LOCATION_HASH}\"]`\n        );\n        if ($tab.length) {\n          this.tabManager.selectTab($tab);\n        }\n      }\n    },\n\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsContainer() {\n      return this.tabManager ? this.tabManager.$container : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabsList() {\n      return this.tabManager ? this.tabManager.$ul : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $tabs() {\n      return this.tabManager ? this.tabManager.$ul.find('> li') : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $selectedTab() {\n      return this.tabManager ? this.tabManager.$selectedTab : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get selectedTabIndex() {\n      return this.tabManager\n        ? this.tabManager.$tabs.index(this.tabManager.$selectedTab)\n        : undefined;\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    get $focusableTab() {\n      return this.tabManager ? this.tabManager.$focusableTab : undefined;\n    },\n    /**\n     * @param {object} tab\n     * @deprecated in 3.7.0\n     */\n    selectTab: function (tab) {\n      if (this.tabManager) {\n        this.tabManager.selectTab(tab);\n      }\n    },\n    /**\n     * @deprecated in 3.7.0\n     */\n    deselectTab: function () {\n      if (this.tabManager) {\n        this.tabManager.deselectTab();\n      }\n    },\n\n    handleWindowResize: function () {\n      this.updateResponsiveTables();\n      this.handleBreadcrumbVisibility();\n    },\n\n    breadcrumbItemsWrap: function () {\n      if (!this.$breadcrumbItems[0]) return;\n\n      this.$breadcrumbList.css(\n        Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n        ''\n      );\n      const listWidth = this.$breadcrumbList[0].getBoundingClientRect().width;\n      let totalItemWidth = 0;\n\n      // Iterate through all list items (inclusive of more button)\n      const $items = this.$breadcrumbList.find('li');\n      for (let i = 0; i < $items.length; i++) {\n        totalItemWidth += $items.get(i).getBoundingClientRect().width;\n      }\n\n      this.breadcrumbListWidth = listWidth;\n\n      if (totalItemWidth <= listWidth) {\n        return false;\n      }\n\n      // If it's less than a pixel off, it's probably just a rounding error.\n      // Give the container an extra pixel to be safe, though\n      if (totalItemWidth < listWidth + 1) {\n        this.$breadcrumbList.css(\n          Craft.orientation === 'ltr' ? 'margin-right' : 'margin-left',\n          '-1px'\n        );\n        return false;\n      }\n\n      return true;\n    },\n\n    handleBreadcrumbVisibility: function () {\n      if (!this.breadcrumbItemsWrap()) return;\n\n      if (this.$breadcrumbList.find('[data-disclosure-item]').length === 0) {\n        this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n      }\n\n      const triggerWidth = this.$breadcrumbList.find(\n        '[data-disclosure-item]'\n      )[0].offsetWidth;\n      let visibleItemWidth = triggerWidth;\n      let finalIndex;\n      let newWidth;\n      const listWidth = this.breadcrumbListWidth;\n\n      // Find breadcrumbs that should remain visible without overflowing\n      this.$breadcrumbItems.each(function (index) {\n        newWidth = visibleItemWidth + this.offsetWidth;\n\n        if (newWidth < listWidth) {\n          finalIndex = index;\n          visibleItemWidth += this.offsetWidth;\n        } else {\n          return false;\n        }\n      });\n\n      // Separate breadcrums that should remain visible vs. hidden\n      const shownItems = this.$breadcrumbItems.slice(0, finalIndex + 1);\n      const hiddenItems = this.$breadcrumbItems.slice(finalIndex + 1);\n\n      // Empty list DOM and add shown items and trigger item\n      this.$breadcrumbList.html('');\n      this.$breadcrumbList.append(shownItems);\n      this.$breadcrumbList.append(this.breadcrumbDisclosureItem);\n\n      // Add hidden items to disclosure menu and initialize\n      this.$breadcrumbList\n        .find('[data-disclosure-menu] ul')\n        .append(hiddenItems);\n      this.$breadcrumbList.find('[data-disclosure-trigger]').disclosureMenu();\n    },\n\n    updateResponsiveTables: function () {\n      for (\n        this.updateResponsiveTables._i = 0;\n        this.updateResponsiveTables._i < this.$collapsibleTables.length;\n        this.updateResponsiveTables._i++\n      ) {\n        this.updateResponsiveTables._$table = this.$collapsibleTables.eq(\n          this.updateResponsiveTables._i\n        );\n        this.updateResponsiveTables._containerWidth =\n          this.updateResponsiveTables._$table.parent().width();\n        this.updateResponsiveTables._check = false;\n\n        if (this.updateResponsiveTables._containerWidth > 0) {\n          // Is this the first time we've checked this table?\n          if (\n            typeof this.updateResponsiveTables._$table.data(\n              'lastContainerWidth'\n            ) === 'undefined'\n          ) {\n            this.updateResponsiveTables._check = true;\n          } else {\n            this.updateResponsiveTables._isCollapsed =\n              this.updateResponsiveTables._$table.hasClass('collapsed');\n\n            // Getting wider?\n            if (\n              this.updateResponsiveTables._containerWidth >\n              this.updateResponsiveTables._$table.data('lastContainerWidth')\n            ) {\n              if (this.updateResponsiveTables._isCollapsed) {\n                this.updateResponsiveTables._$table.removeClass('collapsed');\n                this.updateResponsiveTables._check = true;\n              }\n            } else if (!this.updateResponsiveTables._isCollapsed) {\n              this.updateResponsiveTables._check = true;\n            }\n          }\n\n          // Are we checking the table width?\n          if (this.updateResponsiveTables._check) {\n            if (\n              this.updateResponsiveTables._$table.width() - 30 >\n              this.updateResponsiveTables._containerWidth\n            ) {\n              this.updateResponsiveTables._$table.addClass('collapsed');\n            }\n          }\n\n          // Remember the container width for next time\n          this.updateResponsiveTables._$table.data(\n            'lastContainerWidth',\n            this.updateResponsiveTables._containerWidth\n          );\n        }\n      }\n    },\n\n    updateFixedHeader: function () {\n      if (this.isMobile) {\n        return;\n      }\n\n      // Have we scrolled passed the top of #main?\n      if (\n        this.$main.length &&\n        this.$headerContainer[0].getBoundingClientRect().top < 0\n      ) {\n        if (!this.fixedHeader) {\n          var headerHeight = this.$headerContainer.height();\n\n          // Hard-set the minimum content container height\n          this.$contentContainer.css(\n            'min-height',\n            'calc(100vh - ' + (headerHeight + 14 + 48 - 1) + 'px)'\n          );\n\n          // Hard-set the header container height\n          this.$headerContainer.height(headerHeight);\n          Garnish.$bod.addClass('fixed-header');\n\n          // Fix the sidebar and details pane positions if they are taller than #content-container\n          var contentHeight = this.$contentContainer.outerHeight();\n          var $detailsHeight = this.$details.outerHeight();\n          var css = {\n            top: headerHeight + 'px',\n            'max-height': 'calc(100vh - ' + headerHeight + 'px)',\n          };\n          this.$sidebar.addClass('fixed').css(css);\n          this.$details.addClass('fixed').css(css);\n          this.fixedHeader = true;\n        }\n      } else if (this.fixedHeader) {\n        this.$headerContainer.height('auto');\n        Garnish.$bod.removeClass('fixed-header');\n        this.$contentContainer.css('min-height', '');\n        this.$sidebar.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.$details.removeClass('fixed').css({\n          top: '',\n          'max-height': '',\n        });\n        this.fixedHeader = false;\n      }\n    },\n\n    /**\n     * Dispays a notification.\n     *\n     * @param {string} type\n     * @param {string} message\n     */\n    displayNotification: function (type, message) {\n      var notificationDuration = Craft.CP.notificationDuration;\n\n      if (['cp-error', 'error'].includes(type)) {\n        notificationDuration *= 2;\n        icon = 'alert';\n        label = Craft.t('app', 'Error');\n      } else {\n        icon = 'info';\n        label = Craft.t('app', 'Notice');\n      }\n\n      var $notification = $(`\n            <div class=\"notification ${type.replace('cp-', '')}\">\n                <span data-icon=\"${icon}\" aria-label=\"${label}\"></span>\n                ${message}\n            </div>\n            `).appendTo(this.$notificationContainer);\n\n      var fadedMargin = -($notification.outerWidth() / 2) + 'px';\n\n      $notification\n        .hide()\n        .css({\n          opacity: 0,\n          'margin-left': fadedMargin,\n          'margin-right': fadedMargin,\n        })\n        .velocity(\n          {opacity: 1, 'margin-left': '2px', 'margin-right': '2px'},\n          {display: 'inline-block', duration: 'fast'}\n        )\n        .delay(notificationDuration)\n        .velocity(\n          {opacity: 0, 'margin-left': fadedMargin, 'margin-right': fadedMargin},\n          {\n            complete: function () {\n              $notification.remove();\n            },\n          }\n        );\n\n      this.trigger('displayNotification', {\n        notificationType: type,\n        message: message,\n      });\n    },\n\n    /**\n     * Displays a notice.\n     *\n     * @param {string} message\n     */\n    displayNotice: function (message) {\n      this.displayNotification('notice', message);\n    },\n\n    /**\n     * Displays an error.\n     *\n     * @param {string} message\n     */\n    displayError: function (message) {\n      if (!message) {\n        message = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.displayNotification('error', message);\n    },\n\n    fetchAlerts: function () {\n      var data = {\n        path: Craft.path,\n      };\n\n      Craft.queueActionRequest(\n        'app/get-cp-alerts',\n        data,\n        this.displayAlerts.bind(this)\n      );\n    },\n\n    displayAlerts: function (alerts) {\n      this.$alerts.remove();\n\n      if (Garnish.isArray(alerts) && alerts.length) {\n        this.$alerts = $('<ul id=\"alerts\"/>').prependTo($('#page-container'));\n\n        for (var i = 0; i < alerts.length; i++) {\n          $(\n            `<li><span data-icon=\"alert\" aria-label=\"${Craft.t(\n              'app',\n              'Error'\n            )}\"></span> ${alerts[i]}</li>`\n          ).appendTo(this.$alerts);\n        }\n\n        var height = this.$alerts.outerHeight();\n        this.$alerts\n          .css('margin-top', -height)\n          .velocity({'margin-top': 0}, 'fast');\n\n        this.initAlerts();\n      }\n    },\n\n    initAlerts: function () {\n      // Are there any shunnable alerts?\n      var $shunnableAlerts = this.$alerts.find('a[class^=\"shun:\"]');\n\n      for (var i = 0; i < $shunnableAlerts.length; i++) {\n        this.addListener($shunnableAlerts[i], 'click', (ev) => {\n          ev.preventDefault();\n\n          var $link = $(ev.currentTarget);\n\n          var data = {\n            message: $link.prop('className').substr(5),\n          };\n\n          Craft.queueActionRequest(\n            'app/shun-cp-alert',\n            data,\n            (response, textStatus) => {\n              if (textStatus === 'success') {\n                if (response.success) {\n                  $link.parent().remove();\n                } else {\n                  this.displayError(response.error);\n                }\n              }\n            }\n          );\n        });\n      }\n    },\n\n    checkForUpdates: function (forceRefresh, includeDetails, callback) {\n      // Make 'includeDetails' optional\n      if (typeof includeDetails === 'function') {\n        callback = includeDetails;\n        includeDetails = false;\n      }\n\n      // If forceRefresh == true, we're currently checking for updates, and not currently forcing a refresh,\n      // then just set a new callback that re-checks for updates when the current one is done.\n      if (\n        this.checkingForUpdates &&\n        ((forceRefresh === true && !this.forcingRefreshOnUpdatesCheck) ||\n          (includeDetails === true && !this.includingDetailsOnUpdatesCheck))\n      ) {\n        var realCallback = callback;\n        callback = () => {\n          this.checkForUpdates(forceRefresh, includeDetails, realCallback);\n        };\n      }\n\n      // Callback function?\n      if (typeof callback === 'function') {\n        if (!Garnish.isArray(this.checkForUpdatesCallbacks)) {\n          this.checkForUpdatesCallbacks = [];\n        }\n\n        this.checkForUpdatesCallbacks.push(callback);\n      }\n\n      if (!this.checkingForUpdates) {\n        this.checkingForUpdates = true;\n        this.forcingRefreshOnUpdatesCheck = forceRefresh === true;\n        this.includingDetailsOnUpdatesCheck = includeDetails === true;\n\n        this._checkForUpdates(forceRefresh, includeDetails).then((info) => {\n          this.updateUtilitiesBadge();\n          this.checkingForUpdates = false;\n\n          if (Garnish.isArray(this.checkForUpdatesCallbacks)) {\n            var callbacks = this.checkForUpdatesCallbacks;\n            this.checkForUpdatesCallbacks = null;\n\n            for (var i = 0; i < callbacks.length; i++) {\n              callbacks[i](info);\n            }\n          }\n\n          this.trigger('checkForUpdates', {\n            updateInfo: info,\n          });\n        });\n      }\n    },\n\n    _checkForUpdates: function (forceRefresh, includeDetails) {\n      return new Promise((resolve, reject) => {\n        if (!forceRefresh) {\n          this._checkForCachedUpdates(includeDetails).then((info) => {\n            if (info.cached !== false) {\n              resolve(info);\n            }\n\n            this._getUpdates(includeDetails).then((info) => {\n              resolve(info);\n            });\n          });\n        } else {\n          this._getUpdates(includeDetails).then((info) => {\n            resolve(info);\n          });\n        }\n      });\n    },\n\n    _checkForCachedUpdates: function (includeDetails) {\n      return new Promise(function (resolve, reject) {\n        var data = {\n          onlyIfCached: true,\n          includeDetails: includeDetails,\n        };\n        Craft.postActionRequest(\n          'app/check-for-updates',\n          data,\n          function (info, textStatus) {\n            if (textStatus === 'success') {\n              resolve(info);\n            } else {\n              resolve({cached: false});\n            }\n          }\n        );\n      });\n    },\n\n    _getUpdates: function (includeDetails) {\n      return new Promise((resolve, reject) => {\n        Craft.sendApiRequest('GET', 'updates')\n          .then((updates) => {\n            this._cacheUpdates(updates, includeDetails).then(resolve);\n          })\n          .catch((e) => {\n            this._cacheUpdates({}).then(resolve);\n          });\n      });\n    },\n\n    _cacheUpdates: function (updates, includeDetails) {\n      return new Promise(function (resolve, reject) {\n        Craft.postActionRequest(\n          'app/cache-updates',\n          {\n            updates: updates,\n            includeDetails: includeDetails,\n          },\n          function (info, textStatus) {\n            if (textStatus === 'success') {\n              resolve(info);\n            } else {\n              reject();\n            }\n          },\n          {\n            contentType: 'json',\n          }\n        );\n      });\n    },\n\n    updateUtilitiesBadge: function () {\n      var $utilitiesLink = $('#nav-utilities').find('> a:not(.sel)');\n\n      // Ignore if there is no (non-selected) Utilities nav item\n      if (!$utilitiesLink.length) {\n        return;\n      }\n\n      Craft.queueActionRequest('app/get-utilities-badge-count', (response) => {\n        // Get the existing utility nav badge, if any\n        var $badge = $utilitiesLink.children('.badge');\n\n        if (response.badgeCount) {\n          if (!$badge.length) {\n            $badge = $('<span class=\"badge\"/>').appendTo($utilitiesLink);\n          }\n          $badge.text(response.badgeCount);\n        } else if ($badge.length) {\n          $badge.remove();\n        }\n      });\n    },\n\n    runQueue: function () {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      if (Craft.runQueueAutomatically) {\n        Craft.queueActionRequest('queue/run', (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.trackJobProgress(false, true);\n          }\n        });\n      } else {\n        this.trackJobProgress(false, true);\n      }\n    },\n\n    trackJobProgress: function (delay, force) {\n      if (force && this.trackJobProgressTimeout) {\n        clearTimeout(this.trackJobProgressTimeout);\n        this.trackJobProgressTimeout = null;\n      }\n\n      // Ignore if we're already tracking jobs, or the queue is disabled\n      if (this.trackJobProgressTimeout || !this.enableQueue) {\n        return;\n      }\n\n      if (delay === true) {\n        // Determine the delay based on how long the displayed job info has remained unchanged\n        var timeout = Math.min(60000, this.displayedJobInfoUnchanged * 500);\n        this.trackJobProgressTimeout = setTimeout(\n          this._trackJobProgressInternal.bind(this),\n          timeout\n        );\n      } else {\n        this._trackJobProgressInternal();\n      }\n    },\n\n    _trackJobProgressInternal: function () {\n      Craft.queueActionRequest(\n        'queue/get-job-info?limit=50&dontExtendSession=1',\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.trackJobProgressTimeout = null;\n            this.totalJobs = response.total;\n            this.setJobInfo(response.jobs);\n\n            if (this.jobInfo.length) {\n              // Check again after a delay\n              this.trackJobProgress(true);\n            }\n          }\n        }\n      );\n    },\n\n    setJobInfo: function (jobInfo) {\n      if (!this.enableQueue) {\n        return;\n      }\n\n      this.jobInfo = jobInfo;\n\n      // Update the displayed job info\n      var oldInfo = this.displayedJobInfo;\n      this.displayedJobInfo = this.getDisplayedJobInfo();\n\n      // Same old same old?\n      if (\n        oldInfo &&\n        this.displayedJobInfo &&\n        oldInfo.id === this.displayedJobInfo.id &&\n        oldInfo.progress === this.displayedJobInfo.progress &&\n        oldInfo.progressLabel === this.displayedJobInfo.progressLabel &&\n        oldInfo.status === this.displayedJobInfo.status\n      ) {\n        this.displayedJobInfoUnchanged++;\n      } else {\n        // Reset the counter\n        this.displayedJobInfoUnchanged = 1;\n      }\n\n      this.updateJobIcon();\n\n      // Fire a setJobInfo event\n      this.trigger('setJobInfo');\n    },\n\n    /**\n     * Returns info for the job that should be displayed in the CP sidebar\n     */\n    getDisplayedJobInfo: function () {\n      if (!this.enableQueue) {\n        return null;\n      }\n\n      // Set the status preference order\n      var statuses = [\n        Craft.CP.JOB_STATUS_RESERVED,\n        Craft.CP.JOB_STATUS_FAILED,\n        Craft.CP.JOB_STATUS_WAITING,\n      ];\n\n      for (var i = 0; i < statuses.length; i++) {\n        for (var j = 0; j < this.jobInfo.length; j++) {\n          if (\n            this.jobInfo[j].status === statuses[i] &&\n            (statuses[i] !== Craft.CP.JOB_STATUS_WAITING ||\n              !this.jobInfo[j].delay)\n          ) {\n            return this.jobInfo[j];\n          }\n        }\n      }\n\n      return null;\n    },\n\n    updateJobIcon: function () {\n      if (!this.enableQueue || !this.$nav.length) {\n        return;\n      }\n\n      if (this.displayedJobInfo) {\n        if (!this.jobProgressIcon) {\n          this.jobProgressIcon = new JobProgressIcon();\n        }\n\n        if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_RESERVED ||\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_WAITING\n        ) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.setDescription(\n            this.displayedJobInfo.description,\n            this.displayedJobInfo.progressLabel\n          );\n          this.jobProgressIcon.setProgress(this.displayedJobInfo.progress);\n        } else if (\n          this.displayedJobInfo.status === Craft.CP.JOB_STATUS_FAILED\n        ) {\n          this.jobProgressIcon.showFailMode(Craft.t('app', 'Failed'));\n        }\n      } else {\n        if (this.jobProgressIcon) {\n          this.jobProgressIcon.hideFailMode();\n          this.jobProgressIcon.complete();\n          delete this.jobProgressIcon;\n        }\n      }\n    },\n\n    /**\n     * Returns the active site for the control panel\n     *\n     * @return {number}\n     */\n    getSiteId: function () {\n      // If the old BaseElementIndex.siteId value is in localStorage, go aheand and remove & return that\n      let siteId = Craft.getLocalStorage('BaseElementIndex.siteId');\n      if (typeof siteId !== 'undefined') {\n        Craft.removeLocalStorage('BaseElementIndex.siteId');\n        this.setSiteId(siteId);\n        return siteId;\n      }\n      return Craft.getCookie('siteId');\n    },\n\n    /**\n     * Sets the active site for the control panel\n     * @param {number} siteId\n     */\n    setSiteId: function (siteId) {\n      Craft.setCookie('siteId', siteId, {\n        maxAge: 31536000, // 1 year\n      });\n    },\n  },\n  {\n    //maxWidth: 1051, //1024,\n    notificationDuration: 2000,\n\n    JOB_STATUS_WAITING: 1,\n    JOB_STATUS_RESERVED: 2,\n    JOB_STATUS_DONE: 3,\n    JOB_STATUS_FAILED: 4,\n  }\n);\n\nGarnish.$scrollContainer = Garnish.$win;\nCraft.cp = new Craft.CP();\n\n/**\n * Job progress icon class\n */\nvar JobProgressIcon = Garnish.Base.extend({\n  $li: null,\n  $a: null,\n  $label: null,\n  $progressLabel: null,\n\n  progress: null,\n  failMode: false,\n\n  _$bgCanvas: null,\n  _$staticCanvas: null,\n  _$hoverCanvas: null,\n  _$failCanvas: null,\n\n  _staticCtx: null,\n  _hoverCtx: null,\n  _canvasSize: null,\n  _arcPos: null,\n  _arcRadius: null,\n  _lineWidth: null,\n\n  _arcStartPos: 0,\n  _arcEndPos: 0,\n  _arcStartStepSize: null,\n  _arcEndStepSize: null,\n  _arcStep: null,\n  _arcStepTimeout: null,\n  _arcAnimateCallback: null,\n\n  _progressBar: null,\n\n  init: function () {\n    this.$li = $('<li/>').appendTo(Craft.cp.$nav.children('ul'));\n    this.$a = $('<a/>', {\n      id: 'job-icon',\n      href: Craft.canAccessQueueManager\n        ? Craft.getUrl('utilities/queue-manager')\n        : null,\n    }).appendTo(this.$li);\n    this.$canvasContainer = $('<span class=\"icon\"/>').appendTo(this.$a);\n    var $labelContainer = $('<span class=\"label\"/>').appendTo(this.$a);\n    this.$label = $('<span/>').appendTo($labelContainer);\n    this.$progressLabel = $('<span class=\"progress-label\"/>')\n      .appendTo($labelContainer)\n      .hide();\n\n    let m = window.devicePixelRatio > 1 ? 2 : 1;\n    this._canvasSize = 18 * m;\n    this._arcPos = this._canvasSize / 2;\n    this._arcRadius = 7 * m;\n    this._lineWidth = 3 * m;\n\n    this._$bgCanvas = this._createCanvas('bg', '#61666b');\n    this._$staticCanvas = this._createCanvas('static', '#d7d9db');\n    this._$hoverCanvas = this._createCanvas('hover', '#fff');\n    this._$failCanvas = this._createCanvas('fail', '#da5a47').hide();\n\n    this._staticCtx = this._$staticCanvas[0].getContext('2d');\n    this._hoverCtx = this._$hoverCanvas[0].getContext('2d');\n\n    this._drawArc(this._$bgCanvas[0].getContext('2d'), 0, 1);\n    this._drawArc(this._$failCanvas[0].getContext('2d'), 0, 1);\n  },\n\n  setDescription: function (description, progressLabel) {\n    this.$a.attr('title', description);\n    this.$label.text(description);\n    if (progressLabel) {\n      this.$progressLabel.text(progressLabel).show();\n    } else {\n      this.$progressLabel.hide();\n    }\n  },\n\n  setProgress: function (progress) {\n    if (progress == 0) {\n      this._$staticCanvas.hide();\n      this._$hoverCanvas.hide();\n    } else {\n      this._$staticCanvas.show();\n      this._$hoverCanvas.show();\n      if (this.progress && progress > this.progress) {\n        this._animateArc(0, progress / 100);\n      } else {\n        this._setArc(0, progress / 100);\n      }\n    }\n\n    this.progress = progress;\n  },\n\n  complete: function () {\n    this._animateArc(0, 1, () => {\n      this._$bgCanvas.velocity('fadeOut');\n\n      this._animateArc(1, 1, () => {\n        this.$a.remove();\n        this.destroy();\n      });\n    });\n  },\n\n  showFailMode: function (message) {\n    if (this.failMode) {\n      return;\n    }\n\n    this.failMode = true;\n    this.progress = null;\n\n    this._$bgCanvas.hide();\n    this._$staticCanvas.hide();\n    this._$hoverCanvas.hide();\n    this._$failCanvas.show();\n\n    this.setDescription(message);\n  },\n\n  hideFailMode: function () {\n    if (!this.failMode) {\n      return;\n    }\n\n    this.failMode = false;\n\n    this._$bgCanvas.show();\n    this._$staticCanvas.show();\n    this._$hoverCanvas.show();\n    this._$failCanvas.hide();\n  },\n\n  _createCanvas: function (id, color) {\n    var $canvas = $(\n        '<canvas id=\"job-icon-' +\n          id +\n          '\" width=\"' +\n          this._canvasSize +\n          '\" height=\"' +\n          this._canvasSize +\n          '\"/>'\n      ).appendTo(this.$canvasContainer),\n      ctx = $canvas[0].getContext('2d');\n\n    ctx.strokeStyle = color;\n    ctx.lineWidth = this._lineWidth;\n    ctx.lineCap = 'round';\n    return $canvas;\n  },\n\n  _setArc: function (startPos, endPos) {\n    this._arcStartPos = startPos;\n    this._arcEndPos = endPos;\n\n    this._drawArc(this._staticCtx, startPos, endPos);\n    this._drawArc(this._hoverCtx, startPos, endPos);\n  },\n\n  _drawArc: function (ctx, startPos, endPos) {\n    ctx.clearRect(0, 0, this._canvasSize, this._canvasSize);\n    ctx.beginPath();\n    ctx.arc(\n      this._arcPos,\n      this._arcPos,\n      this._arcRadius,\n      (1.5 + startPos * 2) * Math.PI,\n      (1.5 + endPos * 2) * Math.PI\n    );\n    ctx.stroke();\n    ctx.closePath();\n  },\n\n  _animateArc: function (targetStartPos, targetEndPos, callback) {\n    if (this._arcStepTimeout) {\n      clearTimeout(this._arcStepTimeout);\n    }\n\n    this._arcStep = 0;\n    this._arcStartStepSize = (targetStartPos - this._arcStartPos) / 10;\n    this._arcEndStepSize = (targetEndPos - this._arcEndPos) / 10;\n    this._arcAnimateCallback = callback;\n    this._takeNextArcStep();\n  },\n\n  _takeNextArcStep: function () {\n    this._setArc(\n      this._arcStartPos + this._arcStartStepSize,\n      this._arcEndPos + this._arcEndStepSize\n    );\n\n    this._arcStep++;\n\n    if (this._arcStep < 10) {\n      this._arcStepTimeout = setTimeout(this._takeNextArcStep.bind(this), 50);\n    } else if (this._arcAnimateCallback) {\n      this._arcAnimateCallback();\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category index class\n */\nCraft.CategoryIndex = Craft.BaseElementIndex.extend({\n  editableGroups: null,\n  $newCategoryBtnGroup: null,\n  $newCategoryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible groups the user has permission to create new categories in\n    this.editableGroups = [];\n\n    for (var i = 0; i < Craft.editableCategoryGroups.length; i++) {\n      var group = Craft.editableCategoryGroups[i];\n\n      if (this.getSourceByKey('group:' + group.uid)) {\n        this.editableGroups.push(group);\n      }\n    }\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific category group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultGroupHandle !== 'undefined'\n    ) {\n      for (var i = 0; i < this.$sources.length; i++) {\n        var $source = $(this.$sources[i]);\n\n        if ($source.data('handle') === defaultGroupHandle) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    // Get the handle of the selected source\n    var selectedSourceHandle = this.$source.data('handle');\n\n    var i, href, label;\n\n    // Update the New Category button\n    // ---------------------------------------------------------------------\n\n    if (this.editableGroups.length) {\n      // Remove the old button, if there is one\n      if (this.$newCategoryBtnGroup) {\n        this.$newCategoryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a group that they have permission to create categories in\n      var selectedGroup;\n\n      if (selectedSourceHandle) {\n        for (i = 0; i < this.editableGroups.length; i++) {\n          if (this.editableGroups[i].handle === selectedSourceHandle) {\n            selectedGroup = this.editableGroups[i];\n            break;\n          }\n        }\n      }\n\n      this.$newCategoryBtnGroup = $('<div class=\"btngroup submit\"/>');\n      var $menuBtn;\n\n      // If they are, show a primary \"New category\" button, and a dropdown of the other groups (if any).\n      // Otherwise only show a menu button\n      if (selectedGroup) {\n        href = this._getGroupTriggerHref(selectedGroup);\n        label =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New category')\n            : Craft.t('app', 'New {group} category', {\n                group: selectedGroup.name,\n              });\n        this.$newCategoryBtn = $(\n          '<a class=\"btn submit add icon\" ' +\n            href +\n            ' role=\"button\">' +\n            Craft.escapeHtml(label) +\n            '</a>'\n        ).appendTo(this.$newCategoryBtnGroup);\n\n        if (this.settings.context !== 'index') {\n          this.addListener(this.$newCategoryBtn, 'click', function (ev) {\n            this._openCreateCategoryModal(\n              ev.currentTarget.getAttribute('data-id')\n            );\n          });\n        }\n\n        if (this.editableGroups.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn',\n          }).appendTo(this.$newCategoryBtnGroup);\n        }\n      } else {\n        this.$newCategoryBtn = $menuBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit add icon menubtn',\n          text: Craft.t('app', 'New category'),\n        }).appendTo(this.$newCategoryBtnGroup);\n      }\n\n      if ($menuBtn) {\n        var menuHtml = '<div class=\"menu\"><ul>';\n\n        for (i = 0; i < this.editableGroups.length; i++) {\n          var group = this.editableGroups[i];\n\n          if (this.settings.context === 'index' || group !== selectedGroup) {\n            href = this._getGroupTriggerHref(group);\n            label =\n              this.settings.context === 'index'\n                ? group.name\n                : Craft.t('app', 'New {group} category', {group: group.name});\n            menuHtml +=\n              '<li><a ' + href + '>' + Craft.escapeHtml(label) + '</a></li>';\n          }\n        }\n\n        menuHtml += '</ul></div>';\n\n        $(menuHtml).appendTo(this.$newCategoryBtnGroup);\n        var menuBtn = new Garnish.MenuBtn($menuBtn);\n\n        if (this.settings.context !== 'index') {\n          menuBtn.on('optionSelect', (ev) => {\n            this._openCreateCategoryModal(ev.option.getAttribute('data-id'));\n          });\n        }\n      }\n\n      this.addButton(this.$newCategoryBtnGroup);\n    }\n\n    // Update the URL if we're on the Categories index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index' && typeof history !== 'undefined') {\n      var uri = 'categories';\n\n      if (selectedSourceHandle) {\n        uri += '/' + selectedSourceHandle;\n      }\n\n      history.replaceState({}, '', Craft.getUrl(uri));\n    }\n  },\n\n  _getGroupTriggerHref: function (group) {\n    if (this.settings.context === 'index') {\n      const uri = `categories/${group.handle}/new`;\n      const site = this.getSite();\n      const params = site ? {site: site.handle} : undefined;\n      return `href=\"${Craft.getUrl(uri, params)}\"`;\n    }\n\n    return `data-id=\"${group.id}\"`;\n  },\n\n  _openCreateCategoryModal: function (groupId) {\n    if (this.$newCategoryBtn.hasClass('loading')) {\n      return;\n    }\n\n    // Find the group\n    var group;\n\n    for (var i = 0; i < this.editableGroups.length; i++) {\n      if (this.editableGroups[i].id == groupId) {\n        group = this.editableGroups[i];\n        break;\n      }\n    }\n\n    if (!group) {\n      return;\n    }\n\n    this.$newCategoryBtn.addClass('inactive');\n    var newCategoryBtnText = this.$newCategoryBtn.text();\n    this.$newCategoryBtn.text(\n      Craft.t('app', 'New {group} category', {group: group.name})\n    );\n\n    Craft.createElementEditor(this.elementType, {\n      hudTrigger: this.$newCategoryBtnGroup,\n      siteId: this.siteId,\n      attributes: {\n        groupId: groupId,\n      },\n      onHideHud: () => {\n        this.$newCategoryBtn.removeClass('inactive').text(newCategoryBtnText);\n      },\n      onSaveElement: (response) => {\n        // Make sure the right group is selected\n        var groupSourceKey = 'group:' + group.uid;\n\n        if (this.sourceKey !== groupSourceKey) {\n          this.selectSourceByKey(groupSourceKey);\n        }\n\n        this.clearSearch();\n        this.selectElementAfterUpdate(response.id);\n        this.updateElements();\n      },\n    });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass(\n  'craft\\\\elements\\\\Category',\n  Craft.CategoryIndex\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Category Select input\n */\nCraft.CategorySelectInput = Craft.BaseElementSelectInput.extend({\n  setSettings: function () {\n    this.base.apply(this, arguments);\n    this.settings.sortable = false;\n  },\n\n  getModalSettings: function () {\n    var settings = this.base();\n    settings.hideOnSelect = false;\n    return settings;\n  },\n\n  getElements: function () {\n    return this.$elementsContainer.find('.element');\n  },\n\n  onModalSelect: function (elements) {\n    // Disable the modal\n    this.modal.disable();\n    this.modal.disableCancelBtn();\n    this.modal.disableSelectBtn();\n    this.modal.showFooterSpinner();\n\n    // Get the new category HTML\n    var selectedCategoryIds = this.getSelectedElementIds();\n\n    for (var i = 0; i < elements.length; i++) {\n      selectedCategoryIds.push(elements[i].id);\n    }\n\n    var data = {\n      categoryIds: selectedCategoryIds,\n      siteId: elements[0].siteId,\n      id: this.settings.id,\n      name: this.settings.name,\n      branchLimit: this.settings.branchLimit,\n      selectionLabel: this.settings.selectionLabel,\n    };\n\n    Craft.postActionRequest(\n      'elements/get-categories-input-html',\n      data,\n      (response, textStatus) => {\n        this.modal.enable();\n        this.modal.enableCancelBtn();\n        this.modal.enableSelectBtn();\n        this.modal.hideFooterSpinner();\n\n        if (textStatus === 'success') {\n          var $newInput = $(response.html),\n            $newElementsContainer = $newInput.children('.elements');\n\n          this.$elementsContainer.replaceWith($newElementsContainer);\n          this.$elementsContainer = $newElementsContainer;\n          this.resetElements();\n\n          var filteredElements = [];\n\n          for (var i = 0; i < elements.length; i++) {\n            var element = elements[i],\n              $element = this.getElementById(element.id);\n\n            if ($element) {\n              this.animateElementIntoPlace(element.$element, $element);\n              filteredElements.push(element);\n            }\n          }\n\n          this.updateDisabledElementsInModal();\n          this.modal.hide();\n          this.onSelectElements(filteredElements);\n        }\n      }\n    );\n  },\n\n  removeElement: function ($element) {\n    // Find any descendants this category might have\n    const $allCategories = $element.add(\n      $element.parent().siblings('ul').find('.element')\n    );\n\n    // Remove our record of them all at once\n    this.removeElements($allCategories);\n\n    // Animate them away one at a time\n    for (let i = 0; i < $allCategories.length; i++) {\n      this._animateCategoryAway($allCategories, i);\n    }\n  },\n\n  _animateCategoryAway: function ($allCategories, i) {\n    let callback;\n\n    // Is this the last one?\n    if (i === $allCategories.length - 1) {\n      callback = () => {\n        const $li = $allCategories.first().parent().parent();\n        const $ul = $li.parent();\n\n        if ($ul[0] === this.$elementsContainer[0] || $li.siblings().length) {\n          $li.remove();\n        } else {\n          $ul.remove();\n        }\n      };\n    }\n\n    const func = () => {\n      this.animateElementAway($allCategories.eq(i), callback);\n    };\n\n    if (i === 0) {\n      func();\n    } else {\n      setTimeout(func, 100 * i);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Craft Charts\n */\n\nCraft.charts = {};\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.DataTable\n */\nCraft.charts.DataTable = Garnish.Base.extend({\n  columns: null,\n  rows: null,\n\n  init: function (data) {\n    let columns = data.columns;\n    let rows = data.rows;\n\n    rows.forEach((d) => {\n      $.each(d, function (cellIndex) {\n        var column = columns[cellIndex];\n\n        var parseTime;\n\n        switch (column.type) {\n          case 'date':\n            parseTime = d3.timeParse('%Y-%m-%d');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'datetime':\n            parseTime = d3.timeParse('%Y-%m-%d %H:00:00');\n            d[cellIndex] = parseTime(d[cellIndex]);\n            break;\n\n          case 'percent':\n            d[cellIndex] = d[cellIndex] / 100;\n            break;\n\n          case 'number':\n            d[cellIndex] = +d[cellIndex];\n            break;\n\n          default:\n          // do nothing\n        }\n      });\n    });\n\n    this.columns = columns;\n    this.rows = rows;\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Tip\n */\n\nCraft.charts.Tip = Garnish.Base.extend({\n  $container: null,\n  $tip: null,\n\n  init: function ($container) {\n    this.$container = $container;\n\n    this.$tip = $('<div class=\"tooltip\"></div>').appendTo(this.$container);\n\n    this.hide();\n  },\n\n  setContent: function (html) {\n    this.$tip.html(html);\n  },\n\n  setPosition: function (position) {\n    this.$tip.css('left', `${position.left}px`);\n    this.$tip.css('top', `${position.top}px`);\n  },\n\n  show: function () {\n    this.$tip.css('display', 'block');\n  },\n\n  hide: function () {\n    this.$tip.css('display', 'none');\n  },\n});\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.BaseChart\n */\nCraft.charts.BaseChart = Garnish.Base.extend(\n  {\n    $container: null,\n    $chart: null,\n\n    chartBaseClass: 'cp-chart',\n    dataTable: null,\n\n    formatLocale: null,\n    timeFormatLocale: null,\n    orientation: null,\n\n    svg: null,\n    width: null,\n    height: null,\n\n    init: function (container, settings) {\n      this.$container = container;\n\n      this.setSettings(Craft.charts.BaseChart.defaults);\n      this.setSettings(settings);\n\n      var globalSettings = {\n        formats: window.d3Formats,\n        formatLocaleDefinition: window.d3FormatLocaleDefinition,\n        timeFormatLocaleDefinition: window.d3TimeFormatLocaleDefinition,\n      };\n\n      this.setSettings(globalSettings);\n\n      d3.select(window).on('resize', () => {\n        this.resize();\n      });\n    },\n\n    setSettings: function (settings, defaults) {\n      var baseSettings =\n        typeof this.settings === 'undefined' ? {} : this.settings;\n      this.settings = $.extend(true, {}, baseSettings, defaults, settings);\n    },\n\n    draw: function (dataTable, settings) {\n      // Settings and chart attributes\n\n      this.setSettings(settings);\n\n      this.dataTable = dataTable;\n      this.formatLocale = d3.formatLocale(this.settings.formatLocaleDefinition);\n      this.timeFormatLocale = d3.timeFormatLocale(\n        this.settings.timeFormatLocaleDefinition\n      );\n      this.orientation = this.settings.orientation;\n\n      // Set (or reset) the chart element\n\n      if (this.$chart) {\n        this.$chart.remove();\n      }\n\n      var className = this.chartBaseClass;\n\n      if (this.settings.chartClass) {\n        className += ' ' + this.settings.chartClass;\n      }\n\n      this.$chart = $(`<div class=\"${className}\" />`).appendTo(this.$container);\n    },\n\n    resize: function () {\n      this.draw(this.dataTable, this.settings);\n    },\n\n    onAfterDrawTicks: function () {\n      // White border for ticks' text\n      $('.tick', this.$chart).each(function (tickKey, tick) {\n        var $tickText = $('text', tick);\n\n        var $clone = $tickText.clone();\n        $clone.appendTo(tick);\n\n        $tickText.attr('stroke', '#ffffff');\n        $tickText.attr('stroke-width', 3);\n      });\n    },\n  },\n  {\n    defaults: {\n      formatLocaleDefinition: null,\n      timeFormatLocaleDefinition: null,\n      formats: {\n        numberFormat: ',.2f',\n        percentFormat: ',.2%',\n        currencyFormat: '$,.2f',\n        shortDateFormats: {\n          day: '%-m/%-d',\n          month: '%-m/%y',\n          year: '%Y',\n        },\n      },\n      margin: {top: 0, right: 0, bottom: 0, left: 0},\n      chartClass: null,\n      colors: ['#0594D1', '#DE3800', '#FF9A00', '#009802', '#9B009B'],\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Area\n */\nCraft.charts.Area = Craft.charts.BaseChart.extend(\n  {\n    tip: null,\n    drawingArea: null,\n\n    init: function (container, settings) {\n      this.base(container, Craft.charts.Area.defaults);\n\n      this.setSettings(settings);\n    },\n\n    draw: function (dataTable, settings) {\n      this.base(dataTable, settings);\n\n      if (this.tip) {\n        this.tip = null;\n      }\n\n      var margin = this.getChartMargin();\n\n      this.width = this.$chart.width() - margin.left - margin.right;\n      this.height = this.$chart.height() - margin.top - margin.bottom;\n\n      // Append SVG to chart element\n\n      var svg = {\n        width: this.width + (margin.left + margin.right),\n        height: this.height + (margin.top + margin.bottom),\n        translateX: this.orientation !== 'rtl' ? margin.left : margin.right,\n        translateY: margin.top,\n      };\n\n      this.svg = d3\n        .select(this.$chart.get(0))\n        .append('svg')\n        .attr('width', svg.width)\n        .attr('height', svg.height);\n\n      this.drawingArea = this.svg\n        .append('g')\n        .attr('transform', `translate(${svg.translateX},${svg.translateY})`);\n\n      // Draw elements\n\n      this.drawTicks();\n      this.drawAxes();\n      this.drawChart();\n      this.drawTipTriggers();\n    },\n\n    drawTicks: function () {\n      // Draw X ticks\n\n      var x = this.getX(true);\n      var xTicks = 3;\n      var xAxis = d3\n        .axisBottom(x)\n        .tickFormat(this.getXFormatter())\n        .ticks(xTicks);\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'x ticks-axis')\n        .attr('transform', `translate(0, ${this.height})`)\n        .call(xAxis);\n\n      // Draw Y ticks\n\n      var y = this.getY();\n      var yTicks = 2;\n      var yAxis;\n\n      if (this.orientation !== 'rtl') {\n        yAxis = d3\n          .axisLeft(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea.append('g').attr('class', 'y ticks-axis').call(yAxis);\n      } else {\n        yAxis = d3\n          .axisRight(y)\n          .tickFormat(this.getYFormatter())\n          .tickValues(this.getYTickValues())\n          .ticks(yTicks);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y ticks-axis')\n          .attr('transform', `translate(${this.width},0)`)\n          .call(yAxis);\n      }\n\n      // On after draw ticks\n\n      this.onAfterDrawTicks();\n    },\n\n    drawAxes: function () {\n      if (this.settings.xAxis.showAxis) {\n        var x = this.getX();\n        var xAxis = d3.axisBottom(x).ticks(0).tickSizeOuter(0);\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x axis')\n          .attr('transform', `translate(0, ${this.height})`)\n          .call(xAxis);\n      }\n\n      if (this.settings.yAxis.showAxis) {\n        var y = this.getY();\n        var chartPadding = 0;\n        var yAxis;\n\n        if (this.orientation === 'rtl') {\n          yAxis = d3.axisLeft(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${this.width - chartPadding}, 0)`)\n            .call(yAxis);\n        } else {\n          yAxis = d3.axisRight(y).ticks(0);\n          this.drawingArea\n            .append('g')\n            .attr('class', 'y axis')\n            .attr('transform', `translate(${chartPadding}, 0)`)\n            .call(yAxis);\n        }\n      }\n    },\n\n    drawChart: function () {\n      var x = this.getX(true);\n      var y = this.getY();\n\n      // X & Y grid lines\n\n      if (this.settings.xAxis.gridlines) {\n        var xLineAxis = d3.axisBottom(x);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'x grid-line')\n          .attr('transform', `translate(0,${this.height})`)\n          .call(xLineAxis.tickSize(-this.height, 0, 0).tickFormat(''));\n      }\n\n      var yTicks = 2;\n\n      if (this.settings.yAxis.gridlines) {\n        var yLineAxis = d3.axisLeft(y);\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'y grid-line')\n          .attr('transform', 'translate(0 , 0)')\n          .call(\n            yLineAxis\n              .tickSize(-this.width, 0)\n              .tickFormat('')\n              .tickValues(this.getYTickValues())\n              .ticks(yTicks)\n          );\n      }\n\n      // Line\n\n      var line = d3\n        .line()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-line')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', 'none')\n        .style('stroke', this.settings.colors[0])\n        .style('stroke-width', '3px')\n        .attr('d', line);\n\n      // Area\n\n      var area = d3\n        .area()\n        .x(function (d) {\n          return x(d[0]);\n        })\n        .y0(this.height)\n        .y1(function (d) {\n          return y(d[1]);\n        });\n\n      this.drawingArea\n        .append('g')\n        .attr('class', 'chart-area')\n        .append('path')\n        .datum(this.dataTable.rows)\n        .style('fill', this.settings.colors[0])\n        .style('fill-opacity', '0.3')\n        .attr('d', area);\n\n      // Plots\n\n      if (this.settings.plots) {\n        this.drawingArea\n          .append('g')\n          .attr('class', 'plots')\n          .selectAll('circle')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('circle')\n          .style('fill', this.settings.colors[0])\n          .attr('class', (d, index) => `plot plot-${index}`)\n          .attr('r', 4)\n          .attr('cx', (d) => x(d[0]))\n          .attr('cy', (d) => y(d[1]));\n      }\n    },\n\n    drawTipTriggers: function () {\n      if (this.settings.tips) {\n        if (!this.tip) {\n          this.tip = new Craft.charts.Tip(this.$chart);\n        }\n\n        // Define xAxisTickInterval\n\n        var chartMargin = this.getChartMargin();\n        var tickSizeOuter = 6;\n        var length =\n          this.drawingArea.select('.x path.domain').node().getTotalLength() -\n          chartMargin.left -\n          chartMargin.right -\n          tickSizeOuter * 2;\n        var xAxisTickInterval = length / (this.dataTable.rows.length - 1);\n\n        // Tip trigger width\n\n        var tipTriggerWidth = Math.max(0, xAxisTickInterval);\n\n        // Draw triggers\n\n        var x = this.getX(true);\n        var y = this.getY();\n\n        this.drawingArea\n          .append('g')\n          .attr('class', 'tip-triggers')\n          .selectAll('rect')\n          .data(this.dataTable.rows)\n          .enter()\n          .append('rect')\n          .attr('class', 'tip-trigger')\n          .style('fill', 'transparent')\n          .style('fill-opacity', '1')\n          .attr('width', tipTriggerWidth)\n          .attr('height', this.height)\n          .attr('x', (d) => x(d[0]) - tipTriggerWidth / 2)\n          .on('mouseover', (d, index) => {\n            // Expand plot\n\n            this.drawingArea.select('.plot-' + index).attr('r', 5);\n\n            // Set tip content\n\n            var $content = $('<div />');\n            var $xValue = $('<div class=\"x-value\" />').appendTo($content);\n            var $yValue = $('<div class=\"y-value\" />').appendTo($content);\n\n            $xValue.html(this.getXFormatter()(d[0]));\n            $yValue.html(this.getYFormatter()(d[1]));\n\n            var content = $content.get(0);\n\n            this.tip.setContent(content);\n\n            // Set tip position\n\n            var margin = this.getChartMargin();\n\n            var offset = 24;\n            var top = y(d[1]) + offset;\n            var left;\n\n            if (this.orientation !== 'rtl') {\n              left = x(d[0]) + margin.left + offset;\n\n              var calcLeft =\n                this.$chart.offset().left + left + this.tip.$tip.width();\n              var maxLeft =\n                this.$chart.offset().left + this.$chart.width() - offset;\n\n              if (calcLeft > maxLeft) {\n                left = x(d[0]) - (this.tip.$tip.width() + offset);\n              }\n            } else {\n              left = x(d[0]) - (this.tip.$tip.width() + margin.left + offset);\n            }\n\n            if (left < 0) {\n              left = x(d[0]) + margin.left + offset;\n            }\n\n            var position = {\n              top: top,\n              left: left,\n            };\n\n            this.tip.setPosition(position);\n\n            // Show tip\n\n            this.tip.show();\n          })\n          .on('mouseout', (d, index) => {\n            // Unexpand Plot\n            this.drawingArea.select('.plot-' + index).attr('r', 4);\n\n            // Hide tip\n            this.tip.hide();\n          });\n      }\n    },\n\n    getChartMargin: function () {\n      var margin = this.settings.margin;\n\n      // Estimate the max width of y ticks and set it as the left margin\n\n      var values = this.getYTickValues();\n      var yTicksMaxWidth = 0;\n\n      $.each(values, (key, value) => {\n        var characterWidth = 8;\n\n        var formatter = this.getYFormatter();\n\n        var formattedValue = formatter(value);\n        var computedTickWidth = formattedValue.length * characterWidth;\n\n        if (computedTickWidth > yTicksMaxWidth) {\n          yTicksMaxWidth = computedTickWidth;\n        }\n      });\n\n      yTicksMaxWidth += 10;\n\n      margin.left = yTicksMaxWidth;\n\n      return margin;\n    },\n\n    getX: function (padded) {\n      var xDomainMin = d3.min(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomainMax = d3.max(this.dataTable.rows, function (d) {\n        return d[0];\n      });\n\n      var xDomain = [xDomainMin, xDomainMax];\n\n      if (this.orientation === 'rtl') {\n        xDomain = [xDomainMax, xDomainMin];\n      }\n\n      var left = 0;\n      var right = 0;\n\n      if (padded) {\n        left = 0;\n        right = 0;\n      }\n\n      var x = d3.scaleTime().range([left, this.width - right]);\n\n      x.domain(xDomain);\n\n      return x;\n    },\n\n    getY: function () {\n      var yDomain = [0, this.getYMaxValue()];\n\n      var y = d3.scaleLinear().range([this.height, 0]);\n\n      y.domain(yDomain);\n\n      return y;\n    },\n\n    getXFormatter: function () {\n      var formatter;\n\n      if (this.settings.xAxis.formatter !== $.noop) {\n        formatter = this.settings.xAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getTimeFormatter(\n          this.timeFormatLocale,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYFormatter: function () {\n      var formatter;\n\n      if (this.settings.yAxis.formatter !== $.noop) {\n        formatter = this.settings.yAxis.formatter(this);\n      } else {\n        formatter = Craft.charts.utils.getNumberFormatter(\n          this.formatLocale,\n          this.dataTable.columns[1].type,\n          this.settings\n        );\n      }\n\n      return formatter;\n    },\n\n    getYMaxValue: function () {\n      return d3.max(this.dataTable.rows, function (d) {\n        return d[1];\n      });\n    },\n\n    getYTickValues: function () {\n      var maxValue = this.getYMaxValue();\n\n      if (maxValue > 1) {\n        return [maxValue / 2, maxValue];\n      } else {\n        return [0, maxValue];\n      }\n    },\n  },\n  {\n    defaults: {\n      chartClass: 'area',\n      margin: {top: 25, right: 5, bottom: 25, left: 0},\n      plots: true,\n      tips: true,\n      xAxis: {\n        gridlines: false,\n        showAxis: true,\n        formatter: $.noop,\n      },\n      yAxis: {\n        gridlines: true,\n        showAxis: false,\n        formatter: $.noop,\n      },\n    },\n  }\n);\n\n// ---------------------------------------------------------------------\n\n/**\n * Class Craft.charts.Utils\n */\nCraft.charts.utils = {\n  getDuration: function (seconds) {\n    var secondsNum = parseInt(seconds, 10);\n\n    var duration = {\n      hours: Math.floor(secondsNum / 3600),\n      minutes: Math.floor((secondsNum - duration.hours * 3600) / 60),\n      seconds: secondsNum - duration.hours * 3600 - duration.minutes * 60,\n    };\n\n    if (duration.hours < 10) {\n      duration.hours = `0${duration.hours}`;\n    }\n\n    if (duration.minutes < 10) {\n      duration.minutes = `0${duration.minutes}`;\n    }\n\n    if (duration.seconds < 10) {\n      duration.seconds = `0${duration.seconds}`;\n    }\n\n    return `${duration.hours}:${duration.minutes}:${duration.seconds}`;\n  },\n\n  getTimeFormatter: function (timeFormatLocale, chartSettings) {\n    switch (chartSettings.dataScale) {\n      case 'year':\n        return timeFormatLocale.format('%Y');\n\n      case 'month':\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.month\n        );\n\n      case 'hour':\n        return timeFormatLocale.format(\n          `${chartSettings.formats.shortDateFormats.day} %H:00:00`\n        );\n\n      default:\n        return timeFormatLocale.format(\n          chartSettings.formats.shortDateFormats.day\n        );\n    }\n  },\n\n  getNumberFormatter: function (formatLocale, type, chartSettings) {\n    switch (type) {\n      case 'currency':\n        return formatLocale.format(chartSettings.formats.currencyFormat);\n\n      case 'percent':\n        return formatLocale.format(chartSettings.formats.percentFormat);\n\n      case 'time':\n        return Craft.charts.utils.getDuration;\n\n      case 'number':\n        return formatLocale.format(chartSettings.formats.numberFormat);\n    }\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Color input\n */\nCraft.ColorInput = Garnish.Base.extend(\n  {\n    $container: null,\n    $input: null,\n    $colorContainer: null,\n    $colorPreview: null,\n    $colorInput: null,\n\n    init: function (container) {\n      this.$container = $(container);\n      this.$input = this.$container.find('.color-input');\n      this.$colorContainer = this.$container.children('.color');\n      this.$colorPreview = this.$colorContainer.children('.color-preview');\n\n      this.createColorInput();\n      this.handleTextChange();\n\n      this.addListener(this.$input, 'input', 'handleTextChange');\n    },\n\n    createColorInput: function () {\n      var input = document.createElement('input');\n      input.setAttribute('type', 'color');\n\n      if (input.type !== 'color') {\n        // The browser doesn't support input[type=color]\n        return;\n      }\n\n      this.$colorContainer.removeClass('static');\n      this.$colorInput = $(input)\n        .addClass('color-preview-input')\n        .attr({\n          'aria-controls': this.$input.attr('id'),\n          'aria-label': Craft.t('app', 'Color picker'),\n        })\n        .appendTo(this.$colorPreview);\n\n      this.addListener(this.$colorInput, 'click', function (ev) {\n        ev.stopPropagation();\n      });\n\n      this.addListener(this.$colorContainer, 'click', function () {\n        this.$colorInput.trigger('click');\n      });\n\n      this.addListener(this.$colorInput, 'input', 'updateColor');\n    },\n\n    updateColor: function () {\n      this.$input.val(this.$colorInput.val());\n      this.handleTextChange();\n    },\n\n    handleTextChange: function () {\n      let val = this.$input.val();\n\n      if (val !== (val = Craft.trim(val))) {\n        this.$input.val(val);\n      }\n\n      // Chop off the #\n      if (val.length && val[0] === '#') {\n        val = val.substr(1);\n        this.$input.val(val);\n      }\n\n      // If empty, set the preview to transparent\n      if (!val.length) {\n        this.$colorPreview.css('background-color', '');\n        return;\n      }\n\n      // Now normalize it for the UI stuff\n      if (val.length === 3) {\n        val = val[0].repeat(2) + val[1].repeat(2) + val[2].repeat(2);\n      }\n\n      if (val.match(/^[0-9a-f]{6}$/i)) {\n        this.$colorPreview.css('background-color', `#${val}`);\n        if (this.$colorInput) {\n          this.$colorInput.val(`#${val}`);\n        }\n      } else {\n        this.$colorPreview.css('background-color', '');\n      }\n    },\n  },\n  {\n    _browserSupportsColorInputs: null,\n\n    doesBrowserSupportColorInputs: function () {\n      if (Craft.ColorInput._browserSupportsColorInputs === null) {\n      }\n\n      return Craft.ColorInput._browserSupportsColorInputs;\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n\n// Use old jQuery prefilter behavior\n// see https://jquery.com/upgrade-guide/3.5/\nvar rxhtmlTag =\n  /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\\/\\0>\\x20\\t\\r\\n\\f]*)[^>]*)\\/>/gi;\njQuery.htmlPrefilter = function (html) {\n  return html.replace(rxhtmlTag, '<$1></$2>');\n};\n\n// Set all the standard Craft.* stuff\n$.extend(Craft, {\n  navHeight: 48,\n\n  /**\n   * @callback indexKeyCallback\n   * @param {object} currentValue\n   * @param {number} [index]\n   * @return {string}\n   */\n  /**\n   * Indexes an array of objects by a specified key\n   *\n   * @param {object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  index: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.index() must be an array.';\n    }\n\n    return arr.reduce((index, obj, i) => {\n      index[typeof key === 'string' ? obj[key] : key(obj, i)] = obj;\n      return index;\n    }, {});\n  },\n\n  /**\n   * @callback indexKeyCallback\n   * @param {object} currentValue\n   * @param {number} [index]\n   * @return {string}\n   */\n  /**\n   * Groups an array of objects by a specified key\n   *\n   * @param {object[]} arr\n   * @param {(string|indexKeyCallback)} key\n   */\n  group: function (arr, key) {\n    if (!$.isArray(arr)) {\n      throw 'The first argument passed to Craft.group() must be an array.';\n    }\n\n    let index = {};\n\n    return arr.reduce((grouped, obj, i) => {\n      const thisKey = typeof key === 'string' ? obj[key] : key(obj, i);\n      if (!index.hasOwnProperty(thisKey)) {\n        index[thisKey] = [[], thisKey];\n        grouped.push(index[thisKey]);\n      }\n      index[thisKey][0].push(obj);\n      return grouped;\n    }, []);\n  },\n\n  /**\n   * Get a translated message.\n   *\n   * @param {string} category\n   * @param {string} message\n   * @param {object} params\n   * @return string\n   */\n  t: function (category, message, params) {\n    if (\n      typeof Craft.translations[category] !== 'undefined' &&\n      typeof Craft.translations[category][message] !== 'undefined'\n    ) {\n      message = Craft.translations[category][message];\n    }\n\n    if (params) {\n      return this.formatMessage(message, params);\n    }\n\n    return message;\n  },\n\n  formatMessage: function (pattern, args) {\n    let tokens;\n    if ((tokens = this._tokenizePattern(pattern)) === false) {\n      throw 'Message pattern is invalid.';\n    }\n    for (let i = 0; i < tokens.length; i++) {\n      let token = tokens[i];\n      if (typeof token === 'object') {\n        if ((tokens[i] = this._parseToken(token, args)) === false) {\n          throw 'Message pattern is invalid.';\n        }\n      }\n    }\n    return tokens.join('');\n  },\n\n  _tokenizePattern: function (pattern) {\n    let depth = 1,\n      start,\n      pos;\n    // Get an array of the string characters (factoring in 3+ byte chars)\n    const chars = [...pattern];\n    if ((start = pos = chars.indexOf('{')) === -1) {\n      return [pattern];\n    }\n    let tokens = [chars.slice(0, pos).join('')];\n    while (true) {\n      let open = chars.indexOf('{', pos + 1);\n      let close = chars.indexOf('}', pos + 1);\n      if (open === -1) {\n        open = false;\n      }\n      if (close === -1) {\n        close = false;\n      }\n      if (open === false && close === false) {\n        break;\n      }\n      if (open === false) {\n        open = chars.length;\n      }\n      if (close > open) {\n        depth++;\n        pos = open;\n      } else {\n        depth--;\n        pos = close;\n      }\n      if (depth === 0) {\n        tokens.push(\n          chars\n            .slice(start + 1, pos)\n            .join('')\n            .split(',', 3)\n        );\n        start = pos + 1;\n        tokens.push(chars.slice(start, open).join(''));\n        start = open;\n      }\n\n      if (depth !== 0 && (open === false || close === false)) {\n        break;\n      }\n    }\n    if (depth !== 0) {\n      return false;\n    }\n\n    return tokens;\n  },\n\n  _parseToken: function (token, args) {\n    // parsing pattern based on ICU grammar:\n    // http://icu-project.org/apiref/icu4c/classMessageFormat.html#details\n    const param = Craft.trim(token[0]);\n    if (typeof args[param] === 'undefined') {\n      return `{${token.join(',')}}`;\n    }\n    const arg = args[param];\n    const type =\n      typeof token[1] !== 'undefined' ? Craft.trim(token[1]) : 'none';\n    switch (type) {\n      case 'number':\n        return (() => {\n          let format =\n            typeof token[2] !== 'undefined' ? Craft.trim(token[2]) : null;\n          if (format !== null && format !== 'integer') {\n            throw `Message format 'number' is only supported for integer values.`;\n          }\n          let number = Craft.formatNumber(arg);\n          let pos;\n          if (format === null && (pos = `${arg}`.indexOf('.')) !== -1) {\n            number += `.${arg.substr(pos + 1)}`;\n          }\n          return number;\n        })();\n      case 'none':\n        return arg;\n      case 'select':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html\n                        selectStyle = (selector '{' message '}')+\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let select = this._tokenizePattern(token[2]);\n          let c = select.length;\n          let message = false;\n          for (let i = 0; i + 1 < c; i++) {\n            if (Garnish.isArray(select[i]) || !Garnish.isArray(select[i + 1])) {\n              return false;\n            }\n            let selector = Craft.trim(select[i++]);\n            if (\n              (message === false && selector === 'other') ||\n              selector == arg\n            ) {\n              message = select[i].join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      case 'plural':\n        return (() => {\n          /* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html\n                        pluralStyle = [offsetValue] (selector '{' message '}')+\n                        offsetValue = \"offset:\" number\n                        selector = explicitValue | keyword\n                        explicitValue = '=' number  // adjacent, no white space in between\n                        keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+\n                        message: see MessageFormat\n                        */\n          if (typeof token[2] === 'undefined') {\n            return false;\n          }\n          let plural = this._tokenizePattern(token[2]);\n          const c = plural.length;\n          let message = false;\n          let offset = 0;\n          for (let i = 0; i + 1 < c; i++) {\n            if (\n              typeof plural[i] === 'object' ||\n              typeof plural[i + 1] !== 'object'\n            ) {\n              return false;\n            }\n            let selector = Craft.trim(plural[i++]);\n            let selectorChars = [...selector];\n\n            if (i === 1 && selector.substring(0, 7) === 'offset:') {\n              let pos = [...selector.replace(/[\\n\\r\\t]/g, ' ')].indexOf(' ', 7);\n              if (pos === -1) {\n                throw 'Message pattern is invalid.';\n              }\n              offset = parseInt(\n                Craft.trim(selectorChars.slice(7, pos).join(''))\n              );\n              selector = Craft.trim(\n                selectorChars\n                  .slice(pos + 1, pos + 1 + selectorChars.length)\n                  .join('')\n              );\n            }\n            if (\n              (message === false && selector === 'other') ||\n              (selector[0] === '=' &&\n                parseInt(\n                  selectorChars.slice(1, 1 + selectorChars.length).join('')\n                ) === arg) ||\n              (selector === 'one' && arg - offset === 1)\n            ) {\n              message = (\n                typeof plural[i] === 'string' ? [plural[i]] : plural[i]\n              )\n                .map((p) => {\n                  return p.replace('#', arg - offset);\n                })\n                .join(',');\n            }\n          }\n          if (message === false) {\n            return false;\n          }\n          return this.formatMessage(message, args);\n        })();\n      default:\n        throw `Message format '${type}' is not supported.`;\n    }\n  },\n\n  formatDate: function (date) {\n    if (typeof date !== 'object') {\n      date = new Date(date);\n    }\n\n    return $.datepicker.formatDate(Craft.datepickerOptions.dateFormat, date);\n  },\n\n  /**\n   * Formats a number.\n   *\n   * @param {string} number\n   * @return string D3 format\n   */\n  formatNumber: function (number, format) {\n    if (typeof format == 'undefined') {\n      format = ',.0f';\n    }\n\n    var formatter = d3.formatLocale(d3FormatLocaleDefinition).format(format);\n\n    return formatter(number);\n  },\n\n  /**\n   * @param {string} key\n   * @param {boolean} shift\n   * @param {boolean} alt\n   */\n  shortcutText: function (key, shift, alt) {\n    if (Craft.clientOs === 'Mac') {\n      return (alt ? '⌥' : '') + (shift ? '⇧' : '') + '⌘' + key;\n    }\n    return 'Ctrl+' + (alt ? 'Alt+' : '') + (shift ? 'Shift+' : '') + key;\n  },\n\n  /**\n   * Escapes some HTML.\n   *\n   * @param {string} str\n   * @return string\n   */\n  escapeHtml: function (str) {\n    return $('<div/>').text(str).html();\n  },\n\n  /**\n   * Escapes special regular expression characters.\n   *\n   * @param {string} str\n   * @return string\n   */\n  escapeRegex: function (str) {\n    // h/t https://stackoverflow.com/a/9310752\n    return str.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n  },\n\n  /**\n   * Returns the text in a string that might contain HTML tags.\n   *\n   * @param {string} str\n   * @return string\n   */\n  getText: function (str) {\n    return $('<div/>').html(str).text();\n  },\n\n  /**\n   * Encodes a URI copmonent. Mirrors PHP's rawurlencode().\n   *\n   * @param {string} str\n   * @return string\n   * @see http://stackoverflow.com/questions/1734250/what-is-the-equivalent-of-javascripts-encodeuricomponent-in-php\n   */\n  encodeUriComponent: function (str) {\n    str = encodeURIComponent(str);\n\n    var differences = {\n      '!': '%21',\n      '*': '%2A',\n      \"'\": '%27',\n      '(': '%28',\n      ')': '%29',\n    };\n\n    for (var chr in differences) {\n      var re = new RegExp('\\\\' + chr, 'g');\n      str = str.replace(re, differences[chr]);\n    }\n\n    return str;\n  },\n\n  /**\n   * Selects the full value of a given text input.\n   *\n   * @param input\n   */\n  selectFullValue: function (input) {\n    var $input = $(input);\n    var val = $input.val();\n\n    // Does the browser support setSelectionRange()?\n    if (typeof $input[0].setSelectionRange !== 'undefined') {\n      // Select the whole value\n      var length = val.length * 2;\n      $input[0].setSelectionRange(0, length);\n    } else {\n      // Refresh the value to get the cursor positioned at the end\n      $input.val(val);\n    }\n  },\n\n  /**\n   * Formats an ID out of an input name.\n   *\n   * @param {string} inputName\n   * @return string\n   */\n  formatInputId: function (inputName) {\n    return this.rtrim(inputName.replace(/[^\\w]+/g, '-'), '-');\n  },\n\n  /**\n   * @return string\n   * @param path\n   * @param params\n   * @param baseUrl\n   */\n  getUrl: function (path, params, baseUrl) {\n    if (typeof path !== 'string') {\n      path = '';\n    }\n\n    // Normalize the params\n    var anchor = '';\n\n    if ($.isPlainObject(params)) {\n      var aParams = [];\n\n      for (var name in params) {\n        if (!params.hasOwnProperty(name)) {\n          continue;\n        }\n\n        var value = params[name];\n\n        if (name === '#') {\n          anchor = value;\n        } else if (value !== null && value !== '') {\n          aParams.push(name + '=' + value);\n        }\n      }\n\n      params = aParams;\n    }\n\n    if (Garnish.isArray(params)) {\n      params = params.join('&');\n    } else {\n      params = Craft.trim(params, '&?');\n    }\n\n    // Was there already an anchor on the path?\n    var apos = path.indexOf('#');\n    if (apos !== -1) {\n      // Only keep it if the params didn't specify a new anchor\n      if (!anchor) {\n        anchor = path.substr(apos + 1);\n      }\n      path = path.substr(0, apos);\n    }\n\n    // Were there already any query string params in the path?\n    var qpos = path.indexOf('?');\n    if (qpos !== -1) {\n      params = path.substr(qpos + 1) + (params ? '&' + params : '');\n      path = path.substr(0, qpos);\n    }\n\n    // Return path if it appears to be an absolute URL.\n    if (path.search('://') !== -1 || path[0] === '/') {\n      return path + (params ? '?' + params : '') + (anchor ? '#' + anchor : '');\n    }\n\n    path = Craft.trim(path, '/');\n\n    // Put it all together\n    var url;\n\n    if (baseUrl) {\n      url = baseUrl;\n\n      if (path && Craft.pathParam) {\n        // Does baseUrl already contain a path?\n        var pathMatch = url.match(\n          new RegExp('[&?]' + Craft.escapeRegex(Craft.pathParam) + '=[^&]+')\n        );\n        if (pathMatch) {\n          url = url.replace(\n            pathMatch[0],\n            Craft.rtrim(pathMatch[0], '/') + '/' + path\n          );\n          path = '';\n        }\n      }\n    } else {\n      url = Craft.baseUrl;\n    }\n\n    // Does the base URL already have a query string?\n    qpos = url.indexOf('?');\n    if (qpos !== -1) {\n      params = url.substr(qpos + 1) + (params ? '&' + params : '');\n      url = url.substr(0, qpos);\n    }\n\n    if (!Craft.omitScriptNameInUrls && path) {\n      if (Craft.usePathInfo || !Craft.pathParam) {\n        // Make sure that the script name is in the URL\n        if (url.search(Craft.scriptName) === -1) {\n          url = Craft.rtrim(url, '/') + '/' + Craft.scriptName;\n        }\n      } else {\n        // Move the path into the query string params\n\n        // Is the path param already set?\n        if (\n          params &&\n          params.substr(0, Craft.pathParam.length + 1) === Craft.pathParam + '='\n        ) {\n          var basePath,\n            endPath = params.indexOf('&');\n\n          if (endPath !== -1) {\n            basePath = params.substring(2, endPath);\n            params = params.substr(endPath + 1);\n          } else {\n            basePath = params.substr(2);\n            params = null;\n          }\n\n          // Just in case\n          basePath = Craft.rtrim(basePath);\n\n          path = basePath + (path ? '/' + path : '');\n        }\n\n        // Now move the path into the params\n        params = Craft.pathParam + '=' + path + (params ? '&' + params : '');\n        path = null;\n      }\n    }\n\n    if (path) {\n      url = Craft.rtrim(url, '/') + '/' + path;\n    }\n\n    if (params) {\n      url += '?' + params;\n    }\n\n    if (anchor) {\n      url += '#' + anchor;\n    }\n\n    return url;\n  },\n\n  /**\n   * @return string\n   * @param path\n   * @param params\n   */\n  getCpUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseCpUrl);\n  },\n\n  /**\n   * @return string\n   * @param path\n   * @param params\n   */\n  getSiteUrl: function (path, params) {\n    return this.getUrl(path, params, Craft.baseSiteUrl);\n  },\n\n  /**\n   * Returns an action URL.\n   *\n   * @param {string} path\n   * @param {object|string|undefined} params\n   * @return string\n   */\n  getActionUrl: function (path, params) {\n    return Craft.getUrl(path, params, Craft.actionUrl);\n  },\n\n  /**\n   * Redirects the window to a given URL.\n   *\n   * @param {string} url\n   */\n  redirectTo: function (url) {\n    document.location.href = this.getUrl(url);\n  },\n\n  /**\n   * Returns a hidden CSRF token input, if CSRF protection is enabled.\n   *\n   * @return string\n   */\n  getCsrfInput: function () {\n    if (Craft.csrfTokenName) {\n      return (\n        '<input type=\"hidden\" name=\"' +\n        Craft.csrfTokenName +\n        '\" value=\"' +\n        Craft.csrfTokenValue +\n        '\"/>'\n      );\n    } else {\n      return '';\n    }\n  },\n\n  /**\n   * Posts an action request to the server.\n   *\n   * @param {string} action\n   * @param {object|undefined} data\n   * @param {function|undefined} callback\n   * @param {object|undefined} options\n   * @return jqXHR\n   * @deprecated in 3.4.6. sendActionRequest() should be used instead\n   */\n  postActionRequest: function (action, data, callback, options) {\n    // Make 'data' optional\n    if (typeof data === 'function') {\n      options = callback;\n      callback = data;\n      data = {};\n    }\n\n    options = options || {};\n\n    if (options.contentType && options.contentType.match(/\\bjson\\b/)) {\n      if (typeof data === 'object') {\n        data = JSON.stringify(data);\n      }\n      options.contentType = 'application/json; charset=utf-8';\n    }\n\n    var jqXHR = $.ajax(\n      $.extend(\n        {\n          url: Craft.getActionUrl(action),\n          type: 'POST',\n          dataType: 'json',\n          headers: this._actionHeaders(),\n          data: data,\n          success: callback,\n          error: function (jqXHR, textStatus, errorThrown) {\n            // Ignore incomplete requests, likely due to navigating away from the page\n            // h/t https://stackoverflow.com/a/22107079/1688568\n            if (jqXHR.readyState !== 4) {\n              return;\n            }\n\n            if (typeof Craft.cp !== 'undefined') {\n              Craft.cp.displayError();\n            } else {\n              alert(Craft.t('app', 'A server error occurred.'));\n            }\n\n            if (callback) {\n              callback(null, textStatus, jqXHR);\n            }\n          },\n        },\n        options\n      )\n    );\n\n    // Call the 'send' callback\n    if (typeof options.send === 'function') {\n      options.send(jqXHR);\n    }\n\n    return jqXHR;\n  },\n\n  _waitingOnAjax: false,\n  _ajaxQueue: [],\n\n  /**\n   * Queues up an action request to be posted to the server.\n   */\n  queueActionRequest: function (action, data, callback, options) {\n    // Make 'data' optional\n    if (typeof data === 'function') {\n      options = callback;\n      callback = data;\n      data = undefined;\n    }\n\n    Craft._ajaxQueue.push([action, data, callback, options]);\n\n    if (!Craft._waitingOnAjax) {\n      Craft._postNextActionRequestInQueue();\n    }\n  },\n\n  _postNextActionRequestInQueue: function () {\n    Craft._waitingOnAjax = true;\n\n    var args = Craft._ajaxQueue.shift();\n\n    Craft.postActionRequest(\n      args[0],\n      args[1],\n      function (data, textStatus, jqXHR) {\n        if (args[2] && typeof args[2] === 'function') {\n          args[2](data, textStatus, jqXHR);\n        }\n\n        if (Craft._ajaxQueue.length) {\n          Craft._postNextActionRequestInQueue();\n        } else {\n          Craft._waitingOnAjax = false;\n        }\n      },\n      args[3]\n    );\n  },\n\n  _actionHeaders: function () {\n    let headers = {\n      'X-Registered-Asset-Bundles': Object.keys(\n        Craft.registeredAssetBundles\n      ).join(','),\n      'X-Registered-Js-Files': Object.keys(Craft.registeredJsFiles).join(','),\n    };\n\n    if (Craft.csrfTokenValue) {\n      headers['X-CSRF-Token'] = Craft.csrfTokenValue;\n    }\n\n    return headers;\n  },\n\n  /**\n   * Sends a request to a Craft/plugin action\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {string} action The action to request\n   * @param {Object} options Axios request options\n   * @returns {Promise}\n   * @since 3.4.6\n   */\n  sendActionRequest: function (method, action, options) {\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      options.method = method;\n      options.url = Craft.getActionUrl(action);\n      options.headers = $.extend(\n        {\n          'X-Requested-With': 'XMLHttpRequest',\n        },\n        options.headers || {},\n        this._actionHeaders()\n      );\n      options.params = $.extend({}, options.params || {}, {\n        // Force Safari to not load from cache\n        v: new Date().getTime(),\n      });\n      axios.request(options).then(resolve).catch(reject);\n    });\n  },\n\n  /**\n   * Sends a request to the Craftnet API.\n   * @param {string} method The request action to use ('GET' or 'POST')\n   * @param {string} uri The API endpoint URI\n   * @param {Object} options Axios request options\n   * @returns {Promise}\n   * @since 3.3.16\n   */\n  sendApiRequest: function (method, uri, options) {\n    return new Promise((resolve, reject) => {\n      options = options ? $.extend({}, options) : {};\n      let cancelToken = options.cancelToken || null;\n\n      // Get the latest headers\n      this._getApiHeaders(cancelToken)\n        .then((apiHeaders) => {\n          // Send the API request\n          options.method = method;\n          options.baseURL = Craft.baseApiUrl;\n          options.url = uri;\n          options.headers = $.extend(apiHeaders, options.headers || {});\n          options.params = $.extend(\n            Craft.apiParams || {},\n            options.params || {},\n            {\n              // Force Safari to not load from cache\n              v: new Date().getTime(),\n            }\n          );\n\n          // Force the API to process the Craft headers if this is the first API request\n          if (!this._apiHeaders) {\n            options.params.processCraftHeaders = 1;\n          }\n\n          if (Craft.httpProxy) {\n            options.proxy = Craft.httpProxy;\n          }\n\n          axios\n            .request(options)\n            .then((apiResponse) => {\n              // Process the response headers\n              this._processApiHeaders(apiResponse.headers, cancelToken)\n                .then(() => {\n                  // Finally return the API response data\n                  resolve(apiResponse.data);\n                })\n                .catch(reject);\n            })\n            .catch(reject);\n        })\n        .catch(reject);\n    });\n  },\n\n  _loadingApiHeaders: false,\n  _apiHeaders: null,\n  _apiHeaderWaitlist: [],\n\n  /**\n   * Returns the headers that should be sent with API requests.\n   *\n   * @param {Object|null} cancelToken\n   * @return {Promise}\n   */\n  _getApiHeaders: function (cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Are we already loading them?\n      if (this._loadingApiHeaders) {\n        this._apiHeaderWaitlist.push([resolve, reject]);\n        return;\n      }\n\n      // Are the headers already cached?\n      if (this._apiHeaders) {\n        resolve(this._apiHeaders);\n        return;\n      }\n\n      this._loadingApiHeaders = true;\n      this.sendActionRequest('POST', 'app/api-headers', {\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          resolve(response.data);\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _processApiHeaders: function (headers, cancelToken) {\n    return new Promise((resolve, reject) => {\n      // Have we already processed them?\n      if (this._apiHeaders) {\n        resolve();\n        return;\n      }\n\n      this.sendActionRequest('POST', 'app/process-api-response-headers', {\n        data: {\n          headers: headers,\n        },\n        cancelToken: cancelToken,\n      })\n        .then((response) => {\n          // Make sure we even are waiting for these anymore\n          if (!this._loadingApiHeaders) {\n            reject(e);\n            return;\n          }\n\n          this._apiHeaders = response.data;\n          this._loadingApiHeaders = false;\n\n          resolve();\n\n          // Was anything else waiting for them?\n          while (this._apiHeaderWaitlist.length) {\n            this._apiHeaderWaitlist.shift()[0](this._apiHeaders);\n          }\n        })\n        .catch((e) => {\n          this._rejectApiRequests(reject, e);\n        });\n    });\n  },\n\n  _rejectApiRequests: function (reject, e) {\n    this._loadingApiHeaders = false;\n    reject(e);\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1](e);\n    }\n  },\n\n  /**\n   * Clears the cached API headers.\n   */\n  clearCachedApiHeaders: function () {\n    this._apiHeaders = null;\n    this._loadingApiHeaders = false;\n\n    // Reject anything in the header waitlist\n    while (this._apiHeaderWaitlist.length) {\n      this._apiHeaderWaitlist.shift()[1]();\n    }\n  },\n\n  /**\n   * Requests a URL and downloads the response.\n   *\n   * @param {string} method the request method to use\n   * @param {string} url the URL\n   * @param {string|Object} [body] the request body, if method = POST\n   * @return {Promise}\n   */\n  downloadFromUrl: function (method, url, body) {\n    return new Promise((resolve, reject) => {\n      // h/t https://nehalist.io/downloading-files-from-post-requests/\n      let request = new XMLHttpRequest();\n      request.open(method, url, true);\n      if (typeof body === 'object') {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/json; charset=UTF-8'\n        );\n        body = JSON.stringify(body);\n      } else {\n        request.setRequestHeader(\n          'Content-Type',\n          'application/x-www-form-urlencoded; charset=UTF-8'\n        );\n      }\n      request.responseType = 'blob';\n\n      request.onload = () => {\n        // Only handle status code 200\n        if (request.status === 200) {\n          // Try to find out the filename from the content disposition `filename` value\n          let disposition = request.getResponseHeader('content-disposition');\n          let matches = /\"([^\"]*)\"/.exec(disposition);\n          let filename =\n            matches != null && matches[1] ? matches[1] : 'Download';\n\n          // Encode the download into an anchor href\n          let contentType = request.getResponseHeader('content-type');\n          let blob = new Blob([request.response], {type: contentType});\n          let link = document.createElement('a');\n          link.href = window.URL.createObjectURL(blob);\n          link.download = filename;\n          document.body.appendChild(link);\n          link.click();\n          document.body.removeChild(link);\n\n          resolve();\n        } else {\n          reject();\n        }\n      };\n\n      request.send(body);\n    });\n  },\n\n  /**\n   * Converts a comma-delimited string into an array.\n   *\n   * @param {string} str\n   * @return array\n   */\n  stringToArray: function (str) {\n    if (typeof str !== 'string') {\n      return str;\n    }\n\n    var arr = str.split(',');\n    for (var i = 0; i < arr.length; i++) {\n      arr[i] = $.trim(arr[i]);\n    }\n    return arr;\n  },\n\n  /**\n   * Compares old and new post data, and removes any values that haven't\n   * changed within the given list of delta namespaces.\n   *\n   * @param {string} oldData\n   * @param {string} newData\n   * @param {object} deltaNames\n   * @param {function} [callback] Callback function that should be called whenever a new group of modified params has been found\n   * @param {object} [initialDeltaValues] Initial delta values. If undefined, `Craft.initialDeltaValues` will be used.\n   * @return {string}\n   */\n  findDeltaData: function (\n    oldData,\n    newData,\n    deltaNames,\n    callback,\n    initialDeltaValues\n  ) {\n    // Make sure oldData and newData are always strings. This is important because further below String.split is called.\n    oldData = typeof oldData === 'string' ? oldData : '';\n    newData = typeof newData === 'string' ? newData : '';\n\n    // Sort the delta namespaces from least -> most specific\n    deltaNames.sort(function (a, b) {\n      if (a.length === b.length) {\n        return 0;\n      }\n      return a.length > b.length ? 1 : -1;\n    });\n\n    // Group all of the old & new params by namespace\n    if (typeof initialDeltaValues === 'undefined') {\n      initialDeltaValues = Craft.initialDeltaValues;\n    }\n    var groupedOldParams = this._groupParamsByDeltaNames(\n      oldData.split('&'),\n      deltaNames,\n      false,\n      initialDeltaValues\n    );\n    var groupedNewParams = this._groupParamsByDeltaNames(\n      newData.split('&'),\n      deltaNames,\n      true,\n      false\n    );\n\n    // Figure out which of the new params should actually be posted\n    var params = groupedNewParams.__root__;\n    for (var n = 0; n < deltaNames.length; n++) {\n      if (\n        Craft.inArray(deltaNames[n], Craft.modifiedDeltaNames) ||\n        (typeof groupedNewParams[deltaNames[n]] === 'object' &&\n          (typeof groupedOldParams[deltaNames[n]] !== 'object' ||\n            JSON.stringify(groupedOldParams[deltaNames[n]]) !==\n              JSON.stringify(groupedNewParams[deltaNames[n]])))\n      ) {\n        params = params.concat(groupedNewParams[deltaNames[n]]);\n        params.push('modifiedDeltaNames[]=' + deltaNames[n]);\n        if (callback) {\n          callback(deltaNames[n], groupedNewParams[deltaNames[n]]);\n        }\n      }\n    }\n\n    return params.join('&');\n  },\n\n  /**\n   * @param {object} params\n   * @param {object} deltaNames\n   * @param {boolean} withRoot\n   * @param {boolean|object} initialValues\n   * @returns {{}}\n   * @private\n   */\n  _groupParamsByDeltaNames: function (\n    params,\n    deltaNames,\n    withRoot,\n    initialValues\n  ) {\n    const grouped = {};\n\n    if (withRoot) {\n      grouped.__root__ = [];\n    }\n\n    const encodeURIComponentExceptEqualChar = (o) =>\n      encodeURIComponent(o).replace('%3D', '=');\n\n    params = params.map((p) => decodeURIComponent(p));\n\n    paramLoop: for (let p = 0; p < params.length; p++) {\n      // loop through the delta names from most -> least specific\n      for (let n = deltaNames.length - 1; n >= 0; n--) {\n        const paramName = params[p].substr(0, deltaNames[n].length + 1);\n        if (\n          paramName === deltaNames[n] + '=' ||\n          paramName === deltaNames[n] + '['\n        ) {\n          if (typeof grouped[deltaNames[n]] === 'undefined') {\n            grouped[deltaNames[n]] = [];\n          }\n          grouped[deltaNames[n]].push(\n            encodeURIComponentExceptEqualChar(params[p])\n          );\n          continue paramLoop;\n        }\n      }\n\n      if (withRoot) {\n        grouped.__root__.push(encodeURIComponentExceptEqualChar(params[p]));\n      }\n    }\n\n    if (initialValues) {\n      const serializeParam = (name, value) => {\n        if ($.isArray(value) || $.isPlainObject(value)) {\n          value = $.param(value);\n        } else if (typeof value === 'string') {\n          value = encodeURIComponent(value);\n        } else if (value === null) {\n          value = '';\n        }\n        return `${encodeURIComponent(name)}=${value}`;\n      };\n\n      for (let name in initialValues) {\n        if (initialValues.hasOwnProperty(name)) {\n          if ($.isPlainObject(initialValues[name])) {\n            grouped[name] = [];\n            for (let subName in initialValues[name]) {\n              if (initialValues[name].hasOwnProperty(subName)) {\n                grouped[name].push(\n                  serializeParam(\n                    `${name}[${subName}]`,\n                    initialValues[name][subName]\n                  )\n                );\n              }\n            }\n          } else {\n            grouped[name] = [serializeParam(name, initialValues[name])];\n          }\n        }\n      }\n    }\n\n    return grouped;\n  },\n\n  /**\n   * Expands an array of POST array-style strings into an actual array.\n   *\n   * @param {object} arr\n   * @return array\n   */\n  expandPostArray: function (arr) {\n    var expanded = {};\n    var i;\n\n    for (var key in arr) {\n      if (!arr.hasOwnProperty(key)) {\n        continue;\n      }\n\n      var value = arr[key],\n        m = key.match(/^(\\w+)(\\[.*)?/),\n        keys;\n\n      if (m[2]) {\n        // Get all of the nested keys\n        keys = m[2].match(/\\[[^\\[\\]]*\\]/g);\n\n        // Chop off the brackets\n        for (i = 0; i < keys.length; i++) {\n          keys[i] = keys[i].substring(1, keys[i].length - 1);\n        }\n      } else {\n        keys = [];\n      }\n\n      keys.unshift(m[1]);\n\n      var parentElem = expanded;\n\n      for (i = 0; i < keys.length; i++) {\n        if (i < keys.length - 1) {\n          if (typeof parentElem[keys[i]] !== 'object') {\n            // Figure out what this will be by looking at the next key\n            if (!keys[i + 1] || parseInt(keys[i + 1]) == keys[i + 1]) {\n              parentElem[keys[i]] = [];\n            } else {\n              parentElem[keys[i]] = {};\n            }\n          }\n\n          parentElem = parentElem[keys[i]];\n        } else {\n          // Last one. Set the value\n          if (!keys[i]) {\n            keys[i] = parentElem.length;\n          }\n\n          parentElem[keys[i]] = value;\n        }\n      }\n    }\n\n    return expanded;\n  },\n\n  /**\n   * Creates a form element populated with hidden inputs based on a string of serialized form data.\n   *\n   * @param {string} data\n   * @returns {jQuery|HTMLElement}\n   */\n  createForm: function (data) {\n    var $form = $('<form/>', {\n      attr: {\n        method: 'post',\n        action: '',\n        'accept-charset': 'UTF-8',\n      },\n    });\n\n    if (typeof data === 'string') {\n      var values = data.split('&');\n      var chunks;\n      for (var i = 0; i < values.length; i++) {\n        chunks = values[i].split('=', 2);\n        $('<input/>', {\n          type: 'hidden',\n          name: decodeURIComponent(chunks[0]),\n          value: decodeURIComponent(chunks[1] || ''),\n        }).appendTo($form);\n      }\n    }\n\n    return $form;\n  },\n\n  /**\n   * Compares two variables and returns whether they are equal in value.\n   * Recursively compares array and object values.\n   *\n   * @param obj1\n   * @param obj2\n   * @param sortObjectKeys Whether object keys should be sorted before being compared. Default is true.\n   * @return boolean\n   */\n  compare: function (obj1, obj2, sortObjectKeys) {\n    // Compare the types\n    if (typeof obj1 !== typeof obj2) {\n      return false;\n    }\n\n    if (typeof obj1 === 'object') {\n      // Compare the lengths\n      if (obj1.length !== obj2.length) {\n        return false;\n      }\n\n      // Is one of them an array but the other is not?\n      if (obj1 instanceof Array !== obj2 instanceof Array) {\n        return false;\n      }\n\n      // If they're actual objects (not arrays), compare the keys\n      if (!(obj1 instanceof Array)) {\n        if (typeof sortObjectKeys === 'undefined' || sortObjectKeys === true) {\n          if (\n            !Craft.compare(\n              Craft.getObjectKeys(obj1).sort(),\n              Craft.getObjectKeys(obj2).sort()\n            )\n          ) {\n            return false;\n          }\n        } else {\n          if (\n            !Craft.compare(Craft.getObjectKeys(obj1), Craft.getObjectKeys(obj2))\n          ) {\n            return false;\n          }\n        }\n      }\n\n      // Compare each value\n      for (var i in obj1) {\n        if (!obj1.hasOwnProperty(i)) {\n          continue;\n        }\n\n        if (!Craft.compare(obj1[i], obj2[i])) {\n          return false;\n        }\n      }\n\n      // All clear\n      return true;\n    } else {\n      return obj1 === obj2;\n    }\n  },\n\n  /**\n   * Returns an array of an object's keys.\n   *\n   * @param {object} obj\n   * @return string\n   */\n  getObjectKeys: function (obj) {\n    var keys = [];\n\n    for (var key in obj) {\n      if (!obj.hasOwnProperty(key)) {\n        continue;\n      }\n\n      keys.push(key);\n    }\n\n    return keys;\n  },\n\n  /**\n   * Takes an array or string of chars, and places a backslash before each one, returning the combined string.\n   *\n   * Userd by ltrim() and rtrim()\n   *\n   * @param {string|object} chars\n   * @return string\n   */\n  escapeChars: function (chars) {\n    if (!Garnish.isArray(chars)) {\n      chars = chars.split();\n    }\n\n    var escaped = '';\n\n    for (var i = 0; i < chars.length; i++) {\n      escaped += '\\\\' + chars[i];\n    }\n\n    return escaped;\n  },\n\n  /**\n   * Trim characters off of the beginning of a string.\n   *\n   * @param {string} str\n   * @param {string|object|undefined} chars The characters to trim off. Defaults to a space if left blank.\n   * @return string\n   */\n  ltrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('^[' + Craft.escapeChars(chars) + ']+');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the end of a string.\n   *\n   * @param {string} str\n   * @param {string|object|undefined} chars The characters to trim off. Defaults to a space if left blank.\n   * @return string\n   */\n  rtrim: function (str, chars) {\n    if (!str) {\n      return str;\n    }\n    if (typeof chars === 'undefined') {\n      chars = ' \\t\\n\\r\\0\\x0B';\n    }\n    var re = new RegExp('[' + Craft.escapeChars(chars) + ']+$');\n    return str.replace(re, '');\n  },\n\n  /**\n   * Trim characters off of the beginning and end of a string.\n   *\n   * @param {string} str\n   * @param {string|object|undefined} chars The characters to trim off. Defaults to a space if left blank.\n   * @return string\n   */\n  trim: function (str, chars) {\n    str = Craft.ltrim(str, chars);\n    str = Craft.rtrim(str, chars);\n    return str;\n  },\n\n  /**\n   * Returns whether a string starts with another string.\n   *\n   * @param {string} str\n   * @param {string} substr\n   * @return boolean\n   */\n  startsWith: function (str, substr) {\n    return str.substr(0, substr.length) === substr;\n  },\n\n  /**\n   * Filters an array.\n   *\n   * @param {object} arr\n   * @param {function} callback A user-defined callback function. If null, we'll just remove any elements that equate to false.\n   * @return array\n   */\n  filterArray: function (arr, callback) {\n    var filtered = [];\n\n    for (var i = 0; i < arr.length; i++) {\n      var include;\n\n      if (typeof callback === 'function') {\n        include = callback(arr[i], i);\n      } else {\n        include = arr[i];\n      }\n\n      if (include) {\n        filtered.push(arr[i]);\n      }\n    }\n\n    return filtered;\n  },\n\n  /**\n   * Returns whether an element is in an array (unlike jQuery.inArray(), which returns the element's index, or -1).\n   *\n   * @param elem\n   * @param arr\n   * @return boolean\n   */\n  inArray: function (elem, arr) {\n    if ($.isPlainObject(arr)) {\n      arr = Object.values(arr);\n    }\n    return arr.includes(elem);\n  },\n\n  /**\n   * Removes an element from an array.\n   *\n   * @param elem\n   * @param {object} arr\n   * @return boolean Whether the element could be found or not.\n   */\n  removeFromArray: function (elem, arr) {\n    var index = $.inArray(elem, arr);\n    if (index !== -1) {\n      arr.splice(index, 1);\n      return true;\n    } else {\n      return false;\n    }\n  },\n\n  /**\n   * Returns the last element in an array.\n   *\n   * @param {object} arr\n   * @return mixed\n   */\n  getLast: function (arr) {\n    if (!arr.length) {\n      return null;\n    } else {\n      return arr[arr.length - 1];\n    }\n  },\n\n  /**\n   * Makes the first character of a string uppercase.\n   *\n   * @param {string} str\n   * @return string\n   */\n  uppercaseFirst: function (str) {\n    return str.charAt(0).toUpperCase() + str.slice(1);\n  },\n\n  /**\n   * Makes the first character of a string lowercase.\n   *\n   * @param {string} str\n   * @return string\n   */\n  lowercaseFirst: function (str) {\n    return str.charAt(0).toLowerCase() + str.slice(1);\n  },\n\n  parseUrl: function (url) {\n    var m = url.match(\n      /^(?:(https?):\\/\\/|\\/\\/)([^\\/\\:]*)(?:\\:(\\d+))?(\\/[^\\?]*)?(?:\\?([^#]*))?(#.*)?/\n    );\n    if (!m) {\n      return {};\n    }\n    return {\n      scheme: m[1],\n      host: m[2] + (m[3] ? ':' + m[3] : ''),\n      hostname: m[2],\n      port: m[3] || null,\n      path: m[4] || '/',\n      query: m[5] || null,\n      hash: m[6] || null,\n    };\n  },\n\n  isSameHost: function (url) {\n    var requestUrlInfo = this.parseUrl(document.location.href);\n    if (!requestUrlInfo) {\n      return false;\n    }\n    var urlInfo = this.parseUrl(url);\n    if (!urlInfo) {\n      return false;\n    }\n    return requestUrlInfo.host === urlInfo.host;\n  },\n\n  /**\n   * Converts a number of seconds into a human-facing time duration.\n   */\n  secondsToHumanTimeDuration: function (seconds, showSeconds) {\n    if (typeof showSeconds === 'undefined') {\n      showSeconds = true;\n    }\n\n    var secondsInWeek = 604800,\n      secondsInDay = 86400,\n      secondsInHour = 3600,\n      secondsInMinute = 60;\n\n    var weeks = Math.floor(seconds / secondsInWeek);\n    seconds = seconds % secondsInWeek;\n\n    var days = Math.floor(seconds / secondsInDay);\n    seconds = seconds % secondsInDay;\n\n    var hours = Math.floor(seconds / secondsInHour);\n    seconds = seconds % secondsInHour;\n\n    var minutes;\n\n    if (showSeconds) {\n      minutes = Math.floor(seconds / secondsInMinute);\n      seconds = seconds % secondsInMinute;\n    } else {\n      minutes = Math.round(seconds / secondsInMinute);\n      seconds = 0;\n    }\n\n    var timeComponents = [];\n\n    if (weeks) {\n      timeComponents.push(\n        weeks +\n          ' ' +\n          (weeks === 1 ? Craft.t('app', 'week') : Craft.t('app', 'weeks'))\n      );\n    }\n\n    if (days) {\n      timeComponents.push(\n        days +\n          ' ' +\n          (days === 1 ? Craft.t('app', 'day') : Craft.t('app', 'days'))\n      );\n    }\n\n    if (hours) {\n      timeComponents.push(\n        hours +\n          ' ' +\n          (hours === 1 ? Craft.t('app', 'hour') : Craft.t('app', 'hours'))\n      );\n    }\n\n    if (minutes || (!showSeconds && !weeks && !days && !hours)) {\n      timeComponents.push(\n        minutes +\n          ' ' +\n          (minutes === 1 ? Craft.t('app', 'minute') : Craft.t('app', 'minutes'))\n      );\n    }\n\n    if (seconds || (showSeconds && !weeks && !days && !hours && !minutes)) {\n      timeComponents.push(\n        seconds +\n          ' ' +\n          (seconds === 1 ? Craft.t('app', 'second') : Craft.t('app', 'seconds'))\n      );\n    }\n\n    return timeComponents.join(', ');\n  },\n\n  /**\n   * Converts extended ASCII characters to ASCII.\n   *\n   * @param {string} str\n   * @param {object|undefined} charMap\n   * @return string\n   */\n  asciiString: function (str, charMap) {\n    // Normalize NFD chars to NFC\n    str = str.normalize('NFC');\n\n    var asciiStr = '';\n    var char;\n\n    for (var i = 0; i < str.length; i++) {\n      char = str.charAt(i);\n      asciiStr +=\n        typeof (charMap || Craft.asciiCharMap)[char] === 'string'\n          ? (charMap || Craft.asciiCharMap)[char]\n          : char;\n    }\n\n    return asciiStr;\n  },\n\n  randomString: function (length) {\n    // h/t https://stackoverflow.com/a/1349426/1688568\n    var result = '';\n    var characters =\n      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n    for (var i = 0; i < length; i++) {\n      result += characters.charAt(Math.floor(Math.random() * 62));\n    }\n    return result;\n  },\n\n  /**\n   * Creates a validation error list.\n   *\n   * @param {object} errors\n   * @return jQuery\n   */\n  createErrorList: function (errors) {\n    var $ul = $(document.createElement('ul')).addClass('errors');\n\n    for (var i = 0; i < errors.length; i++) {\n      var $li = $(document.createElement('li'));\n      $li.appendTo($ul);\n      $li.html(errors[i]);\n    }\n\n    return $ul;\n  },\n\n  appendHeadHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any link tags that are already included\n    var $existingCss = $('link[href]');\n\n    if ($existingCss.length) {\n      var existingCss = [];\n      var href;\n\n      for (var i = 0; i < $existingCss.length; i++) {\n        href = $existingCss.eq(i).attr('href').replace(/&/g, '&amp;');\n        existingCss.push(Craft.escapeRegex(href));\n      }\n\n      const regexp = new RegExp(\n        '<link\\\\s[^>]*href=\"(?:' + existingCss.join('|') + ')\".*?></link>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    $('head').append(html);\n  },\n\n  appendFootHtml: function (html) {\n    if (!html) {\n      return;\n    }\n\n    // Prune out any script tags that are already included\n    var $existingJs = $('script[src]');\n\n    if ($existingJs.length) {\n      var existingJs = [];\n      var src;\n\n      for (var i = 0; i < $existingJs.length; i++) {\n        src = $existingJs.eq(i).attr('src').replace(/&/g, '&amp;');\n        existingJs.push(Craft.escapeRegex(src));\n      }\n\n      var regexp = new RegExp(\n        '<script\\\\s[^>]*src=\"(?:' + existingJs.join('|') + ')\".*?></script>',\n        'g'\n      );\n\n      html = html.replace(regexp, '');\n    }\n\n    Garnish.$bod.append(html);\n  },\n\n  /**\n   * Initializes any common UI elements in a given container.\n   *\n   * @param {object} $container\n   */\n  initUiElements: function ($container) {\n    $('.grid', $container).grid();\n    $('.info', $container).infoicon();\n    $('.checkbox-select', $container).checkboxselect();\n    $('.fieldtoggle', $container).fieldtoggle();\n    $('.lightswitch', $container).lightswitch();\n    $('.nicetext', $container).nicetext();\n    $('.formsubmit', $container).formsubmit();\n    $('.menubtn:not([data-disclosure-trigger])', $container).menubtn();\n    $('[data-disclosure-trigger]', $container).disclosureMenu();\n    $('.datetimewrapper', $container).datetime();\n    $(\n      '.datewrapper > input[type=\"date\"], .timewrapper > input[type=\"time\"]',\n      $container\n    ).datetimeinput();\n\n    // Open outbound links in new windows\n    // hat tip: https://stackoverflow.com/a/2911045/1688568\n    $('a', $container).each(function () {\n      if (\n        this.hostname.length &&\n        this.hostname !== location.hostname &&\n        typeof $(this).attr('target') === 'undefined'\n      ) {\n        $(this).attr('rel', 'noopener').attr('target', '_blank');\n      }\n    });\n  },\n\n  _elementIndexClasses: {},\n  _elementSelectorModalClasses: {},\n  _elementEditorClasses: {},\n\n  /**\n   * Registers an element index class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementIndexClass: function (elementType, func) {\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      throw (\n        'An element index class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementIndexClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element selector modal class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementSelectorModalClass: function (elementType, func) {\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      throw (\n        'An element selector modal class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementSelectorModalClasses[elementType] = func;\n  },\n\n  /**\n   * Registers an element editor class for a given element type.\n   *\n   * @param {string} elementType\n   * @param {function} func\n   */\n  registerElementEditorClass: function (elementType, func) {\n    if (typeof this._elementEditorClasses[elementType] !== 'undefined') {\n      throw (\n        'An element editor class has already been registered for the element type “' +\n        elementType +\n        '”.'\n      );\n    }\n\n    this._elementEditorClasses[elementType] = func;\n  },\n\n  /**\n   * Creates a new element index for a given element type.\n   *\n   * @param {string} elementType\n   * @param $container\n   * @param {object} settings\n   * @return BaseElementIndex\n   */\n  createElementIndex: function (elementType, $container, settings) {\n    var func;\n\n    if (typeof this._elementIndexClasses[elementType] !== 'undefined') {\n      func = this._elementIndexClasses[elementType];\n    } else {\n      func = Craft.BaseElementIndex;\n    }\n\n    return new func(elementType, $container, settings);\n  },\n\n  /**\n   * Creates a new element selector modal for a given element type.\n   *\n   * @param {string} elementType\n   * @param {object} settings\n   */\n  createElementSelectorModal: function (elementType, settings) {\n    var func;\n\n    if (typeof this._elementSelectorModalClasses[elementType] !== 'undefined') {\n      func = this._elementSelectorModalClasses[elementType];\n    } else {\n      func = Craft.BaseElementSelectorModal;\n    }\n\n    return new func(elementType, settings);\n  },\n\n  /**\n   * Creates a new element editor HUD for a given element type.\n   *\n   * @param {string} elementType\n   * @param element $element\n   * @param {object} settings\n   */\n  createElementEditor: function (elementType, element, settings) {\n    // Param mapping\n    if (typeof settings === 'undefined' && $.isPlainObject(element)) {\n      // (settings)\n      settings = element;\n      element = null;\n    } else if (typeof settings !== 'object') {\n      settings = {};\n    }\n\n    if (!settings.elementType) {\n      settings.elementType = elementType;\n    }\n\n    var func;\n    if (typeof this._elementEditorClasses[elementType] !== 'undefined') {\n      func = this._elementEditorClasses[elementType];\n    } else {\n      func = Craft.BaseElementEditor;\n    }\n\n    return new func(element, settings);\n  },\n\n  /**\n   * Retrieves a value from localStorage if it exists.\n   *\n   * @param {string} key\n   * @param defaultValue\n   */\n  getLocalStorage: function (key, defaultValue) {\n    key = 'Craft-' + Craft.systemUid + '.' + key;\n\n    if (\n      typeof localStorage !== 'undefined' &&\n      typeof localStorage[key] !== 'undefined'\n    ) {\n      return JSON.parse(localStorage[key]);\n    } else {\n      return defaultValue;\n    }\n  },\n\n  /**\n   * Saves a value to localStorage.\n   *\n   * @param {string} key\n   * @param value\n   */\n  setLocalStorage: function (key, value) {\n    if (typeof localStorage !== 'undefined') {\n      key = 'Craft-' + Craft.systemUid + '.' + key;\n\n      // localStorage might be filled all the way up.\n      // Especially likely if this is a private window in Safari 8+, where localStorage technically exists,\n      // but has a max size of 0 bytes.\n      try {\n        localStorage[key] = JSON.stringify(value);\n      } catch (e) {}\n    }\n  },\n\n  /**\n   * Removes a value from localStorage.\n   * @param key\n   */\n  removeLocalStorage: function (key) {\n    if (typeof localStorage !== 'undefined') {\n      localStorage.removeItem(`Craft-${Craft.systemUid}.${key}`);\n    }\n  },\n\n  /**\n   * Returns a cookie value, if it exists, otherwise returns `false`\n   * @return {(string|boolean)}\n   */\n  getCookie: function (name) {\n    // Adapted from https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie\n    return document.cookie.replace(\n      new RegExp(\n        `(?:(?:^|.*;\\\\s*)Craft-${Craft.systemUid}:${name}\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$`\n      ),\n      '$1'\n    );\n  },\n\n  /**\n   * Sets a cookie value.\n   * @param {string} name\n   * @param {string} value\n   * @param {Object} [options]\n   * @param {string} [options.path] The cookie path.\n   * @param {string} [options.domain] The cookie domain. Defaults to the `defaultCookieDomain` config setting.\n   * @param {number} [options.maxAge] The max age of the cookie (in seconds)\n   * @param {Date} [options.expires] The expiry date of the cookie. Defaults to none (session-based cookie).\n   * @param {boolean} [options.secure] Whether this is a secure cookie. Defaults to the `useSecureCookies`\n   * config setting.\n   * @param {string} [options.sameSite] The SameSite value (`lax` or `strict`). Defaults to the\n   * `sameSiteCookieValue` config setting.\n   */\n  setCookie: function (name, value, options) {\n    options = $.extend({}, this.defaultCookieOptions, options);\n    let cookie = `Craft-${Craft.systemUid}:${name}=${encodeURIComponent(\n      value\n    )}`;\n    if (options.path) {\n      cookie += `;path=${options.path}`;\n    }\n    if (options.domain) {\n      cookie += `;domain=${options.domain}`;\n    }\n    if (options.maxAge) {\n      cookie += `;max-age-in-seconds=${options.maxAge}`;\n    } else if (options.expires) {\n      cookie += `;expires=${options.expires.toUTCString()}`;\n    }\n    if (options.secure) {\n      cookie += ';secure';\n    }\n    document.cookie = cookie;\n  },\n\n  /**\n   * Removes a cookie\n   * @param {string} name\n   */\n  removeCookie: function (name) {\n    this.setCookie(name, '', new Date('1970-01-01T00:00:00'));\n  },\n\n  /**\n   * Returns element information from it's HTML.\n   *\n   * @param element\n   * @returns object\n   */\n  getElementInfo: function (element) {\n    var $element = $(element);\n\n    if (!$element.hasClass('element')) {\n      $element = $element.find('.element:first');\n    }\n\n    return {\n      id: $element.data('id'),\n      siteId: $element.data('site-id'),\n      label: $element.data('label'),\n      status: $element.data('status'),\n      url: $element.data('url'),\n      hasThumb: $element.hasClass('hasthumb'),\n      $element: $element,\n    };\n  },\n\n  /**\n   * Changes an element to the requested size.\n   *\n   * @param element\n   * @param size\n   */\n  setElementSize: function (element, size) {\n    var $element = $(element);\n\n    if (size !== 'small' && size !== 'large') {\n      size = 'small';\n    }\n\n    if ($element.hasClass(size)) {\n      return;\n    }\n\n    var otherSize = size === 'small' ? 'large' : 'small';\n\n    $element.addClass(size).removeClass(otherSize);\n\n    if ($element.hasClass('hasthumb')) {\n      var $oldImg = $element.find('> .elementthumb > img'),\n        imgSize = size === 'small' ? '30' : '100',\n        $newImg = $('<img/>', {\n          sizes: imgSize + 'px',\n          srcset: $oldImg.attr('srcset') || $oldImg.attr('data-pfsrcset'),\n        });\n\n      $oldImg.replaceWith($newImg);\n\n      picturefill({\n        elements: [$newImg[0]],\n      });\n    }\n  },\n\n  /**\n   * Submits a form.\n   * @param {Object} $form\n   * @param {Object} [options]\n   * @param {string} [options.action] The `action` param value override\n   * @param {string} [options.redirect] The `redirect` param value override\n   * @param {string} [options.confirm] A confirmation message that should be shown to the user before submit\n   * @param {Object} [options.params] Additional params that should be added to the form, defined as name/value pairs\n   * @param {Object} [options.data] Additional data to be passed to the submit event\n   * @param {boolean} [options.retainScroll] Whether the scroll position should be stored and reapplied on the next page load\n   */\n  submitForm: function ($form, options) {\n    if (typeof options === 'undefined') {\n      options = {};\n    }\n\n    if (options.confirm && !confirm(options.confirm)) {\n      return;\n    }\n\n    if (options.action) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'action',\n        val: options.action,\n      }).appendTo($form);\n    }\n\n    if (options.redirect) {\n      $('<input/>', {\n        type: 'hidden',\n        name: 'redirect',\n        val: options.redirect,\n      }).appendTo($form);\n    }\n\n    if (options.params) {\n      for (let name in options.params) {\n        let value = options.params[name];\n        $('<input/>', {\n          type: 'hidden',\n          name: name,\n          val: value,\n        }).appendTo($form);\n      }\n    }\n\n    if (options.retainScroll) {\n      this.setLocalStorage('scrollY', window.scrollY);\n    }\n\n    $form.trigger($.extend({type: 'submit'}, options.data));\n  },\n\n  /**\n   * Traps focus within a container, so when focus is tabbed out of it, it’s cycled back into it.\n   * @param {Object} container\n   */\n  trapFocusWithin: function (container) {\n    Garnish.trapFocusWithin(container);\n  },\n\n  /**\n   * Sets focus to the first focusable element within a container.\n   * @param {Object} container\n   */\n  setFocusWithin: function (container) {\n    Garnish.setFocusWithin(container);\n  },\n});\n\n// -------------------------------------------\n//  Custom jQuery plugins\n// -------------------------------------------\n\n$.extend($.fn, {\n  animateLeft: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({left: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({right: pos}, duration, easing, complete);\n    }\n  },\n\n  animateRight: function (pos, duration, easing, complete) {\n    if (Craft.orientation === 'ltr') {\n      return this.velocity({right: pos}, duration, easing, complete);\n    } else {\n      return this.velocity({left: pos}, duration, easing, complete);\n    }\n  },\n\n  /**\n   * Disables elements by adding a .disabled class and preventing them from receiving focus.\n   */\n  disable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.addClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.removeAttr('tabindex');\n      }\n    });\n  },\n\n  /**\n   * Enables elements by removing their .disabled class and allowing them to receive focus.\n   */\n  enable: function () {\n    return this.each(function () {\n      var $elem = $(this);\n      $elem.removeClass('disabled');\n\n      if ($elem.data('activatable')) {\n        $elem.attr('tabindex', '0');\n      }\n    });\n  },\n\n  /**\n   * Sets the element as the container of a grid.\n   */\n  grid: function () {\n    return this.each(function () {\n      var $container = $(this),\n        settings = {};\n\n      if ($container.data('item-selector')) {\n        settings.itemSelector = $container.data('item-selector');\n      }\n      if ($container.data('cols')) {\n        settings.cols = parseInt($container.data('cols'));\n      }\n      if ($container.data('max-cols')) {\n        settings.maxCols = parseInt($container.data('max-cols'));\n      }\n      if ($container.data('min-col-width')) {\n        settings.minColWidth = parseInt($container.data('min-col-width'));\n      }\n      if ($container.data('mode')) {\n        settings.mode = $container.data('mode');\n      }\n      if ($container.data('fill-mode')) {\n        settings.fillMode = $container.data('fill-mode');\n      }\n      if ($container.data('col-class')) {\n        settings.colClass = $container.data('col-class');\n      }\n      if ($container.data('snap-to-grid')) {\n        settings.snapToGrid = !!$container.data('snap-to-grid');\n      }\n\n      new Craft.Grid(this, settings);\n    });\n  },\n\n  infoicon: function () {\n    return this.each(function () {\n      new Craft.InfoIcon(this);\n    });\n  },\n\n  /**\n   * Sets the element as a container for a checkbox select.\n   */\n  checkboxselect: function () {\n    return this.each(function () {\n      if (!$.data(this, 'checkboxselect')) {\n        new Garnish.CheckboxSelect(this);\n      }\n    });\n  },\n\n  /**\n   * Sets the element as a field toggle trigger.\n   */\n  fieldtoggle: function () {\n    return this.each(function () {\n      if (!$.data(this, 'fieldtoggle')) {\n        new Craft.FieldToggle(this);\n      }\n    });\n  },\n\n  lightswitch: function (settings, settingName, settingValue) {\n    // param mapping\n    if (settings === 'settings') {\n      if (typeof settingName === 'string') {\n        settings = {};\n        settings[settingName] = settingValue;\n      } else {\n        settings = settingName;\n      }\n\n      return this.each(function () {\n        var obj = $.data(this, 'lightswitch');\n        if (obj) {\n          obj.setSettings(settings);\n        }\n      });\n    } else {\n      if (!$.isPlainObject(settings)) {\n        settings = {};\n      }\n\n      return this.each(function () {\n        var thisSettings = $.extend({}, settings);\n\n        if (Garnish.hasAttr(this, 'data-value')) {\n          thisSettings.value = $(this).attr('data-value');\n        }\n\n        if (Garnish.hasAttr(this, 'data-indeterminate-value')) {\n          thisSettings.indeterminateValue = $(this).attr(\n            'data-indeterminate-value'\n          );\n        }\n\n        if (!$.data(this, 'lightswitch')) {\n          new Craft.LightSwitch(this, thisSettings);\n        }\n      });\n    }\n  },\n\n  nicetext: function () {\n    return this.each(function () {\n      if (!$.data(this, 'nicetext')) {\n        new Garnish.NiceText(this);\n      }\n    });\n  },\n\n  formsubmit: function () {\n    // Secondary form submit buttons\n    return this.on('click', function (ev) {\n      let $btn = $(ev.currentTarget);\n      let params = $btn.data('params') || {};\n      if ($btn.data('param')) {\n        params[$btn.data('param')] = $btn.data('value');\n      }\n\n      let $anchor = $btn.data('menu') ? $btn.data('menu').$anchor : $btn;\n      let $form = $anchor.attr('data-form')\n        ? $('#' + $anchor.attr('data-form'))\n        : $anchor.closest('form');\n\n      Craft.submitForm($form, {\n        confirm: $btn.data('confirm'),\n        action: $btn.data('action'),\n        redirect: $btn.data('redirect'),\n        params: params,\n        data: $.extend(\n          {\n            customTrigger: $btn,\n          },\n          $btn.data('event-data')\n        ),\n      });\n    });\n  },\n\n  menubtn: function () {\n    return this.each(function () {\n      var $btn = $(this);\n\n      if (!$btn.data('menubtn') && $btn.next().hasClass('menu')) {\n        var settings = {};\n\n        if ($btn.data('menu-anchor')) {\n          settings.menuAnchor = $btn.data('menu-anchor');\n        }\n\n        new Garnish.MenuBtn($btn, settings);\n      }\n    });\n  },\n\n  disclosureMenu: function () {\n    return this.each(function () {\n      const $trigger = $(this);\n      // Only instantiate if it's not already a disclosure trigger, and it references a disclosure content\n      if (!$trigger.data('trigger') && $trigger.attr('aria-controls')) {\n        new Garnish.DisclosureMenu($trigger);\n      }\n    });\n  },\n\n  datetime: function () {\n    return this.each(function () {\n      let $wrapper = $(this);\n      let $inputs = $wrapper.find('input:not([name$=\"[timezone]\"])');\n      let checkValue = () => {\n        let hasValue = false;\n        for (let i = 0; i < $inputs.length; i++) {\n          if ($inputs.eq(i).val()) {\n            hasValue = true;\n            break;\n          }\n        }\n        if (hasValue) {\n          if (!$wrapper.children('.clear-btn').length) {\n            let $btn = $('<button/>', {\n              type: 'button',\n              class: 'clear-btn',\n              title: Craft.t('app', 'Clear'),\n              'aria-label': Craft.t('app', 'Clear'),\n            })\n              .appendTo($wrapper)\n              .on('click', () => {\n                for (let i = 0; i < $inputs.length; i++) {\n                  $inputs.eq(i).val('').trigger('input').trigger('change');\n                }\n                $btn.remove();\n                $inputs.first().filter('[type=\"text\"]').focus();\n              });\n          }\n        } else {\n          $wrapper.children('.clear-btn').remove();\n        }\n      };\n      $inputs.on('change', checkValue);\n      checkValue();\n    });\n  },\n\n  datetimeinput: function () {\n    return this.each(function () {\n      const $input = $(this);\n      const checkValue = () => {\n        if ($input.val() === '') {\n          $input.addClass('empty-value');\n        } else {\n          $input.removeClass('empty-value');\n        }\n      };\n      $input.on('input', checkValue);\n      checkValue();\n    });\n  },\n});\n\n// Override Garnish.NiceText.charsLeftHtml() to be more accessible\nGarnish.NiceText.charsLeftHtml = (charsLeft) => {\n  return Craft.t(\n    'app',\n    '<span class=\"visually-hidden\">Characters left:</span> {chars, number}',\n    {\n      chars: charsLeft,\n    }\n  );\n};\n\nGarnish.$doc.ready(function () {\n  Craft.initUiElements();\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Customize Sources modal\n */\nCraft.CustomizeSourcesModal = Garnish.Modal.extend({\n  elementIndex: null,\n  $elementIndexSourcesContainer: null,\n\n  $sidebar: null,\n  $sourcesContainer: null,\n  $sourceSettingsContainer: null,\n  $newHeadingBtn: null,\n  $footer: null,\n  $footerBtnContainer: null,\n  $saveBtn: null,\n  $cancelBtn: null,\n  $saveSpinner: null,\n  $loadingSpinner: null,\n\n  sourceSort: null,\n  sources: null,\n  selectedSource: null,\n  updateSourcesOnSave: false,\n\n  availableTableAttributes: null,\n\n  init: function (elementIndex, settings) {\n    this.base();\n\n    this.setSettings(settings, {\n      resizable: true,\n    });\n\n    this.elementIndex = elementIndex;\n    this.$elementIndexSourcesContainer = this.elementIndex.$sidebar\n      .children('nav')\n      .children('ul');\n\n    var $container = $(\n      '<form class=\"modal customize-sources-modal\"/>'\n    ).appendTo(Garnish.$bod);\n\n    this.$sidebar = $('<div class=\"cs-sidebar block-types\"/>').appendTo(\n      $container\n    );\n    this.$sourcesContainer = $('<div class=\"sources\">').appendTo(this.$sidebar);\n    this.$sourceSettingsContainer = $('<div class=\"source-settings\">').appendTo(\n      $container\n    );\n\n    this.$footer = $('<div class=\"footer\"/>').appendTo($container);\n    this.$footerBtnContainer = $('<div class=\"buttons right\"/>').appendTo(\n      this.$footer\n    );\n    this.$cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$footerBtnContainer);\n    this.$saveBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn submit disabled',\n      text: Craft.t('app', 'Save'),\n    }).appendTo(this.$footerBtnContainer);\n    this.$saveSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n      this.$footerBtnContainer\n    );\n    this.$newHeadingBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn submit add icon',\n      text: Craft.t('app', 'New heading'),\n    }).appendTo(\n      $('<div class=\"buttons left secondary-buttons\"/>').appendTo(this.$footer)\n    );\n\n    this.$loadingSpinner = $('<div class=\"spinner\"/>').appendTo($container);\n\n    this.setContainer($container);\n    this.show();\n\n    var data = {\n      elementType: this.elementIndex.elementType,\n    };\n\n    Craft.postActionRequest(\n      'element-index-settings/get-customize-sources-modal-data',\n      data,\n      (response, textStatus) => {\n        this.$loadingSpinner.remove();\n\n        if (textStatus === 'success') {\n          this.$saveBtn.removeClass('disabled');\n          this.buildModal(response);\n        }\n      }\n    );\n\n    this.addListener(this.$newHeadingBtn, 'click', 'handleNewHeadingBtnClick');\n    this.addListener(this.$cancelBtn, 'click', 'hide');\n    this.addListener(this.$saveBtn, 'click', 'save');\n    this.addListener(this.$container, 'submit', 'save');\n  },\n\n  buildModal: function (response) {\n    // Store the available table attribute options\n    this.availableTableAttributes = response.availableTableAttributes;\n\n    // Create the source item sorter\n    this.sourceSort = new Garnish.DragSort({\n      handle: '.move',\n      axis: 'y',\n      onSortChange: () => {\n        this.updateSourcesOnSave = true;\n      },\n    });\n\n    // Create the sources\n    this.sources = [];\n\n    for (var i = 0; i < response.sources.length; i++) {\n      var source = this.addSource(response.sources[i]);\n      this.sources.push(source);\n    }\n\n    if (!this.selectedSource && typeof this.sources[0] !== 'undefined') {\n      this.sources[0].select();\n    }\n  },\n\n  addSource: function (sourceData) {\n    var $item = $('<div class=\"customize-sources-item\"/>').appendTo(\n      this.$sourcesContainer\n    );\n    var $itemLabel = $('<div class=\"label\"/>').appendTo($item);\n    var $itemInput = $('<input type=\"hidden\"/>').appendTo($item);\n    $(\n      '<a class=\"move icon\" title=\"' +\n        Craft.t('app', 'Reorder') +\n        '\" role=\"button\"></a>'\n    ).appendTo($item);\n\n    var source;\n\n    // Is this a heading?\n    if (typeof sourceData.heading !== 'undefined') {\n      $item.addClass('heading');\n      $itemInput.attr('name', 'sourceOrder[][heading]');\n      source = new Craft.CustomizeSourcesModal.Heading(\n        this,\n        $item,\n        $itemLabel,\n        $itemInput,\n        sourceData\n      );\n      source.updateItemLabel(sourceData.heading);\n    } else {\n      $itemInput.attr('name', 'sourceOrder[][key]').val(sourceData.key);\n      source = new Craft.CustomizeSourcesModal.Source(\n        this,\n        $item,\n        $itemLabel,\n        $itemInput,\n        sourceData\n      );\n      source.updateItemLabel(sourceData.label);\n\n      // Select this by default?\n      if (\n        (this.elementIndex.sourceKey + '/').substr(\n          0,\n          sourceData.key.length + 1\n        ) ===\n        sourceData.key + '/'\n      ) {\n        source.select();\n      }\n    }\n\n    this.sourceSort.addItems($item);\n\n    return source;\n  },\n\n  handleNewHeadingBtnClick: function () {\n    var source = this.addSource({\n      heading: '',\n    });\n\n    Garnish.scrollContainerToElement(this.$sidebar, source.$item);\n\n    source.select();\n    this.updateSourcesOnSave = true;\n  },\n\n  save: function (ev) {\n    if (ev) {\n      ev.preventDefault();\n    }\n\n    if (\n      this.$saveBtn.hasClass('disabled') ||\n      !this.$saveSpinner.hasClass('hidden')\n    ) {\n      return;\n    }\n\n    this.$saveSpinner.removeClass('hidden');\n    var data =\n      this.$container.serialize() +\n      '&elementType=' +\n      this.elementIndex.elementType;\n\n    Craft.postActionRequest(\n      'element-index-settings/save-customize-sources-modal-settings',\n      data,\n      (response, textStatus) => {\n        this.$saveSpinner.addClass('hidden');\n\n        if (textStatus === 'success' && response.success) {\n          // Have any changes been made to the source list?\n          if (this.updateSourcesOnSave) {\n            if (this.$elementIndexSourcesContainer.length) {\n              var $lastSource = null,\n                $pendingHeading;\n\n              for (var i = 0; i < this.sourceSort.$items.length; i++) {\n                var $item = this.sourceSort.$items.eq(i),\n                  source = $item.data('source'),\n                  $indexSource = source.getIndexSource();\n\n                if (!$indexSource) {\n                  continue;\n                }\n\n                if (source.isHeading()) {\n                  $pendingHeading = $indexSource;\n                } else {\n                  if ($pendingHeading) {\n                    this.appendSource($pendingHeading, $lastSource);\n                    $lastSource = $pendingHeading;\n                    $pendingHeading = null;\n                  }\n\n                  this.appendSource($indexSource, $lastSource);\n                  $lastSource = $indexSource;\n                }\n              }\n\n              // Remove any additional sources (most likely just old headings)\n              if ($lastSource) {\n                var $extraSources = $lastSource.nextAll();\n                this.elementIndex.sourceSelect.removeItems($extraSources);\n                $extraSources.remove();\n              }\n            }\n          }\n\n          // If a source is selected, have the element index select that one by default on the next request\n          if (this.selectedSource && this.selectedSource.sourceData.key) {\n            this.elementIndex.selectSourceByKey(\n              this.selectedSource.sourceData.key\n            );\n            this.elementIndex.updateElements();\n          }\n\n          Craft.cp.displayNotice(Craft.t('app', 'Source settings saved'));\n          this.hide();\n        } else {\n          var error =\n            textStatus === 'success' && response.error\n              ? response.error\n              : Craft.t('app', 'A server error occurred.');\n          Craft.cp.displayError(error);\n        }\n      }\n    );\n  },\n\n  appendSource: function ($source, $lastSource) {\n    if (!$lastSource) {\n      $source.prependTo(this.$elementIndexSourcesContainer);\n    } else {\n      $source.insertAfter($lastSource);\n    }\n  },\n\n  destroy: function () {\n    for (var i = 0; i < this.sources.length; i++) {\n      this.sources[i].destroy();\n    }\n\n    delete this.sources;\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.BaseSource = Garnish.Base.extend({\n  modal: null,\n\n  $item: null,\n  $itemLabel: null,\n  $itemInput: null,\n  $settingsContainer: null,\n\n  sourceData: null,\n\n  init: function (modal, $item, $itemLabel, $itemInput, sourceData) {\n    this.modal = modal;\n    this.$item = $item;\n    this.$itemLabel = $itemLabel;\n    this.$itemInput = $itemInput;\n    this.sourceData = sourceData;\n\n    this.$item.data('source', this);\n\n    this.addListener(this.$item, 'click', 'select');\n  },\n\n  isHeading: function () {\n    return false;\n  },\n\n  isSelected: function () {\n    return this.modal.selectedSource === this;\n  },\n\n  select: function () {\n    if (this.isSelected()) {\n      return;\n    }\n\n    if (this.modal.selectedSource) {\n      this.modal.selectedSource.deselect();\n    }\n\n    this.$item.addClass('sel');\n    this.modal.selectedSource = this;\n\n    if (!this.$settingsContainer) {\n      this.$settingsContainer = this.createSettings().appendTo(\n        this.modal.$sourceSettingsContainer\n      );\n    } else {\n      this.$settingsContainer.removeClass('hidden');\n    }\n\n    this.modal.$sourceSettingsContainer.scrollTop(0);\n  },\n\n  createSettings: function () {\n    return $('<div/>');\n  },\n\n  getIndexSource: function () {},\n\n  deselect: function () {\n    this.$item.removeClass('sel');\n    this.modal.selectedSource = null;\n    this.$settingsContainer.addClass('hidden');\n  },\n\n  updateItemLabel: function (val) {\n    this.$itemLabel.text(val);\n  },\n\n  destroy: function () {\n    this.$item.data('source', null);\n    this.base();\n  },\n});\n\nCraft.CustomizeSourcesModal.Source =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    createSettings: function () {\n      let $settings = $('<div/>').append(\n        Craft.ui.createTextField({\n          label: Craft.t('app', 'Header Column Heading'),\n          id: 'defaultHeaderColHeading' + Math.floor(Math.random() * 100000),\n          name: `sources[${this.sourceData.key}][headerColHeading]`,\n          value: this.sourceData.headerColHeading,\n          placeholder: this.sourceData.defaultHeaderColHeading,\n        })\n      );\n\n      if (this.sourceData.tableAttributes.length) {\n        $settings.append(this.createTableColumnsField());\n      }\n\n      return $settings;\n    },\n\n    createTableColumnsField: function () {\n      // Create the title column option\n      let [firstKey, firstLabel] = this.sourceData.tableAttributes[0];\n      let $titleColumnCheckbox = this.createTableColumnOption(\n        firstKey,\n        firstLabel,\n        true,\n        true\n      );\n\n      // Create the rest of the options\n      let $columnCheckboxes = $('<div/>');\n      let selectedAttributes = [firstKey];\n\n      $(\n        '<input type=\"hidden\" name=\"sources[' +\n          this.sourceData.key +\n          '][tableAttributes][]\" value=\"\"/>'\n      ).appendTo($columnCheckboxes);\n\n      // Add the selected columns, in the selected order\n      for (let i = 1; i < this.sourceData.tableAttributes.length; i++) {\n        let [key, label] = this.sourceData.tableAttributes[i];\n        $columnCheckboxes.append(\n          this.createTableColumnOption(key, label, false, true)\n        );\n        selectedAttributes.push(key);\n      }\n\n      // Add the rest\n      let availableTableAttributes =\n        this.modal.availableTableAttributes.slice(0);\n      availableTableAttributes.push(\n        ...this.sourceData.availableTableAttributes\n      );\n\n      for (let i = 0; i < availableTableAttributes.length; i++) {\n        let [key, label] = availableTableAttributes[i];\n        if (!Craft.inArray(key, selectedAttributes)) {\n          $columnCheckboxes.append(\n            this.createTableColumnOption(key, label, false, false)\n          );\n        }\n      }\n\n      new Garnish.DragSort($columnCheckboxes.children(), {\n        handle: '.move',\n        axis: 'y',\n      });\n\n      return Craft.ui.createField(\n        $([$titleColumnCheckbox[0], $columnCheckboxes[0]]),\n        {\n          label: Craft.t('app', 'Table Columns'),\n          instructions: Craft.t(\n            'app',\n            'Choose which table columns should be visible for this source, and in which order.'\n          ),\n        }\n      );\n    },\n\n    createTableColumnOption: function (key, label, first, checked) {\n      var $option = $('<div class=\"customize-sources-table-column\"/>')\n        .append('<div class=\"icon move\"/>')\n        .append(\n          Craft.ui.createCheckbox({\n            label: Craft.escapeHtml(label),\n            name: 'sources[' + this.sourceData.key + '][tableAttributes][]',\n            value: key,\n            checked: checked,\n            disabled: first,\n          })\n        );\n\n      if (first) {\n        $option.children('.move').addClass('disabled');\n      }\n\n      return $option;\n    },\n\n    getIndexSource: function () {\n      var $source = this.modal.elementIndex.getSourceByKey(this.sourceData.key);\n\n      if ($source) {\n        return $source.closest('li');\n      }\n    },\n  });\n\nCraft.CustomizeSourcesModal.Heading =\n  Craft.CustomizeSourcesModal.BaseSource.extend({\n    $labelField: null,\n    $labelInput: null,\n    $deleteBtn: null,\n\n    isHeading: function () {\n      return true;\n    },\n\n    select: function () {\n      this.base();\n      this.$labelInput.trigger('focus');\n    },\n\n    createSettings: function () {\n      let $settings = $('<div/>');\n\n      this.$labelField = Craft.ui\n        .createTextField({\n          label: Craft.t('app', 'Heading'),\n          instructions: Craft.t(\n            'app',\n            'This can be left blank if you just want an unlabeled separator.'\n          ),\n          value: this.sourceData.heading,\n        })\n        .appendTo($settings);\n\n      this.$labelInput = this.$labelField.find('.text');\n\n      $settings.append('<hr/>');\n\n      this.$deleteBtn = $('<a class=\"error delete\"/>')\n        .text(Craft.t('app', 'Delete heading'))\n        .appendTo($settings);\n\n      this.addListener(this.$labelInput, 'input', 'handleLabelInputChange');\n      this.addListener(this.$deleteBtn, 'click', 'deleteHeading');\n\n      return $settings;\n    },\n\n    handleLabelInputChange: function () {\n      this.updateItemLabel(this.$labelInput.val());\n      this.modal.updateSourcesOnSave = true;\n    },\n\n    updateItemLabel: function (val) {\n      this.$itemLabel.html(\n        (val\n          ? Craft.escapeHtml(val)\n          : '<em class=\"light\">' + Craft.t('app', '(blank)') + '</em>') +\n          '&nbsp;'\n      );\n      this.$itemInput.val(val);\n    },\n\n    deleteHeading: function () {\n      this.modal.sourceSort.removeItems(this.$item);\n      this.modal.sources.splice($.inArray(this, this.modal.sources), 1);\n      this.modal.updateSourcesOnSave = true;\n\n      if (this.isSelected()) {\n        this.deselect();\n\n        if (this.modal.sources.length) {\n          this.modal.sources[0].select();\n        }\n      }\n\n      this.$item.remove();\n      this.$settingsContainer.remove();\n      this.destroy();\n    },\n\n    getIndexSource: function () {\n      var label = this.$labelInput\n        ? this.$labelInput.val()\n        : this.sourceData.heading;\n      return $('<li class=\"heading\"/>').append($('<span/>').text(label));\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * DataTableSorter\n */\nCraft.DataTableSorter = Garnish.DragSort.extend(\n  {\n    $table: null,\n\n    init: function (table, settings) {\n      this.$table = $(table);\n      var $rows = this.$table.children('tbody').children(':not(.filler)');\n\n      settings = $.extend({}, Craft.DataTableSorter.defaults, settings);\n\n      settings.container = this.$table.children('tbody');\n      settings.helper = this.getHelper.bind(this);\n      settings.caboose = '<tr/>';\n      settings.axis = Garnish.Y_AXIS;\n      settings.magnetStrength = 4;\n      settings.helperLagBase = 1.5;\n\n      this.base($rows, settings);\n    },\n\n    getHelper: function ($helperRow) {\n      var $helper = $(\n          '<div class=\"' + this.settings.helperClass + '\"/>'\n        ).appendTo(Garnish.$bod),\n        $table = $('<table/>').appendTo($helper),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the table width and classes\n      $table.width(this.$table.width());\n      $table.prop('className', this.$table.prop('className'));\n\n      // Copy the column widths\n      var $firstRow = this.$table.find('tr:first'),\n        $cells = $firstRow.children(),\n        $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        $($helperCells[i]).width($($cells[i]).width());\n      }\n\n      return $helper;\n    },\n  },\n  {\n    defaults: {\n      handle: '.move',\n      helperClass: 'datatablesorthelper',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Delete User Modal\n */\nCraft.DeleteUserModal = Garnish.Modal.extend(\n  {\n    id: null,\n    userId: null,\n\n    $deleteActionRadios: null,\n    $deleteSpinner: null,\n\n    userSelect: null,\n    _deleting: false,\n\n    init: function (userId, settings) {\n      this.id = Math.floor(Math.random() * 1000000000);\n      this.userId = userId;\n      settings = $.extend(Craft.DeleteUserModal.defaults, settings);\n\n      let $form = $(\n        '<form class=\"modal fitted deleteusermodal\" method=\"post\" accept-charset=\"UTF-8\">' +\n          Craft.getCsrfInput() +\n          '<input type=\"hidden\" name=\"action\" value=\"users/delete-user\"/>' +\n          (!Garnish.isArray(this.userId)\n            ? '<input type=\"hidden\" name=\"userId\" value=\"' + this.userId + '\"/>'\n            : '') +\n          (settings.redirect\n            ? '<input type=\"hidden\" name=\"redirect\" value=\"' +\n              settings.redirect +\n              '\"/>'\n            : '') +\n          '</form>'\n      ).appendTo(Garnish.$bod);\n      let $body = $(\n        '<div class=\"body\">' +\n          '<div class=\"content-summary\">' +\n          '<p>' +\n          Craft.t('app', 'What do you want to do with their content?') +\n          '</p>' +\n          '<ul class=\"bullets\"></ul>' +\n          '</div>' +\n          '<div class=\"options\">' +\n          '<label><input type=\"radio\" name=\"contentAction\" value=\"transfer\"/> ' +\n          Craft.t('app', 'Transfer it to:') +\n          '</label>' +\n          '<div id=\"transferselect' +\n          this.id +\n          '\" class=\"elementselect\">' +\n          '<div class=\"elements\"></div>' +\n          '<button type=\"button\" class=\"btn add icon dashed\">' +\n          Craft.t('app', 'Choose a user') +\n          '</button>' +\n          '</div>' +\n          '</div>' +\n          '<div>' +\n          '<label class=\"error\"><input type=\"radio\" name=\"contentAction\" value=\"delete\"/> ' +\n          Craft.t('app', 'Delete their content') +\n          '</label>' +\n          '</div>' +\n          '</div>'\n      ).appendTo($form);\n      let $buttons = $('<div class=\"buttons right\"/>').appendTo($body);\n      let $cancelBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn',\n        text: Craft.t('app', 'Cancel'),\n      }).appendTo($buttons);\n\n      if (settings.contentSummary.length) {\n        for (let i = 0; i < settings.contentSummary.length; i++) {\n          $body\n            .find('ul')\n            .append($('<li/>', {text: settings.contentSummary[i]}));\n        }\n      } else {\n        $body.find('ul').remove();\n      }\n\n      this.$deleteActionRadios = $body.find('input[type=radio]');\n      this.$deleteSubmitBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit disabled',\n        text: this._submitBtnLabel(false),\n      }).appendTo($buttons);\n      this.$deleteSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n        $buttons\n      );\n\n      var idParam;\n\n      if (Garnish.isArray(this.userId)) {\n        idParam = ['and'];\n\n        for (let i = 0; i < this.userId.length; i++) {\n          idParam.push('not ' + this.userId[i]);\n        }\n      } else {\n        idParam = 'not ' + this.userId;\n      }\n\n      this.userSelect = new Craft.BaseElementSelectInput({\n        id: 'transferselect' + this.id,\n        name: 'transferContentTo',\n        elementType: 'craft\\\\elements\\\\User',\n        criteria: {\n          id: idParam,\n        },\n        limit: 1,\n        modalSettings: {\n          closeOtherModals: false,\n        },\n        onSelectElements: () => {\n          this.updateSizeAndPosition();\n\n          if (!this.$deleteActionRadios.first().prop('checked')) {\n            this.$deleteActionRadios.first().trigger('click');\n          } else {\n            this.validateDeleteInputs();\n          }\n        },\n        onRemoveElements: this.validateDeleteInputs.bind(this),\n        selectable: false,\n        editable: false,\n      });\n\n      this.addListener($cancelBtn, 'click', 'hide');\n\n      this.addListener(\n        this.$deleteActionRadios,\n        'change',\n        'validateDeleteInputs'\n      );\n      this.addListener($form, 'submit', 'handleSubmit');\n\n      this.base($form, settings);\n    },\n\n    _submitBtnLabel: function (withContent) {\n      let message = withContent\n        ? 'Delete {num, plural, =1{user} other{users}} and content'\n        : 'Delete {num, plural, =1{user} other{users}}';\n\n      return Craft.t('app', message, {\n        num: Garnish.isArray(this.userId) ? this.userId.length : 1,\n      });\n    },\n\n    validateDeleteInputs: function () {\n      var validates = false;\n\n      if (this.$deleteActionRadios.eq(1).prop('checked')) {\n        validates = true;\n        this.$deleteSubmitBtn.text(this._submitBtnLabel(true));\n      } else {\n        this.$deleteSubmitBtn.text(this._submitBtnLabel(false));\n        if (this.$deleteActionRadios.eq(0).prop('checked')) {\n          validates = !!this.userSelect.totalSelected;\n        }\n      }\n\n      this.updateSizeAndPosition();\n\n      if (validates) {\n        this.$deleteSubmitBtn.removeClass('disabled');\n      } else {\n        this.$deleteSubmitBtn.addClass('disabled');\n      }\n\n      return validates;\n    },\n\n    handleSubmit: function (ev) {\n      if (this._deleting || !this.validateDeleteInputs()) {\n        ev.preventDefault();\n        return;\n      }\n\n      this.$deleteSubmitBtn.addClass('active');\n      this.$deleteSpinner.removeClass('hidden');\n      this.disable();\n      this.userSelect.disable();\n      this._deleting = true;\n\n      // Let the onSubmit callback prevent the form from getting submitted\n      try {\n        if (this.settings.onSubmit() === false) {\n          ev.preventDefault();\n        }\n      } catch (e) {\n        ev.preventDefault();\n        this.$deleteSpinner.addClass('hidden');\n        throw e;\n      }\n    },\n\n    onFadeIn: function () {\n      // Auto-focus the first radio\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$deleteActionRadios.first().trigger('focus');\n      }\n\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      contentSummary: [],\n      onSubmit: $.noop,\n      redirect: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element draft editor\n */\nCraft.DraftEditor = Garnish.Base.extend(\n  {\n    $revisionBtn: null,\n    $revisionLabel: null,\n    $spinner: null,\n    $expandSiteStatusesBtn: null,\n    $statusIcon: null,\n\n    $editMetaBtn: null,\n    metaHud: null,\n    $nameTextInput: null,\n    $saveMetaBtn: null,\n\n    $siteStatusPane: null,\n    $globalLightswitch: null,\n    $siteLightswitches: null,\n    $addlSiteField: null,\n\n    siteIds: null,\n    newSiteIds: null,\n\n    enableAutosave: null,\n    lastSerializedValue: null,\n    listeningForChanges: false,\n    pauseLevel: 0,\n    timeout: null,\n    saving: false,\n    cancelToken: null,\n    ignoreFailedRequest: false,\n    queue: null,\n    submittingForm: false,\n\n    duplicatedElements: null,\n    errors: null,\n    httpStatus: null,\n    httpError: null,\n\n    openingPreview: false,\n    preview: null,\n    activatingPreviewToken: false,\n    activatedPreviewToken: false,\n    previewTokenQueue: null,\n    previewLinks: null,\n    scrollY: null,\n    createdProvisionalDraft: false,\n\n    bc: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.DraftEditor.defaults);\n\n      this.queue = [];\n      this.previewTokenQueue = [];\n      this.duplicatedElements = {};\n      this.enableAutosave = Craft.autosaveDrafts;\n      this.previewLinks = [];\n\n      this.siteIds = Object.keys(this.settings.siteStatuses).map((siteId) => {\n        return parseInt(siteId);\n      });\n\n      this.$revisionBtn = $('#context-btn');\n      this.$revisionLabel = $('#revision-label');\n      this.$spinner = $('#revision-spinner');\n      this.$expandSiteStatusesBtn = $('#expand-status-btn');\n      this.$statusIcon = $('#revision-status');\n      this.$statusMessage = $('#revision-status-message');\n\n      if (this.settings.canEditMultipleSites) {\n        this.addListener(\n          this.$expandSiteStatusesBtn,\n          'click',\n          'expandSiteStatuses'\n        );\n      }\n\n      if (this.settings.previewTargets.length) {\n        if (this.settings.enablePreview) {\n          this.addListener($('#preview-btn'), 'click', 'openPreview');\n        }\n\n        const $previewBtnContainer = $('#preview-btn-container');\n\n        if (this.settings.previewTargets.length === 1) {\n          const [target] = this.settings.previewTargets;\n          this.createPreviewLink(target)\n            .attr('id', 'share-btn')\n            .addClass('btn')\n            .appendTo($previewBtnContainer);\n        } else {\n          this.createShareMenu($previewBtnContainer);\n        }\n      }\n\n      // If this is a revision, we're done here\n      if (this.settings.revisionId) {\n        return;\n      }\n\n      // Override the serializer to use our own\n      Craft.cp.$primaryForm.data('serializer', () => this.serializeForm(true));\n\n      this.addListener(Craft.cp.$primaryForm, 'submit', 'handleFormSubmit');\n\n      if (this.settings.isProvisionalDraft) {\n        this.initForProvisionalDraft();\n      } else if (this.settings.draftId && !this.settings.isUnpublishedDraft) {\n        this.initForDraft();\n      } else if (!this.settings.canUpdateSource) {\n        // Override the save shortcut to create a draft too\n        this.addListener(Craft.cp.$primaryForm, 'submit.saveShortcut', (ev) => {\n          if (ev.saveShortcut) {\n            ev.preventDefault();\n            this.createDraft();\n            this.removeListener(Craft.cp.$primaryForm, 'submit.saveShortcut');\n          }\n        });\n      }\n\n      this.listenForChanges();\n\n      this.addListener(this.$statusIcon, 'click', () => {\n        this.showStatusHud(this.$statusIcon);\n      });\n\n      if (\n        typeof BroadcastChannel !== 'undefined' &&\n        !this.settings.revisionId\n      ) {\n        this.bc = new BroadcastChannel('DraftEditor');\n        this.bc.onmessage = (ev) => {\n          if (\n            ev.data.event === 'saveDraft' &&\n            ev.data.canonicalId === this.settings.sourceId &&\n            (ev.data.draftId === this.settings.draftId ||\n              (ev.data.isProvisionalDraft && !this.settings.draftId))\n          ) {\n            window.location.reload();\n          }\n        };\n      }\n    },\n\n    listenForChanges: function () {\n      if (\n        this.listeningForChanges ||\n        this.pauseLevel > 0 ||\n        !this.enableAutosave ||\n        !this.settings.saveDraftAction\n      ) {\n        return;\n      }\n\n      this.listeningForChanges = true;\n\n      this.addListener(\n        Garnish.$bod,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup',\n        function (ev) {\n          if ($(ev.target).is(this.statusIcons())) {\n            return;\n          }\n          clearTimeout(this.timeout);\n          // If they are typing, wait half a second before checking the form\n          if (['keypress', 'keyup', 'change'].includes(ev.type)) {\n            this.timeout = setTimeout(this.checkForm.bind(this), 500);\n          } else {\n            this.checkForm();\n          }\n        }\n      );\n    },\n\n    stopListeningForChanges: function () {\n      if (!this.listeningForChanges) {\n        return;\n      }\n\n      this.removeListener(\n        Garnish.$bod,\n        'keypress,keyup,change,focus,blur,click,mousedown,mouseup'\n      );\n      clearTimeout(this.timeout);\n      this.listeningForChanges = false;\n    },\n\n    pause: function () {\n      this.pauseLevel++;\n      this.stopListeningForChanges();\n    },\n\n    resume: function () {\n      if (this.pauseLevel === 0) {\n        throw 'Craft.DraftEditor::resume() should only be called after pause().';\n      }\n\n      // Only actually resume operation if this has been called the same\n      // number of times that pause() was called\n      this.pauseLevel--;\n      if (this.pauseLevel === 0) {\n        if (this.enableAutosave) {\n          this.checkForm();\n          this.listenForChanges();\n        }\n      }\n    },\n\n    initForProvisionalDraft: function () {\n      let $button = $('#discard-changes');\n      if (!$button.length) {\n        $button = this.$revisionBtn.data('menubtn')\n          ? this.$revisionBtn\n              .data('menubtn')\n              .menu.$container.find('#discard-changes')\n          : null;\n      }\n      if ($button && $button.length) {\n        this.addListener($button, 'click', () => {\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to discard your changes?')\n            )\n          ) {\n            Craft.submitForm(Craft.cp.$primaryForm, {\n              action: this.settings.deleteDraftAction,\n              redirect: this.settings.hashedCpEditUrl,\n              params: {\n                draftId: this.settings.draftId,\n                provisional: this.settings.isProvisionalDraft,\n              },\n            });\n          }\n        });\n      }\n    },\n\n    initForDraft: function () {\n      // Create the edit draft button\n      this.createEditMetaBtn();\n\n      if (this.settings.canUpdateSource) {\n        Garnish.uiLayerManager.registerShortcut(\n          {\n            keyCode: Garnish.S_KEY,\n            ctrl: true,\n            alt: true,\n          },\n          () => {\n            Craft.submitForm(Craft.cp.$primaryForm, {\n              action: this.settings.publishDraftAction,\n              redirect: this.settings.hashedCpEditUrl,\n            });\n          },\n          0\n        );\n      }\n    },\n\n    expandSiteStatuses: function () {\n      this.removeListener(this.$expandSiteStatusesBtn, 'click');\n      this.$expandSiteStatusesBtn.velocity({opacity: 0}, 'fast', () => {\n        this.$expandSiteStatusesBtn.remove();\n      });\n\n      const $enabledForSiteField = $(\n        `#enabledForSite-${this.settings.siteId}-field`\n      );\n      this.$siteStatusPane = $enabledForSiteField.parent();\n\n      // If this is a revision, just show the site statuses statically and be done\n      if (this.settings.revisionId) {\n        this._getOtherSupportedSites().forEach((s) =>\n          this._createSiteStatusField(s)\n        );\n        return;\n      }\n\n      $enabledForSiteField.addClass('nested');\n      const $globalField = Craft.ui\n        .createLightswitchField({\n          id: 'enabled',\n          label: Craft.t('app', 'Enabled'),\n          name: 'enabled',\n        })\n        .insertBefore($enabledForSiteField);\n      $globalField.find('label').css('font-weight', 'bold');\n      this.$globalLightswitch = $globalField.find('.lightswitch');\n\n      if (!this.settings.revisionId) {\n        this._showField($globalField);\n      }\n\n      // Figure out what the \"Enabled everywhere\" lightswitch would have been set to when the page first loaded\n      const siteStatusValues = Object.values(this.settings.siteStatuses);\n      const hasEnabled = siteStatusValues.includes(true);\n      const hasDisabled = siteStatusValues.includes(false);\n      const originalEnabledValue =\n        hasEnabled && hasDisabled ? '-' : hasEnabled ? '1' : '';\n      const originalSerializedStatus =\n        encodeURIComponent(`enabledForSite[${this.settings.siteId}]`) +\n        '=' +\n        (this.settings.enabledForSite ? '1' : '');\n\n      this.$siteLightswitches = $enabledForSiteField\n        .find('.lightswitch')\n        .on('change', this._updateGlobalStatus.bind(this));\n\n      this._getOtherSupportedSites().forEach((s) =>\n        this._createSiteStatusField(s)\n      );\n\n      let serializedStatuses = `enabled=${originalEnabledValue}`;\n      for (let i = 0; i < this.$siteLightswitches.length; i++) {\n        const $input = this.$siteLightswitches.eq(i).data('lightswitch').$input;\n        serializedStatuses +=\n          '&' + encodeURIComponent($input.attr('name')) + '=' + $input.val();\n      }\n\n      Craft.cp.$primaryForm.data(\n        'initialSerializedValue',\n        Craft.cp.$primaryForm\n          .data('initialSerializedValue')\n          .replace(originalSerializedStatus, serializedStatuses)\n      );\n\n      if (this.lastSerializedValue) {\n        this.lastSerializedValue = this.lastSerializedValue.replace(\n          originalSerializedStatus,\n          serializedStatuses\n        );\n      }\n\n      // Are there additional sites that can be added?\n      if (this.settings.addlSites && this.settings.addlSites.length) {\n        this._createAddlSiteField();\n      }\n\n      this.$globalLightswitch.on('change', this._updateSiteStatuses.bind(this));\n      this._updateGlobalStatus();\n    },\n\n    /**\n     * @returns {Array}\n     */\n    _getOtherSupportedSites: function () {\n      return Craft.sites.filter(\n        (s) => s.id != this.settings.siteId && this.siteIds.includes(s.id)\n      );\n    },\n\n    _showField: function ($field) {\n      const height = $field.height();\n      $field\n        .css('overflow', 'hidden')\n        .height(0)\n        .velocity({height}, 'fast', () => {\n          $field.css({\n            overflow: '',\n            height: '',\n          });\n        });\n    },\n\n    _removeField: function ($field) {\n      const height = $field.height();\n      $field.css('overflow', 'hidden').velocity({height: 0}, 'fast', () => {\n        $field.remove();\n      });\n    },\n\n    _updateGlobalStatus: function () {\n      let allEnabled = true,\n        allDisabled = true;\n      this.$siteLightswitches.each(function () {\n        const enabled = $(this).data('lightswitch').on;\n        if (enabled) {\n          allDisabled = false;\n        } else {\n          allEnabled = false;\n        }\n        if (!allEnabled && !allDisabled) {\n          return false;\n        }\n      });\n      if (allEnabled) {\n        this.$globalLightswitch.data('lightswitch').turnOn(true);\n      } else if (allDisabled) {\n        this.$globalLightswitch.data('lightswitch').turnOff(true);\n      } else {\n        this.$globalLightswitch.data('lightswitch').turnIndeterminate(true);\n      }\n    },\n\n    _updateSiteStatuses: function () {\n      const enabled = this.$globalLightswitch.data('lightswitch').on;\n      this.$siteLightswitches.each(function () {\n        if (enabled) {\n          $(this).data('lightswitch').turnOn(true);\n        } else {\n          $(this).data('lightswitch').turnOff(true);\n        }\n      });\n    },\n\n    _createSiteStatusField: function (site, status) {\n      const $field = Craft.ui.createLightswitchField({\n        id: `enabledForSite-${site.id}`,\n        label: Craft.t('app', 'Enabled for {site}', {site: site.name}),\n        name: `enabledForSite[${site.id}]`,\n        on:\n          typeof status != 'undefined'\n            ? status\n            : this.settings.siteStatuses.hasOwnProperty(site.id)\n            ? this.settings.siteStatuses[site.id]\n            : true,\n        disabled: !!this.settings.revisionId,\n      });\n\n      if (this.$addlSiteField) {\n        $field.insertBefore(this.$addlSiteField);\n      } else {\n        $field.appendTo(this.$siteStatusPane);\n      }\n\n      if (!this.settings.revisionId) {\n        $field.addClass('nested');\n        const $lightswitch = $field\n          .find('.lightswitch')\n          .on('change', this._updateGlobalStatus.bind(this));\n        this.$siteLightswitches = this.$siteLightswitches.add($lightswitch);\n      }\n\n      this._showField($field);\n\n      return $field;\n    },\n\n    _createAddlSiteField: function () {\n      const addlSites = Craft.sites.filter((site) => {\n        return (\n          !this.siteIds.includes(site.id) &&\n          this.settings.addlSites.some((s) => s.siteId == site.id)\n        );\n      });\n\n      if (!addlSites.length) {\n        return;\n      }\n\n      const $addlSiteSelectContainer = Craft.ui\n        .createSelect({\n          options: [\n            {label: Craft.t('app', 'Add a site…')},\n            ...addlSites.map((s) => {\n              return {label: s.name, value: s.id};\n            }),\n          ],\n        })\n        .addClass('fullwidth');\n\n      this.$addlSiteField = Craft.ui\n        .createField($addlSiteSelectContainer, {})\n        .addClass('nested add')\n        .appendTo(this.$siteStatusPane);\n\n      const $addlSiteSelect = $addlSiteSelectContainer.find('select');\n\n      $addlSiteSelect.on('change', () => {\n        const siteId = parseInt($addlSiteSelect.val());\n        const site = Craft.sites.find((s) => s.id === siteId);\n\n        if (!site) {\n          return;\n        }\n\n        const addlSiteInfo = this.settings.addlSites.find(\n          (s) => s.siteId == site.id\n        );\n        this._createSiteStatusField(site, addlSiteInfo.enabledByDefault);\n        this._updateGlobalStatus();\n\n        $addlSiteSelect.val('').find(`option[value=\"${siteId}\"]`).remove();\n\n        if (this.newSiteIds === null) {\n          this.newSiteIds = [];\n        }\n\n        this.siteIds.push(siteId);\n        this.newSiteIds.push(siteId);\n\n        // Was that the last site?\n        if ($addlSiteSelect.find('option').length === 1) {\n          this._removeField(this.$addlSiteField);\n        }\n      });\n\n      this._showField(this.$addlSiteField);\n    },\n\n    showStatusHud: function (target) {\n      let bodyHtml;\n\n      if (this.errors === null) {\n        bodyHtml = `<p>${this._saveSuccessMessage()}</p>`;\n      } else {\n        bodyHtml = `<p class=\"error\"><strong>${this._saveFailMessage()}</strong></p>`;\n\n        if (this.errors.length) {\n          bodyHtml +=\n            '<ul class=\"errors\">' +\n            this.errors.map((e) => `<li>${Craft.escapeHtml(e)}</li>`).join('') +\n            '</ul>';\n        }\n\n        if (this.httpError) {\n          bodyHtml += `<p class=\"http-error code\">${Craft.escapeHtml(\n            this.httpError\n          )}</p>`;\n        }\n\n        if (this.httpStatus === 400) {\n          bodyHtml += `<button class=\"btn refresh-btn\">${Craft.t(\n            'app',\n            'Refresh'\n          )}</button>`;\n        }\n      }\n\n      const hud = new Garnish.HUD(target, bodyHtml, {\n        hudClass: 'hud revision-status-hud',\n        onHide: function () {\n          hud.destroy();\n        },\n      });\n\n      hud.$mainContainer.find('.refresh-btn').on('click', () => {\n        window.location.reload();\n      });\n    },\n\n    /**\n     * @return {string}\n     */\n    _saveSuccessMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes have been stored.')\n        : Craft.t('app', 'The draft has been saved.');\n    },\n\n    /**\n     * @return {string}\n     */\n    _saveFailMessage: function () {\n      return this.settings.isProvisionalDraft ||\n        this.settings.isUnpublishedDraft\n        ? Craft.t('app', 'Your changes could not be stored.')\n        : Craft.t('app', 'The draft could not be saved.');\n    },\n\n    spinners: function () {\n      return this.preview\n        ? this.$spinner.add(this.preview.$spinner)\n        : this.$spinner;\n    },\n\n    statusIcons: function () {\n      return this.preview\n        ? this.$statusIcon.add(this.preview.$statusIcon)\n        : this.$statusIcon;\n    },\n\n    statusMessage: function () {\n      return this.preview\n        ? this.$statusMessage.add(this.preview.$statusMessage)\n        : this.$statusMessage;\n    },\n\n    createEditMetaBtn: function () {\n      const $btnGroup = $('#context-btngroup');\n      this.$editMetaBtn = $('<button/>', {\n        type: 'button',\n        class: 'btn edit icon',\n        title: Craft.t('app', 'Edit draft settings'),\n      }).appendTo($btnGroup);\n      $btnGroup.find('.btngroup-btn-last').removeClass('btngroup-btn-last');\n      this.addListener(this.$editMetaBtn, 'click', 'showMetaHud');\n    },\n\n    createPreviewLink: function (target, label) {\n      const $a = $('<a/>', {\n        href: this.getTokenizedPreviewUrl(target.url, null, false),\n        text: label || Craft.t('app', 'View'),\n        target: '_blank',\n        data: {\n          targetUrl: target.url,\n          targetLabel: target.label,\n        },\n      });\n\n      this.addListener($a, 'click', () => {\n        setTimeout(() => {\n          this.activatePreviewToken();\n        }, 1);\n      });\n\n      this.previewLinks.push($a);\n      return $a;\n    },\n\n    updatePreviewLinks: function () {\n      this.previewLinks.forEach(($a) => {\n        this.updatePreviewLinkHref($a);\n        if (this.activatedPreviewToken) {\n          this.removeListener($a, 'click');\n        }\n      });\n    },\n\n    updatePreviewLinkHref: function ($a) {\n      $a.attr(\n        'href',\n        this.getTokenizedPreviewUrl($a.data('targetUrl'), null, false)\n      );\n    },\n\n    activatePreviewToken: function () {\n      if (this.settings.isLive) {\n        // don't do anything yet, but leave the event in case we need it later\n        return;\n      }\n\n      this.activatedPreviewToken = true;\n      this.updatePreviewLinks();\n    },\n\n    createShareMenu: function ($container) {\n      $('<button/>', {\n        id: 'share-btn',\n        type: 'button',\n        class: 'btn menubtn',\n        text: Craft.t('app', 'View'),\n      }).appendTo($container);\n\n      const $menu = $('<div/>', {class: 'menu'}).appendTo($container);\n      const $ul = $('<ul/>').appendTo($menu);\n\n      this.settings.previewTargets.forEach((target) => {\n        $('<li/>')\n          .append(this.createPreviewLink(target, target.label))\n          .appendTo($ul);\n      });\n    },\n\n    getPreviewTokenParams: function () {\n      const params = {\n        elementType: this.settings.elementType,\n        sourceId: this.settings.sourceId,\n        siteId: this.settings.siteId,\n        revisionId: this.settings.revisionId,\n        previewToken: this.settings.previewToken,\n      };\n\n      if (this.settings.draftId && !this.settings.isProvisionalDraft) {\n        params.draftId = this.settings.draftId;\n      }\n\n      return params;\n    },\n\n    getPreviewToken: function () {\n      return new Promise((resolve, reject) => {\n        if (this.activatedPreviewToken) {\n          resolve(this.settings.previewToken);\n          return;\n        }\n\n        if (this.activatingPreviewToken) {\n          this.previewTokenQueue.push(resolve);\n          return;\n        }\n\n        this.activatingPreviewToken = true;\n\n        Craft.sendActionRequest('POST', 'preview/create-token', {\n          data: this.getPreviewTokenParams(),\n        })\n          .then(() => {\n            this.activatingPreviewToken = false;\n            this.activatePreviewToken();\n            resolve(this.settings.previewToken);\n\n            while (this.previewTokenQueue.length) {\n              this.previewTokenQueue.shift()(this.settings.previewToken);\n            }\n          })\n          .catch(reject);\n      });\n    },\n\n    /**\n     * @param {string} url\n     * @param {string|null} [randoParam]\n     * @param {boolean} [asPromise=false]\n     * @return Promise|string\n     */\n    getTokenizedPreviewUrl: function (url, randoParam, asPromise) {\n      if (typeof asPromise === 'undefined') {\n        asPromise = true;\n      }\n\n      const params = {};\n\n      if (randoParam || !this.settings.isLive) {\n        // Randomize the URL so CDNs don't return cached pages\n        params[randoParam || 'x-craft-preview'] = Craft.randomString(10);\n      }\n\n      if (this.settings.siteToken) {\n        params[Craft.siteToken] = this.settings.siteToken;\n      }\n\n      // No need for a token if we're looking at a live element\n      if (this.settings.isLive) {\n        const previewUrl = Craft.getUrl(url, params);\n\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (!this.settings.previewToken) {\n        throw 'Missing preview token';\n      }\n\n      params[Craft.tokenParam] = this.settings.previewToken;\n      const previewUrl = Craft.getUrl(url, params);\n\n      if (this.activatedPreviewToken) {\n        if (asPromise) {\n          return new Promise((resolve) => {\n            resolve(previewUrl);\n          });\n        }\n\n        return previewUrl;\n      }\n\n      if (asPromise) {\n        return new Promise((resolve, reject) => {\n          this.getPreviewToken()\n            .then(() => {\n              resolve(previewUrl);\n            })\n            .catch(reject);\n        });\n      }\n\n      const createTokenParams = this.getPreviewTokenParams();\n      createTokenParams.redirect = encodeURIComponent(previewUrl);\n      return Craft.getActionUrl('preview/create-token', createTokenParams);\n    },\n\n    getPreview: function () {\n      if (!this.preview) {\n        this.preview = new Craft.Preview(this);\n        if (!this.enableAutosave) {\n          this.preview.on('open', () => {\n            this.enableAutosave = true;\n            this.listenForChanges();\n          });\n          this.preview.on('close', () => {\n            this.enableAutosave = false;\n            this.stopListeningForChanges();\n\n            // Hide the status icon if the save was successful\n            const $statusIcons = this.statusIcons();\n            if ($statusIcons.hasClass('checkmark-icon')) {\n              $statusIcons.addClass('hidden');\n            }\n          });\n        }\n        this.preview.on('close', () => {\n          if (this.scrollY) {\n            window.scrollTo(0, this.scrollY);\n            this.scrollY = null;\n          }\n        });\n      }\n      return this.preview;\n    },\n\n    openPreview: function () {\n      return new Promise((resolve, reject) => {\n        this.openingPreview = true;\n        this.ensureIsDraftOrRevision(true)\n          .then(() => {\n            this.scrollY = window.scrollY;\n            this.getPreview().open();\n            this.openingPreview = false;\n            resolve();\n          })\n          .catch(reject);\n      });\n    },\n\n    ensureIsDraftOrRevision: function (onlyIfChanged) {\n      return new Promise((resolve, reject) => {\n        if (!this.settings.draftId && !this.settings.revisionId) {\n          if (\n            onlyIfChanged &&\n            this.serializeForm(true) ===\n              Craft.cp.$primaryForm.data('initialSerializedValue')\n          ) {\n            resolve();\n            return;\n          }\n\n          this.createDraft().then(resolve).catch(reject);\n        } else {\n          resolve();\n        }\n      });\n    },\n\n    serializeForm: function (removeActionParams) {\n      let data = Craft.cp.$primaryForm.serialize();\n\n      if (this.isPreviewActive()) {\n        // Replace the temp input with the preview form data\n        data = data.replace(\n          '__PREVIEW_FIELDS__=1',\n          this.preview.$editor.serialize()\n        );\n      }\n\n      if (removeActionParams && !this.settings.isUnpublishedDraft) {\n        // Remove action and redirect params\n        data = data.replace(/&action=[^&]*/, '');\n        data = data.replace(/&redirect=[^&]*/, '');\n      }\n\n      return data;\n    },\n\n    checkForm: function (force) {\n      // If this isn't a draft and there's no active preview, then there's nothing to check\n      if (\n        this.settings.revisionId ||\n        this.pauseLevel > 0 ||\n        !this.enableAutosave ||\n        !this.settings.saveDraftAction\n      ) {\n        return;\n      }\n\n      clearTimeout(this.timeout);\n      this.timeout = null;\n\n      // If we haven't had a chance to fetch the initial data yet, try again in a bit\n      if (\n        typeof Craft.cp.$primaryForm.data('initialSerializedValue') ===\n        'undefined'\n      ) {\n        this.timeout = setTimeout(this.checkForm.bind(this), 500);\n        return;\n      }\n\n      // Has anything changed?\n      const data = this.serializeForm(true);\n      if (\n        force ||\n        data !==\n          (this.lastSerializedValue ||\n            Craft.cp.$primaryForm.data('initialSerializedValue'))\n      ) {\n        const provisional =\n          (!this.settings.draftId || this.settings.isProvisionalDraft) &&\n          !this.settings.revisionId;\n        this.saveDraft(data, provisional).catch((e) => {\n          console.warn('Couldn’t save draft:', e);\n        });\n      }\n    },\n\n    isPreviewActive: function () {\n      return this.preview && this.preview.isActive;\n    },\n\n    createDraft: function () {\n      return new Promise((resolve, reject) => {\n        this.saveDraft(this.serializeForm(true)).then(resolve).catch(reject);\n      });\n    },\n\n    /**\n     * @param {object} data\n     * @returns {Promise<unknown>}\n     */\n    saveDraft: function (data) {\n      return new Promise((resolve, reject) => {\n        // Ignore if we're already submitting the main form\n        if (this.submittingForm) {\n          reject('Form already being submitted.');\n          return;\n        }\n\n        if (this.saving) {\n          this.queue.push(() => {\n            this.checkForm();\n          });\n          return;\n        }\n\n        this.lastSerializedValue = data;\n        this.saving = true;\n        this.errors = null;\n        this.httpStatus = null;\n        this.httpError = null;\n        this.cancelToken = axios.CancelToken.source();\n        this.spinners().removeClass('hidden');\n\n        this.statusIcons()\n          .velocity('stop')\n          .css('opacity', '')\n          .removeClass('invisible checkmark-icon alert-icon fade-out')\n          .addClass('hidden');\n\n        // Clear previous status message\n        this.statusMessage().empty();\n\n        if (this.$saveMetaBtn) {\n          this.$saveMetaBtn.addClass('active');\n        }\n\n        // Prep the data to be saved, keeping track of the first input name for each delta group\n        let modifiedFieldNames = [];\n        let preparedData = this.prepareData(\n          data,\n          !this.settings.isUnpublishedDraft\n            ? (deltaName, params) => {\n                if (params.length) {\n                  modifiedFieldNames.push(\n                    decodeURIComponent(params[0].split('=')[0])\n                  );\n                }\n              }\n            : undefined\n        );\n\n        // Are we saving a provisional draft?\n        if (this.settings.isProvisionalDraft || !this.settings.draftId) {\n          preparedData += '&provisional=1';\n        }\n\n        Craft.sendActionRequest('POST', this.settings.saveDraftAction, {\n          cancelToken: this.cancelToken.token,\n          headers: {\n            'content-type': 'application/x-www-form-urlencoded',\n          },\n          data: preparedData,\n        })\n          .then((response) => {\n            this._afterSaveRequest();\n\n            if (response.data.errors) {\n              this.errors = response.data.errors;\n              this._showFailStatus();\n              reject(response.data.errors);\n            }\n\n            const createdProvisionalDraft = !this.settings.draftId;\n\n            if (createdProvisionalDraft) {\n              this.settings.isProvisionalDraft = true;\n              this.createdProvisionalDraft = true;\n            }\n\n            if (response.data.title) {\n              $('#header h1').text(response.data.title);\n            }\n\n            if (response.data.docTitle) {\n              document.title = response.data.docTitle;\n            }\n\n            if (this.settings.isProvisionalDraft) {\n              if (createdProvisionalDraft) {\n                this.$revisionLabel.append(\n                  $('<span/>', {\n                    text: ` — ${Craft.t('app', 'Edited')}`,\n                  })\n                );\n              }\n            } else {\n              this.$revisionLabel.text(response.data.draftName);\n              this.settings.draftName = response.data.draftName;\n            }\n\n            let revisionMenu = this.$revisionBtn.data('menubtn')\n              ? this.$revisionBtn.data('menubtn').menu\n              : null;\n\n            // Did we just add a site?\n            if (this.newSiteIds) {\n              // Do we need to create the revision menu?\n              if (!revisionMenu) {\n                this.$revisionBtn.removeClass('disabled').addClass('menubtn');\n                new Garnish.MenuBtn(this.$revisionBtn);\n                revisionMenu = this.$revisionBtn.data('menubtn').menu;\n                revisionMenu.$container.removeClass('hidden');\n              }\n              this.newSiteIds.forEach((siteId) => {\n                const $option = revisionMenu.$options.filter(\n                  `[data-site-id=${siteId}]`\n                );\n                const siteSettings = this.settings.addlSites.find(\n                  (s) => s.siteId == siteId\n                );\n                if (\n                  !siteSettings ||\n                  typeof siteSettings.enabledByDefault === 'undefined' ||\n                  siteSettings.enabledByDefault\n                ) {\n                  $option\n                    .find('.status')\n                    .removeClass('disabled')\n                    .addClass('enabled');\n                }\n                const $li = $option.parent().removeClass('hidden');\n                $li.closest('.site-group').removeClass('hidden');\n              });\n              revisionMenu.$container\n                .find('.revision-hr')\n                .removeClass('hidden');\n              this.newSiteIds = null;\n            }\n\n            if (this.settings.isProvisionalDraft) {\n              if (createdProvisionalDraft) {\n                // Replace the action\n                const $actionInput = $('#action').attr(\n                  'value',\n                  this.settings.publishDraftAction\n                );\n\n                // Update the editor settings\n                this.settings.draftId = response.data.draftId;\n                this.settings.isLive = false;\n                this.previewToken = null;\n\n                if (revisionMenu) {\n                  // Add edited description to the “Current” option\n                  revisionMenu.$container.find('#current-revision').append(\n                    $('<div/>', {\n                      class: 'edited-desc',\n                    })\n                      .append(\n                        $('<p/>', {\n                          text: Craft.t('app', 'Showing your unsaved changes.'),\n                        })\n                      )\n                      .append(\n                        $('<button/>', {\n                          id: 'discard-changes',\n                          class: 'btn',\n                          text: Craft.t('app', 'Discard changes'),\n                        })\n                      )\n                  );\n                }\n\n                this.initForProvisionalDraft();\n              }\n            } else if (revisionMenu) {\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-name')\n                .text(response.data.draftName);\n              revisionMenu.$options\n                .filter('.sel')\n                .find('.draft-meta')\n                .text(\n                  response.data.creator\n                    ? Craft.t('app', 'Saved {timestamp} by {creator}', {\n                        timestamp: response.data.timestamp,\n                        creator: response.data.creator,\n                      })\n                    : Craft.t('app', 'Saved {timestamp}', {\n                        timestamp: response.data.timestamp,\n                      })\n                );\n            }\n\n            // Did the controller send us updated preview targets?\n            if (\n              response.data.previewTargets &&\n              JSON.stringify(response.data.previewTargets) !==\n                JSON.stringify(this.settings.previewTargets)\n            ) {\n              this.updatePreviewTargets(response.data.previewTargets);\n            }\n\n            if (createdProvisionalDraft) {\n              this.updatePreviewLinks();\n              this.trigger('createProvisionalDraft');\n            }\n\n            if (this.$nameTextInput) {\n              this.checkMetaValues();\n            }\n\n            for (const oldId in response.data.duplicatedElements) {\n              if (\n                oldId != this.settings.sourceId &&\n                response.data.duplicatedElements.hasOwnProperty(oldId)\n              ) {\n                this.duplicatedElements[oldId] =\n                  response.data.duplicatedElements[oldId];\n              }\n            }\n\n            // Add missing field modified indicators\n            const selectors = response.data.modifiedAttributes\n              .map((attr) => `[name=\"${attr}\"],[name^=\"${attr}[\"]`)\n              .concat(modifiedFieldNames.map((name) => `[name=\"${name}\"]`));\n\n            const $fields = $(selectors.join(','))\n              .parents()\n              .filter('.field:not(:has(> .status-badge))');\n            for (let i = 0; i < $fields.length; i++) {\n              $fields.eq(i).prepend(\n                $('<div/>', {\n                  class: 'status-badge modified',\n                  title: Craft.t('app', 'This field has been modified.'),\n                }).append(\n                  $('<span/>', {\n                    class: 'visually-hidden',\n                    html: Craft.t('app', 'This field has been modified.'),\n                  })\n                )\n              );\n            }\n\n            this.afterUpdate(data);\n\n            if (this.bc) {\n              this.bc.postMessage({\n                event: 'saveDraft',\n                canonicalId: this.settings.sourceId,\n                draftId: this.settings.draftId,\n                isProvisionalDraft: this.settings.isProvisionalDraft,\n              });\n            }\n\n            resolve();\n          })\n          .catch((e) => {\n            this._afterSaveRequest();\n\n            if (!this.ignoreFailedRequest) {\n              this.errors = [];\n              if (e && e.response) {\n                this.httpStatus = e.response.status;\n                this.httpError = e.response.data ? e.response.data.error : null;\n              }\n              this._showFailStatus();\n              reject(e);\n            }\n\n            this.ignoreFailedRequest = false;\n          });\n      });\n    },\n\n    _afterSaveRequest: function () {\n      this.spinners().addClass('hidden');\n      if (this.$saveMetaBtn) {\n        this.$saveMetaBtn.removeClass('active');\n      }\n      this.saving = false;\n    },\n\n    _showFailStatus: function () {\n      this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden checkmark-icon')\n        .addClass('alert-icon');\n\n      this.setStatusMessage(this._saveFailMessage());\n    },\n\n    /**\n     * @param {string} data\n     * @param {function} [deltaCallback] Callback function that should be passed to `Craft.findDeltaData()`\n     * @returns {string}\n     */\n    prepareData: function (data, deltaCallback) {\n      // Filter out anything that hasn't changed since the last time the form was submitted\n      data = Craft.findDeltaData(\n        Craft.cp.$primaryForm.data('initialSerializedValue'),\n        data,\n        Craft.deltaNames,\n        deltaCallback\n      );\n\n      // Swap out element IDs with their duplicated ones\n      data = this.swapDuplicatedElementIds(data);\n\n      // Add the draft info\n      if (this.settings.draftId) {\n        data += `&draftId=${this.settings.draftId}`;\n        if (this.settings.isProvisionalDraft) {\n          data += '&provisional=1';\n        }\n      }\n\n      if (this.settings.draftName !== null) {\n        data += `&draftName=${this.settings.draftName}`;\n      }\n\n      return data;\n    },\n\n    /**\n     * @param {string} data\n     * @returns {string}\n     */\n    swapDuplicatedElementIds: function (data) {\n      const idsRE = Object.keys(this.duplicatedElements).join('|');\n      if (idsRE === '') {\n        return data;\n      }\n      const lb = encodeURIComponent('[');\n      const rb = encodeURIComponent(']');\n      // Keep replacing field IDs until data stops changing\n      while (true) {\n        if (\n          data ===\n          (data = data\n            // &fields[...][X]\n            .replace(\n              new RegExp(`(&fields${lb}[^=]+${rb}${lb})(${idsRE})(${rb})`, 'g'),\n              (m, pre, id, post) => {\n                return pre + this.duplicatedElements[id] + post;\n              }\n            )\n            // &fields[...=X\n            .replace(\n              new RegExp(`&(fields${lb}[^=]+)=(${idsRE})\\\\b`, 'g'),\n              (m, name, id) => {\n                // Ignore param names that end in `[enabled]`, `[type]`, etc.\n                // (`[sortOrder]` should pass here, which could be set to a specific order index, but *not* `[sortOrder][]`!)\n                if (\n                  name.match(\n                    new RegExp(`${lb}(enabled|sortOrder|type|typeId)${rb}$`)\n                  )\n                ) {\n                  return m;\n                }\n                return `&${name}=${this.duplicatedElements[id]}`;\n              }\n            ))\n        ) {\n          break;\n        }\n      }\n      return data;\n    },\n\n    updatePreviewTargets: function (previewTargets) {\n      previewTargets.forEach((newTarget) => {\n        const currentTarget = this.settings.previewTargets.find(\n          (t) => t.label === newTarget.label\n        );\n        if (currentTarget) {\n          currentTarget.url = newTarget.url;\n        }\n\n        const $previewLink = this.previewLinks.find(\n          ($a) => $a.data('targetLabel') === newTarget.label\n        );\n        if ($previewLink) {\n          $previewLink.data('targetUrl', newTarget.url);\n          this.updatePreviewLinkHref($previewLink);\n        }\n      });\n    },\n\n    afterUpdate: function (data) {\n      Craft.cp.$primaryForm.data('initialSerializedValue', data);\n      Craft.initialDeltaValues = {};\n\n      const $statusIcons = this.statusIcons()\n        .velocity('stop')\n        .css('opacity', '')\n        .removeClass('hidden')\n        .addClass('checkmark-icon');\n\n      this.setStatusMessage(this._saveSuccessMessage());\n\n      if (!Craft.autosaveDrafts) {\n        // Fade the icon out after a couple seconds, since it won't be accurate as content continues to change\n        $statusIcons.velocity('stop').velocity(\n          {\n            opacity: 0,\n          },\n          {\n            delay: 2000,\n            complete: () => {\n              $statusIcons.addClass('hidden');\n            },\n          }\n        );\n      }\n\n      this.trigger('update');\n\n      this.nextInQueue();\n    },\n\n    setStatusMessage: function (message) {\n      this.statusIcons().attr('title', message);\n      this.statusMessage()\n        .empty()\n        .append(\n          $('<span/>', {\n            class: 'visually-hidden',\n            text: message,\n          })\n        );\n    },\n\n    nextInQueue: function () {\n      if (this.queue.length) {\n        this.queue.shift()();\n      }\n    },\n\n    showMetaHud: function () {\n      if (!this.metaHud) {\n        this.createMetaHud();\n        this.onMetaHudShow();\n      } else {\n        this.metaHud.show();\n      }\n\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$nameTextInput.trigger('focus');\n      }\n    },\n\n    createMetaHud: function () {\n      const $hudBody = $('<div/>');\n\n      // Add the Name field\n      const $nameField = $(\n        '<div class=\"field\"><div class=\"heading\"><label for=\"draft-name\">' +\n          Craft.t('app', 'Draft Name') +\n          '</label></div></div>'\n      ).appendTo($hudBody);\n      const $nameInputContainer = $('<div class=\"input\"/>').appendTo(\n        $nameField\n      );\n      this.$nameTextInput = $(\n        '<input type=\"text\" class=\"text fullwidth\" id=\"draft-name\"/>'\n      )\n        .appendTo($nameInputContainer)\n        .val(this.settings.draftName);\n\n      // HUD footer\n      const $footer = $('<div class=\"hud-footer flex flex-center\"/>').appendTo(\n        $hudBody\n      );\n\n      $('<div class=\"flex-grow\"></div>').appendTo($footer);\n      this.$saveMetaBtn = $('<button/>', {\n        type: 'submit',\n        class: 'btn submit disabled',\n        text: Craft.t('app', 'Save'),\n      }).appendTo($footer);\n\n      this.metaHud = new Garnish.HUD(this.$editMetaBtn, $hudBody, {\n        onSubmit: this.saveMeta.bind(this),\n      });\n\n      this.addListener(this.$nameTextInput, 'input', 'checkMetaValues');\n\n      this.metaHud.on('show', this.onMetaHudShow.bind(this));\n      this.metaHud.on('hide', this.onMetaHudHide.bind(this));\n      this.metaHud.on('escape', this.onMetaHudEscape.bind(this));\n    },\n\n    onMetaHudShow: function () {\n      this.$editMetaBtn.addClass('active');\n    },\n\n    onMetaHudHide: function () {\n      this.$editMetaBtn.removeClass('active');\n    },\n\n    onMetaHudEscape: function () {\n      this.$nameTextInput.val(this.settings.draftName);\n    },\n\n    checkMetaValues: function () {\n      if (\n        this.$nameTextInput.val() &&\n        this.$nameTextInput.val() !== this.settings.draftName\n      ) {\n        this.$saveMetaBtn.removeClass('disabled');\n        return true;\n      }\n\n      this.$saveMetaBtn.addClass('disabled');\n      return false;\n    },\n\n    shakeMetaHud: function () {\n      Garnish.shake(this.metaHud.$hud);\n    },\n\n    saveMeta: function () {\n      if (!this.checkMetaValues()) {\n        this.shakeMetaHud();\n        return;\n      }\n\n      this.settings.draftName = this.$nameTextInput.val();\n\n      this.metaHud.hide();\n      this.checkForm(true);\n    },\n\n    handleFormSubmit: function (ev) {\n      ev.preventDefault();\n\n      // Prevent double form submits\n      if (this.submittingForm) {\n        return;\n      }\n\n      // If this a draft and was this a normal save (either via submit button or save shortcut),\n      // then trigger an autosave\n      if (\n        this.settings.draftId &&\n        !this.settings.isUnpublishedDraft &&\n        !this.settings.isProvisionalDraft &&\n        (typeof ev.autosave === 'undefined' || ev.autosave) &&\n        (ev.saveShortcut ||\n          (ev.customTrigger &&\n            ev.customTrigger.data('action') ===\n              this.settings.saveDraftAction)) &&\n        this.enableAutosave\n      ) {\n        this.checkForm(true);\n        return;\n      }\n\n      // Prevent the normal unload confirmation dialog\n      Craft.cp.$confirmUnloadForms = Craft.cp.$confirmUnloadForms.not(\n        Craft.cp.$primaryForm\n      );\n\n      // Abort the current save request if there is one\n      if (this.cancelToken) {\n        this.ignoreFailedRequest = true;\n        this.cancelToken.cancel();\n      }\n\n      // Duplicate the form with normalized data\n      const data = this.prepareData(this.serializeForm(false));\n      const $form = Craft.createForm(data);\n\n      $form.appendTo(Garnish.$bod);\n      $form.submit();\n      this.submittingForm = true;\n    },\n  },\n  {\n    defaults: {\n      elementType: null,\n      sourceId: null,\n      siteId: null,\n      isUnpublishedDraft: false,\n      enabled: false,\n      enabledForSite: false,\n      isLive: false,\n      isProvisionalDraft: false,\n      siteStatuses: null,\n      addlSites: [],\n      cpEditUrl: null,\n      draftId: null,\n      revisionId: null,\n      draftName: null,\n      canEditMultipleSites: false,\n      canUpdateSource: false,\n      saveDraftAction: null,\n      deleteDraftAction: null,\n      publishDraftAction: null,\n      hashedCpEditUrl: null,\n      hashedAddAnotherRedirectUrl: null,\n      enablePreview: false,\n      previewTargets: [],\n      previewToken: null,\n      siteToken: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.DynamicGenerator = Craft.BaseInputGenerator.extend({\n  callback: $.noop,\n\n  init: function (source, target, callback) {\n    this.callback = callback;\n    this.base(source, target);\n  },\n\n  generateTargetValue: function (sourceVal) {\n    return this.callback(sourceVal);\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Editable table class\n */\nCraft.EditableTable = Garnish.Base.extend(\n  {\n    initialized: false,\n\n    id: null,\n    baseName: null,\n    columns: null,\n    sorter: null,\n    biggestId: -1,\n\n    $table: null,\n    $tbody: null,\n    $addRowBtn: null,\n    $tableParent: null,\n    $statusMessage: null,\n\n    rowCount: 0,\n    hasMaxRows: false,\n    hasMinRows: false,\n\n    radioCheckboxes: null,\n\n    init: function (id, baseName, columns, settings) {\n      this.id = id;\n      this.baseName = baseName;\n      this.columns = columns;\n      this.setSettings(settings, Craft.EditableTable.defaults);\n      this.radioCheckboxes = {};\n\n      this.$table = $('#' + id);\n      this.$tbody = this.$table.children('tbody');\n      this.$tableParent = this.$table.parent();\n      this.$statusMessage = this.$tableParent.find('[data-status-message]');\n      this.rowCount = this.$tbody.find('tr').length;\n\n      // Is this already an editable table?\n      if (this.$table.data('editable-table')) {\n        console.warn('Double-instantiating an editable table on an element');\n        this.$table.data('editable-table').destroy();\n      }\n\n      this.$table.data('editable-table', this);\n\n      this.sorter = new Craft.DataTableSorter(this.$table, {\n        helperClass: 'editabletablesorthelper',\n        copyDraggeeInputValuesToHelper: true,\n        onSortChange: () => {\n          this.updateAllRows();\n        },\n      });\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        // Give everything a chance to initialize\n        setTimeout(this.initializeIfVisible.bind(this), 500);\n      }\n\n      if (this.settings.minRows && this.rowCount < this.settings.minRows) {\n        for (var i = this.rowCount; i < this.settings.minRows; i++) {\n          this.addRow();\n        }\n      }\n    },\n\n    isVisible: function () {\n      return this.$table.parent().height() > 0;\n    },\n\n    initialize: function () {\n      if (this.initialized) {\n        return false;\n      }\n\n      this.initialized = true;\n      this.removeListener(Garnish.$win, 'resize');\n\n      var $rows = this.$tbody.children();\n\n      for (var i = 0; i < $rows.length; i++) {\n        this.createRowObj($rows[i]);\n      }\n\n      const $container = this.$table.parent('.input');\n      if ($container.length && this.$table.width() > $container.width()) {\n        $container.css('overflow-x', 'auto');\n      }\n\n      this.$addRowBtn = this.$table.next('.add');\n      this.updateAddRowButton();\n      this.addListener(this.$addRowBtn, 'activate', 'addRow');\n      return true;\n    },\n    initializeIfVisible: function () {\n      this.removeListener(Garnish.$win, 'resize');\n\n      if (this.isVisible()) {\n        this.initialize();\n      } else {\n        this.addListener(Garnish.$win, 'resize', 'initializeIfVisible');\n      }\n    },\n    updateAddRowButton: function () {\n      if (!this.canAddRow()) {\n        this.$addRowBtn.css('opacity', '0.2');\n        this.$addRowBtn.css('pointer-events', 'none');\n        this.$addRowBtn.attr('aria-disabled', 'true');\n      } else {\n        this.$addRowBtn.css('opacity', '1');\n        this.$addRowBtn.css('pointer-events', 'auto');\n        this.$addRowBtn.attr('aria-disabled', 'false');\n      }\n    },\n    updateAllRows: function () {\n      if (this.settings.staticRows) {\n        return;\n      }\n      const $rows = this.$table.find('> tbody > tr');\n      for (let i = 0; i < $rows.length; i++) {\n        this.updateRow($rows.eq(i));\n      }\n    },\n    updateRow: function ($row) {\n      if (this.settings.staticRows) {\n        return;\n      }\n\n      const $deleteBtn = $row.find('button.delete');\n\n      if ($deleteBtn.length) {\n        $deleteBtn.attr(\n          'aria-label',\n          Craft.t('app', 'Delete row {index}', {\n            index: $row.index() + 1,\n          })\n        );\n        if (this.canDeleteRow()) {\n          $deleteBtn.removeAttr('disabled').removeClass('disabled');\n        } else {\n          $deleteBtn.attr('disabled', 'disabled').addClass('disabled');\n        }\n      }\n    },\n    /**\n     * @deprecated\n     */\n    updateDeleteRowButton: function (rowId) {\n      this.updateRow(this.$table.find(`tr[data-id=\"${rowId}\"]`));\n    },\n    updateStatusMessage: function () {\n      this.$statusMessage.empty();\n      let message;\n\n      if (!this.canAddRow()) {\n        message = Craft.t(\n          'app',\n          'Row could not be added. Maximum number of rows reached.'\n        );\n      } else {\n        message = Craft.t(\n          'app',\n          'Row could not be deleted. Minimum number of rows reached.'\n        );\n      }\n\n      setTimeout(() => {\n        this.$statusMessage.text(message);\n      }, 250);\n    },\n    canDeleteRow: function () {\n      return this.rowCount > this.settings.minRows;\n    },\n    deleteRow: function (row) {\n      if (!this.canDeleteRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      this.sorter.removeItems(row.$tr);\n      row.$tr.remove();\n\n      this.rowCount--;\n\n      this.updateAllRows();\n      this.updateAddRowButton();\n\n      if (this.rowCount === 0) {\n        this.$table.addClass('hidden');\n      }\n\n      // onDeleteRow callback\n      this.settings.onDeleteRow(row.$tr);\n\n      row.destroy();\n    },\n    canAddRow: function () {\n      if (this.settings.staticRows) {\n        return false;\n      }\n\n      if (this.settings.maxRows) {\n        return this.rowCount < this.settings.maxRows;\n      }\n\n      return true;\n    },\n    addRow: function (focus, prepend) {\n      if (!this.canAddRow()) {\n        this.updateStatusMessage();\n        return;\n      }\n\n      var rowId = this.settings.rowIdPrefix + (this.biggestId + 1),\n        $tr = this.createRow(\n          rowId,\n          this.columns,\n          this.baseName,\n          $.extend({}, this.settings.defaultValues)\n        );\n\n      if (prepend) {\n        $tr.prependTo(this.$tbody);\n      } else {\n        $tr.appendTo(this.$tbody);\n      }\n\n      var row = this.createRowObj($tr);\n      this.sorter.addItems($tr);\n\n      // Focus the first input in the row\n      if (focus !== false) {\n        $tr\n          .find('input:visible,textarea:visible,select:visible')\n          .first()\n          .trigger('focus');\n      }\n\n      this.rowCount++;\n      this.updateAllRows();\n      this.updateAddRowButton();\n      this.$table.removeClass('hidden');\n\n      // onAddRow callback\n      this.settings.onAddRow($tr);\n\n      return row;\n    },\n\n    createRow: function (rowId, columns, baseName, values) {\n      return Craft.EditableTable.createRow(rowId, columns, baseName, values);\n    },\n\n    createRowObj: function ($tr) {\n      return new Craft.EditableTable.Row(this, $tr);\n    },\n\n    focusOnPrevRow: function ($tr, tdIndex, blurTd) {\n      var $prevTr = $tr.prev('tr');\n      var prevRow;\n\n      if ($prevTr.length) {\n        prevRow = $prevTr.data('editable-table-row');\n      } else {\n        prevRow = this.addRow(false, true);\n      }\n\n      // Focus on the same cell in the previous row\n      if (!prevRow) {\n        return;\n      }\n\n      if (!prevRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(prevRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($prevTr) {\n          this.focusOnPrevRow($prevTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', prevRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    focusOnNextRow: function ($tr, tdIndex, blurTd) {\n      var $nextTr = $tr.next('tr');\n      var nextRow;\n\n      if ($nextTr.length) {\n        nextRow = $nextTr.data('editable-table-row');\n      } else {\n        nextRow = this.addRow(false);\n      }\n\n      // Focus on the same cell in the next row\n      if (!nextRow) {\n        return;\n      }\n\n      if (!nextRow.$tds[tdIndex]) {\n        return;\n      }\n\n      if ($(nextRow.$tds[tdIndex]).hasClass('disabled')) {\n        if ($nextTr) {\n          this.focusOnNextRow($nextTr, tdIndex, blurTd);\n        }\n        return;\n      }\n\n      var $input = $('textarea,input.text', nextRow.$tds[tdIndex]);\n      if ($input.length) {\n        $(blurTd).trigger('blur');\n        $input.trigger('focus');\n      }\n    },\n\n    importData: function (data, row, tdIndex) {\n      let lines = data.split(/\\r?\\n|\\r/);\n      for (let i = 0; i < lines.length; i++) {\n        let values = lines[i].split('\\t');\n        for (let j = 0; j < values.length; j++) {\n          let value = values[j];\n          row.$tds\n            .eq(tdIndex + j)\n            .find('textarea,input[type!=hidden]')\n            .val(value)\n            .trigger('input');\n        }\n\n        // move onto the next row\n        let $nextTr = row.$tr.next('tr');\n        if ($nextTr.length) {\n          row = $nextTr.data('editable-table-row');\n        } else {\n          row = this.addRow(false);\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$table.removeData('editable-table');\n      this.base();\n    },\n  },\n  {\n    textualColTypes: [\n      'autosuggest',\n      'color',\n      'date',\n      'email',\n      'multiline',\n      'number',\n      'singleline',\n      'template',\n      'time',\n      'url',\n    ],\n    defaults: {\n      rowIdPrefix: '',\n      defaultValues: {},\n      staticRows: false,\n      minRows: null,\n      maxRows: null,\n      onAddRow: $.noop,\n      onDeleteRow: $.noop,\n    },\n\n    createRow: function (rowId, columns, baseName, values) {\n      var $tr = $('<tr/>', {\n        'data-id': rowId,\n      });\n\n      for (var colId in columns) {\n        if (!columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        var col = columns[colId],\n          value = typeof values[colId] !== 'undefined' ? values[colId] : '',\n          $cell;\n\n        if (col.type === 'heading') {\n          $cell = $('<th/>', {\n            scope: 'row',\n            class: col['class'],\n            html: value,\n          });\n        } else {\n          var name = baseName + '[' + rowId + '][' + colId + ']';\n\n          $cell = $('<td/>', {\n            class: `${col.class} ${col.type}-cell`,\n            width: col.width,\n          });\n\n          if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n            $cell.addClass('textual');\n          }\n\n          if (col.code) {\n            $cell.addClass('code');\n          }\n\n          switch (col.type) {\n            case 'checkbox':\n              $('<div class=\"checkbox-wrapper\"/>')\n                .append(\n                  Craft.ui.createCheckbox({\n                    name: name,\n                    value: col.value || '1',\n                    checked: !!value,\n                  })\n                )\n                .appendTo($cell);\n              break;\n\n            case 'color':\n              Craft.ui\n                .createColorInput({\n                  name: name,\n                  value: value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'date':\n              Craft.ui\n                .createDateInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'lightswitch':\n              Craft.ui\n                .createLightswitch({\n                  name: name,\n                  value: col.value || '1',\n                  on: !!value,\n                  small: true,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'select':\n              Craft.ui\n                .createSelect({\n                  name: name,\n                  options: col.options,\n                  value:\n                    value ||\n                    (function () {\n                      for (var key in col.options) {\n                        if (\n                          col.options.hasOwnProperty(key) &&\n                          col.options[key].default\n                        ) {\n                          return typeof col.options[key].value !== 'undefined'\n                            ? col.options[key].value\n                            : key;\n                        }\n                      }\n                      return null;\n                    })(),\n                  class: 'small',\n                })\n                .appendTo($cell);\n              break;\n\n            case 'time':\n              Craft.ui\n                .createTimeInput({\n                  name: name,\n                  value: value,\n                })\n                .appendTo($cell);\n              break;\n\n            case 'email':\n            case 'url':\n              Craft.ui\n                .createTextInput({\n                  name: name,\n                  value: value,\n                  type: col.type,\n                  placeholder: col.placeholder || null,\n                })\n                .appendTo($cell);\n              break;\n\n            default:\n              $('<textarea/>', {\n                name: name,\n                rows: col.rows || 1,\n                val: value,\n                placeholder: col.placeholder,\n              }).appendTo($cell);\n          }\n        }\n\n        $cell.appendTo($tr);\n      }\n\n      $('<td/>', {\n        class: 'thin action',\n      })\n        .append(\n          $('<a/>', {\n            class: 'move icon',\n            title: Craft.t('app', 'Reorder'),\n          })\n        )\n        .appendTo($tr);\n\n      $('<td/>', {\n        class: 'thin action',\n      })\n        .append(\n          $('<button/>', {\n            class: 'delete icon',\n            title: Craft.t('app', 'Delete'),\n            type: 'button',\n          })\n        )\n        .appendTo($tr);\n\n      return $tr;\n    },\n  }\n);\n\n/**\n * Editable table row class\n */\nCraft.EditableTable.Row = Garnish.Base.extend(\n  {\n    table: null,\n    id: null,\n    niceTexts: null,\n\n    $tr: null,\n    $tds: null,\n    tds: null,\n    $textareas: null,\n    $deleteBtn: null,\n\n    init: function (table, tr) {\n      this.table = table;\n      this.$tr = $(tr);\n      this.$tds = this.$tr.children();\n      this.tds = [];\n      this.id = this.$tr.attr('data-id');\n\n      this.$tr.data('editable-table-row', this);\n\n      // Get the row ID, sans prefix\n      var id = parseInt(this.id.substr(this.table.settings.rowIdPrefix.length));\n\n      if (id > this.table.biggestId) {\n        this.table.biggestId = id;\n      }\n\n      this.$textareas = $();\n      this.niceTexts = [];\n      var textareasByColId = {};\n\n      var i = 0;\n      var colId, col, td, $textarea, $checkbox;\n\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n        td = this.tds[colId] = this.$tds[i];\n\n        if (Craft.inArray(col.type, Craft.EditableTable.textualColTypes)) {\n          $textarea = $('textarea', td);\n          this.$textareas = this.$textareas.add($textarea);\n\n          this.addListener($textarea, 'focus', 'onTextareaFocus');\n          this.addListener($textarea, 'mousedown', 'ignoreNextTextareaFocus');\n\n          this.niceTexts.push(\n            new Garnish.NiceText($textarea, {\n              onHeightChange: this.onTextareaHeightChange.bind(this),\n            })\n          );\n\n          this.addListener(\n            $textarea,\n            'keypress',\n            {tdIndex: i, type: col.type},\n            'handleKeypress'\n          );\n          this.addListener(\n            $textarea,\n            'input',\n            {type: col.type},\n            'validateValue'\n          );\n          $textarea.trigger('input');\n\n          if (col.type !== 'multiline') {\n            this.addListener(\n              $textarea,\n              'paste',\n              {tdIndex: i, type: col.type},\n              'handlePaste'\n            );\n          }\n\n          textareasByColId[colId] = $textarea;\n        } else if (col.type === 'checkbox') {\n          $checkbox = $('input[type=\"checkbox\"]', td);\n\n          if (col.radioMode) {\n            if (typeof this.table.radioCheckboxes[colId] === 'undefined') {\n              this.table.radioCheckboxes[colId] = [];\n            }\n            this.table.radioCheckboxes[colId].push($checkbox[0]);\n            this.addListener(\n              $checkbox,\n              'change',\n              {colId},\n              'onRadioCheckboxChange'\n            );\n          }\n\n          if (col.toggle) {\n            this.addListener($checkbox, 'change', {colId}, function (ev) {\n              this.applyToggleCheckbox(ev.data.colId);\n            });\n          }\n        }\n\n        if (!$(td).hasClass('disabled')) {\n          this.addListener(td, 'click', {td}, function (ev) {\n            if (ev.target === ev.data.td) {\n              $(ev.data.td).find('textarea,input,select,.lightswitch').focus();\n            }\n          });\n        }\n\n        i++;\n      }\n\n      // Now that all of the text cells have been nice-ified, let's normalize the heights\n      this.onTextareaHeightChange();\n\n      // See if we need to apply any checkbox toggles now that we've indexed all the TDs\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n        col = this.table.columns[colId];\n        if (col.type === 'checkbox' && col.toggle) {\n          this.applyToggleCheckbox(colId);\n        }\n      }\n\n      // Now look for any autopopulate columns\n      for (colId in this.table.columns) {\n        if (!this.table.columns.hasOwnProperty(colId)) {\n          continue;\n        }\n\n        col = this.table.columns[colId];\n\n        if (\n          col.autopopulate &&\n          typeof textareasByColId[col.autopopulate] !== 'undefined' &&\n          !textareasByColId[colId].val()\n        ) {\n          new Craft.HandleGenerator(\n            textareasByColId[colId],\n            textareasByColId[col.autopopulate],\n            {\n              allowNonAlphaStart: true,\n            }\n          );\n        }\n      }\n\n      var $deleteBtn = this.$tr.children().last().find('.delete');\n      this.addListener($deleteBtn, 'click', 'deleteRow');\n\n      var $inputs = this.$tr.find('input,textarea,select,.lightswitch');\n      this.addListener($inputs, 'focus', function (ev) {\n        $(ev.currentTarget).closest('td:not(.disabled)').addClass('focus');\n      });\n      this.addListener($inputs, 'blur', function (ev) {\n        $(ev.currentTarget).closest('td').removeClass('focus');\n      });\n    },\n\n    onTextareaFocus: function (ev) {\n      this.onTextareaHeightChange();\n\n      var $textarea = $(ev.currentTarget);\n\n      if ($textarea.data('ignoreNextFocus')) {\n        $textarea.data('ignoreNextFocus', false);\n        return;\n      }\n\n      setTimeout(function () {\n        Craft.selectFullValue($textarea);\n      }, 0);\n    },\n\n    onRadioCheckboxChange: function (ev) {\n      if (ev.currentTarget.checked) {\n        for (\n          var i = 0;\n          i < this.table.radioCheckboxes[ev.data.colId].length;\n          i++\n        ) {\n          var checkbox = this.table.radioCheckboxes[ev.data.colId][i];\n          checkbox.checked = checkbox === ev.currentTarget;\n        }\n      }\n    },\n\n    applyToggleCheckbox: function (checkboxColId) {\n      var checkboxCol = this.table.columns[checkboxColId];\n      var checked = $('input[type=\"checkbox\"]', this.tds[checkboxColId]).prop(\n        'checked'\n      );\n      var colId, colIndex, neg;\n      for (var i = 0; i < checkboxCol.toggle.length; i++) {\n        colId = checkboxCol.toggle[i];\n        colIndex = this.table.colum;\n        neg = colId[0] === '!';\n        if (neg) {\n          colId = colId.substr(1);\n        }\n        if ((checked && !neg) || (!checked && neg)) {\n          $(this.tds[colId])\n            .removeClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', false);\n        } else {\n          $(this.tds[colId])\n            .addClass('disabled')\n            .find('textarea, input')\n            .prop('disabled', true);\n        }\n      }\n    },\n\n    ignoreNextTextareaFocus: function (ev) {\n      $.data(ev.currentTarget, 'ignoreNextFocus', true);\n    },\n\n    handleKeypress: function (ev) {\n      var keyCode = ev.keyCode ? ev.keyCode : ev.charCode;\n      var ctrl = Garnish.isCtrlKeyPressed(ev);\n\n      // Going to the next/previous row?\n      if (\n        keyCode === Garnish.RETURN_KEY &&\n        (ev.data.type !== 'multiline' || ctrl)\n      ) {\n        ev.preventDefault();\n        if (ev.shiftKey) {\n          this.table.focusOnPrevRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        } else {\n          this.table.focusOnNextRow(\n            this.$tr,\n            ev.data.tdIndex,\n            ev.currentTarget\n          );\n        }\n        return;\n      }\n\n      // Was this an invalid number character?\n      if (\n        ev.data.type === 'number' &&\n        !ctrl &&\n        !Craft.inArray(keyCode, Craft.EditableTable.Row.numericKeyCodes)\n      ) {\n        ev.preventDefault();\n      }\n    },\n\n    handlePaste: function (ev) {\n      let data = Craft.trim(\n        ev.originalEvent.clipboardData.getData('Text'),\n        ' \\n\\r'\n      );\n      if (!data.match(/[\\t\\r\\n]/)) {\n        return;\n      }\n      ev.preventDefault();\n      this.table.importData(data, this, ev.data.tdIndex);\n    },\n\n    validateValue: function (ev) {\n      if (ev.data.type === 'multiline') {\n        return;\n      }\n\n      var safeValue;\n\n      if (ev.data.type === 'number') {\n        // Only grab the number at the beginning of the value (if any)\n        var match = ev.currentTarget.value.match(/^\\s*(-?[\\d\\\\.]*)/);\n\n        if (match !== null) {\n          safeValue = match[1];\n        } else {\n          safeValue = '';\n        }\n      } else {\n        // Just strip any newlines\n        safeValue = ev.currentTarget.value.replace(/[\\r\\n]/g, '');\n      }\n\n      if (safeValue !== ev.currentTarget.value) {\n        ev.currentTarget.value = safeValue;\n      }\n    },\n\n    onTextareaHeightChange: function () {\n      // Keep all the textareas' heights in sync\n      var tallestTextareaHeight = -1;\n\n      for (var i = 0; i < this.niceTexts.length; i++) {\n        if (this.niceTexts[i].height > tallestTextareaHeight) {\n          tallestTextareaHeight = this.niceTexts[i].height;\n        }\n      }\n\n      this.$textareas.css('min-height', tallestTextareaHeight);\n\n      // If the <td> is still taller, go with that instead\n      var tdHeight = this.$textareas\n        .filter(':visible')\n        .first()\n        .parent()\n        .height();\n\n      if (tdHeight > tallestTextareaHeight) {\n        this.$textareas.css('min-height', tdHeight);\n      }\n    },\n\n    deleteRow: function () {\n      this.table.deleteRow(this);\n    },\n  },\n  {\n    numericKeyCodes: [\n      9 /* (tab) */, 8 /* (delete) */, 37, 38, 39, 40 /* (arrows) */, 45,\n      91 /* (minus) */, 46, 190 /* period */, 48, 49, 50, 51, 52, 53, 54, 55,\n      56, 57 /* (0-9) */,\n    ],\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Element Action Trigger\n */\nCraft.ElementActionTrigger = Garnish.Base.extend(\n  {\n    maxLevels: null,\n    newChildUrl: null,\n    $trigger: null,\n    $selectedItems: null,\n    triggerEnabled: true,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.ElementActionTrigger.defaults);\n\n      this.$trigger = $(\n        '#' + settings.type.replace(/[\\[\\]\\\\]+/g, '-') + '-actiontrigger'\n      );\n\n      // Do we have a custom handler?\n      if (this.settings.activate) {\n        // Prevent the element index's click handler\n        this.$trigger.data('custom-handler', true);\n\n        // Is this a custom trigger?\n        if (this.$trigger.prop('nodeName') === 'FORM') {\n          this.addListener(this.$trigger, 'submit', 'handleTriggerActivation');\n        } else {\n          this.addListener(this.$trigger, 'click', 'handleTriggerActivation');\n        }\n      }\n\n      this.updateTrigger();\n      Craft.elementIndex.on('selectionChange', this.updateTrigger.bind(this));\n    },\n\n    updateTrigger: function () {\n      // Ignore if the last element was just unselected\n      if (Craft.elementIndex.getSelectedElements().length === 0) {\n        return;\n      }\n\n      if (this.validateSelection()) {\n        this.enableTrigger();\n      } else {\n        this.disableTrigger();\n      }\n    },\n\n    /**\n     * Determines if this action can be performed on the currently selected elements.\n     *\n     * @return boolean\n     */\n    validateSelection: function () {\n      var valid = true;\n      this.$selectedItems = Craft.elementIndex.getSelectedElements();\n\n      if (!this.settings.batch && this.$selectedItems.length > 1) {\n        valid = false;\n      } else if (typeof this.settings.validateSelection === 'function') {\n        valid = this.settings.validateSelection(this.$selectedItems);\n      }\n\n      return valid;\n    },\n\n    enableTrigger: function () {\n      if (this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.removeClass('disabled');\n      this.triggerEnabled = true;\n    },\n\n    disableTrigger: function () {\n      if (!this.triggerEnabled) {\n        return;\n      }\n\n      this.$trigger.addClass('disabled');\n      this.triggerEnabled = false;\n    },\n\n    handleTriggerActivation: function (ev) {\n      ev.preventDefault();\n      ev.stopPropagation();\n\n      if (this.triggerEnabled) {\n        this.settings.activate(this.$selectedItems);\n      }\n    },\n  },\n  {\n    defaults: {\n      type: null,\n      batch: true,\n      validateSelection: null,\n      activate: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Base Element Index View\n */\nCraft.ElementThumbLoader = Garnish.Base.extend(\n  {\n    queue: null,\n    workers: [],\n\n    init: function () {\n      this.queue = [];\n\n      for (var i = 0; i < 3; i++) {\n        this.workers.push(new Craft.ElementThumbLoader.Worker(this));\n      }\n    },\n\n    load: function ($elements) {\n      // Only immediately load the visible images\n      let $thumbs = $elements.find('.elementthumb');\n      for (let i = 0; i < $thumbs.length; i++) {\n        let $thumb = $thumbs.eq(i);\n        let $scrollParent = $thumb.scrollParent();\n        if ($scrollParent.prop('nodeName') === 'FIELDSET') {\n          $scrollParent = $scrollParent.scrollParent();\n        }\n        if ($scrollParent[0] === document.body) {\n          $scrollParent = Garnish.$doc;\n        }\n        if (this.isVisible($thumb, $scrollParent)) {\n          this.addToQueue($thumb[0]);\n        } else {\n          let key = 'thumb' + Math.floor(Math.random() * 1000000);\n          Craft.ElementThumbLoader.invisibleThumbs[key] = [\n            this,\n            $thumb,\n            $scrollParent,\n          ];\n          $scrollParent.on(\n            `scroll.${key}`,\n            {\n              $thumb: $thumb,\n              $scrollParent: $scrollParent,\n              key: key,\n            },\n            (ev) => {\n              if (this.isVisible(ev.data.$thumb, ev.data.$scrollParent)) {\n                delete Craft.ElementThumbLoader.invisibleThumbs[ev.data.key];\n                $scrollParent.off(`scroll.${ev.data.key}`);\n                this.addToQueue(ev.data.$thumb[0]);\n              }\n            }\n          );\n        }\n      }\n    },\n\n    addToQueue: function (thumb) {\n      this.queue.push(thumb);\n\n      // See if there are any inactive workers\n      for (var i = 0; i < this.workers.length; i++) {\n        if (!this.workers[i].active) {\n          this.workers[i].loadNext();\n        }\n      }\n    },\n\n    isVisible: function ($thumb, $scrollParent) {\n      let thumbOffset = $thumb.offset().top;\n      let scrollParentOffset, scrollParentHeight;\n      if ($scrollParent[0] === document) {\n        scrollParentOffset = $scrollParent.scrollTop();\n        scrollParentHeight = Garnish.$win.height();\n      } else {\n        scrollParentOffset = $scrollParent.offset().top;\n        scrollParentHeight = $scrollParent.height();\n      }\n      return (\n        thumbOffset > scrollParentOffset &&\n        thumbOffset < scrollParentOffset + scrollParentHeight + 1000\n      );\n    },\n\n    destroy: function () {\n      for (var i = 0; i < this.workers.length; i++) {\n        this.workers[i].destroy();\n      }\n\n      this.base();\n    },\n  },\n  {\n    invisibleThumbs: {},\n    retryAll: function () {\n      for (let key in Craft.ElementThumbLoader.invisibleThumbs) {\n        let [queue, $thumb, $scrollParent] =\n          Craft.ElementThumbLoader.invisibleThumbs[key];\n        delete Craft.ElementThumbLoader.invisibleThumbs[key];\n        $scrollParent.off(`scroll.${key}`);\n        queue.load($thumb.parent());\n      }\n    },\n  }\n);\n\nCraft.ElementThumbLoader.Worker = Garnish.Base.extend({\n  loader: null,\n  active: false,\n\n  init: function (loader) {\n    this.loader = loader;\n  },\n\n  loadNext: function () {\n    var container = this.loader.queue.shift();\n    if (typeof container === 'undefined') {\n      this.active = false;\n      return;\n    }\n\n    this.active = true;\n    var $container = $(container);\n    if ($container.find('img').length) {\n      this.loadNext();\n      return;\n    }\n    var $img = $('<img/>', {\n      sizes: $container.attr('data-sizes'),\n      srcset: $container.attr('data-srcset'),\n      alt: '',\n    });\n    this.addListener($img, 'load,error', 'loadNext');\n    $img.appendTo($container);\n    picturefill({\n      elements: [$img[0]],\n    });\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Form\n */\nCraft.ElevatedSessionForm = Garnish.Base.extend({\n  $form: null,\n  inputs: null,\n\n  init: function (form, inputs) {\n    this.$form = $(form);\n\n    // Only check specific inputs?\n    if (typeof inputs !== 'undefined') {\n      this.inputs = [];\n      inputs = $.makeArray(inputs);\n\n      for (var i = 0; i < inputs.length; i++) {\n        var $inputs = $(inputs[i]);\n\n        for (var j = 0; j < $inputs.length; j++) {\n          var $input = $inputs.eq(j);\n\n          this.inputs.push({\n            input: $input,\n            val: Garnish.getInputPostVal($input),\n          });\n        }\n      }\n    }\n\n    this.addListener(this.$form, 'submit', 'handleFormSubmit');\n  },\n\n  handleFormSubmit: function (ev) {\n    // Ignore if we're in the middle of getting the elevated session timeout\n    if (Craft.elevatedSessionManager.fetchingTimeout) {\n      ev.preventDefault();\n      ev.stopImmediatePropagation();\n      return;\n    }\n\n    // Are we only interested in certain inputs?\n    if (this.inputs) {\n      var inputsChanged = false;\n      var $input;\n\n      for (var i = 0; i < this.inputs.length; i++) {\n        $input = this.inputs[i].input;\n        // Is this a password input?\n        if ($input.data('passwordInput')) {\n          $input = $input.data('passwordInput').$currentInput;\n        }\n\n        // Has this input's value changed?\n        if (Garnish.getInputPostVal($input) !== this.inputs[i].val) {\n          inputsChanged = true;\n          break;\n        }\n      }\n\n      if (!inputsChanged) {\n        // No need to interrupt the submit\n        return;\n      }\n    }\n\n    // Prevent the form from submitting until the user has an elevated session\n    ev.preventDefault();\n    ev.stopImmediatePropagation();\n    Craft.elevatedSessionManager.requireElevatedSession(\n      this.submitForm.bind(this)\n    );\n  },\n\n  submitForm: function () {\n    // Don't let handleFormSubmit() interrupt this time\n    this.disable();\n    this.$form.trigger('submit');\n    this.enable();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Elevated Session Manager\n */\nCraft.ElevatedSessionManager = Garnish.Base.extend(\n  {\n    fetchingTimeout: false,\n\n    passwordModal: null,\n    $passwordInput: null,\n    $passwordSpinner: null,\n    $submitBtn: null,\n    $errorPara: null,\n\n    callback: null,\n\n    /**\n     * Requires that the user has an elevated session.\n     *\n     * @param {function} callback The callback function that should be called once the user has an elevated session\n     */\n    requireElevatedSession: function (callback) {\n      this.callback = callback;\n\n      // Check the time remaining on the user's elevated session (if any)\n      this.fetchingTimeout = true;\n\n      Craft.postActionRequest(\n        'users/get-elevated-session-timeout',\n        (response, textStatus) => {\n          this.fetchingTimeout = false;\n\n          if (textStatus === 'success') {\n            // Is there still enough time left or has it been disabled?\n            if (\n              response.timeout === false ||\n              response.timeout >=\n                Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout\n            ) {\n              this.callback();\n            } else {\n              // Show the password modal\n              this.showPasswordModal();\n            }\n          }\n        }\n      );\n    },\n\n    showPasswordModal: function () {\n      if (!this.passwordModal) {\n        var $passwordModal = $(\n            '<form id=\"elevatedsessionmodal\" class=\"modal secure fitted\"/>'\n          ),\n          $body = $(\n            '<div class=\"body\"><p>' +\n              Craft.t('app', 'Enter your password to continue.') +\n              '</p></div>'\n          ).appendTo($passwordModal),\n          $inputContainer = $('<div class=\"inputcontainer\">').appendTo($body),\n          $inputsFlexContainer = $('<div class=\"flex\"/>').appendTo(\n            $inputContainer\n          ),\n          $passwordContainer = $('<div class=\"flex-grow\"/>').appendTo(\n            $inputsFlexContainer\n          ),\n          $buttonContainer = $('<td/>').appendTo($inputsFlexContainer),\n          $passwordWrapper = $('<div class=\"passwordwrapper\"/>').appendTo(\n            $passwordContainer\n          );\n\n        this.$passwordInput = $(\n          '<input type=\"password\" class=\"text password fullwidth\" placeholder=\"' +\n            Craft.t('app', 'Password') +\n            '\" autocomplete=\"current-password\"/>'\n        ).appendTo($passwordWrapper);\n        this.$passwordSpinner = $('<div class=\"spinner hidden\"/>').appendTo(\n          $inputContainer\n        );\n        this.$submitBtn = $('<button/>', {\n          type: 'submit',\n          class: 'btn submit disabled',\n          text: Craft.t('app', 'Submit'),\n        }).appendTo($buttonContainer);\n        this.$errorPara = $('<p class=\"error\"/>').appendTo($body);\n\n        this.passwordModal = new Garnish.Modal($passwordModal, {\n          closeOtherModals: false,\n          onFadeIn: () => {\n            setTimeout(this.focusPasswordInput.bind(this), 100);\n          },\n          onFadeOut: () => {\n            this.$passwordInput.val('');\n          },\n        });\n\n        new Craft.PasswordInput(this.$passwordInput, {\n          onToggleInput: ($newPasswordInput) => {\n            this.$passwordInput = $newPasswordInput;\n          },\n        });\n\n        this.addListener(this.$passwordInput, 'input', 'validatePassword');\n        this.addListener($passwordModal, 'submit', 'submitPassword');\n      } else {\n        this.passwordModal.show();\n      }\n    },\n\n    focusPasswordInput: function () {\n      if (!Garnish.isMobileBrowser(true)) {\n        this.$passwordInput.trigger('focus');\n      }\n    },\n\n    validatePassword: function () {\n      if (this.$passwordInput.val().length >= 6) {\n        this.$submitBtn.removeClass('disabled');\n        return true;\n      } else {\n        this.$submitBtn.addClass('disabled');\n        return false;\n      }\n    },\n\n    submitPassword: function (ev) {\n      if (ev) {\n        ev.preventDefault();\n      }\n\n      if (!this.validatePassword()) {\n        return;\n      }\n\n      this.$passwordSpinner.removeClass('hidden');\n      this.clearLoginError();\n\n      var data = {\n        currentPassword: this.$passwordInput.val(),\n      };\n\n      Craft.postActionRequest(\n        'users/start-elevated-session',\n        data,\n        (response, textStatus) => {\n          this.$passwordSpinner.addClass('hidden');\n\n          if (textStatus === 'success') {\n            if (response.success) {\n              this.passwordModal.hide();\n              this.callback();\n            } else {\n              this.showPasswordError(\n                response.message || Craft.t('app', 'Incorrect password.')\n              );\n              Garnish.shake(this.passwordModal.$container);\n              this.focusPasswordInput();\n            }\n          } else {\n            this.showPasswordError();\n          }\n        }\n      );\n    },\n\n    showPasswordError: function (error) {\n      if (error === null || typeof error === 'undefined') {\n        error = Craft.t('app', 'A server error occurred.');\n      }\n\n      this.$errorPara.text(error);\n      this.passwordModal.updateSizeAndPosition();\n    },\n\n    clearLoginError: function () {\n      this.showPasswordError('');\n    },\n  },\n  {\n    minSafeElevatedSessionTimeout: 5,\n  }\n);\n\n// Instantiate it\nCraft.elevatedSessionManager = new Craft.ElevatedSessionManager();\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Entry index class\n */\nCraft.EntryIndex = Craft.BaseElementIndex.extend({\n  publishableSections: null,\n  $newEntryBtnGroup: null,\n  $newEntryBtn: null,\n\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateButton.bind(this));\n    this.on('selectSite', this.updateButton.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  afterInit: function () {\n    // Find which of the visible sections the user has permission to create new entries in\n    this.publishableSections = [];\n\n    for (var i = 0; i < Craft.publishableSections.length; i++) {\n      var section = Craft.publishableSections[i];\n\n      if (this.getSourceByKey('section:' + section.uid)) {\n        this.publishableSections.push(section);\n      }\n    }\n\n    this.base();\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific section in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSectionHandle !== 'undefined'\n    ) {\n      if (defaultSectionHandle === 'singles') {\n        return 'singles';\n      } else {\n        for (var i = 0; i < this.$sources.length; i++) {\n          var $source = $(this.$sources[i]);\n\n          if ($source.data('handle') === defaultSectionHandle) {\n            return $source.data('key');\n          }\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateButton: function () {\n    if (!this.$source) {\n      return;\n    }\n\n    var handle;\n\n    // Get the handle of the selected source\n    if (this.$source.data('key') === 'singles') {\n      handle = 'singles';\n    } else {\n      handle = this.$source.data('handle');\n    }\n\n    // Update the New Entry button\n    // ---------------------------------------------------------------------\n\n    var i, href, label;\n\n    if (this.publishableSections.length) {\n      // Remove the old button, if there is one\n      if (this.$newEntryBtnGroup) {\n        this.$newEntryBtnGroup.remove();\n      }\n\n      // Determine if they are viewing a section that they have permission to create entries in\n      var selectedSection;\n\n      if (handle) {\n        for (i = 0; i < this.publishableSections.length; i++) {\n          if (this.publishableSections[i].handle === handle) {\n            selectedSection = this.publishableSections[i];\n            break;\n          }\n        }\n      }\n\n      this.$newEntryBtnGroup = $('<div class=\"btngroup submit\"/>');\n      var $menuBtn;\n\n      // If they are, show a primary \"New entry\" button, and a dropdown of the other sections (if any).\n      // Otherwise only show a menu button\n      if (selectedSection) {\n        href = this._getSectionTriggerHref(selectedSection);\n        label =\n          this.settings.context === 'index'\n            ? Craft.t('app', 'New entry')\n            : Craft.t('app', 'New {section} entry', {\n                section: selectedSection.name,\n              });\n        this.$newEntryBtn = $(\n          '<a class=\"btn submit add icon\" ' +\n            href +\n            ' role=\"button\" tabindex=\"0\">' +\n            Craft.escapeHtml(label) +\n            '</a>'\n        ).appendTo(this.$newEntryBtnGroup);\n\n        if (this.settings.context !== 'index') {\n          this.addListener(this.$newEntryBtn, 'click', function (ev) {\n            this._openCreateEntryModal(\n              ev.currentTarget.getAttribute('data-id')\n            );\n          });\n        }\n\n        if (this.publishableSections.length > 1) {\n          $menuBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn submit menubtn',\n          }).appendTo(this.$newEntryBtnGroup);\n        }\n      } else {\n        this.$newEntryBtn = $menuBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit add icon menubtn',\n          text: Craft.t('app', 'New entry'),\n        }).appendTo(this.$newEntryBtnGroup);\n      }\n\n      if ($menuBtn) {\n        var menuHtml = '<div class=\"menu\"><ul>';\n\n        for (i = 0; i < this.publishableSections.length; i++) {\n          var section = this.publishableSections[i];\n\n          if (\n            (this.settings.context === 'index' &&\n              $.inArray(this.siteId, section.sites) !== -1) ||\n            (this.settings.context !== 'index' && section !== selectedSection)\n          ) {\n            href = this._getSectionTriggerHref(section);\n            label =\n              this.settings.context === 'index'\n                ? section.name\n                : Craft.t('app', 'New {section} entry', {\n                    section: section.name,\n                  });\n            menuHtml +=\n              '<li><a ' + href + '>' + Craft.escapeHtml(label) + '</a></li>';\n          }\n        }\n\n        menuHtml += '</ul></div>';\n\n        $(menuHtml).appendTo(this.$newEntryBtnGroup);\n        var menuBtn = new Garnish.MenuBtn($menuBtn);\n\n        if (this.settings.context !== 'index') {\n          menuBtn.on('optionSelect', (ev) => {\n            this._openCreateEntryModal(ev.option.getAttribute('data-id'));\n          });\n        }\n      }\n\n      this.addButton(this.$newEntryBtnGroup);\n    }\n\n    // Update the URL if we're on the Entries index\n    // ---------------------------------------------------------------------\n\n    if (this.settings.context === 'index' && typeof history !== 'undefined') {\n      var uri = 'entries';\n\n      if (handle) {\n        uri += '/' + handle;\n      }\n\n      history.replaceState({}, '', Craft.getUrl(uri));\n    }\n  },\n\n  _getSectionTriggerHref: function (section) {\n    if (this.settings.context === 'index') {\n      const uri = `entries/${section.handle}/new`;\n      const site = this.getSite();\n      const params = site ? {site: site.handle} : undefined;\n      return `href=\"${Craft.getUrl(uri, params)}\"`;\n    }\n\n    return `data-id=\"${section.id}\"`;\n  },\n\n  _openCreateEntryModal: function (sectionId) {\n    if (this.$newEntryBtn.hasClass('loading')) {\n      return;\n    }\n\n    // Find the section\n    var section;\n\n    for (var i = 0; i < this.publishableSections.length; i++) {\n      if (this.publishableSections[i].id == sectionId) {\n        section = this.publishableSections[i];\n        break;\n      }\n    }\n\n    if (!section) {\n      return;\n    }\n\n    this.$newEntryBtn.addClass('inactive');\n    var newEntryBtnText = this.$newEntryBtn.text();\n    this.$newEntryBtn.text(\n      Craft.t('app', 'New {section} entry', {section: section.name})\n    );\n\n    Craft.createElementEditor(this.elementType, {\n      hudTrigger: this.$newEntryBtnGroup,\n      siteId: this.siteId,\n      attributes: {\n        sectionId: sectionId,\n        typeId: section.entryTypes[0].id,\n        enabled: section.canPublish ? 1 : 0,\n      },\n      onHideHud: () => {\n        this.$newEntryBtn.removeClass('inactive').text(newEntryBtnText);\n      },\n      onSaveElement: (response) => {\n        // Make sure the right section is selected\n        var sectionSourceKey = 'section:' + section.uid;\n\n        if (this.sourceKey !== sectionSourceKey) {\n          this.selectSourceByKey(sectionSourceKey);\n        }\n\n        this.clearSearch();\n        this.setSortAttribute('dateCreated');\n        this.setSortDirection('desc');\n        this.selectElementAfterUpdate(response.id);\n        this.updateElements();\n      },\n    });\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\Entry', Craft.EntryIndex);\n","/** global: Craft */\n/** global: Garnish */\nCraft.FieldLayoutDesigner = Garnish.Base.extend(\n  {\n    $container: null,\n    $tabContainer: null,\n    $newTabBtn: null,\n    $sidebar: null,\n    $libraryToggle: null,\n    $selectedLibrary: null,\n    $fieldLibrary: null,\n    $uiLibrary: null,\n    $uiLibraryElements: null,\n    $fieldSearch: null,\n    $clearFieldSearchBtn: null,\n    $fieldGroups: null,\n    $fields: null,\n\n    tabGrid: null,\n    elementDrag: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.FieldLayoutDesigner.defaults);\n\n      let $workspace = this.$container.children('.fld-workspace');\n      this.$tabContainer = $workspace.children('.fld-tabs');\n      this.$newTabBtn = $workspace.children('.fld-new-tab-btn');\n      this.$sidebar = this.$container.children('.fld-sidebar');\n\n      this.$fieldLibrary = this.$selectedLibrary =\n        this.$sidebar.children('.fld-field-library');\n      let $fieldSearchContainer = this.$fieldLibrary.children('.search');\n      this.$fieldSearch = $fieldSearchContainer.children('input');\n      this.$clearFieldSearchBtn = $fieldSearchContainer.children('.clear');\n      this.$fieldGroups = this.$sidebar.find('.fld-field-group');\n      this.$fields = this.$fieldGroups.children('.fld-element');\n      this.$uiLibrary = this.$sidebar.children('.fld-ui-library');\n      this.$uiLibraryElements = this.$uiLibrary.children();\n\n      // Set up the layout grids\n      this.tabGrid = new Craft.Grid(this.$tabContainer, {\n        itemSelector: '.fld-tab',\n        minColWidth: 24 * 11,\n        fillMode: 'grid',\n        snapToGrid: 24,\n      });\n\n      let $tabs = this.$tabContainer.children();\n      for (let i = 0; i < $tabs.length; i++) {\n        this.initTab($($tabs[i]));\n      }\n\n      // create a placeholder input so *something* gets posted even if there are no tabs/elements\n      $('<input/>', {\n        type: 'hidden',\n        name: this.settings.elementPlacementInputName.replace(\n          '[__TAB_NAME__][]',\n          ''\n        ),\n        value: '',\n      }).insertBefore(this.$container);\n\n      this.elementDrag = new Craft.FieldLayoutDesigner.ElementDrag(this);\n\n      if (this.settings.customizableTabs) {\n        this.tabDrag = new Craft.FieldLayoutDesigner.TabDrag(this);\n\n        this.addListener(this.$newTabBtn, 'activate', 'addTab');\n      }\n\n      // Set up the sidebar\n      if (this.settings.customizableUi) {\n        let $libraryPicker = this.$sidebar.children('.btngroup');\n        new Craft.Listbox($libraryPicker, {\n          onChange: ($selectedOption) => {\n            this.$selectedLibrary.addClass('hidden');\n            this.$selectedLibrary =\n              this[`$${$selectedOption.data('library')}Library`].removeClass(\n                'hidden'\n              );\n          },\n        });\n      }\n\n      this.addListener(this.$fieldSearch, 'input', () => {\n        let val = this.$fieldSearch.val().toLowerCase().replace(/['\"]/g, '');\n        if (!val) {\n          this.$fieldLibrary.find('.filtered').removeClass('filtered');\n          this.$clearFieldSearchBtn.addClass('hidden');\n          return;\n        }\n\n        this.$clearFieldSearchBtn.removeClass('hidden');\n        let $matches = this.$fields\n          .filter(`[data-keywords*=\"${val}\"]`)\n          .add(\n            this.$fieldGroups\n              .filter(`[data-name*=\"${val}\"]`)\n              .children('.fld-element')\n          )\n          .removeClass('filtered');\n        this.$fields.not($matches).addClass('filtered');\n\n        // hide any groups that don't have any results\n        for (let i = 0; i < this.$fieldGroups.length; i++) {\n          let $group = this.$fieldGroups.eq(i);\n          if ($group.find('.fld-element:not(.hidden):not(.filtered)').length) {\n            $group.removeClass('filtered');\n          } else {\n            $group.addClass('filtered');\n          }\n        }\n      });\n\n      this.addListener(this.$fieldSearch, 'keydown', (ev) => {\n        switch (ev.keyCode) {\n          case Garnish.ESC_KEY:\n            this.$fieldSearch.val('').trigger('input');\n            break;\n          case Garnish.RETURN_KEY:\n            // they most likely don't want to submit the form from here\n            ev.preventDefault();\n            break;\n        }\n      });\n\n      // Clear the search when the X button is clicked\n      this.addListener(this.$clearFieldSearchBtn, 'click', () => {\n        this.$fieldSearch.val('').trigger('input');\n      });\n    },\n\n    initTab: function ($tab) {\n      if (this.settings.customizableTabs) {\n        let $editBtn = $tab.find('.tabs .settings');\n        $('<div class=\"menu\" data-align=\"center\"/>')\n          .insertAfter($editBtn)\n          .append(\n            $('<ul/>')\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'rename',\n                    text: Craft.t('app', 'Rename'),\n                  })\n                )\n              )\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'remove',\n                    text: Craft.t('app', 'Remove'),\n                  })\n                )\n              )\n          )\n          .append($('<hr/>'))\n          .append(\n            $('<ul/>')\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'moveLeft',\n                    text: Craft.t('app', 'Move to the left'),\n                  })\n                )\n              )\n              .append(\n                $('<li/>').append(\n                  $('<a/>', {\n                    'data-action': 'moveRight',\n                    text: Craft.t('app', 'Move to the right'),\n                  })\n                )\n              )\n          );\n\n        let menuBtn = new Garnish.MenuBtn($editBtn, {\n          onOptionSelect: this.onTabOptionSelect.bind(this),\n        });\n        menuBtn.menu.on('show', () => {\n          if ($tab.prev('.fld-tab').length) {\n            menuBtn.menu.$container\n              .find('[data-action=moveLeft]')\n              .removeClass('disabled');\n          } else {\n            menuBtn.menu.$container\n              .find('[data-action=moveLeft]')\n              .addClass('disabled');\n          }\n\n          if ($tab.next('.fld-tab').length) {\n            menuBtn.menu.$container\n              .find('[data-action=moveRight]')\n              .removeClass('disabled');\n          } else {\n            menuBtn.menu.$container\n              .find('[data-action=moveRight]')\n              .addClass('disabled');\n          }\n        });\n      }\n\n      // initialize the elements\n      let $elements = $tab.children('.fld-tabcontent').children();\n\n      for (let i = 0; i < $elements.length; i++) {\n        this.initElement($($elements[i]));\n      }\n    },\n\n    initElement: function ($element) {\n      new Craft.FieldLayoutDesigner.Element(this, $element);\n    },\n\n    onTabOptionSelect: function (option) {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      let $option = $(option);\n      let $tab = $option.data('menu').$anchor.parent().parent().parent();\n      let action = $option.data('action');\n\n      switch (action) {\n        case 'rename':\n          this.renameTab($tab);\n          break;\n        case 'remove':\n          this.removeTab($tab);\n          break;\n        case 'moveLeft':\n          let $prev = $tab.prev('.fld-tab');\n          if ($prev.length) {\n            $tab.insertBefore($prev);\n          }\n          break;\n        case 'moveRight':\n          let $next = $tab.next('.fld-tab');\n          if ($next.length) {\n            $tab.insertAfter($next);\n          }\n          break;\n      }\n    },\n\n    renameTab: function ($tab) {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      const $labelSpan = $tab.find('.tabs .tab span');\n      const oldName = $labelSpan.text();\n      const newName = this.promptForTabName(oldName);\n\n      if (newName && newName !== oldName) {\n        $labelSpan.text(newName);\n        $tab\n          .find('.placement-input')\n          .attr('name', this.getElementPlacementInputName(newName));\n      }\n    },\n\n    promptForTabName: function (oldName) {\n      return Craft.escapeHtml(\n        prompt(Craft.t('app', 'Give your tab a name.'), oldName)\n      );\n    },\n\n    removeTab: function ($tab) {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      // Find all the fields in this tab\n      let $fields = $tab.find('.fld-element');\n\n      for (let i = 0; i < $fields.length; i++) {\n        let attribute = $($fields[i]).attr('data-attribute');\n        this.removeFieldByHandle(attribute);\n      }\n\n      this.tabGrid.removeItems($tab);\n      this.tabDrag.removeItems($tab);\n\n      $tab.remove();\n    },\n\n    removeField: function ($field) {\n      let attribute = $field.attr('data-attribute');\n\n      $field.remove();\n\n      this.removeFieldByHandle(attribute);\n      this.tabGrid.refreshCols(true);\n    },\n\n    removeFieldByHandle: function (attribute) {\n      this.$fields\n        .filter(`[data-attribute=\"${attribute}\"]:first`)\n        .removeClass('hidden')\n        .closest('.fld-field-group')\n        .removeClass('hidden');\n    },\n\n    addTab: function () {\n      if (!this.settings.customizableTabs) {\n        return;\n      }\n\n      const name = this.promptForTabName();\n      if (!name) {\n        return;\n      }\n\n      const $tab = $(`\n<div class=\"fld-tab\">\n  <div class=\"tabs\">\n    <div class=\"tab sel draggable\">\n      <span>${name}</span>\n      <a class=\"settings icon\" title=\"${Craft.t('app', 'Rename')}\"></a>\n    </div>\n  </div>\n  <div class=\"fld-tabcontent\"></div>\n</div>\n`).appendTo(this.$tabContainer);\n\n      this.tabGrid.addItems($tab);\n      this.tabDrag.addItems($tab);\n\n      this.initTab($tab);\n    },\n\n    getElementPlacementInputName: function (tabName) {\n      return this.settings.elementPlacementInputName.replace(\n        /__TAB_NAME__/g,\n        Craft.encodeUriComponent(tabName)\n      );\n    },\n  },\n  {\n    defaults: {\n      customizableTabs: true,\n      customizableUi: true,\n      elementPlacementInputName: 'elementPlacements[__TAB_NAME__][]',\n      elementConfigInputName: 'elementConfigs[__ELEMENT_KEY__]',\n    },\n  }\n);\n\nCraft.FieldLayoutDesigner.Element = Garnish.Base.extend({\n  designer: null,\n  $container: null,\n  $placementInput: null,\n  $configInput: null,\n  $settingsContainer: null,\n  $editBtn: null,\n\n  config: null,\n  isField: false,\n  attribute: null,\n  requirable: false,\n  key: null,\n  hasCustomWidth: false,\n  hasSettings: false,\n  hud: null,\n\n  init: function (designer, $container) {\n    this.designer = designer;\n    this.$container = $container;\n    this.$container.data('fld-element', this);\n\n    this.config = this.$container.data('config');\n    if (!$.isPlainObject(this.config)) {\n      this.config = {};\n    }\n    this.config.type = this.$container.data('type');\n\n    this.isField = this.$container.hasClass('fld-field');\n    this.requirable =\n      this.isField && Garnish.hasAttr(this.$container, 'data-requirable');\n    this.key = Craft.randomString(10);\n\n    if (this.isField) {\n      this.attribute = this.$container.data('attribute');\n    }\n\n    let settingsHtml = this.$container.data('settings-html');\n    let isRequired =\n      this.requirable && this.$container.hasClass('fld-required');\n    this.hasCustomWidth =\n      this.designer.settings.customizableUi &&\n      Garnish.hasAttr(this.$container, 'data-has-custom-width');\n    this.hasSettings = settingsHtml || this.requirable;\n\n    if (this.hasSettings) {\n      // swap the __ELEMENT_KEY__ placeholder for the actual element key\n      settingsHtml = settingsHtml\n        ? settingsHtml.replace(/\\b__ELEMENT_KEY__\\b/g, this.key)\n        : '';\n\n      // create the setting container\n      this.$settingsContainer = $('<div/>', {\n        class: 'hidden',\n      });\n\n      // create the edit button\n      this.$editBtn = $('<a/>', {\n        role: 'button',\n        tabindex: 0,\n        class: 'settings icon',\n        title: Craft.t('app', 'Edit'),\n      });\n\n      this.$editBtn.on('click', () => {\n        if (!this.hud) {\n          this.createSettingsHud(settingsHtml, isRequired);\n        } else {\n          this.hud.show();\n          this.hud.updateSizeAndPosition(true);\n        }\n      });\n    }\n\n    this.initUi();\n\n    // cleanup\n    this.$container.attr('data-config', null);\n    this.$container.attr('data-keywords', null);\n    this.$container.attr('data-settings-html', null);\n  },\n\n  initUi: function () {\n    this.$placementInput = $('<input/>', {\n      class: 'placement-input',\n      type: 'hidden',\n      name: '',\n      value: this.key,\n    }).appendTo(this.$container);\n    this.updatePlacementInput();\n\n    this.$configInput = $('<input/>', {\n      type: 'hidden',\n      name: this.designer.settings.elementConfigInputName.replace(\n        /\\b__ELEMENT_KEY__\\b/g,\n        this.key\n      ),\n    }).appendTo(this.$container);\n    this.updateConfigInput();\n\n    if (this.hasCustomWidth) {\n      let widthSlider = new Craft.SlidePicker(this.config.width || 100, {\n        min: 25,\n        max: 100,\n        step: 25,\n        valueLabel: (width) => {\n          return Craft.t('app', '{pct} width', {pct: `${width}%`});\n        },\n        onChange: (width) => {\n          this.config.width = width;\n          this.updateConfigInput();\n        },\n      });\n      widthSlider.$container.appendTo(this.$container);\n    }\n\n    if (this.hasSettings) {\n      this.$editBtn.appendTo(this.$container);\n    }\n  },\n\n  createSettingsHud: function (settingsHtml, isRequired) {\n    let bodyHtml = `\n<div class=\"fld-element-settings\">\n  ${settingsHtml}\n  <div class=\"hud-footer\">\n    <div class=\"buttons right\">\n      <button class=\"btn submit\" type=\"submit\">${Craft.t(\n        'app',\n        'Apply'\n      )}</button>\n      <div class=\"spinner hidden\"></div>\n    </div>\n  </div>\n</div>\n`;\n    this.hud = new Garnish.HUD(this.$container, bodyHtml, {\n      onShow: (e) => {\n        // Hold off a sec until it's positioned...\n        Garnish.requestAnimationFrame(() => {\n          // Focus on the first text input\n          this.hud.$main.find('.text:first').trigger('focus');\n        });\n      },\n      onSubmit: () => {\n        this.applyHudSettings();\n      },\n    });\n\n    Craft.initUiElements(this.hud.$main);\n\n    if (this.requirable) {\n      let $lightswitchField = Craft.ui\n        .createLightswitchField({\n          label: Craft.t('app', 'Required'),\n          id: `${this.key}-required`,\n          name: 'required',\n          on: isRequired,\n        })\n        .prependTo(this.hud.$main);\n    }\n\n    this.trigger('createSettingsHud');\n  },\n\n  applyHudSettings: function () {\n    this.hud.$body.serializeArray().forEach(({name, value}) => {\n      this.config[name] = value;\n    });\n    this.updateConfigInput();\n\n    // update the UI\n    let $spinner = this.hud.$body.find('.spinner').removeClass('hidden');\n\n    Craft.sendActionRequest('POST', 'fields/render-layout-element-selector', {\n      data: {\n        config: this.config,\n      },\n    })\n      .then((response) => {\n        $spinner.addClass('hidden');\n        this.$editBtn.detach();\n        this.$container.html($(response.data.html).html());\n        this.initUi();\n        this.updateRequiredClass();\n        this.hud.hide();\n      })\n      .catch((e) => {\n        // oh well, not worth fussing over\n        console.error(e);\n        $spinner.addClass('hidden');\n        this.updateRequiredClass();\n        this.hud.hide();\n      });\n  },\n\n  updatePlacementInput: function () {\n    let $tab = this.$container.closest('.fld-tab').find('.tab span');\n    if (!$tab.length) {\n      return;\n    }\n    let inputName = this.designer.getElementPlacementInputName($tab.text());\n    this.$placementInput.attr('name', inputName);\n  },\n\n  updateConfigInput: function () {\n    this.$configInput.val(JSON.stringify(this.config));\n  },\n\n  updateRequiredClass: function () {\n    if (!this.requirable) {\n      return;\n    }\n\n    if (this.config.required) {\n      this.$container.addClass('fld-required');\n    } else {\n      this.$container.removeClass('fld-required');\n    }\n  },\n});\n\nCraft.FieldLayoutDesigner.BaseDrag = Garnish.Drag.extend({\n  designer: null,\n  $insertion: null,\n  showingInsertion: false,\n  $caboose: null,\n\n  /**\n   * Constructor\n   */\n  init: function (designer, settings) {\n    this.designer = designer;\n    this.base(this.findItems(), settings);\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n\n    // Create the insertion\n    this.$insertion = this.createInsertion();\n\n    // Add the caboose\n    this.$caboose = this.createCaboose();\n    this.$items = $().add(this.$items.add(this.$caboose));\n\n    Garnish.$bod.addClass('dragging');\n  },\n\n  removeCaboose: function () {\n    this.$items = this.$items.not(this.$caboose);\n    this.$caboose.remove();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.$insertion.insertBefore(this.$draggee);\n    this.$draggee.detach();\n    this.$items = $().add(this.$items.not(this.$draggee).add(this.$insertion));\n    this.showingInsertion = true;\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.$insertion.replaceWith(this.$draggee);\n    this.$items = $().add(this.$items.not(this.$insertion).add(this.$draggee));\n    this.showingInsertion = false;\n  },\n\n  /**\n   * Sets the item midpoints up front so we don't have to keep checking on every mouse move\n   */\n  setMidpoints: function () {\n    for (let i = 0; i < this.$items.length; i++) {\n      let $item = $(this.$items[i]);\n      let offset = $item.offset();\n\n      // Skip library elements\n      if ($item.hasClass('unused')) {\n        continue;\n      }\n\n      $item.data('midpoint', {\n        left: offset.left + $item.outerWidth() / 2,\n        top: offset.top + $item.outerHeight() / 2,\n      });\n    }\n  },\n\n  /**\n   * Returns the closest item to the cursor.\n   */\n  getClosestItem: function () {\n    this.getClosestItem._closestItem = null;\n    this.getClosestItem._closestItemMouseDiff = null;\n\n    for (\n      this.getClosestItem._i = 0;\n      this.getClosestItem._i < this.$items.length;\n      this.getClosestItem._i++\n    ) {\n      this.getClosestItem._$item = $(this.$items[this.getClosestItem._i]);\n\n      this.getClosestItem._midpoint =\n        this.getClosestItem._$item.data('midpoint');\n      if (!this.getClosestItem._midpoint) {\n        continue;\n      }\n\n      this.getClosestItem._mouseDiff = Garnish.getDist(\n        this.getClosestItem._midpoint.left,\n        this.getClosestItem._midpoint.top,\n        this.mouseX,\n        this.mouseY\n      );\n\n      if (\n        this.getClosestItem._closestItem === null ||\n        this.getClosestItem._mouseDiff <\n          this.getClosestItem._closestItemMouseDiff\n      ) {\n        this.getClosestItem._closestItem = this.getClosestItem._$item[0];\n        this.getClosestItem._closestItemMouseDiff =\n          this.getClosestItem._mouseDiff;\n      }\n    }\n\n    return this.getClosestItem._closestItem;\n  },\n\n  checkForNewClosestItem: function () {\n    // Is there a new closest item?\n    this.checkForNewClosestItem._closestItem = this.getClosestItem();\n\n    if (this.checkForNewClosestItem._closestItem === this.$insertion[0]) {\n      return;\n    }\n\n    if (\n      this.showingInsertion &&\n      $.inArray(this.$insertion[0], this.$items) <\n        $.inArray(this.checkForNewClosestItem._closestItem, this.$items) &&\n      $.inArray(this.checkForNewClosestItem._closestItem, this.$caboose) === -1\n    ) {\n      this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem);\n    } else {\n      this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem);\n    }\n\n    this.$items = $().add(this.$items.add(this.$insertion));\n    this.showingInsertion = true;\n    this.designer.tabGrid.refreshCols(true);\n    this.setMidpoints();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    if (this.showingInsertion) {\n      this.swapInsertionWithDraggee();\n    }\n\n    this.removeCaboose();\n\n    this.designer.tabGrid.refreshCols(true);\n\n    // return the helpers to the draggees\n    let offset = this.$draggee.offset();\n    if (!offset || (offset.top === 0 && offset.left === 0)) {\n      this.$draggee\n        .css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n          opacity: 0,\n        })\n        .velocity({opacity: 1}, Garnish.FX_DURATION);\n      this.helpers[0].velocity({opacity: 0}, Garnish.FX_DURATION, () => {\n        this._showDraggee();\n      });\n    } else {\n      this.returnHelpersToDraggees();\n    }\n\n    this.base();\n\n    Garnish.$bod.removeClass('dragging');\n  },\n});\n\nCraft.FieldLayoutDesigner.TabDrag = Craft.FieldLayoutDesigner.BaseDrag.extend({\n  /**\n   * Constructor\n   */\n  init: function (designer) {\n    let settings = {\n      handle: '.tab',\n    };\n\n    this.base(designer, settings);\n  },\n\n  findItems: function () {\n    return this.designer.$tabContainer.find('> div.fld-tab');\n  },\n\n  /**\n   * On Drag Start\n   */\n  onDragStart: function () {\n    this.base();\n    this.swapDraggeeWithInsertion();\n    this.setMidpoints();\n  },\n\n  swapDraggeeWithInsertion: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$draggee);\n    this.designer.tabGrid.addItems(this.$insertion);\n  },\n\n  swapInsertionWithDraggee: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$insertion);\n    this.designer.tabGrid.addItems(this.$draggee);\n  },\n\n  /**\n   * On Drag\n   */\n  onDrag: function () {\n    this.checkForNewClosestItem();\n    this.base();\n  },\n\n  /**\n   * On Drag Stop\n   */\n  onDragStop: function () {\n    this.base();\n\n    // \"show\" the tab, but make it invisible\n    this.$draggee.css({\n      display: this.draggeeDisplay,\n      visibility: 'hidden',\n    });\n  },\n\n  /**\n   * Creates the caboose\n   */\n  createCaboose: function () {\n    let $caboose = $('<div class=\"fld-tab fld-tab-caboose\"/>').appendTo(\n      this.designer.$tabContainer\n    );\n    this.designer.tabGrid.addItems($caboose);\n    return $caboose;\n  },\n\n  /**\n   * Removes the caboose\n   */\n  removeCaboose: function () {\n    this.base();\n    this.designer.tabGrid.removeItems(this.$caboose);\n  },\n\n  /**\n   * Creates the insertion\n   */\n  createInsertion: function () {\n    let $tab = this.$draggee.find('.tab');\n\n    return $(`\n<div class=\"fld-tab fld-insertion\" style=\"height: ${this.$draggee.height()}px;\">\n  <div class=\"tabs\"><div class=\"tab sel draggable\" style=\"width: ${$tab.width()}px; height: ${$tab.height()}px;\"></div></div>\n  <div class=\"fld-tabcontent\" style=\"height: ${this.$draggee\n    .find('.fld-tabcontent')\n    .height()}px;\"></div>\n</div>\n`);\n  },\n});\n\nCraft.FieldLayoutDesigner.ElementDrag =\n  Craft.FieldLayoutDesigner.BaseDrag.extend({\n    draggingLibraryElement: false,\n    draggingField: false,\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      this.base();\n\n      // Are we dragging an element from the library?\n      this.draggingLibraryElement = this.$draggee.hasClass('unused');\n\n      // Is it a field?\n      this.draggingField = this.$draggee.hasClass('fld-field');\n\n      // keep UI elements visible\n      if (this.draggingLibraryElement && !this.draggingField) {\n        this.$draggee.css({\n          display: this.draggeeDisplay,\n          visibility: 'visible',\n        });\n      }\n\n      // Swap the draggee with the insertion if dragging a selected item\n      if (!this.draggingLibraryElement) {\n        this.swapDraggeeWithInsertion();\n      }\n\n      this.setMidpoints();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      if (this.isDraggeeMandatory() || this.isHoveringOverTab()) {\n        this.checkForNewClosestItem();\n      } else if (this.showingInsertion) {\n        this.$insertion.remove();\n        this.$items = $().add(this.$items.not(this.$insertion));\n        this.showingInsertion = false;\n        this.designer.tabGrid.refreshCols(true);\n        this.setMidpoints();\n      }\n\n      this.base();\n    },\n\n    isDraggeeMandatory: function () {\n      return Garnish.hasAttr(this.$draggee, 'data-mandatory');\n    },\n\n    isHoveringOverTab: function () {\n      for (let i = 0; i < this.designer.tabGrid.$items.length; i++) {\n        if (\n          Garnish.hitTest(\n            this.mouseX,\n            this.mouseY,\n            this.designer.tabGrid.$items.eq(i)\n          )\n        ) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    findItems: function () {\n      // Return all of the used + unused fields\n      return this.designer.$tabContainer\n        .find('.fld-element')\n        .add(this.designer.$sidebar.find('.fld-element'));\n    },\n\n    /**\n     * Creates the caboose\n     */\n    createCaboose: function () {\n      let $caboose = $();\n      let $fieldContainers = this.designer.$tabContainer.find(\n        '> .fld-tab > .fld-tabcontent'\n      );\n\n      for (let i = 0; i < $fieldContainers.length; i++) {\n        $caboose = $caboose.add($('<div/>').appendTo($fieldContainers[i]));\n      }\n\n      return $caboose;\n    },\n\n    /**\n     * Creates the insertion\n     */\n    createInsertion: function () {\n      return $(\n        `<div class=\"fld-element fld-insertion\" style=\"height: ${this.$draggee.outerHeight()}px;\"/>`\n      );\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      let showingInsertion = this.showingInsertion;\n      if (showingInsertion) {\n        if (this.draggingLibraryElement) {\n          // Create a new element based on that one\n          let $element = this.$draggee.clone().removeClass('unused');\n          this.designer.initElement($element);\n\n          if (this.draggingField) {\n            // Hide the library field\n            this.$draggee\n              .css({visibility: 'inherit', display: 'field'})\n              .addClass('hidden');\n\n            // Hide the group too?\n            if (\n              this.$draggee.siblings('.fld-field:not(.hidden)').length === 0\n            ) {\n              this.$draggee.closest('.fld-field-group').addClass('hidden');\n            }\n          }\n\n          // Set this.$draggee to the clone, as if we were dragging that all along\n          this.$draggee = $element;\n\n          // Remember it for later\n          this.addItems($element);\n        }\n      } else if (!this.draggingLibraryElement) {\n        let $libraryElement = this.draggingField\n          ? this.designer.$fields.filter(\n              `[data-attribute=\"${this.$draggee.data('attribute')}\"]:first`\n            )\n          : this.designer.$uiLibraryElements.filter(\n              `[data-type=\"${this.$draggee\n                .data('type')\n                .replace(/\\\\/g, '\\\\\\\\')}\"]:first`\n            );\n\n        if (this.draggingField) {\n          // show the field in the library\n          $libraryElement.removeClass('hidden');\n          $libraryElement.closest('.fld-field-group').removeClass('hidden');\n        }\n\n        // forget the original element\n        this.removeItems(this.$draggee);\n\n        // Set this.$draggee to the library element, as if we were dragging that all along\n        this.$draggee = $libraryElement;\n      }\n\n      this.base();\n\n      this.$draggee.css({\n        display: this.draggeeDisplay,\n        visibility:\n          this.draggingField || showingInsertion ? 'hidden' : 'visible',\n      });\n\n      if (showingInsertion) {\n        this.$draggee.data('fld-element').updatePlacementInput();\n      }\n    },\n  });\n","/** global: Craft */\n/** global: Garnish */\n/**\n * FieldToggle\n */\nCraft.FieldToggle = Garnish.Base.extend({\n  $toggle: null,\n  targetPrefix: null,\n  targetSelector: null,\n  reverseTargetSelector: null,\n\n  _$target: null,\n  _$reverseTarget: null,\n  type: null,\n\n  init: function (toggle) {\n    this.$toggle = $(toggle);\n\n    // Is this already a field toggle?\n    if (this.$toggle.data('fieldtoggle')) {\n      console.warn('Double-instantiating a field toggle on an element');\n      this.$toggle.data('fieldtoggle').destroy();\n    }\n\n    this.$toggle.data('fieldtoggle', this);\n\n    this.type = this.getType();\n\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.targetPrefix = this.$toggle.attr('data-target-prefix') || '';\n    } else {\n      this.targetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('target')\n      );\n      this.reverseTargetSelector = this.normalizeTargetSelector(\n        this.$toggle.data('reverse-target')\n      );\n    }\n\n    this.findTargets();\n\n    switch (this.type) {\n      case 'link':\n        this.addListener(this.$toggle, 'click', 'onToggleChange');\n        break;\n      case 'fieldset':\n        this.addListener(\n          this.$toggle.find('input'),\n          'change',\n          'onToggleChange'\n        );\n        break;\n      default:\n        this.addListener(this.$toggle, 'change', 'onToggleChange');\n        this.onToggleChange();\n    }\n  },\n\n  normalizeTargetSelector: function (selector) {\n    if (selector && !selector.match(/^[#\\.]/)) {\n      selector = '#' + selector;\n    }\n\n    return selector;\n  },\n\n  getType: function () {\n    let nodeName = this.$toggle.prop('nodeName');\n    if (\n      (nodeName === 'INPUT' && this.$toggle.attr('type') === 'checkbox') ||\n      this.$toggle.attr('role') === 'checkbox' ||\n      this.$toggle.attr('role') === 'switch'\n    ) {\n      return 'checkbox';\n    }\n\n    switch (nodeName) {\n      case 'SELECT':\n        if (Garnish.hasAttr(this.$toggle, 'data-boolean-menu')) {\n          return 'booleanMenu';\n        }\n        return 'select';\n      case 'A':\n        return 'link';\n      case 'FIELDSET':\n        return 'fieldset';\n    }\n\n    console.warn('Unexpected field toggle:', this.$toggle[0]);\n  },\n\n  findTargets: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      var toggleVal = this.getToggleVal();\n      this._$target = $(\n        this.normalizeTargetSelector(this.targetPrefix + this.getToggleVal())\n      );\n    } else {\n      if (this.targetSelector) {\n        this._$target = $(this.targetSelector);\n      }\n\n      if (this.reverseTargetSelector) {\n        this._$reverseTarget = $(this.reverseTargetSelector);\n      }\n    }\n  },\n\n  getToggleVal: function () {\n    switch (this.type) {\n      case 'checkbox':\n        if (typeof this.$toggle.prop('checked') !== 'undefined') {\n          return this.$toggle.prop('checked');\n        }\n        return this.$toggle.attr('aria-checked') === 'true';\n\n      case 'booleanMenu':\n        const boolean = this.$toggle.data('boolean');\n        if (typeof boolean !== 'undefined') {\n          return boolean;\n        }\n        const val = this.$toggle.val();\n        return val && val !== '0';\n\n      default:\n        let postVal;\n        if (this.type === 'fieldset') {\n          postVal = this.$toggle.find('input:checked:first').val();\n        } else {\n          postVal = Garnish.getInputPostVal(this.$toggle);\n        }\n\n        // Normalize the value\n        return typeof postVal === 'undefined' || postVal === null\n          ? null\n          : postVal.replace(/[^\\w]+/g, '-');\n    }\n  },\n\n  onToggleChange: function () {\n    if (this.type === 'select' || this.type === 'fieldset') {\n      this.hideTarget(this._$target);\n      this.findTargets();\n      this.showTarget(this._$target);\n    } else {\n      this.findTargets();\n\n      if (this.type === 'link') {\n        this.onToggleChange._show =\n          this.$toggle.hasClass('collapsed') ||\n          !this.$toggle.hasClass('expanded');\n      } else {\n        this.onToggleChange._show = !!this.getToggleVal();\n      }\n\n      if (this.onToggleChange._show) {\n        this.showTarget(this._$target);\n        this.hideTarget(this._$reverseTarget);\n      } else {\n        this.hideTarget(this._$target);\n        this.showTarget(this._$reverseTarget);\n      }\n\n      delete this.onToggleChange._show;\n    }\n  },\n\n  showTarget: function ($target) {\n    if ($target && $target.length) {\n      this.showTarget._currentHeight = $target.height();\n\n      $target.removeClass('hidden');\n\n      if (this.type !== 'select' && this.type !== 'fieldset') {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('collapsed');\n          this.$toggle.addClass('expanded');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.prop('nodeName') !== 'SPAN') {\n              $t.height('auto');\n              this.showTarget._targetHeight = $t.height();\n              $t.css({\n                height: this.showTarget._currentHeight,\n                overflow: 'hidden',\n              });\n\n              $t.velocity('stop');\n\n              $t.velocity(\n                {height: this.showTarget._targetHeight},\n                'fast',\n                function () {\n                  $t.css({\n                    height: '',\n                    overflow: '',\n                  });\n                }\n              );\n            }\n          })($target.eq(i));\n        }\n\n        delete this.showTarget._targetHeight;\n      }\n\n      delete this.showTarget._currentHeight;\n\n      // Trigger a resize event in case there are any grids in the target that need to initialize\n      Garnish.$win.trigger('resize');\n    }\n  },\n\n  hideTarget: function ($target) {\n    if ($target && $target.length) {\n      if (this.type === 'select' || this.type === 'fieldset') {\n        $target.addClass('hidden');\n      } else {\n        if (this.type === 'link') {\n          this.$toggle.removeClass('expanded');\n          this.$toggle.addClass('collapsed');\n        }\n\n        for (let i = 0; i < $target.length; i++) {\n          (($t) => {\n            if ($t.hasClass('hidden')) {\n              return;\n            }\n            if ($t.prop('nodeName') === 'SPAN') {\n              $t.addClass('hidden');\n            } else {\n              $t.css('overflow', 'hidden');\n              $t.velocity('stop');\n              $t.velocity({height: 0}, 'fast', function () {\n                $t.addClass('hidden');\n              });\n            }\n          })($target.eq(i));\n        }\n      }\n    }\n  },\n\n  destroy: function () {\n    this.$toggle.removeData('fieldtoggle');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.Grid = Garnish.Base.extend(\n  {\n    $container: null,\n\n    $items: null,\n    items: null,\n    totalCols: null,\n    colGutterDrop: null,\n    colPctWidth: null,\n\n    possibleItemColspans: null,\n    possibleItemPositionsByColspan: null,\n\n    itemPositions: null,\n    itemColspansByPosition: null,\n\n    layouts: null,\n    layout: null,\n    itemHeights: null,\n    leftPadding: null,\n\n    _refreshingCols: false,\n    _refreshColsAfterRefresh: false,\n    _forceRefreshColsAfterRefresh: false,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n\n      // Is this already a grid?\n      if (this.$container.data('grid')) {\n        console.warn('Double-instantiating a grid on an element');\n        this.$container.data('grid').destroy();\n      }\n\n      this.$container.data('grid', this);\n\n      this.setSettings(settings, Craft.Grid.defaults);\n\n      // Set the refreshCols() proxy that container resizes will trigger\n      this.handleContainerHeightProxy = () => {\n        this.refreshCols(false, true);\n      };\n\n      this.$items = this.$container.children(this.settings.itemSelector);\n      this.setItems();\n      this.refreshCols(true, false);\n\n      Garnish.$doc.ready(() => {\n        this.refreshCols(false, false);\n      });\n    },\n\n    addItems: function (items) {\n      this.$items = $().add(this.$items.add(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    removeItems: function (items) {\n      this.$items = $().add(this.$items.not(items));\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    resetItemOrder: function () {\n      this.$items = $().add(this.$items);\n      this.setItems();\n      this.refreshCols(true, true);\n    },\n\n    setItems: function () {\n      this.setItems._ = {};\n\n      this.items = [];\n\n      for (\n        this.setItems._.i = 0;\n        this.setItems._.i < this.$items.length;\n        this.setItems._.i++\n      ) {\n        this.items.push($(this.$items[this.setItems._.i]));\n      }\n\n      delete this.setItems._;\n    },\n\n    refreshCols: function (force) {\n      if (this._refreshingCols) {\n        this._refreshColsAfterRefresh = true;\n        if (force) {\n          this._forceRefreshColsAfterRefresh = true;\n        }\n        return;\n      }\n\n      this._refreshingCols = true;\n\n      if (!this.items.length) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.refreshCols._ = {};\n\n      // Check to see if the grid is actually visible\n      this.refreshCols._.oldHeight = this.$container[0].style.height;\n      this.$container[0].style.height = 1;\n      this.refreshCols._.scrollHeight = this.$container[0].scrollHeight;\n      this.$container[0].style.height = this.refreshCols._.oldHeight;\n\n      if (this.refreshCols._.scrollHeight === 0) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      if (this.settings.cols) {\n        this.refreshCols._.totalCols = this.settings.cols;\n      } else {\n        this.refreshCols._.totalCols = Math.floor(\n          this.$container.width() / this.settings.minColWidth\n        );\n\n        // If we're adding a new column, require an extra 20 pixels in case a scrollbar shows up\n        if (\n          this.totalCols !== null &&\n          this.refreshCols._.totalCols > this.totalCols\n        ) {\n          this.refreshCols._.totalCols = Math.floor(\n            (this.$container.width() - 20) / this.settings.minColWidth\n          );\n        }\n\n        if (\n          this.settings.maxCols &&\n          this.refreshCols._.totalCols > this.settings.maxCols\n        ) {\n          this.refreshCols._.totalCols = this.settings.maxCols;\n        }\n      }\n\n      if (this.refreshCols._.totalCols === 0) {\n        this.refreshCols._.totalCols = 1;\n      }\n\n      // Same number of columns as before?\n      if (force !== true && this.totalCols === this.refreshCols._.totalCols) {\n        this.completeRefreshCols();\n        return;\n      }\n\n      this.totalCols = this.refreshCols._.totalCols;\n      this.colGutterDrop =\n        (this.settings.gutter * (this.totalCols - 1)) / this.totalCols;\n\n      // Temporarily stop listening to container resizes\n      this.removeListener(this.$container, 'resize');\n\n      if (this.settings.fillMode === 'grid') {\n        this.refreshCols._.itemIndex = 0;\n\n        while (this.refreshCols._.itemIndex < this.items.length) {\n          // Append the next X items and figure out which one is the tallest\n          this.refreshCols._.tallestItemHeight = -1;\n          this.refreshCols._.colIndex = 0;\n\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.itemHeight = this.items[this.refreshCols._.i]\n              .height('auto')\n              .height();\n\n            if (\n              this.refreshCols._.itemHeight >\n              this.refreshCols._.tallestItemHeight\n            ) {\n              this.refreshCols._.tallestItemHeight =\n                this.refreshCols._.itemHeight;\n            }\n\n            this.refreshCols._.colIndex++;\n          }\n\n          if (this.settings.snapToGrid) {\n            this.refreshCols._.remainder =\n              this.refreshCols._.tallestItemHeight % this.settings.snapToGrid;\n\n            if (this.refreshCols._.remainder) {\n              this.refreshCols._.tallestItemHeight +=\n                this.settings.snapToGrid - this.refreshCols._.remainder;\n            }\n          }\n\n          // Now set their heights to the tallest one\n          for (\n            this.refreshCols._.i = this.refreshCols._.itemIndex;\n            this.refreshCols._.i <\n              this.refreshCols._.itemIndex + this.totalCols &&\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.items[this.refreshCols._.i].height(\n              this.refreshCols._.tallestItemHeight\n            );\n          }\n\n          // set the this.refreshCols._.itemIndex pointer to the next one up\n          this.refreshCols._.itemIndex += this.totalCols;\n        }\n      } else {\n        this.removeListener(this.$items, 'resize');\n\n        // If there's only one column, sneak out early\n        if (this.totalCols === 1) {\n          this.$container.height('auto');\n          this.$items\n            .show()\n            .css({\n              position: 'relative',\n              width: 'auto',\n              top: 0,\n            })\n            .css(Craft.left, 0);\n        } else {\n          this.$items.css('position', 'absolute');\n          this.colPctWidth = 100 / this.totalCols;\n\n          // The setup\n\n          this.layouts = [];\n\n          this.itemPositions = [];\n          this.itemColspansByPosition = [];\n\n          // Figure out all of the possible colspans for each item,\n          // as well as all the possible positions for each item at each of its colspans\n\n          this.possibleItemColspans = [];\n          this.possibleItemPositionsByColspan = [];\n          this.itemHeightsByColspan = [];\n\n          for (\n            this.refreshCols._.item = 0;\n            this.refreshCols._.item < this.items.length;\n            this.refreshCols._.item++\n          ) {\n            this.possibleItemColspans[this.refreshCols._.item] = [];\n            this.possibleItemPositionsByColspan[this.refreshCols._.item] = {};\n            this.itemHeightsByColspan[this.refreshCols._.item] = {};\n\n            this.refreshCols._.$item =\n              this.items[this.refreshCols._.item].show();\n            this.refreshCols._.positionRight =\n              this.refreshCols._.$item.data('position') === 'right';\n            this.refreshCols._.positionLeft =\n              this.refreshCols._.$item.data('position') === 'left';\n            this.refreshCols._.minColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('min-colspan')\n              ? this.refreshCols._.$item.data('min-colspan')\n              : 1;\n            this.refreshCols._.maxColspan = this.refreshCols._.$item.data(\n              'colspan'\n            )\n              ? this.refreshCols._.$item.data('colspan')\n              : this.refreshCols._.$item.data('max-colspan')\n              ? this.refreshCols._.$item.data('max-colspan')\n              : this.totalCols;\n\n            if (this.refreshCols._.minColspan > this.totalCols) {\n              this.refreshCols._.minColspan = this.totalCols;\n            }\n            if (this.refreshCols._.maxColspan > this.totalCols) {\n              this.refreshCols._.maxColspan = this.totalCols;\n            }\n\n            for (\n              this.refreshCols._.colspan = this.refreshCols._.minColspan;\n              this.refreshCols._.colspan <= this.refreshCols._.maxColspan;\n              this.refreshCols._.colspan++\n            ) {\n              // Get the height for this colspan\n              this.refreshCols._.$item.css(\n                'width',\n                this.getItemWidthCss(this.refreshCols._.colspan)\n              );\n              this.itemHeightsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = this.refreshCols._.$item.outerHeight();\n\n              this.possibleItemColspans[this.refreshCols._.item].push(\n                this.refreshCols._.colspan\n              );\n              this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                this.refreshCols._.colspan\n              ] = [];\n\n              if (this.refreshCols._.positionLeft) {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition = 0;\n              } else if (this.refreshCols._.positionRight) {\n                this.refreshCols._.minPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n                this.refreshCols._.maxPosition = this.refreshCols._.minPosition;\n              } else {\n                this.refreshCols._.minPosition = 0;\n                this.refreshCols._.maxPosition =\n                  this.totalCols - this.refreshCols._.colspan;\n              }\n\n              for (\n                this.refreshCols._.position = this.refreshCols._.minPosition;\n                this.refreshCols._.position <= this.refreshCols._.maxPosition;\n                this.refreshCols._.position++\n              ) {\n                this.possibleItemPositionsByColspan[this.refreshCols._.item][\n                  this.refreshCols._.colspan\n                ].push(this.refreshCols._.position);\n              }\n            }\n          }\n\n          // Find all the possible layouts\n\n          this.refreshCols._.colHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.totalCols;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.colHeights.push(0);\n          }\n\n          this.createLayouts(0, [], [], this.refreshCols._.colHeights, 0);\n\n          // Now find the layout that looks the best.\n\n          // First find the layouts with the highest number of used columns\n          this.refreshCols._.layoutTotalCols = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutTotalCols[this.refreshCols._.i] = 0;\n\n            for (\n              this.refreshCols._.j = 0;\n              this.refreshCols._.j < this.totalCols;\n              this.refreshCols._.j++\n            ) {\n              if (\n                this.layouts[this.refreshCols._.i].colHeights[\n                  this.refreshCols._.j\n                ]\n              ) {\n                this.refreshCols._.layoutTotalCols[this.refreshCols._.i]++;\n              }\n            }\n          }\n\n          this.refreshCols._.highestTotalCols = Math.max.apply(\n            null,\n            this.refreshCols._.layoutTotalCols\n          );\n\n          // Filter out the ones that aren't using as many columns as they could be\n          for (\n            this.refreshCols._.i = this.layouts.length - 1;\n            this.refreshCols._.i >= 0;\n            this.refreshCols._.i--\n          ) {\n            if (\n              this.refreshCols._.layoutTotalCols[this.refreshCols._.i] !==\n              this.refreshCols._.highestTotalCols\n            ) {\n              this.layouts.splice(this.refreshCols._.i, 1);\n            }\n          }\n\n          // Find the layout(s) with the least overall height\n          this.refreshCols._.layoutHeights = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.layouts.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.layoutHeights.push(\n              Math.max.apply(\n                null,\n                this.layouts[this.refreshCols._.i].colHeights\n              )\n            );\n          }\n\n          this.refreshCols._.shortestHeight = Math.min.apply(\n            null,\n            this.refreshCols._.layoutHeights\n          );\n          this.refreshCols._.shortestLayouts = [];\n          this.refreshCols._.emptySpaces = [];\n\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.refreshCols._.layoutHeights.length;\n            this.refreshCols._.i++\n          ) {\n            if (\n              this.refreshCols._.layoutHeights[this.refreshCols._.i] ===\n              this.refreshCols._.shortestHeight\n            ) {\n              this.refreshCols._.shortestLayouts.push(\n                this.layouts[this.refreshCols._.i]\n              );\n\n              // Now get its total empty space, including any trailing empty space\n              this.refreshCols._.emptySpace =\n                this.layouts[this.refreshCols._.i].emptySpace;\n\n              for (\n                this.refreshCols._.j = 0;\n                this.refreshCols._.j < this.totalCols;\n                this.refreshCols._.j++\n              ) {\n                this.refreshCols._.emptySpace +=\n                  this.refreshCols._.shortestHeight -\n                  this.layouts[this.refreshCols._.i].colHeights[\n                    this.refreshCols._.j\n                  ];\n              }\n\n              this.refreshCols._.emptySpaces.push(\n                this.refreshCols._.emptySpace\n              );\n            }\n          }\n\n          // And the layout with the least empty space is...\n          this.layout =\n            this.refreshCols._.shortestLayouts[\n              $.inArray(\n                Math.min.apply(null, this.refreshCols._.emptySpaces),\n                this.refreshCols._.emptySpaces\n              )\n            ];\n\n          // Set the item widths and left positions\n          for (\n            this.refreshCols._.i = 0;\n            this.refreshCols._.i < this.items.length;\n            this.refreshCols._.i++\n          ) {\n            this.refreshCols._.css = {\n              width: this.getItemWidthCss(\n                this.layout.colspans[this.refreshCols._.i]\n              ),\n            };\n            this.refreshCols._.css[Craft.left] = this.getItemLeftPosCss(\n              this.layout.positions[this.refreshCols._.i]\n            );\n            this.items[this.refreshCols._.i].css(this.refreshCols._.css);\n          }\n\n          // If every item is at position 0, then let them lay out au naturel\n          if (this.isSimpleLayout()) {\n            this.$container.height('auto');\n            this.$items.css({\n              position: 'relative',\n              top: 0,\n              'margin-bottom': this.settings.gutter + 'px',\n            });\n          } else {\n            this.$items.css('position', 'absolute');\n\n            // Now position the items\n            this.positionItems();\n\n            // Update the positions as the items' heigthts change\n            this.addListener(this.$items, 'resize', 'onItemResize');\n          }\n        }\n      }\n\n      this.completeRefreshCols();\n\n      // Resume container resize listening\n      this.addListener(\n        this.$container,\n        'resize',\n        this.handleContainerHeightProxy\n      );\n\n      this.onRefreshCols();\n    },\n\n    completeRefreshCols: function () {\n      // Delete the internal variable object\n      if (typeof this.refreshCols._ !== 'undefined') {\n        delete this.refreshCols._;\n      }\n\n      this._refreshingCols = false;\n\n      if (this._refreshColsAfterRefresh) {\n        var force = this._forceRefreshColsAfterRefresh;\n        this._refreshColsAfterRefresh = false;\n        this._forceRefreshColsAfterRefresh = false;\n\n        Garnish.requestAnimationFrame(() => {\n          this.refreshCols(force);\n        });\n      }\n    },\n\n    getItemWidth: function (colspan) {\n      return this.colPctWidth * colspan;\n    },\n\n    getItemWidthCss: function (colspan) {\n      return (\n        'calc(' +\n        this.getItemWidth(colspan) +\n        '% - ' +\n        this.colGutterDrop +\n        'px)'\n      );\n    },\n\n    getItemWidthInPx: function (colspan) {\n      return (\n        (this.getItemWidth(colspan) / 100) * this.$container.width() -\n        this.colGutterDrop\n      );\n    },\n\n    getItemLeftPosCss: function (position) {\n      return (\n        'calc(' +\n        '(' +\n        this.getItemWidth(1) +\n        '% + ' +\n        (this.settings.gutter - this.colGutterDrop) +\n        'px) * ' +\n        position +\n        ')'\n      );\n    },\n\n    getItemLeftPosInPx: function (position) {\n      return (\n        ((this.getItemWidth(1) / 100) * this.$container.width() +\n          (this.settings.gutter - this.colGutterDrop)) *\n        position\n      );\n    },\n\n    createLayouts: function (\n      item,\n      prevPositions,\n      prevColspans,\n      prevColHeights,\n      prevEmptySpace\n    ) {\n      new Craft.Grid.LayoutGenerator(this).createLayouts(\n        item,\n        prevPositions,\n        prevColspans,\n        prevColHeights,\n        prevEmptySpace\n      );\n    },\n\n    isSimpleLayout: function () {\n      this.isSimpleLayout._ = {};\n\n      for (\n        this.isSimpleLayout._.i = 0;\n        this.isSimpleLayout._.i < this.layout.positions.length;\n        this.isSimpleLayout._.i++\n      ) {\n        if (this.layout.positions[this.isSimpleLayout._.i] !== 0) {\n          delete this.isSimpleLayout._;\n          return false;\n        }\n      }\n\n      delete this.isSimpleLayout._;\n      return true;\n    },\n\n    positionItems: function () {\n      this.positionItems._ = {};\n\n      this.positionItems._.colHeights = [];\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.totalCols;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.colHeights.push(0);\n      }\n\n      for (\n        this.positionItems._.i = 0;\n        this.positionItems._.i < this.items.length;\n        this.positionItems._.i++\n      ) {\n        this.positionItems._.endingCol =\n          this.layout.positions[this.positionItems._.i] +\n          this.layout.colspans[this.positionItems._.i] -\n          1;\n        this.positionItems._.affectedColHeights = [];\n\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.affectedColHeights.push(\n            this.positionItems._.colHeights[this.positionItems._.col]\n          );\n        }\n\n        this.positionItems._.top = Math.max.apply(\n          null,\n          this.positionItems._.affectedColHeights\n        );\n        if (this.positionItems._.top > 0) {\n          this.positionItems._.top += this.settings.gutter;\n        }\n\n        this.items[this.positionItems._.i].css('top', this.positionItems._.top);\n\n        // Now add the new heights to those columns\n        for (\n          this.positionItems._.col =\n            this.layout.positions[this.positionItems._.i];\n          this.positionItems._.col <= this.positionItems._.endingCol;\n          this.positionItems._.col++\n        ) {\n          this.positionItems._.colHeights[this.positionItems._.col] =\n            this.positionItems._.top +\n            this.itemHeightsByColspan[this.positionItems._.i][\n              this.layout.colspans[this.positionItems._.i]\n            ];\n        }\n      }\n\n      // Set the container height\n      this.$container.height(\n        Math.max.apply(null, this.positionItems._.colHeights)\n      );\n\n      delete this.positionItems._;\n    },\n\n    onItemResize: function (ev) {\n      this.onItemResize._ = {};\n\n      // Prevent this from bubbling up to the container, which has its own resize listener\n      ev.stopPropagation();\n\n      this.onItemResize._.item = $.inArray(ev.currentTarget, this.$items);\n\n      if (this.onItemResize._.item !== -1) {\n        // Update the height and reposition the items\n        this.onItemResize._.newHeight =\n          this.items[this.onItemResize._.item].outerHeight();\n\n        if (\n          this.onItemResize._.newHeight !==\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ]\n        ) {\n          this.itemHeightsByColspan[this.onItemResize._.item][\n            this.layout.colspans[this.onItemResize._.item]\n          ] = this.onItemResize._.newHeight;\n          this.positionItems(false);\n        }\n      }\n\n      delete this.onItemResize._;\n    },\n\n    onRefreshCols: function () {\n      this.trigger('refreshCols');\n      this.settings.onRefreshCols();\n    },\n\n    destroy: function () {\n      this.$container.removeData('grid');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      itemSelector: '.item',\n      cols: null,\n      maxCols: null,\n      minColWidth: 320,\n      gutter: 14,\n      fillMode: 'top',\n      colClass: 'col',\n      snapToGrid: null,\n\n      onRefreshCols: $.noop,\n    },\n  }\n);\n\nCraft.Grid.LayoutGenerator = Garnish.Base.extend({\n  grid: null,\n  _: null,\n\n  init: function (grid) {\n    this.grid = grid;\n  },\n\n  createLayouts: function (\n    item,\n    prevPositions,\n    prevColspans,\n    prevColHeights,\n    prevEmptySpace\n  ) {\n    this._ = {};\n\n    // Loop through all possible colspans\n    for (\n      this._.c = 0;\n      this._.c < this.grid.possibleItemColspans[item].length;\n      this._.c++\n    ) {\n      this._.colspan = this.grid.possibleItemColspans[item][this._.c];\n\n      // Loop through all the possible positions for this colspan,\n      // and find the one that is closest to the top\n\n      this._.tallestColHeightsByPosition = [];\n\n      for (\n        this._.p = 0;\n        this._.p <\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan].length;\n        this._.p++\n      ) {\n        this._.position =\n          this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n            this._.p\n          ];\n\n        this._.colHeightsForPosition = [];\n        this._.endingCol = this._.position + this._.colspan - 1;\n\n        for (\n          this._.col = this._.position;\n          this._.col <= this._.endingCol;\n          this._.col++\n        ) {\n          this._.colHeightsForPosition.push(prevColHeights[this._.col]);\n        }\n\n        this._.tallestColHeightsByPosition[this._.p] = Math.max.apply(\n          null,\n          this._.colHeightsForPosition\n        );\n      }\n\n      // And the shortest position for this colspan is...\n      this._.p = $.inArray(\n        Math.min.apply(null, this._.tallestColHeightsByPosition),\n        this._.tallestColHeightsByPosition\n      );\n      this._.position =\n        this.grid.possibleItemPositionsByColspan[item][this._.colspan][\n          this._.p\n        ];\n\n      // Now log the colspan/position placement\n      this._.positions = prevPositions.slice(0);\n      this._.colspans = prevColspans.slice(0);\n      this._.colHeights = prevColHeights.slice(0);\n      this._.emptySpace = prevEmptySpace;\n\n      this._.positions.push(this._.position);\n      this._.colspans.push(this._.colspan);\n\n      // Add the new heights to those columns\n      this._.tallestColHeight = this._.tallestColHeightsByPosition[this._.p];\n      this._.endingCol = this._.position + this._.colspan - 1;\n\n      for (\n        this._.col = this._.position;\n        this._.col <= this._.endingCol;\n        this._.col++\n      ) {\n        this._.emptySpace +=\n          this._.tallestColHeight - this._.colHeights[this._.col];\n        this._.colHeights[this._.col] =\n          this._.tallestColHeight +\n          this.grid.itemHeightsByColspan[item][this._.colspan];\n      }\n\n      // If this is the last item, create the layout\n      if (item === this.grid.items.length - 1) {\n        this.grid.layouts.push({\n          positions: this._.positions,\n          colspans: this._.colspans,\n          colHeights: this._.colHeights,\n          emptySpace: this._.emptySpace,\n        });\n      } else {\n        // Dive deeper\n        this.grid.createLayouts(\n          item + 1,\n          this._.positions,\n          this._.colspans,\n          this._.colHeights,\n          this._.emptySpace\n        );\n      }\n    }\n\n    delete this._;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.HandleGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    var handle = sourceVal.replace('/<(.*?)>/g', '');\n\n    // Remove inner-word punctuation\n    handle = handle.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    handle = handle.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    handle = Craft.asciiString(handle);\n\n    if (!this.settings.allowNonAlphaStart) {\n      // Handle must start with a letter\n      handle = handle.replace(/^[^a-z]+/, '');\n    }\n\n    // Get the \"words\"\n    var words = Craft.filterArray(handle.split(/[^a-z0-9]+/));\n    handle = '';\n\n    if (Craft.handleCasing === 'snake') {\n      return words.join('_');\n    }\n\n    // Make it camelCase\n    for (let i = 0; i < words.length; i++) {\n      if (Craft.handleCasing !== 'pascal' && i === 0) {\n        handle += words[i];\n      } else {\n        handle += words[i].charAt(0).toUpperCase() + words[i].substr(1);\n      }\n    }\n\n    return handle;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n\n/**\n * Image upload class for user photos, site icon and logo.\n */\nCraft.ImageUpload = Garnish.Base.extend(\n  {\n    $container: null,\n    progressBar: null,\n    uploader: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.ImageUpload.defaults);\n      this.initImageUpload();\n    },\n\n    initImageUpload: function () {\n      this.$container = $(this.settings.containerSelector);\n      this.progressBar = new Craft.ProgressBar(\n        $('<div class=\"progress-shade\"></div>').appendTo(this.$container)\n      );\n\n      var options = {\n        url: Craft.getActionUrl(this.settings.uploadAction),\n        formData: this.settings.postParameters,\n        fileInput: this.$container.find(this.settings.fileInputSelector),\n        paramName: this.settings.uploadParamName,\n      };\n\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      options.events = {};\n      options.events.fileuploadstart = this._onUploadStart.bind(this);\n      options.events.fileuploadprogressall = this._onUploadProgress.bind(this);\n      options.events.fileuploaddone = this._onUploadComplete.bind(this);\n      options.events.fileuploadfail = this._onUploadFailure.bind(this);\n\n      this.uploader = new Craft.Uploader(this.$container, options);\n\n      this.initButtons();\n    },\n\n    initButtons: function () {\n      this.$container\n        .find(this.settings.uploadButtonSelector)\n        .on('click', (ev) => {\n          this.$container\n            .find(this.settings.fileInputSelector)\n            .trigger('click');\n        });\n\n      this.$container\n        .find(this.settings.deleteButtonSelector)\n        .on('click', (ev) => {\n          if (\n            confirm(\n              Craft.t('app', 'Are you sure you want to delete this image?')\n            )\n          ) {\n            $(ev.currentTarget)\n              .parent()\n              .append('<div class=\"blocking-modal\"></div>');\n            Craft.postActionRequest(\n              this.settings.deleteAction,\n              this.settings.postParameters,\n              (response, textStatus) => {\n                if (textStatus === 'success') {\n                  this.refreshImage(response);\n                }\n              }\n            );\n          }\n        });\n    },\n\n    refreshImage: function (response) {\n      $(this.settings.containerSelector).replaceWith(response.html);\n      this.settings.onAfterRefreshImage(response);\n      this.initImageUpload();\n    },\n\n    /**\n     * On upload start.\n     */\n    _onUploadStart: function (event) {\n      this.progressBar.$progressBar.css({\n        top: Math.round(this.$container.outerHeight() / 2) - 6,\n      });\n\n      this.$container.addClass('uploading');\n      this.progressBar.resetProgressBar();\n      this.progressBar.showProgressBar();\n    },\n\n    /**\n     * On upload progress.\n     */\n    _onUploadProgress: function (event, data) {\n      var progress = parseInt((data.loaded / data.total) * 100, 10);\n      this.progressBar.setProgressPercentage(progress);\n    },\n\n    /**\n     * On a file being uploaded.\n     */\n    _onUploadComplete: function (event, data) {\n      if (data.result.error) {\n        alert(data.result.error);\n      } else {\n        var html = $(data.result.html);\n        this.refreshImage(data.result);\n      }\n\n      // Last file\n      if (this.uploader.isLastUpload()) {\n        this.progressBar.hideProgressBar();\n        this.$container.removeClass('uploading');\n      }\n    },\n\n    /**\n     * On Upload Failure.\n     */\n    _onUploadFailure: function (event, data) {\n      if (data.jqXHR.responseJSON.error) {\n        alert(data.jqXHR.responseJSON.error);\n        this.progressBar.hideProgressBar();\n        this.$container.removeClass('uploading');\n      }\n    },\n  },\n  {\n    defaults: {\n      postParameters: {},\n      uploadAction: '',\n      deleteAction: '',\n      fileInputSelector: '',\n\n      onAfterRefreshImage: $.noop,\n      containerSelector: null,\n\n      uploadButtonSelector: null,\n      deleteButtonSelector: null,\n\n      uploadParamName: 'files',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Info icon class\n */\nCraft.InfoIcon = Garnish.Base.extend({\n  $icon: null,\n  content: null,\n  hud: null,\n\n  init: function (icon) {\n    this.$icon = $(icon);\n\n    if (this.$icon.data('infoicon')) {\n      console.warn('Double-instantiating an info icon on an element');\n      this.content = this.$icon.data('infoicon').content;\n      this.$icon.data('infoicon').destroy();\n    } else {\n      this.content = this.$icon.html();\n      this.$icon.html('').attr({\n        tabindex: 0,\n        role: 'button',\n        'aria-label': Craft.t('app', 'Information'),\n      });\n    }\n\n    this.$icon.data('infoicon', this);\n\n    if (\n      this.$icon[0].previousSibling &&\n      this.$icon[0].previousSibling.nodeType === Node.TEXT_NODE\n    ) {\n      // Make sure it's in a .nowrap container\n      const $parent = this.$icon.parent();\n      if (!$parent.hasClass('nowrap')) {\n        // Find the last word in the text\n        const m = this.$icon[0].previousSibling.nodeValue.match(/[^\\s\\-]+\\s*$/);\n        if (m) {\n          this.$icon[0].previousSibling.nodeValue =\n            this.$icon[0].previousSibling.nodeValue.substr(0, m.index);\n          $('<span/>', {\n            class: 'nowrap',\n            html: m[0].replace(/\\s+$/, '') + ' ',\n          })\n            .insertAfter(this.$icon[0].previousSibling)\n            .append(this.$icon);\n        }\n      }\n    }\n\n    this.addListener(this.$icon, 'click', (ev) => {\n      ev.preventDefault();\n      ev.stopPropagation();\n      this.showHud();\n    });\n\n    this.addListener(this.$icon, 'keydown', (ev) => {\n      if (\n        !(this.hud && this.hud.showing) &&\n        [Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)\n      ) {\n        ev.preventDefault();\n        ev.stopPropagation();\n        this.showHud();\n      }\n    });\n  },\n\n  showHud: function (ev) {\n    if (!this.hud) {\n      this.hud = new Garnish.HUD(this.$icon, this.content, {\n        hudClass: 'hud info-hud',\n        closeOtherHUDs: false,\n        onShow: () => {\n          Garnish.uiLayerManager.registerShortcut(Garnish.SPACE_KEY, () => {\n            this.hud.hide();\n          });\n        },\n      });\n      Craft.initUiElements(this.hud.$body);\n    } else {\n      this.hud.show();\n    }\n  },\n\n  destroy: function () {\n    this.$icon.removeData('infoicon');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Light Switch\n */\nCraft.LightSwitch = Garnish.Base.extend(\n  {\n    settings: null,\n    $outerContainer: null,\n    $innerContainer: null,\n    $input: null,\n    small: false,\n    on: false,\n    indeterminate: false,\n    dragger: null,\n\n    dragStartMargin: null,\n\n    init: function (outerContainer, settings) {\n      this.$outerContainer = $(outerContainer);\n\n      // Is this already a lightswitch?\n      if (this.$outerContainer.data('lightswitch')) {\n        console.warn('Double-instantiating a lightswitch on an element');\n        this.$outerContainer.data('lightswitch').destroy();\n      }\n\n      this.$outerContainer.data('lightswitch', this);\n\n      this.small = this.$outerContainer.hasClass('small');\n\n      this.setSettings(settings, Craft.LightSwitch.defaults);\n\n      this.$innerContainer = this.$outerContainer.find(\n        '.lightswitch-container:first'\n      );\n      this.$input = this.$outerContainer.find('input:first');\n\n      // If the input is disabled, go no further\n      if (this.$input.prop('disabled')) {\n        return;\n      }\n\n      this.on = this.$outerContainer.hasClass('on');\n      this.indeterminate = this.$outerContainer.hasClass('indeterminate');\n\n      this.addListener(this.$outerContainer, 'mousedown', '_onMouseDown');\n      this.addListener(this.$outerContainer, 'keydown', '_onKeyDown');\n\n      this.dragger = new Garnish.BaseDrag(this.$outerContainer, {\n        axis: Garnish.X_AXIS,\n        ignoreHandleSelector: null,\n        onDragStart: this._onDragStart.bind(this),\n        onDrag: this._onDrag.bind(this),\n        onDragStop: this._onDragStop.bind(this),\n      });\n\n      // Does the input have on/off labels?\n      let $wrapper = this.$outerContainer.parent(\n        '.lightswitch-inner-container'\n      );\n      if ($wrapper.length) {\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"off\"]'),\n          'click',\n          this.turnOff\n        );\n        this.addListener(\n          $wrapper.children('span[data-toggle=\"on\"]'),\n          'click',\n          this.turnOn\n        );\n      }\n    },\n\n    turnOn: function (muteEvent) {\n      var changed = !this.on;\n\n      this.on = true;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, 0);\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = 0;\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val(this.settings.value);\n      this.$outerContainer.addClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'true');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnOff: function (muteEvent) {\n      var changed = this.on || this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = false;\n\n      this.$outerContainer.addClass('dragging');\n\n      if (Garnish.prefersReducedMotion()) {\n        this.$innerContainer.css('margin-' + Craft.left, this._getOffMargin());\n      } else {\n        var animateCss = {};\n        animateCss['margin-' + Craft.left] = this._getOffMargin();\n        this.$innerContainer\n          .velocity('stop')\n          .velocity(\n            animateCss,\n            Craft.LightSwitch.animationDuration,\n            this._onSettle.bind(this)\n          );\n      }\n\n      this.$input.val('');\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.removeClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'false');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    turnIndeterminate: function (muteEvent) {\n      var changed = !this.indeterminate;\n\n      this.on = false;\n      this.indeterminate = true;\n\n      this.$outerContainer.addClass('dragging');\n      var animateCss = {};\n      animateCss['margin-' + Craft.left] = this._getOffMargin() / 2;\n      this.$innerContainer\n        .velocity('stop')\n        .velocity(\n          animateCss,\n          Craft.LightSwitch.animationDuration,\n          this._onSettle.bind(this)\n        );\n\n      this.$input.val(this.settings.indeterminateValue);\n      this.$outerContainer.removeClass('on');\n      this.$outerContainer.addClass('indeterminate');\n      this.$outerContainer.attr('aria-checked', 'mixed');\n\n      if (changed && muteEvent !== true) {\n        this.onChange();\n      }\n    },\n\n    toggle: function () {\n      if (this.indeterminate || !this.on) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    onChange: function () {\n      this.trigger('change');\n      this.settings.onChange(this.on);\n      this.$outerContainer.trigger('change');\n    },\n\n    _onMouseDown: function () {\n      this.addListener(Garnish.$doc, 'mouseup', '_onMouseUp');\n    },\n\n    _onMouseUp: function () {\n      this.removeListener(Garnish.$doc, 'mouseup');\n\n      // Was this a click?\n      if (!this.dragger.dragging) {\n        this.toggle();\n      }\n    },\n\n    _onKeyDown: function (event) {\n      switch (event.keyCode) {\n        case Garnish.SPACE_KEY: {\n          this.toggle();\n          event.preventDefault();\n          break;\n        }\n        case Garnish.RIGHT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOn();\n          } else {\n            this.turnOff();\n          }\n\n          event.preventDefault();\n          break;\n        }\n        case Garnish.LEFT_KEY: {\n          if (Craft.orientation === 'ltr') {\n            this.turnOff();\n          } else {\n            this.turnOn();\n          }\n\n          event.preventDefault();\n          break;\n        }\n      }\n    },\n\n    _getMargin: function () {\n      return parseInt(this.$innerContainer.css('margin-' + Craft.left));\n    },\n\n    _onDragStart: function () {\n      this.$outerContainer.addClass('dragging');\n      this.dragStartMargin = this._getMargin();\n    },\n\n    _onDrag: function () {\n      var margin;\n\n      if (Craft.orientation === 'ltr') {\n        margin = this.dragStartMargin + this.dragger.mouseDistX;\n      } else {\n        margin = this.dragStartMargin - this.dragger.mouseDistX;\n      }\n\n      if (margin < this._getOffMargin()) {\n        margin = this._getOffMargin();\n      } else if (margin > 0) {\n        margin = 0;\n      }\n\n      this.$innerContainer.css('margin-' + Craft.left, margin);\n    },\n\n    _onDragStop: function () {\n      var margin = this._getMargin();\n      console.log(margin);\n\n      if (margin > this._getOffMargin() / 2) {\n        this.turnOn();\n      } else {\n        this.turnOff();\n      }\n    },\n\n    _onSettle: function () {\n      this.$outerContainer.removeClass('dragging');\n    },\n\n    destroy: function () {\n      this.$outerContainer.removeData('lightswitch');\n      this.base();\n      this.dragger.destroy();\n    },\n\n    _getOffMargin: function () {\n      return this.small ? -10 : -12;\n    },\n  },\n  {\n    animationDuration: 100,\n    defaults: {\n      value: '1',\n      indeterminateValue: '-',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Listbox\n */\nCraft.Listbox = Garnish.Base.extend(\n  {\n    $container: null,\n    $options: null,\n    $selectedOption: null,\n    selectedOptionIndex: null,\n\n    init: function (container, settings) {\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Listbox.defaults);\n\n      // Is this already a listbox?\n      if (this.$container.data('listbox')) {\n        console.warn('Double-instantiating a listbox on an element');\n        this.$container.data('listbox').destroy();\n      }\n\n      this.$container.data('listbox', this);\n      this.$options = this.$container.find('[role=option]');\n\n      // is there already a selected option?\n      this.$selectedOption = this.$options.filter('[aria-selected=true]');\n      if (this.$selectedOption.length) {\n        this.selectedOptionIndex = this.$options.index(this.$selectedOption);\n      } else {\n        this.$selectedOption = null;\n      }\n\n      this.addListener(this.$container, 'keydown', (ev) => {\n        switch (ev.keyCode) {\n          case Garnish.UP_KEY:\n            this.selectPrev();\n            ev.preventDefault();\n            break;\n          case Garnish.DOWN_KEY:\n            this.selectNext();\n            ev.preventDefault();\n            break;\n          case Garnish.LEFT_KEY:\n            if (Craft.orientation === 'ltr') {\n              this.selectPrev();\n            } else {\n              this.selectNext();\n            }\n            ev.preventDefault();\n            break;\n          case Garnish.RIGHT_KEY:\n            if (Craft.orientation === 'ltr') {\n              this.selectNext();\n            } else {\n              this.selectPrev();\n            }\n            ev.preventDefault();\n            break;\n        }\n      });\n\n      this.addListener(this.$options, 'click', (ev) => {\n        this.select(this.$options.index($(ev.currentTarget)));\n        ev.preventDefault();\n      });\n    },\n\n    select: function (index) {\n      if (\n        index < 0 ||\n        index >= this.$options.length ||\n        index === this.selectedOptionIndex\n      ) {\n        return;\n      }\n\n      this.$selectedOption\n        .removeClass(this.settings.selectedClass)\n        .attr('aria-selected', 'false');\n\n      this.$selectedOption = this.$options\n        .eq(index)\n        .addClass(this.settings.selectedClass)\n        .attr('aria-selected', 'true');\n\n      this.selectedOptionIndex = index;\n\n      this.settings.onChange(this.$selectedOption, index);\n      this.trigger('change', {\n        $selectedOption: this.$selectedOption,\n        selectedOptionIndex: index,\n      });\n    },\n\n    selectPrev: function () {\n      if (this.selectedOptionIndex === null) {\n        this.select(0);\n      } else {\n        this.select(this.selectedOptionIndex - 1);\n      }\n    },\n\n    selectNext: function () {\n      if (this.selectedOptionIndex === null) {\n        this.select(0);\n      } else {\n        this.select(this.selectedOptionIndex + 1);\n      }\n    },\n\n    destroy: function () {\n      this.$container.removeData('listbox');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      selectedClass: 'active',\n      focusClass: 'focus',\n      onChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Live Preview\n */\nCraft.LivePreview = Garnish.Base.extend(\n  {\n    $extraFields: null,\n    $trigger: null,\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $dragHandle: null,\n    $previewContainer: null,\n    $iframeContainer: null,\n    $iframe: null,\n    $fieldPlaceholder: null,\n\n    previewUrl: null,\n    token: null,\n    basePostData: null,\n    inPreviewMode: false,\n    fields: null,\n    lastPostData: null,\n    updateIframeInterval: null,\n    loading: false,\n    checkAgain: false,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _slideInOnIframeLoad: false,\n    _forceUpdateIframeProxy: null,\n\n    _scrollX: null,\n    _scrollY: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (settings) {\n      this.setSettings(settings, Craft.LivePreview.defaults);\n\n      // Should preview requests use a specific URL?\n      // This won't affect how the request gets routed (the action param will override it),\n      // but it will allow the templates to change behavior based on the request URI.\n      if (this.settings.previewUrl) {\n        this.previewUrl = this.settings.previewUrl;\n      } else {\n        this.previewUrl = Craft.baseSiteUrl.replace(/\\/+$/, '') + '/';\n      }\n\n      // Load the preview over SSL if the current request is\n      if (document.location.protocol === 'https:') {\n        this.previewUrl = this.previewUrl.replace(/^http:/, 'https:');\n      }\n\n      // Set the base post data\n      this.basePostData = $.extend({}, this.settings.previewParams);\n\n      this._forceUpdateIframeProxy = this.forceUpdateIframe.bind(this);\n\n      // Find the DOM elements\n      this.$extraFields = $(this.settings.extraFields);\n      this.$trigger = $(this.settings.trigger);\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.LivePreview.defaultEditorWidth\n      );\n\n      // Event Listeners\n      this.addListener(this.$trigger, 'activate', 'toggle');\n\n      Craft.cp.on('beforeSaveShortcut', () => {\n        if (this.inPreviewMode) {\n          this.moveFieldsBack();\n        }\n      });\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.LivePreview.minEditorWidthInPx) {\n        inPx = Craft.LivePreview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    toggle: function () {\n      if (this.inPreviewMode) {\n        this.exit();\n      } else {\n        this.enter();\n      }\n    },\n\n    enter: function () {\n      if (this.inPreviewMode) {\n        return;\n      }\n\n      if (!this.token) {\n        this.createToken();\n        return;\n      }\n\n      this.trigger('beforeEnter');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n        }).appendTo(Garnish.$bod);\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(Garnish.$bod);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        let $saveBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn submit',\n          text: Craft.t('app', 'Save'),\n        }).appendTo($editorHeader);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'exit');\n        this.addListener($saveBtn, 'click', 'save');\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Move all the fields into the editor rather than copying them\n      // so any JS that's referencing the elements won't break.\n      this.fields = [];\n      var $fields = $(this.settings.fields);\n\n      for (var i = 0; i < $fields.length; i++) {\n        var $field = $($fields[i]),\n          $clone = this._getClone($field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter($field);\n        $field.detach();\n        this.$fieldPlaceholder.replaceWith($clone);\n        $field.appendTo(this.$editor);\n\n        this.fields.push({\n          $field: $field,\n          $clone: $clone,\n        });\n      }\n\n      if (this.updateIframe()) {\n        this._slideInOnIframeLoad = true;\n      } else {\n        this.slideIn();\n      }\n\n      Garnish.on(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._forceUpdateIframeProxy\n      );\n      Garnish.on(Craft.AssetImageEditor, 'save', this._forceUpdateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.exit();\n      });\n\n      this.inPreviewMode = true;\n      this.trigger('enter');\n    },\n\n    createToken: function () {\n      Craft.postActionRequest(\n        'live-preview/create-token',\n        {\n          previewAction: this.settings.previewAction,\n        },\n        (response, textStatus) => {\n          if (textStatus === 'success') {\n            this.token = response.token;\n            this.enter();\n          }\n        }\n      );\n    },\n\n    save: function () {\n      Craft.cp.submitPrimaryForm();\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(0, 'slow', () => {\n          this.trigger('slideIn');\n          Garnish.$win.trigger('resize');\n        });\n\n      this.$previewContainer\n        .show()\n        .velocity('stop')\n        .animateRight(0, 'slow', () => {\n          this.updateIframeInterval = setInterval(\n            this.updateIframe.bind(this),\n            1000\n          );\n        });\n    },\n\n    exit: function () {\n      if (!this.inPreviewMode) {\n        return;\n      }\n\n      this.trigger('beforeExit');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n\n      if (this.updateIframeInterval) {\n        clearInterval(this.updateIframeInterval);\n      }\n\n      this.moveFieldsBack();\n\n      this.$shade.delay(200).velocity('fadeOut');\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(-this.editorWidthInPx, 'slow', () => {\n          for (var i = 0; i < this.fields.length; i++) {\n            this.fields[i].$newClone.remove();\n          }\n          this.$editorContainer.hide();\n          this.trigger('slideOut');\n        });\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(-this.getIframeWidth(), 'slow', () => {\n          this.$previewContainer.hide();\n        });\n\n      Garnish.off(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._forceUpdateIframeProxy\n      );\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.inPreviewMode = false;\n      this.trigger('exit');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n    },\n\n    updateIframe: function (force) {\n      if (force) {\n        this.lastPostData = null;\n      }\n\n      if (!this.inPreviewMode) {\n        return false;\n      }\n\n      if (this.loading) {\n        this.checkAgain = true;\n        return false;\n      }\n\n      // Has the post data changed?\n      var postData = $.extend(\n        Garnish.getPostData(this.$editor),\n        Garnish.getPostData(this.$extraFields)\n      );\n\n      if (\n        !this.lastPostData ||\n        !Craft.compare(postData, this.lastPostData, false)\n      ) {\n        this.lastPostData = postData;\n        this.loading = true;\n\n        var $doc = this.$iframe\n          ? $(this.$iframe[0].contentWindow.document)\n          : null;\n\n        this._scrollX = $doc ? $doc.scrollLeft() : 0;\n        this._scrollY = $doc ? $doc.scrollTop() : 0;\n\n        $.ajax({\n          url:\n            this.previewUrl +\n            (this.previewUrl.indexOf('?') !== -1 ? '&' : '?') +\n            Craft.tokenParam +\n            '=' +\n            this.token,\n          method: 'POST',\n          data: $.extend({}, postData, this.basePostData),\n          headers: {\n            'X-Craft-Token': this.token,\n          },\n          xhrFields: {\n            withCredentials: true,\n          },\n          crossDomain: true,\n          success: this.handleSuccess.bind(this),\n          error: this.handleError.bind(this),\n        });\n\n        return true;\n      } else {\n        return false;\n      }\n    },\n\n    forceUpdateIframe: function () {\n      return this.updateIframe(true);\n    },\n\n    handleSuccess: function (data) {\n      var html =\n        data +\n        '<script type=\"text/javascript\">window.scrollTo(' +\n        this._scrollX +\n        ', ' +\n        this._scrollY +\n        ');</script>';\n\n      // Create a new iframe\n      var $iframe = $('<iframe class=\"lp-preview\" frameborder=\"0\"/>');\n      if (this.$iframe) {\n        $iframe.insertBefore(this.$iframe);\n      } else {\n        $iframe.appendTo(this.$iframeContainer);\n      }\n\n      this.addListener($iframe, 'load', function () {\n        if (this.$iframe) {\n          this.$iframe.remove();\n        }\n        this.$iframe = $iframe;\n\n        if (this._slideInOnIframeLoad) {\n          this.slideIn();\n          this._slideInOnIframeLoad = false;\n        }\n\n        this.removeListener($iframe, 'load');\n      });\n\n      Garnish.requestAnimationFrame(() => {\n        $iframe[0].contentWindow.document.open();\n        $iframe[0].contentWindow.document.write(html);\n        $iframe[0].contentWindow.document.close();\n        this.onResponse();\n      });\n    },\n\n    handleError: function () {\n      this.onResponse();\n    },\n\n    onResponse: function () {\n      this.loading = false;\n\n      if (this.checkAgain) {\n        this.checkAgain = false;\n        this.updateIframe();\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n\n    defaults: {\n      trigger: '.livepreviewbtn',\n      fields: null,\n      extraFields: null,\n      previewUrl: null,\n      previewAction: null,\n      previewParams: {},\n    },\n  }\n);\n\nCraft.LivePreview.init = function (settings) {\n  Craft.livePreview = new Craft.LivePreview(settings);\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Password Input\n */\nCraft.PasswordInput = Garnish.Base.extend(\n  {\n    $passwordWrapper: null,\n    $passwordInput: null,\n    $textInput: null,\n    $currentInput: null,\n\n    $showPasswordToggle: null,\n    showingPassword: null,\n\n    init: function (passwordInput, settings) {\n      this.$passwordInput = $(passwordInput);\n      this.$passwordWrapper = this.$passwordInput.parent('.passwordwrapper');\n      this.settings = $.extend({}, Craft.PasswordInput.defaults, settings);\n\n      // Is this already a password input?\n      if (this.$passwordInput.data('passwordInput')) {\n        console.warn('Double-instantiating a password input on an element');\n        this.$passwordInput.data('passwordInput').destroy();\n      }\n\n      this.$passwordInput.data('passwordInput', this);\n\n      this.$showPasswordToggle = $(\n        '<button type=\"button\" class=\"invisible\" />'\n      );\n      this.$showPasswordToggle.addClass('password-toggle');\n      this.$showPasswordToggle.insertAfter(this.$passwordInput);\n\n      this.initInputFocusEvents(this.$passwordInput);\n      this.addListener(this.$showPasswordToggle, 'click', 'onClick');\n      this.hidePassword();\n\n      this.addListener(\n        this.$passwordWrapper.closest('form'),\n        'submit',\n        'hidePassword'\n      );\n    },\n\n    setCurrentInput: function ($input) {\n      if (this.$currentInput) {\n        // Swap the inputs, while preventing the focus animation\n        $input.insertAfter(this.$currentInput);\n        this.$currentInput.detach();\n        $input.trigger('focus');\n\n        // Restore the input value\n        $input.val(this.$currentInput.val());\n      }\n\n      this.$currentInput = $input;\n\n      this.addListener(\n        this.$currentInput,\n        'keypress,keyup,change,blur',\n        'onInputChange'\n      );\n    },\n\n    updateToggleLabel: function (label) {\n      this.$showPasswordToggle.text(label);\n    },\n\n    initInputFocusEvents: function ($input) {\n      this.addListener($input, 'focus', function () {\n        this.$passwordWrapper.addClass('focus');\n      });\n      this.addListener($input, 'blur', function () {\n        this.$passwordWrapper.removeClass('focus');\n      });\n    },\n\n    showPassword: function () {\n      if (this.showingPassword) {\n        return;\n      }\n\n      if (!this.$textInput) {\n        this.$textInput = this.$passwordInput.clone(true);\n        this.$textInput.attr({\n          type: 'text',\n          autocapitalize: 'off',\n        });\n        this.initInputFocusEvents(this.$textInput);\n      }\n\n      this.setCurrentInput(this.$textInput);\n      this.updateToggleLabel(Craft.t('app', 'Hide'));\n      this.showingPassword = true;\n    },\n\n    hidePassword: function () {\n      // showingPassword could be null, which is acceptable\n      if (this.showingPassword === false) {\n        return;\n      }\n\n      this.setCurrentInput(this.$passwordInput);\n      this.updateToggleLabel(Craft.t('app', 'Show'));\n      this.showingPassword = false;\n\n      // Alt key temporarily shows the password\n      this.addListener(this.$passwordInput, 'keydown', 'onKeyDown');\n    },\n\n    togglePassword: function () {\n      if (this.showingPassword) {\n        this.hidePassword();\n      } else {\n        this.showPassword();\n      }\n\n      this.settings.onToggleInput(this.$currentInput);\n    },\n\n    onKeyDown: function (ev) {\n      if (ev.keyCode === Garnish.ALT_KEY && this.$currentInput.val()) {\n        this.showPassword();\n        this.$showPasswordToggle.addClass('invisible');\n        this.addListener(this.$textInput, 'keyup', 'onKeyUp');\n      }\n    },\n\n    onKeyUp: function (ev) {\n      ev.preventDefault();\n\n      if (ev.keyCode === Garnish.ALT_KEY) {\n        this.hidePassword();\n        this.$showPasswordToggle.removeClass('invisible');\n      }\n    },\n\n    onInputChange: function () {\n      if (this.$currentInput.val()) {\n        this.$showPasswordToggle.removeClass('invisible');\n      } else {\n        this.$showPasswordToggle.addClass('invisible');\n      }\n    },\n\n    onClick: function (ev) {\n      if (this.$currentInput[0].setSelectionRange) {\n        var selectionStart = this.$currentInput[0].selectionStart,\n          selectionEnd = this.$currentInput[0].selectionEnd;\n\n        this.togglePassword();\n        this.$currentInput[0].setSelectionRange(selectionStart, selectionEnd);\n      } else {\n        this.togglePassword();\n      }\n    },\n\n    destroy: function () {\n      this.$passwordInput.removeData('passwordInput');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      onToggleInput: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview\n */\nCraft.Preview = Garnish.Base.extend(\n  {\n    draftEditor: null,\n\n    $shade: null,\n    $editorContainer: null,\n    $editor: null,\n    $spinner: null,\n    $statusIcon: null,\n    $dragHandle: null,\n    $previewContainer: null,\n    $iframeContainer: null,\n    $previewHeader: null,\n    $targetBtn: null,\n    $targetMenu: null,\n    $deviceTypeContainer: null,\n    $orientationBtn: null,\n    $refreshBtn: null,\n    $deviceMask: null,\n    $devicePreviewContainer: null,\n    $iframe: null,\n    iframeLoaded: false,\n    $tempInput: null,\n    $fieldPlaceholder: null,\n\n    isActive: false,\n    isVisible: false,\n    activeTarget: 0,\n\n    currentDeviceType: 'desktop',\n    deviceOrientation: null,\n    deviceWidth: '',\n    deviceHeight: '',\n    deviceMaskDimensions: {\n      phone: {\n        width: 375,\n        height: 753,\n      },\n      tablet: {\n        width: 768,\n        height: 1110,\n      },\n    },\n\n    draftId: null,\n    url: null,\n    fields: null,\n\n    iframeHeight: null,\n    scrollTop: null,\n\n    dragger: null,\n    dragStartEditorWidth: null,\n\n    _updateIframeProxy: null,\n\n    _editorWidth: null,\n    _editorWidthInPx: null,\n\n    init: function (draftEditor) {\n      this.draftEditor = draftEditor;\n\n      this._updateIframeProxy = this.updateIframe.bind(this);\n\n      this.$tempInput = $('<input/>', {\n        type: 'hidden',\n        name: '__PREVIEW_FIELDS__',\n        value: '1',\n      });\n      this.$fieldPlaceholder = $('<div/>');\n\n      // Set the initial editor width\n      this.editorWidth = Craft.getLocalStorage(\n        'LivePreview.editorWidth',\n        Craft.Preview.defaultEditorWidth\n      );\n    },\n\n    get editorWidth() {\n      return this._editorWidth;\n    },\n\n    get editorWidthInPx() {\n      return this._editorWidthInPx;\n    },\n\n    set editorWidth(width) {\n      var inPx;\n\n      // Is this getting set in pixels?\n      if (width >= 1) {\n        inPx = width;\n        width /= Garnish.$win.width();\n      } else {\n        inPx = Math.round(width * Garnish.$win.width());\n      }\n\n      // Make sure it's no less than the minimum\n      if (inPx < Craft.Preview.minEditorWidthInPx) {\n        inPx = Craft.Preview.minEditorWidthInPx;\n        width = inPx / Garnish.$win.width();\n      }\n\n      this._editorWidth = width;\n      this._editorWidthInPx = inPx;\n    },\n\n    open: function () {\n      if (this.isActive) {\n        return;\n      }\n\n      this.isActive = true;\n      this.trigger('beforeOpen');\n\n      $(document.activeElement).trigger('blur');\n\n      if (!this.$editor) {\n        this.$shade = $('<div/>', {class: 'modal-shade dark'}).appendTo(\n          Garnish.$bod\n        );\n        this.$previewContainer = $('<div/>', {\n          class: 'lp-preview-container',\n        }).appendTo(Garnish.$bod);\n        this.$editorContainer = $('<div/>', {\n          class: 'lp-editor-container',\n        }).appendTo(Garnish.$bod);\n\n        var $editorHeader = $('<header/>', {class: 'flex'}).appendTo(\n          this.$editorContainer\n        );\n        this.$editor = $('<form/>', {class: 'lp-editor'}).appendTo(\n          this.$editorContainer\n        );\n        this.$dragHandle = $('<div/>', {class: 'lp-draghandle'}).appendTo(\n          this.$editorContainer\n        );\n        var $closeBtn = $('<button/>', {\n          type: 'button',\n          class: 'btn',\n          text: Craft.t('app', 'Close Preview'),\n        }).appendTo($editorHeader);\n        $('<div/>', {class: 'flex-grow'}).appendTo($editorHeader);\n        this.$spinner = $('<div/>', {\n          class: 'spinner hidden',\n          title: Craft.t('app', 'Saving'),\n        }).appendTo($editorHeader);\n        this.$statusIcon = $('<div/>', {class: 'invisible'}).appendTo(\n          $editorHeader\n        );\n        this.$statusMessage = $('<span/>', {\n          class: 'visually-hidden',\n          'aria-live': 'polite',\n        }).appendTo($editorHeader);\n\n        if (Craft.Pro) {\n          this.$previewHeader = $('<header/>', {\n            class: 'lp-preview-header',\n          }).appendTo(this.$previewContainer);\n\n          // Preview targets\n          if (this.draftEditor.settings.previewTargets.length > 1) {\n            this.$targetBtn = $('<button/>', {\n              type: 'button',\n              class: 'btn menubtn',\n              text: this.draftEditor.settings.previewTargets[0].label,\n            }).appendTo(this.$previewHeader);\n            this.$targetMenu = $('<div/>', {\n              class: 'menu lp-target-menu',\n            }).insertAfter(this.$targetBtn);\n            const $ul = $('<ul/>', {class: 'padded'}).appendTo(\n              this.$targetMenu\n            );\n            let $li, $a;\n            for (\n              let i = 0;\n              i < this.draftEditor.settings.previewTargets.length;\n              i++\n            ) {\n              $li = $('<li/>').appendTo($ul);\n              $a = $('<a/>', {\n                data: {target: i},\n                text: this.draftEditor.settings.previewTargets[i].label,\n                class: i === 0 ? 'sel' : null,\n              }).appendTo($li);\n            }\n            new Garnish.MenuBtn(this.$targetBtn, {\n              onOptionSelect: (option) => {\n                this.switchTarget($(option).data('target'));\n              },\n            });\n\n            $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          }\n\n          this._buildDeviceTypeFieldset();\n\n          $('<div class=\"flex-grow\"/>').appendTo(this.$previewHeader);\n          const $buttonContainer = $('<div class=\"buttons\"/>').appendTo(\n            this.$previewHeader\n          );\n\n          // Orientation toggle\n          this.$orientationBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn disabled',\n            'data-icon': 'rotate',\n            disabled: '',\n            text: Craft.t('app', 'Rotate'),\n            'aria-label': Craft.t('app', 'Rotate'),\n          }).appendTo($buttonContainer);\n          this.addListener(this.$orientationBtn, 'click', 'switchOrientation');\n\n          // Refresh button\n          this.$refreshBtn = $('<button/>', {\n            type: 'button',\n            class: 'btn hidden',\n            text: Craft.t('app', 'Refresh'),\n            'data-icon': 'refresh',\n          }).appendTo($buttonContainer);\n          this._updateRefreshBtn();\n          this.addListener(this.$refreshBtn, 'click', () => {\n            this.updateIframe(false, true);\n          });\n\n          // Get the last stored orientation\n          this.deviceOrientation = Craft.getLocalStorage(\n            'LivePreview.orientation'\n          );\n\n          // Device type input change handler\n          this.addListener(\n            $('input', this.$deviceTypeContainer),\n            'change',\n            'switchDeviceType'\n          );\n        }\n\n        this.$iframeContainer = $('<div/>', {\n          class: 'lp-iframe-container',\n        }).appendTo(this.$previewContainer);\n        this.$devicePreviewContainer = $('<div/>', {\n          class: 'lp-device-preview-container',\n        }).appendTo(this.$iframeContainer);\n        this.$deviceMask = $('<div/>', {\n          class: 'lp-device-mask',\n        }).appendTo(this.$iframeContainer);\n\n        this.dragger = new Garnish.BaseDrag(this.$dragHandle, {\n          axis: Garnish.X_AXIS,\n          onDragStart: this._onDragStart.bind(this),\n          onDrag: this._onDrag.bind(this),\n          onDragStop: this._onDragStop.bind(this),\n        });\n\n        this.addListener($closeBtn, 'click', 'close');\n        this.addListener(this.$statusIcon, 'click', () => {\n          this.draftEditor.showStatusHud(this.$statusIcon);\n        });\n      }\n\n      // Set the sizes\n      this.handleWindowResize();\n      this.addListener(Garnish.$win, 'resize', 'handleWindowResize');\n\n      this.$editorContainer.css(Craft.left, -this.editorWidthInPx + 'px');\n      this.$previewContainer.css(Craft.right, -this.getIframeWidth());\n\n      // Find the fields, excluding nested fields\n      this.fields = [];\n      var $fields = $('#content .field').not($('#content .field .field'));\n\n      if ($fields.length) {\n        // Insert our temporary input before the first field so we know where to swap in the serialized form values\n        this.$tempInput.insertBefore($fields.get(0));\n\n        // Move all the fields into the editor rather than copying them\n        // so any JS that's referencing the elements won't break.\n        for (let i = 0; i < $fields.length; i++) {\n          let $field = $($fields[i]),\n            $clone = this._getClone($field);\n\n          // It's important that the actual field is added to the DOM *after* the clone,\n          // so any radio buttons in the field get deselected from the clone rather than the actual field.\n          this.$fieldPlaceholder.insertAfter($field);\n          $field.detach();\n          this.$fieldPlaceholder.replaceWith($clone);\n          $field.appendTo(this.$editor);\n\n          this.fields.push({\n            $field: $field,\n            $clone: $clone,\n          });\n        }\n      }\n\n      this.updateIframe();\n\n      this.draftEditor.on('update', this._updateIframeProxy);\n      Garnish.on(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._updateIframeProxy\n      );\n      Garnish.on(Craft.AssetImageEditor, 'save', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.trigger('open');\n    },\n\n    _buildDeviceTypeFieldset: function () {\n      this.$deviceTypeContainer = $('<fieldset/>', {\n        class: 'lp-device-type',\n      }).appendTo(this.$previewHeader);\n\n      $('<legend/>', {\n        text: Craft.t('app', 'Device type'),\n        class: 'visually-hidden',\n      }).appendTo(this.$deviceTypeContainer);\n\n      const $radioGroup = $('<div/>', {\n        class: 'lp-device-type__radio-group',\n      }).appendTo(this.$deviceTypeContainer);\n\n      // Desktop\n      const $desktopWrapper = $('<div/>', {\n        class: 'lp-device-type__item',\n      }).appendTo($radioGroup);\n\n      $('<input/>', {\n        class: 'lp-device-type__input visually-hidden',\n        type: 'radio',\n        name: 'device',\n        value: 'desktop',\n        id: 'device-desktop',\n        checked: true,\n        data: {\n          width: '',\n          height: '',\n        },\n      }).appendTo($desktopWrapper);\n\n      const $desktopLabel = $('<label/>', {\n        for: 'device-desktop',\n        class:\n          'btn lp-device-type__label lp-device-type__label--desktop active',\n        title: Craft.t('app', 'Desktop'),\n      }).appendTo($desktopWrapper);\n\n      $('<span/>', {\n        class: 'visually-hidden',\n        text: Craft.t('app', 'Desktop'),\n      }).appendTo($desktopLabel);\n\n      // Tablet\n      const $tabletWrapper = $('<div/>', {\n        class: 'lp-device-type__item',\n      }).appendTo($radioGroup);\n\n      $('<input/>', {\n        class: 'lp-device-type__input visually-hidden',\n        type: 'radio',\n        name: 'device',\n        value: 'tablet',\n        id: 'device-tablet',\n        data: {\n          width: 768,\n          height: 1024,\n        },\n      }).appendTo($tabletWrapper);\n\n      const $tabletLabel = $('<label/>', {\n        for: 'device-tablet',\n        class: 'btn lp-device-type__label lp-device-type__label--tablet',\n        title: Craft.t('app', 'Tablet'),\n      }).appendTo($tabletWrapper);\n\n      $('<span/>', {\n        class: 'visually-hidden',\n        text: Craft.t('app', 'Tablet'),\n      }).appendTo($tabletLabel);\n\n      // Mobile\n      const $mobileWrapper = $('<div/>', {\n        class: 'lp-device-type__item',\n      }).appendTo($radioGroup);\n\n      $('<input/>', {\n        class: 'lp-device-type__input visually-hidden',\n        type: 'radio',\n        name: 'device',\n        value: 'phone',\n        id: 'device-phone',\n        data: {\n          width: 375,\n          height: 667,\n        },\n      }).appendTo($mobileWrapper);\n\n      const $mobileLabel = $('<label/>', {\n        for: 'device-phone',\n        class: 'btn lp-device-type__label lp-device-type__label--phone',\n        title: Craft.t('app', 'Mobile'),\n      }).appendTo($mobileWrapper);\n\n      $('<span/>', {\n        class: 'visually-hidden',\n        text: Craft.t('app', 'Mobile'),\n      }).appendTo($mobileLabel);\n    },\n\n    _activeTarget: function () {\n      return this.draftEditor.settings.previewTargets[this.activeTarget];\n    },\n\n    /**\n     * @returns {boolean}\n     * @private\n     */\n    _autoRefresh: function () {\n      const target = this._activeTarget();\n      return typeof typeof target.refresh === 'undefined' || !!target.refresh;\n    },\n\n    _updateRefreshBtn: function () {\n      if (!this._autoRefresh()) {\n        this.$refreshBtn.removeClass('hidden');\n      } else {\n        this.$refreshBtn.addClass('hidden');\n      }\n    },\n\n    switchTarget: function (i) {\n      this.activeTarget = i;\n      this.$targetBtn.text(this.draftEditor.settings.previewTargets[i].label);\n      this.$targetMenu.find('a.sel').removeClass('sel');\n      this.$targetMenu.find('a').eq(i).addClass('sel');\n      this.updateIframe(true);\n      this._updateRefreshBtn();\n      this.trigger('switchTarget', {\n        previewTarget: this.draftEditor.settings.previewTargets[i],\n      });\n    },\n\n    handleWindowResize: function () {\n      // Reset the width so the min width is enforced\n      this.editorWidth = this.editorWidth;\n\n      // Update the editor/iframe sizes\n      this.updateWidths();\n    },\n\n    slideIn: function () {\n      if (!this.isActive || this.isVisible) {\n        return;\n      }\n\n      $('html').addClass('noscroll');\n      this.$shade.velocity('fadeIn');\n\n      this.$editorContainer\n        .show()\n        .velocity('stop')\n        .animateLeft(0, 'slow', () => {\n          this.trigger('slideIn');\n          Garnish.$win.trigger('resize');\n        });\n\n      this.$previewContainer.show().velocity('stop').animateRight(0, 'slow');\n\n      this.isVisible = true;\n\n      Garnish.uiLayerManager.addLayer(this.$sidebar);\n      Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n        this.close();\n      });\n    },\n\n    close: function () {\n      if (!this.isActive || !this.isVisible) {\n        return;\n      }\n\n      this.trigger('beforeClose');\n\n      $('html').removeClass('noscroll');\n\n      this.removeListener(Garnish.$win, 'resize');\n      Garnish.uiLayerManager.removeLayer();\n\n      // Remove our temporary input and move the preview fields back into place\n      this.$tempInput.detach();\n      this.moveFieldsBack();\n\n      this.$shade.delay(200).velocity('fadeOut');\n\n      this.$editorContainer\n        .velocity('stop')\n        .animateLeft(-this.editorWidthInPx, 'slow', () => {\n          for (var i = 0; i < this.fields.length; i++) {\n            this.fields[i].$newClone.remove();\n          }\n          this.$editorContainer.hide();\n          this.trigger('slideOut');\n        });\n\n      this.$previewContainer\n        .velocity('stop')\n        .animateRight(-this.getIframeWidth(), 'slow', () => {\n          this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n          this.$previewContainer.hide();\n        });\n\n      this.draftEditor.off('update', this._updateIframeProxy);\n      Garnish.off(\n        Craft.BaseElementEditor,\n        'saveElement',\n        this._updateIframeProxy\n      );\n      Garnish.off(Craft.AssetImageEditor, 'save', this._updateIframeProxy);\n\n      Craft.ElementThumbLoader.retryAll();\n\n      this.isActive = false;\n      this.isVisible = false;\n      this.trigger('close');\n    },\n\n    moveFieldsBack: function () {\n      for (var i = 0; i < this.fields.length; i++) {\n        var field = this.fields[i];\n        field.$newClone = this._getClone(field.$field);\n\n        // It's important that the actual field is added to the DOM *after* the clone,\n        // so any radio buttons in the field get deselected from the clone rather than the actual field.\n        this.$fieldPlaceholder.insertAfter(field.$field);\n        field.$field.detach();\n        this.$fieldPlaceholder.replaceWith(field.$newClone);\n        field.$clone.replaceWith(field.$field);\n      }\n\n      Garnish.$win.trigger('resize');\n      Garnish.$doc.trigger('scroll');\n    },\n\n    getIframeWidth: function () {\n      return Garnish.$win.width() - this.editorWidthInPx;\n    },\n\n    updateWidths: function () {\n      this.$editorContainer.css('width', this.editorWidthInPx + 'px');\n      this.$previewContainer.width(this.getIframeWidth());\n      if (this._devicePreviewIsActive()) {\n        this.updateDevicePreview();\n      }\n    },\n\n    _useIframeResizer: function () {\n      return Craft.previewIframeResizerOptions !== false;\n    },\n\n    /**\n     * @param {boolean} [resetScroll=false]\n     * @param {boolean} [refresh]\n     */\n    updateIframe: function (resetScroll, refresh) {\n      if (!this.isActive) {\n        return false;\n      }\n\n      // Ignore non-boolean resetScroll values\n      resetScroll = resetScroll === true;\n\n      // If the draft ID has changed or there's no iframe, we definitely need to refresh\n      if (\n        this.draftId !== (this.draftId = this.draftEditor.settings.draftId) ||\n        !this.$iframe\n      ) {\n        refresh = true;\n      }\n\n      const target = this._activeTarget();\n      if (typeof refresh === 'undefined') {\n        refresh = resetScroll || this._autoRefresh();\n      }\n\n      this.trigger('beforeUpdateIframe', {\n        previewTarget: target,\n        resetScroll: resetScroll,\n        refresh: refresh,\n      });\n\n      // If this is an existing preview target, make sure it wants to be refreshed automatically\n      if (!refresh) {\n        this.slideIn();\n        return;\n      }\n\n      this.draftEditor\n        .getTokenizedPreviewUrl(target.url, 'x-craft-live-preview')\n        .then((url) => {\n          // Maintain the current scroll position?\n          let sameHost;\n          if (resetScroll) {\n            this.scrollTop = null;\n          } else if (this.iframeLoaded && this.$iframe) {\n            if (this._useIframeResizer()) {\n              this.iframeHeight = this.$iframe.height();\n              this.scrollTop = this.$iframeContainer.scrollTop();\n            } else {\n              sameHost = Craft.isSameHost(url);\n              if (sameHost && this.$iframe[0].contentWindow) {\n                this.scrollTop = $(\n                  this.$iframe[0].contentWindow.document\n                ).scrollTop();\n              }\n            }\n          }\n\n          this.iframeLoaded = false;\n\n          var $iframe = $('<iframe/>', {\n            class: 'lp-preview',\n            frameborder: 0,\n            src: url,\n            title: Craft.t('app', 'Preview'),\n          });\n\n          if (this.$iframe) {\n            this.$iframe.replaceWith($iframe);\n          } else {\n            $iframe.appendTo(this.$devicePreviewContainer);\n          }\n\n          // Keep the iframe height consistent with its content\n          if (this._useIframeResizer()) {\n            if (!resetScroll && this.iframeHeight !== null) {\n              $iframe.height(this.iframeHeight);\n              this.$iframeContainer.scrollTop(this.scrollTop);\n            }\n\n            iFrameResize(\n              $.extend(\n                {\n                  checkOrigin: false,\n                  // Allow iframe scrolling until we've successfully initialized the resizer\n                  scrolling: true,\n                  onInit: (iframe) => {\n                    this.iframeLoaded = true;\n                    this.iframeHeight = null;\n                    this.scrollTop = null;\n                    iframe.scrolling = 'no';\n                  },\n                },\n                Craft.previewIframeResizerOptions || {}\n              ),\n              $iframe[0]\n            );\n          } else {\n            $iframe.on('load', () => {\n              this.iframeLoaded = true;\n              if (!resetScroll && sameHost && this.scrollTop !== null) {\n                $($iframe[0].contentWindow.document).scrollTop(this.scrollTop);\n              }\n            });\n          }\n\n          this.url = url;\n          this.$iframe = $iframe;\n\n          if (this._devicePreviewIsActive()) {\n            this.updateDevicePreview();\n          }\n\n          this.trigger('afterUpdateIframe', {\n            previewTarget:\n              this.draftEditor.settings.previewTargets[this.activeTarget],\n            $iframe: this.$iframe,\n          });\n\n          this.slideIn();\n        });\n    },\n\n    _devicePreviewIsActive: function () {\n      return this.currentDeviceType !== 'desktop';\n    },\n\n    switchDeviceType: function (ev) {\n      this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n\n      const $input = $(ev.target);\n      const $inputWrapper = $input.closest('.lp-device-type__item');\n      const newDeviceType = $input.val();\n\n      // Bail if we’re just smashing the same button\n      if (newDeviceType === this.currentDeviceType) {\n        return false;\n      }\n\n      // Store new device type data\n      this.currentDeviceType = newDeviceType;\n      this.deviceWidth = $input.data('width');\n      this.deviceHeight = $input.data('height');\n\n      // Set the active state on the label\n      this.$deviceTypeContainer.find('.btn').removeClass('active');\n\n      $inputWrapper.find('.btn').addClass('active');\n\n      if (this.currentDeviceType === 'desktop') {\n        // Disable the orientation button\n        this.$orientationBtn.addClass('disabled').attr('disabled', '');\n\n        this.$iframeContainer.removeClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      } else {\n        // Enable the orientation button\n        this.$orientationBtn.removeClass('disabled').removeAttr('disabled');\n\n        this.$iframeContainer.addClass(\n          'lp-iframe-container--has-device-preview'\n        );\n      }\n\n      // Add the tablet class if needed\n      if (this.currentDeviceType === 'tablet') {\n        this.$iframeContainer.addClass('lp-iframe-container--tablet');\n      } else {\n        this.$iframeContainer.removeClass('lp-iframe-container--tablet');\n      }\n\n      if (this.currentDeviceType !== 'desktop') {\n        this.updateDevicePreview();\n      }\n    },\n\n    switchOrientation: function () {\n      if (!this._devicePreviewIsActive()) {\n        return false;\n      }\n\n      // Switch to whichever orientation is currently not stored\n      if (!this.deviceOrientation || this.deviceOrientation === 'portrait') {\n        this.deviceOrientation = 'landscape';\n      } else {\n        this.deviceOrientation = 'portrait';\n      }\n\n      // Store the new one\n      Craft.setLocalStorage('LivePreview.orientation', this.deviceOrientation);\n\n      // Allow the animation to take place\n      this.$iframeContainer.addClass('lp-iframe-container--rotating');\n\n      // Update the device preview\n      this.updateDevicePreview();\n\n      setTimeout(() => {\n        this.$iframeContainer.removeClass('lp-iframe-container--rotating');\n      }, 300);\n    },\n\n    updateDevicePreview: function () {\n      // Figure out the best zoom\n      let hZoom = 1;\n      let wZoom = 1;\n      let zoom = 1;\n      let previewHeight = this.$previewContainer.height() - 50 - 48; // 50px for the header bar and 24px clearance\n      let previewWidth = this.$previewContainer.width() - 48;\n      let maskHeight = this.deviceMaskDimensions[this.currentDeviceType].height;\n      let maskWidth = this.deviceMaskDimensions[this.currentDeviceType].width;\n\n      if (this.deviceOrientation === 'landscape') {\n        if (previewWidth < maskHeight) {\n          hZoom = previewWidth / maskHeight;\n        }\n        if (previewHeight < maskWidth) {\n          wZoom = previewHeight / maskWidth;\n        }\n      } else {\n        if (previewHeight < maskHeight) {\n          hZoom = previewHeight / maskHeight;\n        }\n        if (previewWidth < maskWidth) {\n          wZoom = previewWidth / maskWidth;\n        }\n      }\n\n      zoom = hZoom;\n      if (wZoom < hZoom) {\n        zoom = wZoom;\n      }\n\n      // Figure out the css values\n      const translate = -(100 / zoom / 2);\n      const rotationDeg =\n        this.deviceOrientation === 'landscape' ? '-90deg' : '0deg';\n\n      // Apply first to the device mask\n      this.$deviceMask.css({\n        width: this.deviceMaskDimensions[this.currentDeviceType].width + 'px',\n        height: this.deviceMaskDimensions[this.currentDeviceType].height + 'px',\n        transform:\n          'scale(' +\n          zoom +\n          ') translate(' +\n          translate +\n          '%, ' +\n          translate +\n          '%) rotate(' +\n          rotationDeg +\n          ')',\n      });\n\n      if (this.deviceOrientation === 'landscape') {\n        this.$devicePreviewContainer.css({\n          width: this.deviceHeight + 'px',\n          height: this.deviceWidth + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: 0,\n          marginLeft: '-' + 12 * zoom + 'px',\n        });\n      } else {\n        this.$devicePreviewContainer.css({\n          width: this.deviceWidth + 'px',\n          height: this.deviceHeight + 'px',\n          transform:\n            'scale(' +\n            zoom +\n            ') translate(' +\n            translate +\n            '%, ' +\n            translate +\n            '%)',\n          marginTop: '-' + 12 * zoom + 'px',\n          marginLeft: 0,\n        });\n      }\n    },\n\n    _getClone: function ($field) {\n      var $clone = $field.clone();\n\n      // clone() won't account for input values that have changed since the original HTML set them\n      Garnish.copyInputValues($field, $clone);\n\n      // Remove any id= attributes\n      $clone.attr('id', '');\n      $clone.find('[id]').attr('id', '');\n\n      // Disable anything with a name attribute\n      $clone.find('[name]').prop('disabled', true);\n\n      return $clone;\n    },\n\n    _onDragStart: function () {\n      this.dragStartEditorWidth = this.editorWidthInPx;\n      this.$previewContainer.addClass('dragging');\n    },\n\n    _onDrag: function () {\n      if (Craft.orientation === 'ltr') {\n        this.editorWidth = this.dragStartEditorWidth + this.dragger.mouseDistX;\n      } else {\n        this.editorWidth = this.dragStartEditorWidth - this.dragger.mouseDistX;\n      }\n\n      this.updateWidths();\n    },\n\n    _onDragStop: function () {\n      this.$previewContainer.removeClass('dragging');\n      Craft.setLocalStorage('LivePreview.editorWidth', this.editorWidth);\n    },\n  },\n  {\n    defaultEditorWidth: 0.33,\n    minEditorWidthInPx: 320,\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Preview File Modal\n */\nCraft.PreviewFileModal = Garnish.Modal.extend(\n  {\n    assetId: null,\n    $spinner: null,\n    elementSelect: null,\n    type: null,\n    loaded: null,\n    requestId: 0,\n\n    /**\n     * Initialize the preview file modal.\n     * @returns {*|void}\n     */\n    init: function (assetId, elementSelect, settings) {\n      settings = $.extend(this.defaultSettings, settings);\n\n      settings.onHide = this._onHide.bind(this);\n\n      if (Craft.PreviewFileModal.openInstance) {\n        var instance = Craft.PreviewFileModal.openInstance;\n\n        if (instance.assetId !== assetId) {\n          instance.loadAsset(\n            assetId,\n            settings.startingWidth,\n            settings.startingHeight\n          );\n          instance.elementSelect = elementSelect;\n        }\n\n        return this.destroy();\n      }\n\n      Craft.PreviewFileModal.openInstance = this;\n      this.elementSelect = elementSelect;\n\n      this.$container = $('<div class=\"modal previewmodal loading\"/>').appendTo(\n        Garnish.$bod\n      );\n\n      this.base(\n        this.$container,\n        $.extend(\n          {\n            resizable: true,\n          },\n          settings\n        )\n      );\n\n      // Cut the flicker, just show the nice person the preview.\n      if (this.$container) {\n        this.$container.velocity('stop');\n        this.$container.show().css('opacity', 1);\n\n        this.$shade.velocity('stop');\n        this.$shade.show().css('opacity', 1);\n      }\n\n      this.loadAsset(assetId, settings.startingWidth, settings.startingHeight);\n    },\n\n    /**\n     * When hiding, remove all traces and focus last focused element.\n     * @private\n     */\n    _onHide: function () {\n      Craft.PreviewFileModal.openInstance = null;\n      if (this.elementSelect) {\n        this.elementSelect.focusItem(this.elementSelect.$focusedItem);\n      }\n\n      this.$shade.remove();\n\n      return this.destroy();\n    },\n\n    /**\n     * Disappear immediately forever.\n     * @returns {boolean}\n     */\n    selfDestruct: function () {\n      var instance = Craft.PreviewFileModal.openInstance;\n\n      instance.hide();\n      instance.$shade.remove();\n      instance.destroy();\n\n      Craft.PreviewFileModal.openInstance = null;\n\n      return true;\n    },\n\n    /**\n     * Load an asset, using starting width and height, if applicable\n     * @param assetId\n     * @param startingWidth\n     * @param startingHeight\n     */\n    loadAsset: function (assetId, startingWidth, startingHeight) {\n      this.assetId = assetId;\n\n      this.$container.empty();\n      this.loaded = false;\n\n      this.desiredHeight = null;\n      this.desiredWidth = null;\n\n      var containerHeight = Garnish.$win.height() * 0.66;\n      var containerWidth = Math.min(\n        (containerHeight / 3) * 4,\n        Garnish.$win.width() - this.settings.minGutter * 2\n      );\n      containerHeight = (containerWidth / 4) * 3;\n\n      if (startingWidth && startingHeight) {\n        var ratio = startingWidth / startingHeight;\n        containerWidth = Math.min(\n          startingWidth,\n          Garnish.$win.width() - this.settings.minGutter * 2\n        );\n        containerHeight = Math.min(\n          containerWidth / ratio,\n          Garnish.$win.height() - this.settings.minGutter * 2\n        );\n        containerWidth = containerHeight * ratio;\n\n        // This might actually have put width over the viewport limits, so doublecheck\n        if (\n          containerWidth >\n          Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          )\n        ) {\n          containerWidth = Math.min(\n            startingWidth,\n            Garnish.$win.width() - this.settings.minGutter * 2\n          );\n          containerHeight = containerWidth / ratio;\n        }\n      }\n\n      this._resizeContainer(containerWidth, containerHeight);\n\n      this.$spinner = $('<div class=\"spinner centeralign\"></div>').appendTo(\n        this.$container\n      );\n      var top =\n          this.$container.height() / 2 - this.$spinner.height() / 2 + 'px',\n        left = this.$container.width() / 2 - this.$spinner.width() / 2 + 'px';\n\n      this.$spinner.css({left: left, top: top, position: 'absolute'});\n      this.requestId++;\n\n      Craft.postActionRequest(\n        'assets/preview-file',\n        {assetId: assetId, requestId: this.requestId},\n        (response, textStatus) => {\n          this.$container.removeClass('loading');\n          this.$spinner.remove();\n          this.loaded = true;\n\n          if (textStatus === 'success') {\n            if (response.success) {\n              if (response.requestId != this.requestId) {\n                return;\n              }\n\n              if (!response.previewHtml) {\n                this.$container.addClass('zilch');\n                this.$container.append(\n                  $('<p/>', {text: Craft.t('app', 'No preview available.')})\n                );\n                return;\n              }\n\n              this.$container.removeClass('zilch');\n              this.$container.append(response.previewHtml);\n              Craft.appendHeadHtml(response.headHtml);\n              Craft.appendFootHtml(response.footHtml);\n            } else {\n              alert(response.error);\n\n              this.hide();\n            }\n          }\n        }\n      );\n    },\n\n    /**\n     * Resize the container to specified dimensions\n     * @param containerWidth\n     * @param containerHeight\n     * @private\n     */\n    _resizeContainer: function (containerWidth, containerHeight) {\n      this.$container.css({\n        width: containerWidth,\n        'min-width': containerWidth,\n        'max-width': containerWidth,\n        height: containerHeight,\n        'min-height': containerHeight,\n        'max-height': containerHeight,\n        top: (Garnish.$win.height() - containerHeight) / 2,\n        left: (Garnish.$win.width() - containerWidth) / 2,\n      });\n    },\n  },\n  {\n    defaultSettings: {\n      startingWidth: null,\n      startingHeight: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.ProgressBar = Garnish.Base.extend({\n  $progressBar: null,\n  $innerProgressBar: null,\n  $progressBarStatus: null,\n\n  _itemCount: 0,\n  _processedItemCount: 0,\n  _displaySteps: false,\n\n  init: function ($element, displaySteps) {\n    if (displaySteps) {\n      this._displaySteps = true;\n    }\n\n    this.$progressBar = $('<div class=\"progressbar pending hidden\"/>').appendTo(\n      $element\n    );\n    this.$innerProgressBar = $('<div class=\"progressbar-inner\"/>').appendTo(\n      this.$progressBar\n    );\n    this.$progressBarStatus = $(\n      '<div class=\"progressbar-status hidden\" />'\n    ).insertAfter(this.$progressBar);\n\n    this.resetProgressBar();\n  },\n\n  /**\n   * Reset the progress bar\n   */\n  resetProgressBar: function () {\n    // Since setting the progress percentage implies that there is progress to be shown\n    // It removes the pending class - we must add it back.\n    this.setProgressPercentage(100);\n    this.$progressBar.addClass('pending');\n\n    // Reset all the counters\n    this.setItemCount(1);\n    this.setProcessedItemCount(0);\n    this.$progressBarStatus.html('');\n\n    if (this._displaySteps) {\n      this.$progressBar.addClass('has-status');\n    }\n  },\n\n  /**\n   * Fade to invisible, hide it using a class and reset opacity to visible\n   */\n  hideProgressBar: function () {\n    this.$progressBar.fadeTo('fast', 0.01, () => {\n      this.$progressBar.addClass('hidden').fadeTo(1, 1, $.noop);\n    });\n    this.$progressBarStatus.fadeTo('fast', 0.01, () => {\n      this.$progressBarStatus.addClass('hidden').fadeTo(1, 1, $.noop);\n    });\n  },\n\n  showProgressBar: function () {\n    this.$progressBar.removeClass('hidden');\n    this.$progressBarStatus.removeClass('hidden');\n  },\n\n  setItemCount: function (count) {\n    this._itemCount = count;\n  },\n\n  incrementItemCount: function (count) {\n    this._itemCount += count;\n  },\n\n  setProcessedItemCount: function (count) {\n    this._processedItemCount = count;\n  },\n\n  incrementProcessedItemCount: function (count) {\n    this._processedItemCount += count;\n  },\n\n  updateProgressBar: function () {\n    // Only fools would allow accidental division by zero.\n    this._itemCount = Math.max(this._itemCount, 1);\n\n    var width = Math.min(\n      100,\n      Math.round((100 * this._processedItemCount) / this._itemCount)\n    );\n\n    this.setProgressPercentage(width);\n\n    if (this._displaySteps) {\n      this.$progressBarStatus.html(\n        this._processedItemCount + ' / ' + this._itemCount\n      );\n    }\n  },\n\n  setProgressPercentage: function (percentage, animate) {\n    if (percentage === 0) {\n      this.$progressBar.addClass('pending');\n    } else {\n      this.$progressBar.removeClass('pending');\n\n      if (animate) {\n        this.$innerProgressBar\n          .velocity('stop')\n          .velocity({width: percentage + '%'}, 'fast');\n      } else {\n        this.$innerProgressBar.velocity('stop').width(percentage + '%');\n      }\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.PromptHandler = Garnish.Base.extend({\n  modal: null,\n  $modalContainerDiv: null,\n  $prompt: null,\n  $promptApplyToRemainingContainer: null,\n  $promptApplyToRemainingCheckbox: null,\n  $promptApplyToRemainingLabel: null,\n  $pomptChoices: null,\n\n  _prompts: [],\n  _promptBatchCallback: $.noop,\n  _promptBatchReturnData: [],\n  _promptBatchNum: 0,\n\n  resetPrompts: function () {\n    this._prompts = [];\n    this._promptBatchCallback = $.noop;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n  },\n\n  addPrompt: function (prompt) {\n    this._prompts.push(prompt);\n  },\n\n  getPromptCount: function () {\n    return this._prompts.length;\n  },\n\n  showBatchPrompts: function (callback) {\n    this._promptBatchCallback = callback;\n    this._promptBatchReturnData = [];\n    this._promptBatchNum = 0;\n\n    this._showNextPromptInBatch();\n  },\n\n  _showNextPromptInBatch: function () {\n    var prompt = this._prompts[this._promptBatchNum].prompt,\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    this._showPrompt(\n      prompt.message,\n      prompt.choices,\n      this._handleBatchPromptSelection.bind(this),\n      remainingInBatch\n    );\n  },\n\n  /**\n   * Handles a prompt choice selection.\n   *\n   * @param choice\n   * @param applyToRemaining\n   * @private\n   */\n  _handleBatchPromptSelection: function (choice, applyToRemaining) {\n    var prompt = this._prompts[this._promptBatchNum],\n      remainingInBatch = this._prompts.length - (this._promptBatchNum + 1);\n\n    // Record this choice\n    var choiceData = $.extend(prompt, {choice});\n    this._promptBatchReturnData.push(choiceData);\n\n    // Are there any remaining items in the batch?\n    if (remainingInBatch) {\n      // Get ready to deal with the next prompt\n      this._promptBatchNum++;\n\n      // Apply the same choice to the remaining items?\n      if (applyToRemaining) {\n        this._handleBatchPromptSelection(choice, true);\n      } else {\n        // Show the next prompt\n        this._showNextPromptInBatch();\n      }\n    } else {\n      // All done! Call the callback\n      if (typeof this._promptBatchCallback === 'function') {\n        this._promptBatchCallback(this._promptBatchReturnData);\n      }\n    }\n  },\n\n  /**\n   * Show the user prompt with a given message and choices, plus an optional \"Apply to remaining\" checkbox.\n   *\n   * @param {string} message\n   * @param {object} choices\n   * @param {function} callback\n   * @param {number} itemsToGo\n   */\n  _showPrompt: function (message, choices, callback, itemsToGo) {\n    this._promptCallback = callback;\n\n    if (this.modal === null) {\n      this.modal = new Garnish.Modal({closeOtherModals: false});\n    }\n\n    if (this.$modalContainerDiv === null) {\n      this.$modalContainerDiv = $(\n        '<div class=\"modal fitted prompt-modal\"></div>'\n      )\n        .addClass()\n        .appendTo(Garnish.$bod);\n    }\n\n    this.$prompt = $('<div class=\"body\"></div>').appendTo(\n      this.$modalContainerDiv.empty()\n    );\n\n    this.$promptMessage = $('<p class=\"prompt-msg\"/>').appendTo(this.$prompt);\n\n    this.$promptChoices = $('<div class=\"options\"></div>').appendTo(\n      this.$prompt\n    );\n\n    this.$promptApplyToRemainingContainer = $(\n      '<label class=\"assets-applytoremaining\"/>'\n    )\n      .appendTo(this.$prompt)\n      .hide();\n    this.$promptApplyToRemainingCheckbox = $(\n      '<input type=\"checkbox\"/>'\n    ).appendTo(this.$promptApplyToRemainingContainer);\n    this.$promptApplyToRemainingLabel = $('<span/>').appendTo(\n      this.$promptApplyToRemainingContainer\n    );\n\n    this.$promptButtons = $('<div class=\"buttons right\"/>').appendTo(\n      this.$prompt\n    );\n\n    this.modal.setContainer(this.$modalContainerDiv);\n\n    this.$promptMessage.html(message);\n\n    let $cancelBtn = $('<button/>', {\n      type: 'button',\n      class: 'btn',\n      text: Craft.t('app', 'Cancel'),\n    }).appendTo(this.$promptButtons);\n    let $submitBtn = $('<button/>', {\n      type: 'submit',\n      class: 'btn submit disabled',\n      text: Craft.t('app', 'OK'),\n    }).appendTo(this.$promptButtons);\n\n    for (var i = 0; i < choices.length; i++) {\n      var $radioButtonHtml = $(\n          '<div><label><input type=\"radio\" name=\"promptAction\" value=\"' +\n            choices[i].value +\n            '\"/> ' +\n            choices[i].title +\n            '</label></div>'\n        ).appendTo(this.$promptChoices),\n        $radioButton = $radioButtonHtml.find('input');\n\n      this.addListener($radioButton, 'click', function () {\n        $submitBtn.removeClass('disabled');\n      });\n    }\n\n    this.addListener($submitBtn, 'activate', function (ev) {\n      var choice = $(ev.currentTarget)\n          .parents('.modal')\n          .find('input[name=promptAction]:checked')\n          .val(),\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    this.addListener($cancelBtn, 'activate', function () {\n      var choice = 'cancel',\n        applyToRemaining = this.$promptApplyToRemainingCheckbox.prop('checked');\n\n      this._selectPromptChoice(choice, applyToRemaining);\n    });\n\n    if (itemsToGo) {\n      this.$promptApplyToRemainingContainer.show();\n      this.$promptApplyToRemainingLabel.html(\n        ' ' +\n          Craft.t('app', 'Apply this to the {number} remaining conflicts?', {\n            number: itemsToGo,\n          })\n      );\n    }\n\n    this.modal.show();\n    this.modal.removeListener(Garnish.Modal.$shade, 'click');\n    this.addListener(Garnish.Modal.$shade, 'click', '_cancelPrompt');\n  },\n\n  /**\n   * Handles when a user selects one of the prompt choices.\n   *\n   * @param choice\n   * @param applyToRemaining\n   * @private\n   */\n  _selectPromptChoice: function (choice, applyToRemaining) {\n    this.$prompt.fadeOut('fast', () => {\n      this.modal.hide();\n      this._promptCallback(choice, applyToRemaining);\n    });\n  },\n\n  /**\n   * Cancels the prompt.\n   */\n  _cancelPrompt: function () {\n    this._selectPromptChoice('cancel', true);\n  },\n});\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.SlidePicker = Garnish.Base.extend(\n    {\n      min: null,\n      max: null,\n      totalSteps: null,\n      value: null,\n\n      $container: null,\n      $buttons: null,\n\n      init: function (value, settings) {\n        this.setSettings(settings, Craft.SlidePicker.defaults);\n\n        this.$container = $('<div/>', {\n          class: 'slide-picker',\n          role: 'slider',\n          tabindex: 0,\n        });\n\n        this.refresh();\n        this.setValue(value, false);\n\n        this.addListener(this.$container, 'keydown', (ev) => {\n          switch (ev.keyCode) {\n            case Garnish.UP_KEY:\n              this.setValue(this.value + this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.DOWN_KEY:\n              this.setValue(this.value - this.settings.step);\n              ev.preventDefault();\n              break;\n            case Garnish.RIGHT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value + this.settings.step);\n              } else {\n                this.setValue(this.value - this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n            case Garnish.LEFT_KEY:\n              if (Craft.orientation === 'ltr') {\n                this.setValue(this.value - this.settings.step);\n              } else {\n                this.setValue(this.value + this.settings.step);\n              }\n              ev.preventDefault();\n              break;\n          }\n        });\n      },\n\n      refresh: function () {\n        // Figure out what the min/max values are\n        this.min = this._min();\n        this.max = this._max();\n        this.totalSteps = (this.max - this.min) / this.settings.step;\n\n        if (!Number.isInteger(this.totalSteps)) {\n          throw 'Invalid SlidePicker config';\n        }\n\n        if (this.$buttons) {\n          this.$buttons.remove();\n        }\n\n        this.$container.attr('aria-valuemin', this.min);\n        this.$container.attr('aria-valuemax', this.max);\n        this.$buttons = $();\n\n        // Create the buttons\n        for (\n          let value = this.min;\n          value <= this.max;\n          value += this.settings.step\n        ) {\n          this.$buttons = this.$buttons.add(\n            $('<a/>', {\n              title: this.settings.valueLabel(value),\n              data: {value},\n            })\n          );\n        }\n\n        this.$buttons.appendTo(this.$container);\n\n        if (this.value !== null) {\n          let value = this.value;\n          this.value = null;\n          this.setValue(value, false);\n        }\n\n        this.addListener(this.$buttons, 'mouseover', (ev) => {\n          this.$buttons.removeClass('active-hover last-active-hover');\n          $(ev.currentTarget)\n            .addClass('active-hover last-active-hover')\n            .prevAll()\n            .addClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'mouseout', () => {\n          this.$buttons.removeClass('active-hover');\n        });\n\n        this.addListener(this.$buttons, 'click', (ev) => {\n          this.setValue($.data(ev.currentTarget, 'value'));\n          ev.stopPropagation();\n          this.$container.focus();\n        });\n      },\n\n      setValue: function (value, triggerEvent) {\n        value = Math.max(Math.min(value, this.max), this.min);\n\n        if (this.value === (this.value = value)) {\n          return;\n        }\n\n        this.$container.attr({\n          'aria-valuenow': this.value,\n          'aria-valuetext': this.settings.valueLabel(this.value),\n        });\n\n        this.$buttons.removeClass('last-active active');\n        let $activeButton = this.$buttons.eq(\n          (this.value - this.min) / this.settings.step\n        );\n        $activeButton.add($activeButton.prevAll()).addClass('active');\n        $activeButton.addClass('last-active');\n\n        if (triggerEvent !== false) {\n          this.settings.onChange(value);\n        }\n      },\n\n      _min: function () {\n        if (typeof this.settings.min === 'function') {\n          return this.settings.min();\n        }\n        return this.settings.min;\n      },\n\n      _max: function () {\n        if (typeof this.settings.max === 'function') {\n          return this.settings.max();\n        }\n        return this.settings.max;\n      },\n    },\n    {\n      defaults: {\n        min: 0,\n        max: 100,\n        step: 10,\n        valueLabel: null,\n        onChange: $.noop,\n      },\n    }\n  );\n})(jQuery);\n","/** global: Garnish */\n\nCraft.SlideRuleInput = Garnish.Base.extend({\n  $container: null,\n  $options: null,\n  $selectedOption: null,\n  $input: null,\n  value: null,\n\n  startPositionX: null,\n\n  init: function (id, settings) {\n    this.setSettings(settings, Craft.SlideRuleInput.defaultSettings);\n\n    this.value = 0;\n    this.graduationsMin = -70;\n    this.graduationsMax = 70;\n    this.slideMin = -45;\n    this.slideMax = 45;\n\n    this.$container = $('#' + id);\n    this.$overlay = $('<div class=\"overlay\"></div>').appendTo(this.$container);\n    this.$cursor = $('<div class=\"cursor\"></div>').appendTo(this.$container);\n    this.$graduations = $('<div class=\"graduations\"></div>').appendTo(\n      this.$container\n    );\n    this.$graduationsUl = $('<ul></ul>').appendTo(this.$graduations);\n\n    for (var i = this.graduationsMin; i <= this.graduationsMax; i++) {\n      var $li = $(\n        '<li class=\"graduation\" data-graduation=\"' +\n          i +\n          '\"><div class=\"label\">' +\n          i +\n          '</div></li>'\n      ).appendTo(this.$graduationsUl);\n\n      if (i % 5 === 0) {\n        $li.addClass('main-graduation');\n      }\n\n      if (i === 0) {\n        $li.addClass('selected');\n      }\n    }\n\n    this.$options = this.$container.find('.graduation');\n\n    this.addListener(this.$container, 'resize', this._handleResize.bind(this));\n    this.addListener(\n      this.$container,\n      'tapstart',\n      this._handleTapStart.bind(this)\n    );\n    this.addListener(Garnish.$bod, 'tapmove', this._handleTapMove.bind(this));\n    this.addListener(Garnish.$bod, 'tapend', this._handleTapEnd.bind(this));\n\n    // Set to zero\n\n    // this.setValue(0);\n\n    setTimeout(() => {\n      // (n -1) options because the border is placed on the left of the 10px box\n      this.graduationsCalculatedWidth = (this.$options.length - 1) * 10;\n      this.$graduationsUl.css(\n        'left',\n        -this.graduationsCalculatedWidth / 2 + this.$container.width() / 2\n      );\n    }, 50);\n  },\n\n  _handleResize: function () {\n    var left = this.valueToPosition(this.value);\n    this.$graduationsUl.css('left', left);\n  },\n\n  _handleTapStart: function (ev, touch) {\n    ev.preventDefault();\n\n    this.startPositionX = touch.position.x;\n    this.startLeft = this.$graduationsUl.position().left;\n\n    this.dragging = true;\n    this.onStart();\n  },\n\n  _handleTapMove: function (ev, touch) {\n    if (this.dragging) {\n      ev.preventDefault();\n\n      var curX = this.startPositionX - touch.position.x;\n      var left = this.startLeft - curX;\n      var value = this.positionToValue(left);\n\n      this.setValue(value);\n\n      this.onChange();\n    }\n  },\n\n  setValue: function (value) {\n    var left = this.valueToPosition(value);\n    if (value < this.slideMin) {\n      value = this.slideMin;\n      left = this.valueToPosition(value);\n    } else if (value > this.slideMax) {\n      value = this.slideMax;\n      left = this.valueToPosition(value);\n    }\n\n    this.$graduationsUl.css('left', left);\n\n    if (value >= this.slideMin && value <= this.slideMax) {\n      this.$options.removeClass('selected');\n\n      $.each(this.$options, function (key, option) {\n        if ($(option).data('graduation') > 0) {\n          if ($(option).data('graduation') <= value) {\n            $(option).addClass('selected');\n          }\n        }\n        if ($(option).data('graduation') < 0) {\n          if ($(option).data('graduation') >= value) {\n            $(option).addClass('selected');\n          }\n        }\n\n        if ($(option).data('graduation') == 0) {\n          $(option).addClass('selected');\n        }\n      });\n    }\n\n    this.value = value;\n  },\n\n  _handleTapEnd: function (ev) {\n    if (this.dragging) {\n      ev.preventDefault();\n      this.dragging = false;\n      this.onEnd();\n    }\n  },\n\n  positionToValue: function (position) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return (\n      ((this.$graduations.width() / 2 + position * -1) /\n        this.graduationsCalculatedWidth) *\n        scaleMax -\n      scaleMin\n    );\n  },\n\n  valueToPosition: function (value) {\n    var scaleMin = this.graduationsMin * -1;\n    var scaleMax = (this.graduationsMin - this.graduationsMax) * -1;\n\n    return -(\n      ((value + scaleMin) * this.graduationsCalculatedWidth) / scaleMax -\n      this.$graduations.width() / 2\n    );\n  },\n\n  onStart: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onStart(this);\n    }\n  },\n\n  onChange: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onChange(this);\n    }\n  },\n\n  onEnd: function () {\n    if (typeof this.settings.onChange === 'function') {\n      this.settings.onEnd(this);\n    }\n  },\n\n  defaultSettings: {\n    onStart: $.noop,\n    onChange: $.noop,\n    onEnd: $.noop,\n  },\n});\n","(function ($) {\n  /** global: Craft */\n  /** global: Garnish */\n  /**\n   * Slide Picker\n   */\n  Craft.Slideout = Garnish.Base.extend(\n    {\n      $outerContainer: null,\n      $container: null,\n      $shade: null,\n      isOpen: false,\n\n      init: function (contents, settings) {\n        this.setSettings(settings, Craft.Slideout.defaults);\n\n        if (!Garnish.isMobileBrowser()) {\n          this.$shade = $('<div class=\"slideout-shade\"/>').appendTo(\n            Garnish.$bod\n          );\n\n          if (this.settings.closeOnShadeClick) {\n            this.addListener(this.$shade, 'click', (ev) => {\n              ev.stopPropagation();\n              this.close();\n            });\n          }\n        }\n\n        this.$outerContainer = $('<div/>', {\n          class: 'slideout-container hidden',\n        });\n        this.$container = $(\n          `<${this.settings.containerElement}/>`,\n          this.settings.containerAttributes\n        )\n          .addClass('slideout')\n          .append(contents)\n          .data('slideout', this)\n          .appendTo(this.$outerContainer);\n\n        Garnish.addModalAttributes(this.$outerContainer);\n\n        if (Garnish.isMobileBrowser()) {\n          this.$container.addClass('so-mobile');\n        }\n\n        Craft.trapFocusWithin(this.$container);\n\n        if (this.settings.autoOpen) {\n          this.open();\n        }\n      },\n\n      open: function () {\n        if (this.isOpen) {\n          return;\n        }\n\n        this.setTriggerElement(document.activeElement);\n\n        this._cancelTransitionListeners();\n\n        // Move the shade + container to the end of <body> so they get the highest sub-z-indexes\n        if (this.$shade) {\n          this.$shade.appendTo(Garnish.$bod).show();\n        }\n\n        this.$outerContainer.appendTo(Garnish.$bod).removeClass('hidden');\n\n        if (Garnish.isMobileBrowser()) {\n          this.$container.css('top', '100vh');\n        } else {\n          this.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n        }\n\n        this.$container.one('transitionend.slideout', () => {\n          Craft.setFocusWithin(this.$container);\n        });\n\n        if (this.$shade) {\n          this.$shade[0].offsetWidth;\n          this.$shade.addClass('so-visible');\n        }\n\n        this.$container[0].offsetWidth;\n        Craft.Slideout.addPanel(this);\n\n        this.enable();\n        Garnish.uiLayerManager.addLayer(this.$outerContainer);\n        Garnish.hideModalBackgroundLayers(this.$outerContainer);\n\n        if (this.settings.closeOnEsc) {\n          Garnish.uiLayerManager.registerShortcut(Garnish.ESC_KEY, () => {\n            this.close();\n          });\n        }\n\n        this.isOpen = true;\n        this.trigger('open');\n      },\n\n      setTriggerElement: function (trigger) {\n        this.settings.triggerElement = trigger;\n      },\n\n      close: function () {\n        if (!this.isOpen) {\n          return;\n        }\n\n        this.trigger('beforeClose');\n        this.disable();\n        this.isOpen = false;\n\n        this._cancelTransitionListeners();\n\n        if (this.$shade) {\n          this.$shade\n            .removeClass('so-visible')\n            .one('transitionend.slideout', () => {\n              this.$shade.hide();\n            });\n        }\n\n        Craft.Slideout.removePanel(this);\n        Garnish.uiLayerManager.removeLayer();\n        Garnish.resetModalBackgroundLayerVisibility(this.$outerContainer);\n        this.$container.one('transitionend.slideout', () => {\n          this.$outerContainer.addClass('hidden');\n          this.trigger('close');\n        });\n\n        if (this.settings.triggerElement) {\n          this.settings.triggerElement.focus();\n        }\n      },\n\n      _cancelTransitionListeners: function () {\n        if (this.$shade) {\n          this.$shade.off('transitionend.slideout');\n        }\n\n        this.$container.off('transitionend.slideout');\n      },\n\n      /**\n       * Destroy\n       */\n      destroy: function () {\n        if (this.$shade) {\n          this.$shade.remove();\n          this.$shade = null;\n        }\n\n        this.$outerContainer.remove();\n        this.$outerContainer = null;\n        this.$container = null;\n\n        this.base();\n      },\n    },\n    {\n      defaults: {\n        containerElement: 'div',\n        containerAttributes: {},\n        autoOpen: true,\n        closeOnEsc: true,\n        closeOnShadeClick: true,\n        triggerElement: null,\n      },\n      openPanels: [],\n      addPanel: function (panel) {\n        Craft.Slideout.openPanels.unshift(panel);\n        if (Garnish.isMobileBrowser()) {\n          panel.$container.css('top', 0);\n        } else {\n          Craft.Slideout.updateStyles();\n        }\n      },\n      removePanel: function (panel) {\n        Craft.Slideout.openPanels = Craft.Slideout.openPanels.filter(\n          (m) => m !== panel\n        );\n        if (Garnish.isMobileBrowser()) {\n          panel.$container.css('top', '100vh');\n        } else {\n          panel.$container.css(Garnish.ltr ? 'left' : 'right', '100vw');\n          Craft.Slideout.updateStyles();\n        }\n      },\n      updateStyles: function () {\n        const totalPanels = Craft.Slideout.openPanels.length;\n        Craft.Slideout.openPanels.forEach((panel, i) => {\n          panel.$container.css(\n            Garnish.ltr ? 'left' : 'right',\n            `${50 * ((totalPanels - i) / totalPanels)}vw`\n          );\n        });\n\n        if (totalPanels !== 0) {\n          Garnish.$bod.addClass('no-scroll');\n        } else {\n          Garnish.$bod.removeClass('no-scroll');\n        }\n      },\n    }\n  );\n})(jQuery);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Slug Generator\n */\nCraft.SlugGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace(/<(.*?)>/g, '');\n\n    // Remove inner-word punctuation\n    sourceVal = sourceVal.replace(/['\"‘’“”\\[\\]\\(\\)\\{\\}:]/g, '');\n\n    // Make it lowercase\n    if (!Craft.allowUppercaseInSlug) {\n      sourceVal = sourceVal.toLowerCase();\n    }\n\n    if (Craft.limitAutoSlugsToAscii) {\n      // Convert extended ASCII characters to basic ASCII\n      sourceVal = Craft.asciiString(sourceVal, this.settings.charMap);\n    }\n\n    // Get the \"words\". Split on anything that is not alphanumeric.\n    // Reference: http://www.regular-expressions.info/unicode.html\n    var words = Craft.filterArray(\n      XRegExp.matchChain(sourceVal, [XRegExp('[\\\\p{L}\\\\p{N}\\\\p{M}]+')])\n    );\n\n    if (words.length) {\n      return words.join(Craft.slugWordSeparator);\n    } else {\n      return '';\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure class\n */\nCraft.Structure = Garnish.Base.extend(\n  {\n    id: null,\n\n    $container: null,\n    state: null,\n    structureDrag: null,\n\n    /**\n     * Init\n     */\n    init: function (id, container, settings) {\n      this.id = id;\n      this.$container = $(container);\n      this.setSettings(settings, Craft.Structure.defaults);\n\n      // Is this already a structure?\n      if (this.$container.data('structure')) {\n        console.warn('Double-instantiating a structure on an element');\n        this.$container.data('structure').destroy();\n      }\n\n      this.$container.data('structure', this);\n\n      this.state = {};\n\n      if (this.settings.storageKey) {\n        $.extend(\n          this.state,\n          Craft.getLocalStorage(this.settings.storageKey, {})\n        );\n      }\n\n      if (typeof this.state.collapsedElementIds === 'undefined') {\n        this.state.collapsedElementIds = [];\n      }\n\n      var $parents = this.$container.find('ul').prev('.row');\n\n      for (var i = 0; i < $parents.length; i++) {\n        var $row = $($parents[i]),\n          $li = $row.parent(),\n          $toggle = $(\n            '<div class=\"toggle\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\"/>'\n          ).prependTo($row);\n\n        if (\n          $.inArray(\n            $row.children('.element').data('id'),\n            this.state.collapsedElementIds\n          ) !== -1\n        ) {\n          $li.addClass('collapsed');\n        }\n\n        this.initToggle($toggle);\n      }\n\n      if (this.settings.sortable) {\n        this.structureDrag = new Craft.StructureDrag(\n          this,\n          this.settings.maxLevels\n        );\n      }\n\n      if (this.settings.newChildUrl) {\n        this.initNewChildMenus(this.$container.find('.add'));\n      }\n    },\n\n    initToggle: function ($toggle) {\n      $toggle.on('click', (ev) => {\n        var $li = $(ev.currentTarget).closest('li'),\n          elementId = $li.children('.row').find('.element:first').data('id'),\n          viewStateKey = $.inArray(elementId, this.state.collapsedElementIds);\n\n        if ($li.hasClass('collapsed')) {\n          $li.removeClass('collapsed');\n\n          if (viewStateKey !== -1) {\n            this.state.collapsedElementIds.splice(viewStateKey, 1);\n          }\n        } else {\n          $li.addClass('collapsed');\n\n          if (viewStateKey === -1) {\n            this.state.collapsedElementIds.push(elementId);\n          }\n        }\n\n        if (this.settings.storageKey) {\n          Craft.setLocalStorage(this.settings.storageKey, this.state);\n        }\n      });\n    },\n\n    initNewChildMenus: function ($addBtns) {\n      this.addListener($addBtns, 'click', 'onNewChildMenuClick');\n    },\n\n    onNewChildMenuClick: function (ev) {\n      var $btn = $(ev.currentTarget);\n\n      if (!$btn.data('menubtn')) {\n        var elementId = $btn.parent().children('.element').data('id'),\n          newChildUrl = Craft.getUrl(\n            this.settings.newChildUrl,\n            'parentId=' + elementId\n          );\n\n        $(\n          '<div class=\"menu\"><ul><li><a href=\"' +\n            newChildUrl +\n            '\">' +\n            Craft.t('app', 'New child') +\n            '</a></li></ul></div>'\n        ).insertAfter($btn);\n\n        var menuBtn = new Garnish.MenuBtn($btn);\n        menuBtn.showMenu();\n      }\n    },\n\n    getIndent: function (level) {\n      return (\n        Craft.Structure.baseIndent + (level - 1) * Craft.Structure.nestedIndent\n      );\n    },\n\n    addElement: function ($element) {\n      var $li = $('<li data-level=\"1\"/>').appendTo(this.$container),\n        $row = $(\n          '<div class=\"row\" style=\"margin-' +\n            Craft.left +\n            ': -' +\n            Craft.Structure.baseIndent +\n            'px; padding-' +\n            Craft.left +\n            ': ' +\n            Craft.Structure.baseIndent +\n            'px;\">'\n        ).appendTo($li);\n\n      $row.append($element);\n\n      if (this.settings.sortable) {\n        $row.append(\n          '<a class=\"move icon\" title=\"' + Craft.t('app', 'Move') + '\"></a>'\n        );\n        this.structureDrag.addItems($li);\n      }\n\n      if (this.settings.newChildUrl) {\n        var $addBtn = $(\n          '<a class=\"add icon\" title=\"' + Craft.t('app', 'New child') + '\"></a>'\n        ).appendTo($row);\n        this.initNewChildMenus($addBtn);\n      }\n\n      $row.css('margin-bottom', -30);\n      $row.velocity({'margin-bottom': 0}, 'fast');\n    },\n\n    removeElement: function ($element) {\n      var $li = $element.parent().parent();\n\n      if (this.settings.sortable) {\n        this.structureDrag.removeItems($li);\n      }\n\n      var $parentUl;\n\n      if (!$li.siblings().length) {\n        $parentUl = $li.parent();\n      }\n\n      $li\n        .css('visibility', 'hidden')\n        .velocity({marginBottom: -$li.height()}, 'fast', () => {\n          $li.remove();\n\n          if (typeof $parentUl !== 'undefined') {\n            this._removeUl($parentUl);\n          }\n        });\n    },\n\n    _removeUl: function ($ul) {\n      $ul.siblings('.row').children('.toggle').remove();\n      $ul.remove();\n    },\n\n    destroy: function () {\n      this.$container.removeData('structure');\n      this.base();\n    },\n  },\n  {\n    baseIndent: 8,\n    nestedIndent: 35,\n\n    defaults: {\n      storageKey: null,\n      sortable: false,\n      newChildUrl: null,\n      maxLevels: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Structure drag class\n */\nCraft.StructureDrag = Garnish.Drag.extend({\n  structure: null,\n  maxLevels: null,\n  draggeeLevel: null,\n\n  $helperLi: null,\n  $targets: null,\n  draggeeHeight: null,\n\n  init: function (structure, maxLevels) {\n    this.structure = structure;\n    this.maxLevels = maxLevels;\n\n    this.$insertion = $('<li class=\"draginsertion\"/>');\n\n    var $items = this.structure.$container.find('li');\n\n    this.base($items, {\n      handle: '.element:first, .move:first',\n      helper: this.getHelper.bind(this),\n    });\n  },\n\n  getHelper: function ($helper) {\n    this.$helperLi = $helper;\n    var $ul = $('<ul class=\"structure draghelper\"/>').append($helper);\n    $helper.css(\n      'padding-' + Craft.left,\n      this.$draggee.css('padding-' + Craft.left)\n    );\n    $helper.find('.move').removeAttr('title');\n    return $ul;\n  },\n\n  onDragStart: function () {\n    this.$targets = $();\n\n    // Recursively find each of the targets, in the order they appear to be in\n    this.findTargets(this.structure.$container);\n\n    // How deep does the rabbit hole go?\n    this.draggeeLevel = 0;\n    var $level = this.$draggee;\n    do {\n      this.draggeeLevel++;\n      $level = $level.find('> ul > li');\n    } while ($level.length);\n\n    // Collapse the draggee\n    this.draggeeHeight = this.$draggee.height();\n    this.$draggee.velocity(\n      {\n        height: 0,\n      },\n      'fast',\n      () => {\n        this.$draggee.addClass('hidden');\n      }\n    );\n    this.base();\n\n    this.addListener(Garnish.$doc, 'keydown', function (ev) {\n      if (ev.keyCode === Garnish.ESC_KEY) {\n        this.cancelDrag();\n      }\n    });\n  },\n\n  findTargets: function ($ul) {\n    var $lis = $ul.children().not(this.$draggee);\n\n    for (var i = 0; i < $lis.length; i++) {\n      var $li = $($lis[i]);\n      this.$targets = this.$targets.add($li.children('.row'));\n\n      if (!$li.hasClass('collapsed')) {\n        this.findTargets($li.children('ul'));\n      }\n    }\n  },\n\n  onDrag: function () {\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n      this.$insertion.remove();\n    }\n\n    // First let's find the closest target\n    this._.$closestTarget = null;\n    this._.closestTargetPos = null;\n    this._.closestTargetYDiff = null;\n    this._.closestTargetOffset = null;\n    this._.closestTargetHeight = null;\n\n    for (this._.i = 0; this._.i < this.$targets.length; this._.i++) {\n      this._.$target = $(this.$targets[this._.i]);\n      this._.targetOffset = this._.$target.offset();\n      this._.targetHeight = this._.$target.outerHeight();\n      this._.targetYMidpoint =\n        this._.targetOffset.top + this._.targetHeight / 2;\n      this._.targetYDiff = Math.abs(this.mouseY - this._.targetYMidpoint);\n\n      if (\n        this._.i === 0 ||\n        (this.mouseY >= this._.targetOffset.top + 5 &&\n          this._.targetYDiff < this._.closestTargetYDiff)\n      ) {\n        this._.$closestTarget = this._.$target;\n        this._.closestTargetPos = this._.i;\n        this._.closestTargetYDiff = this._.targetYDiff;\n        this._.closestTargetOffset = this._.targetOffset;\n        this._.closestTargetHeight = this._.targetHeight;\n      } else {\n        // Getting colder\n        break;\n      }\n    }\n\n    if (!this._.$closestTarget) {\n      return;\n    }\n\n    // Are we hovering above the first row?\n    if (\n      this._.closestTargetPos === 0 &&\n      this.mouseY < this._.closestTargetOffset.top + 5\n    ) {\n      this.$insertion.prependTo(this.structure.$container);\n    } else {\n      this._.$closestTargetLi = this._.$closestTarget.parent();\n      this._.closestTargetLevel = this._.$closestTargetLi.data('level');\n\n      // Is there a next row?\n      if (this._.closestTargetPos < this.$targets.length - 1) {\n        this._.$nextTargetLi = $(\n          this.$targets[this._.closestTargetPos + 1]\n        ).parent();\n        this._.nextTargetLevel = this._.$nextTargetLi.data('level');\n      } else {\n        this._.$nextTargetLi = null;\n        this._.nextTargetLevel = null;\n      }\n\n      // Are we hovering between this row and the next one?\n      this._.hoveringBetweenRows =\n        this.mouseY >=\n        this._.closestTargetOffset.top + this._.closestTargetHeight - 5;\n\n      /**\n       * Scenario 1: Both rows have the same level.\n       *\n       *     * Row 1\n       *     ----------------------\n       *     * Row 2\n       */\n\n      if (\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel == this._.closestTargetLevel\n      ) {\n        if (this._.hoveringBetweenRows) {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel - 1\n          ) {\n            // Position the insertion after the closest target\n            this.$insertion.insertAfter(this._.$closestTargetLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      } else if (\n        /**\n         * Scenario 2: Next row is a child of this one.\n         *\n         *     * Row 1\n         *     ----------------------\n         *         * Row 2\n         */\n        this._.$nextTargetLi &&\n        this._.nextTargetLevel > this._.closestTargetLevel\n      ) {\n        if (\n          !this.maxLevels ||\n          this.maxLevels >= this._.nextTargetLevel + this.draggeeLevel - 1\n        ) {\n          if (this._.hoveringBetweenRows) {\n            // Position the insertion as the first child of the closest target\n            this.$insertion.insertBefore(this._.$nextTargetLi);\n          } else {\n            this._.$closestTarget.addClass('draghover');\n            this.$insertion.appendTo(this._.$closestTargetLi.children('ul'));\n          }\n        }\n      } else {\n        /**\n         * Scenario 3: Next row is a child of a parent node, or there is no next row.\n         *\n         *         * Row 1\n         *     ----------------------\n         *     * Row 2\n         */\n        if (this._.hoveringBetweenRows) {\n          // Determine which <li> to position the insertion after\n          this._.draggeeX = this.mouseX - this.targetItemMouseDiffX;\n\n          if (Craft.orientation === 'rtl') {\n            this._.draggeeX += this.$helperLi.width();\n          }\n\n          this._.$parentLis = this._.$closestTarget.parentsUntil(\n            this.structure.$container,\n            'li'\n          );\n          this._.$closestParentLi = null;\n          this._.closestParentLiXDiff = null;\n          this._.closestParentLevel = null;\n\n          for (this._.i = 0; this._.i < this._.$parentLis.length; this._.i++) {\n            this._.$parentLi = $(this._.$parentLis[this._.i]);\n            this._.parentLiX = this._.$parentLi.offset().left;\n\n            if (Craft.orientation === 'rtl') {\n              this._.parentLiX += this._.$parentLi.width();\n            }\n\n            this._.parentLiXDiff = Math.abs(this._.parentLiX - this._.draggeeX);\n            this._.parentLevel = this._.$parentLi.data('level');\n\n            if (\n              (!this.maxLevels ||\n                this.maxLevels >= this._.parentLevel + this.draggeeLevel - 1) &&\n              (!this._.$closestParentLi ||\n                (this._.parentLiXDiff < this._.closestParentLiXDiff &&\n                  (!this._.$nextTargetLi ||\n                    this._.parentLevel >= this._.nextTargetLevel)))\n            ) {\n              this._.$closestParentLi = this._.$parentLi;\n              this._.closestParentLiXDiff = this._.parentLiXDiff;\n              this._.closestParentLevel = this._.parentLevel;\n            }\n          }\n\n          if (this._.$closestParentLi) {\n            this.$insertion.insertAfter(this._.$closestParentLi);\n          }\n        } else {\n          if (\n            !this.maxLevels ||\n            this.maxLevels >= this._.closestTargetLevel + this.draggeeLevel\n          ) {\n            this._.$closestTarget.addClass('draghover');\n          }\n        }\n      }\n    }\n  },\n\n  cancelDrag: function () {\n    this.$insertion.remove();\n\n    if (this._.$closestTarget) {\n      this._.$closestTarget.removeClass('draghover');\n    }\n\n    this.onMouseUp();\n  },\n\n  onDragStop: function () {\n    // Are we repositioning the draggee?\n    if (\n      this._.$closestTarget &&\n      (this.$insertion.parent().length ||\n        this._.$closestTarget.hasClass('draghover'))\n    ) {\n      var $draggeeParent, moved;\n\n      // Are we about to leave the draggee's original parent childless?\n      if (!this.$draggee.siblings().length) {\n        $draggeeParent = this.$draggee.parent();\n      }\n\n      if (this.$insertion.parent().length) {\n        // Make sure the insertion isn't right next to the draggee\n        var $closestSiblings = this.$insertion\n          .next()\n          .add(this.$insertion.prev());\n\n        if ($.inArray(this.$draggee[0], $closestSiblings) === -1) {\n          this.$insertion.replaceWith(this.$draggee);\n          moved = true;\n        } else {\n          this.$insertion.remove();\n          moved = false;\n        }\n      } else {\n        var $ul = this._.$closestTargetLi.children('ul');\n\n        // Make sure this is a different parent than the draggee's\n        if (!$draggeeParent || !$ul.length || $ul[0] !== $draggeeParent[0]) {\n          if (!$ul.length) {\n            var $toggle = $(\n              '<div class=\"toggle\" title=\"' +\n                Craft.t('app', 'Show/hide children') +\n                '\"/>'\n            ).prependTo(this._.$closestTarget);\n            this.structure.initToggle($toggle);\n\n            $ul = $('<ul>').appendTo(this._.$closestTargetLi);\n          } else if (this._.$closestTargetLi.hasClass('collapsed')) {\n            this._.$closestTarget.children('.toggle').trigger('click');\n          }\n\n          this.$draggee.appendTo($ul);\n          moved = true;\n        } else {\n          moved = false;\n        }\n      }\n\n      // Remove the class either way\n      this._.$closestTarget.removeClass('draghover');\n\n      if (moved) {\n        // Now deal with the now-childless parent\n        if ($draggeeParent) {\n          this.structure._removeUl($draggeeParent);\n        }\n\n        // Has the level changed?\n        var newLevel =\n          this.$draggee.parentsUntil(this.structure.$container, 'li').length +\n          1;\n\n        var animateCss;\n\n        if (newLevel != this.$draggee.data('level')) {\n          // Correct the helper's padding if moving to/from level 1\n          if (this.$draggee.data('level') == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = 38;\n            this.$helperLi.velocity(animateCss, 'fast');\n          } else if (newLevel == 1) {\n            animateCss = {};\n            animateCss['padding-' + Craft.left] = Craft.Structure.baseIndent;\n            this.$helperLi.velocity(animateCss, 'fast');\n          }\n\n          this.setLevel(this.$draggee, newLevel);\n        }\n\n        // Make it real\n        var $element = this.$draggee.children('.row').children('.element');\n\n        var data = {\n          structureId: this.structure.id,\n          elementId: $element.data('id'),\n          siteId: $element.data('site-id'),\n          prevId: this.$draggee\n            .prev()\n            .children('.row')\n            .children('.element')\n            .data('id'),\n          parentId: this.$draggee\n            .parent('ul')\n            .parent('li')\n            .children('.row')\n            .children('.element')\n            .data('id'),\n        };\n\n        Craft.postActionRequest(\n          'structures/move-element',\n          data,\n          function (response, textStatus) {\n            if (textStatus === 'success') {\n              Craft.cp.displayNotice(Craft.t('app', 'New order saved.'));\n            }\n          }\n        );\n      }\n    }\n\n    // Animate things back into place\n    this.$draggee\n      .velocity('stop')\n      .removeClass('hidden')\n      .velocity(\n        {\n          height: this.draggeeHeight,\n        },\n        'fast',\n        () => {\n          this.$draggee.css('height', 'auto');\n        }\n      );\n\n    this.returnHelpersToDraggees();\n\n    this.base();\n  },\n\n  setLevel: function ($li, level) {\n    $li.data('level', level);\n\n    var indent = this.structure.getIndent(level);\n\n    var css = {};\n    css['margin-' + Craft.left] = '-' + indent + 'px';\n    css['padding-' + Craft.left] = indent + 'px';\n    this.$draggee.children('.row').css(css);\n\n    var $childLis = $li.children('ul').children();\n\n    for (var i = 0; i < $childLis.length; i++) {\n      this.setLevel($($childLis[i]), level + 1);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.StructureTableSorter = Garnish.DragSort.extend(\n  {\n    tableView: null,\n    structureId: null,\n    maxLevels: null,\n\n    _basePadding: null,\n    _helperMargin: null,\n\n    _$firstRowCells: null,\n    _$titleHelperCell: null,\n\n    _titleHelperCellOuterWidth: null,\n\n    _ancestors: null,\n    _updateAncestorsFrame: null,\n\n    _draggeeLevel: null,\n    _draggeeLevelDelta: null,\n    draggingLastElements: null,\n    _loadingDraggeeLevelDelta: false,\n\n    _targetLevel: null,\n    _targetLevelBounds: null,\n\n    _positionChanged: null,\n\n    /**\n     * Constructor\n     */\n    init: function (tableView, $elements, settings) {\n      this.tableView = tableView;\n      this.structureId = this.tableView.$table.data('structure-id');\n      this.maxLevels = parseInt(this.tableView.$table.attr('data-max-levels'));\n\n      this._basePadding = 14 + (this.tableView.elementIndex.actions ? 14 : 24); // see _elements/tableview/elements.html\n      this._helperMargin = this.tableView.elementIndex.actions ? 54 : 0;\n\n      settings = $.extend({}, Craft.StructureTableSorter.defaults, settings, {\n        handle: '.move',\n        collapseDraggees: true,\n        singleHelper: true,\n        helperSpacingY: 2,\n        magnetStrength: 4,\n        helper: this.getHelper.bind(this),\n        helperLagBase: 1.5,\n        axis: Garnish.Y_AXIS,\n      });\n\n      this.base($elements, settings);\n    },\n\n    /**\n     * Returns the draggee rows (including any descendent rows).\n     */\n    findDraggee: function () {\n      this._draggeeLevel = this._targetLevel = this.$targetItem.data('level');\n      this._draggeeLevelDelta = 0;\n\n      var $draggee = $(this.$targetItem),\n        $nextRow = this.$targetItem.next();\n\n      while ($nextRow.length) {\n        // See if this row is a descendant of the draggee\n        var nextRowLevel = $nextRow.data('level');\n\n        if (nextRowLevel <= this._draggeeLevel) {\n          break;\n        }\n\n        // Is this the deepest descendant we've seen so far?\n        var nextRowLevelDelta = nextRowLevel - this._draggeeLevel;\n\n        if (nextRowLevelDelta > this._draggeeLevelDelta) {\n          this._draggeeLevelDelta = nextRowLevelDelta;\n        }\n\n        // Add it and prep the next row\n        $draggee = $draggee.add($nextRow);\n        $nextRow = $nextRow.next();\n      }\n\n      // Are we dragging the last elements on the page?\n      this.draggingLastElements = !$nextRow.length;\n\n      // Do we have a maxLevels to enforce,\n      // and does it look like this draggee has descendants we don't know about yet?\n      if (\n        this.maxLevels &&\n        this.draggingLastElements &&\n        this.tableView.getMorePending()\n      ) {\n        // Only way to know the true descendant level delta is to ask PHP\n        this._loadingDraggeeLevelDelta = true;\n\n        var data = this._getAjaxBaseData(this.$targetItem);\n\n        Craft.postActionRequest(\n          'structures/get-element-level-delta',\n          data,\n          (response, textStatus) => {\n            if (textStatus === 'success') {\n              this._loadingDraggeeLevelDelta = false;\n\n              if (this.dragging) {\n                this._draggeeLevelDelta = response.delta;\n                this.drag(false);\n              }\n            }\n          }\n        );\n      }\n\n      return $draggee;\n    },\n\n    /**\n     * Returns the drag helper.\n     */\n    getHelper: function ($helperRow) {\n      var $outerContainer = $(\n          '<div class=\"elements datatablesorthelper\"/>'\n        ).appendTo(Garnish.$bod),\n        $innerContainer = $('<div class=\"tableview\"/>').appendTo(\n          $outerContainer\n        ),\n        $table = $('<table class=\"data\"/>').appendTo($innerContainer),\n        $tbody = $('<tbody/>').appendTo($table);\n\n      $helperRow.appendTo($tbody);\n\n      // Copy the column widths\n      this._$firstRowCells = this.tableView.$elementContainer\n        .children('tr:first')\n        .children();\n      var $helperCells = $helperRow.children();\n\n      for (var i = 0; i < $helperCells.length; i++) {\n        var $helperCell = $($helperCells[i]);\n\n        // Skip the checkbox cell\n        if ($helperCell.hasClass('checkbox-cell')) {\n          $helperCell.remove();\n          continue;\n        }\n\n        // Hard-set the cell widths\n        var $firstRowCell = $(this._$firstRowCells[i]);\n        var width = $firstRowCell[0].getBoundingClientRect().width;\n\n        $firstRowCell.css('width', width + 'px');\n        $helperCell.css('width', width + 'px');\n\n        // Is this the title cell?\n        if (Garnish.hasAttr($firstRowCell, 'data-titlecell')) {\n          this._$titleHelperCell = $helperCell;\n\n          var padding = parseInt($firstRowCell.css('padding-' + Craft.left));\n          this._titleHelperCellOuterWidth = width;\n\n          $helperCell.css('padding-' + Craft.left, this._basePadding);\n        }\n      }\n\n      return $outerContainer;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted before a given item.\n     */\n    canInsertBefore: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item.prev(), $item) !== false;\n    },\n\n    /**\n     * Returns whether the draggee can be inserted after a given item.\n     */\n    canInsertAfter: function ($item) {\n      if (this._loadingDraggeeLevelDelta) {\n        return false;\n      }\n\n      return this._getLevelBounds($item, $item.next()) !== false;\n    },\n\n    // Events\n    // -------------------------------------------------------------------------\n\n    /**\n     * On Drag Start\n     */\n    onDragStart: function () {\n      // Get the initial set of ancestors, before the item gets moved\n      this._ancestors = this._getAncestors(\n        this.$targetItem,\n        this.$targetItem.data('level')\n      );\n\n      // Set the initial target level bounds\n      this._setTargetLevelBounds();\n\n      // Check to see if we should load more elements now\n      this.tableView.maybeLoadMore();\n\n      this.base();\n    },\n\n    /**\n     * On Drag\n     */\n    onDrag: function () {\n      this.base();\n      this._updateIndent();\n    },\n\n    /**\n     * On Insertion Point Change\n     */\n    onInsertionPointChange: function () {\n      this._setTargetLevelBounds();\n      this._updateAncestorsBeforeRepaint();\n      this.base();\n    },\n\n    /**\n     * On Drag Stop\n     */\n    onDragStop: function () {\n      this._positionChanged = false;\n      this.base();\n\n      // Update the draggee's padding if the position just changed\n      // ---------------------------------------------------------------------\n\n      if (this._targetLevel != this._draggeeLevel) {\n        var levelDiff = this._targetLevel - this._draggeeLevel;\n\n        for (var i = 0; i < this.$draggee.length; i++) {\n          var $draggee = $(this.$draggee[i]),\n            oldLevel = $draggee.data('level'),\n            newLevel = oldLevel + levelDiff,\n            padding = this._basePadding + this._getLevelIndent(newLevel);\n\n          $draggee.data('level', newLevel);\n          $draggee.find('.element').data('level', newLevel);\n          $draggee\n            .children('[data-titlecell]:first')\n            .css('padding-' + Craft.left, padding);\n        }\n\n        this._positionChanged = true;\n      }\n\n      // Keep in mind this could have also been set by onSortChange()\n      if (this._positionChanged) {\n        // Tell the server about the new position\n        // -----------------------------------------------------------------\n\n        var data = this._getAjaxBaseData(this.$draggee);\n\n        // Find the previous sibling/parent, if there is one\n        var $prevRow = this.$draggee.first().prev();\n\n        while ($prevRow.length) {\n          var prevRowLevel = $prevRow.data('level');\n\n          if (prevRowLevel == this._targetLevel) {\n            data.prevId = $prevRow.data('id');\n            break;\n          }\n\n          if (prevRowLevel < this._targetLevel) {\n            data.parentId = $prevRow.data('id');\n\n            // Is this row collapsed?\n            var $toggle = $prevRow.find('> th > .toggle');\n\n            if (!$toggle.hasClass('expanded')) {\n              // Make it look expanded\n              $toggle.addClass('expanded');\n\n              // Add a temporary row\n              var $spinnerRow = this.tableView._createSpinnerRowAfter($prevRow);\n\n              // Remove the target item\n              if (this.tableView.elementSelect) {\n                this.tableView.elementSelect.removeItems(this.$targetItem);\n              }\n\n              this.removeItems(this.$targetItem);\n              this.$targetItem.remove();\n              this.tableView._totalVisible--;\n            }\n\n            break;\n          }\n\n          $prevRow = $prevRow.prev();\n        }\n\n        Craft.postActionRequest(\n          'structures/move-element',\n          data,\n          (response, textStatus) => {\n            if (textStatus === 'success') {\n              if (!response.success) {\n                Craft.cp.displayError(\n                  Craft.t('app', 'A server error occurred.')\n                );\n                this.tableView.elementIndex.updateElements();\n                return;\n              }\n              Craft.cp.displayNotice(Craft.t('app', 'New position saved.'));\n              this.onPositionChange();\n\n              // Were we waiting on this to complete so we can expand the new parent?\n              if ($spinnerRow && $spinnerRow.parent().length) {\n                $spinnerRow.remove();\n                this.tableView._expandElement($toggle, true);\n              }\n\n              // See if we should run any pending tasks\n              Craft.cp.runQueue();\n            }\n          }\n        );\n      }\n    },\n\n    onSortChange: function () {\n      if (this.tableView.elementSelect) {\n        this.tableView.elementSelect.resetItemOrder();\n      }\n\n      this._positionChanged = true;\n      this.base();\n    },\n\n    onPositionChange: function () {\n      Garnish.requestAnimationFrame(() => {\n        this.trigger('positionChange');\n        this.settings.onPositionChange();\n      });\n    },\n\n    onReturnHelpersToDraggees: function () {\n      this._$firstRowCells.css('width', '');\n\n      // If we were dragging the last elements on the page and ended up loading any additional elements in,\n      // there could be a gap between the last draggee item and whatever now comes after it.\n      // So remove the post-draggee elements and possibly load up the next batch.\n      if (this.draggingLastElements && this.tableView.getMorePending()) {\n        // Update the element index's record of how many items are actually visible\n        this.tableView._totalVisible +=\n          this.newDraggeeIndexes[0] - this.oldDraggeeIndexes[0];\n\n        var $postDraggeeItems = this.$draggee.last().nextAll();\n\n        if ($postDraggeeItems.length) {\n          this.removeItems($postDraggeeItems);\n          $postDraggeeItems.remove();\n          this.tableView.maybeLoadMore();\n        }\n      }\n\n      this.base();\n    },\n\n    /**\n     * Returns the min and max levels that the draggee could occupy between\n     * two given rows, or false if it’s not going to work out.\n     */\n    _getLevelBounds: function ($prevRow, $nextRow) {\n      // Can't go any lower than the next row, if there is one\n      if ($nextRow && $nextRow.length) {\n        this._getLevelBounds._minLevel = $nextRow.data('level');\n      } else {\n        this._getLevelBounds._minLevel = 1;\n      }\n\n      // Can't go any higher than the previous row + 1\n      if ($prevRow && $prevRow.length) {\n        this._getLevelBounds._maxLevel = $prevRow.data('level') + 1;\n      } else {\n        this._getLevelBounds._maxLevel = 1;\n      }\n\n      // Does this structure have a max level?\n      if (this.maxLevels) {\n        // Make sure it's going to fit at all here\n        if (\n          this._getLevelBounds._minLevel != 1 &&\n          this._getLevelBounds._minLevel + this._draggeeLevelDelta >\n            this.maxLevels\n        ) {\n          return false;\n        }\n\n        // Limit the max level if we have to\n        if (\n          this._getLevelBounds._maxLevel + this._draggeeLevelDelta >\n          this.maxLevels\n        ) {\n          this._getLevelBounds._maxLevel =\n            this.maxLevels - this._draggeeLevelDelta;\n\n          if (this._getLevelBounds._maxLevel < this._getLevelBounds._minLevel) {\n            this._getLevelBounds._maxLevel = this._getLevelBounds._minLevel;\n          }\n        }\n      }\n\n      return {\n        min: this._getLevelBounds._minLevel,\n        max: this._getLevelBounds._maxLevel,\n      };\n    },\n\n    /**\n     * Determines the min and max possible levels at the current draggee's position.\n     */\n    _setTargetLevelBounds: function () {\n      this._targetLevelBounds = this._getLevelBounds(\n        this.$draggee.first().prev(),\n        this.$draggee.last().next()\n      );\n    },\n\n    /**\n     * Determines the target level based on the current mouse position.\n     */\n    _updateIndent: function (forcePositionChange) {\n      // Figure out the target level\n      // ---------------------------------------------------------------------\n\n      // How far has the cursor moved?\n      this._updateIndent._mouseDist = this.realMouseX - this.mousedownX;\n\n      // Flip that if this is RTL\n      if (Craft.orientation === 'rtl') {\n        this._updateIndent._mouseDist *= -1;\n      }\n\n      // What is that in indentation levels?\n      this._updateIndent._indentationDist = Math.round(\n        this._updateIndent._mouseDist / Craft.StructureTableSorter.LEVEL_INDENT\n      );\n\n      // Combine with the original level to get the new target level\n      this._updateIndent._targetLevel =\n        this._draggeeLevel + this._updateIndent._indentationDist;\n\n      // Contain it within our min/max levels\n      if (this._updateIndent._targetLevel < this._targetLevelBounds.min) {\n        this._updateIndent._indentationDist +=\n          this._targetLevelBounds.min - this._updateIndent._targetLevel;\n        this._updateIndent._targetLevel = this._targetLevelBounds.min;\n      } else if (\n        this._updateIndent._targetLevel > this._targetLevelBounds.max\n      ) {\n        this._updateIndent._indentationDist -=\n          this._updateIndent._targetLevel - this._targetLevelBounds.max;\n        this._updateIndent._targetLevel = this._targetLevelBounds.max;\n      }\n\n      // Has the target level changed?\n      if (\n        this._targetLevel !==\n        (this._targetLevel = this._updateIndent._targetLevel)\n      ) {\n        // Target level is changing, so update the ancestors\n        this._updateAncestorsBeforeRepaint();\n      }\n\n      // Update the UI\n      // ---------------------------------------------------------------------\n\n      // How far away is the cursor from the exact target level distance?\n      this._updateIndent._targetLevelMouseDiff =\n        this._updateIndent._mouseDist -\n        this._updateIndent._indentationDist *\n          Craft.StructureTableSorter.LEVEL_INDENT;\n\n      // What's the magnet impact of that?\n      this._updateIndent._magnetImpact = Math.round(\n        this._updateIndent._targetLevelMouseDiff / 15\n      );\n\n      // Put it on a leash\n      if (\n        Math.abs(this._updateIndent._magnetImpact) >\n        Craft.StructureTableSorter.MAX_GIVE\n      ) {\n        this._updateIndent._magnetImpact =\n          (this._updateIndent._magnetImpact > 0 ? 1 : -1) *\n          Craft.StructureTableSorter.MAX_GIVE;\n      }\n\n      // Apply the new margin/width\n      this._updateIndent._closestLevelMagnetIndent =\n        this._getLevelIndent(this._targetLevel) +\n        this._updateIndent._magnetImpact;\n      this.helpers[0].css(\n        'margin-' + Craft.left,\n        this._updateIndent._closestLevelMagnetIndent + this._helperMargin\n      );\n      this._$titleHelperCell.css(\n        'width',\n        this._titleHelperCellOuterWidth -\n          this._updateIndent._closestLevelMagnetIndent\n      );\n    },\n\n    /**\n     * Returns the indent size for a given level\n     */\n    _getLevelIndent: function (level) {\n      return (level - 1) * Craft.StructureTableSorter.LEVEL_INDENT;\n    },\n\n    /**\n     * Returns the base data that should be sent with StructureController Ajax requests.\n     */\n    _getAjaxBaseData: function ($row) {\n      return {\n        structureId: this.structureId,\n        elementId: $row.data('id'),\n        siteId: $row.find('.element:first').data('site-id'),\n      };\n    },\n\n    /**\n     * Returns a row's ancestor rows\n     */\n    _getAncestors: function ($row, targetLevel) {\n      this._getAncestors._ancestors = [];\n\n      if (targetLevel != 0) {\n        this._getAncestors._level = targetLevel;\n        this._getAncestors._$prevRow = $row.prev();\n\n        while (this._getAncestors._$prevRow.length) {\n          if (\n            this._getAncestors._$prevRow.data('level') <\n            this._getAncestors._level\n          ) {\n            this._getAncestors._ancestors.unshift(this._getAncestors._$prevRow);\n            this._getAncestors._level =\n              this._getAncestors._$prevRow.data('level');\n\n            // Did we just reach the top?\n            if (this._getAncestors._level == 0) {\n              break;\n            }\n          }\n\n          this._getAncestors._$prevRow = this._getAncestors._$prevRow.prev();\n        }\n      }\n\n      return this._getAncestors._ancestors;\n    },\n\n    /**\n     * Prepares to have the ancestors updated before the screen is repainted.\n     */\n    _updateAncestorsBeforeRepaint: function () {\n      if (this._updateAncestorsFrame) {\n        Garnish.cancelAnimationFrame(this._updateAncestorsFrame);\n      }\n\n      this._updateAncestorsFrame = Garnish.requestAnimationFrame(\n        this._updateAncestors.bind(this)\n      );\n    },\n\n    _updateAncestors: function () {\n      this._updateAncestorsFrame = null;\n\n      // Update the old ancestors\n      // -----------------------------------------------------------------\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._ancestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._ancestors[this._updateAncestors._i];\n\n        // One less descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') - 1\n        );\n\n        // Is it now childless?\n        if (this._updateAncestors._$ancestor.data('descendants') == 0) {\n          // Remove its toggle\n          this._updateAncestors._$ancestor\n            .find('> th > .toggle:first')\n            .remove();\n        }\n      }\n\n      // Update the new ancestors\n      // -----------------------------------------------------------------\n\n      this._updateAncestors._newAncestors = this._getAncestors(\n        this.$targetItem,\n        this._targetLevel\n      );\n\n      for (\n        this._updateAncestors._i = 0;\n        this._updateAncestors._i < this._updateAncestors._newAncestors.length;\n        this._updateAncestors._i++\n      ) {\n        this._updateAncestors._$ancestor =\n          this._updateAncestors._newAncestors[this._updateAncestors._i];\n\n        // One more descendant now\n        this._updateAncestors._$ancestor.data(\n          'descendants',\n          this._updateAncestors._$ancestor.data('descendants') + 1\n        );\n\n        // Is this its first child?\n        if (this._updateAncestors._$ancestor.data('descendants') == 1) {\n          // Create its toggle\n          $(\n            '<span class=\"toggle expanded\" title=\"' +\n              Craft.t('app', 'Show/hide children') +\n              '\"></span>'\n          ).insertAfter(\n            this._updateAncestors._$ancestor.find('> th .move:first')\n          );\n        }\n      }\n\n      this._ancestors = this._updateAncestors._newAncestors;\n\n      delete this._updateAncestors._i;\n      delete this._updateAncestors._$ancestor;\n      delete this._updateAncestors._newAncestors;\n    },\n  },\n  {\n    HELPER_MARGIN: 0,\n    LEVEL_INDENT: 44,\n    MAX_GIVE: 22,\n\n    defaults: {\n      onPositionChange: $.noop,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Table Element Index View\n */\nCraft.TableElementIndexView = Craft.BaseElementIndexView.extend({\n  $table: null,\n  $selectedSortHeader: null,\n\n  structureTableSort: null,\n\n  _totalVisiblePostStructureTableDraggee: null,\n  _morePendingPostStructureTableDraggee: false,\n\n  getElementContainer: function () {\n    // Save a reference to the table\n    this.$table = this.$container.find('table:first');\n    return this.$table.children('tbody:first');\n  },\n\n  afterInit: function () {\n    // Set the sort header\n    this.initTableHeaders();\n\n    // Create the Structure Table Sorter\n    if (\n      this.elementIndex.settings.context === 'index' &&\n      this.elementIndex.getSelectedSortAttribute() === 'structure' &&\n      Garnish.hasAttr(this.$table, 'data-structure-id')\n    ) {\n      this.structureTableSort = new Craft.StructureTableSorter(\n        this,\n        this.getAllElements()\n      );\n    } else {\n      this.structureTableSort = null;\n    }\n\n    // Handle expand/collapse toggles for Structures\n    if (this.elementIndex.getSelectedSortAttribute() === 'structure') {\n      this.addListener(this.$elementContainer, 'click', function (ev) {\n        var $target = $(ev.target);\n\n        if ($target.hasClass('toggle')) {\n          if (this._collapseElement($target) === false) {\n            this._expandElement($target);\n          }\n        }\n      });\n    }\n  },\n\n  initTableHeaders: function () {\n    var selectedSortAttr = this.elementIndex.getSelectedSortAttribute(),\n      $tableHeaders = this.$table\n        .children('thead')\n        .children()\n        .children('[data-attribute]');\n\n    for (var i = 0; i < $tableHeaders.length; i++) {\n      var $header = $tableHeaders.eq(i),\n        attr = $header.attr('data-attribute');\n\n      // Is this the selected sort attribute?\n      if (attr === selectedSortAttr) {\n        this.$selectedSortHeader = $header;\n        var selectedSortDir = this.elementIndex.getSelectedSortDirection();\n\n        $header\n          .addClass('ordered ' + selectedSortDir)\n          .on('click', this._handleSelectedSortHeaderClick.bind(this));\n      } else {\n        // Is this attribute sortable?\n        var $sortAttribute = this.elementIndex.getSortAttributeOption(attr);\n\n        if ($sortAttribute.length) {\n          $header\n            .addClass('orderable')\n            .on('click', this._handleUnselectedSortHeaderClick.bind(this));\n        }\n      }\n    }\n  },\n\n  isVerticalList: function () {\n    return true;\n  },\n\n  getTotalVisible: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._totalVisiblePostStructureTableDraggee;\n    } else {\n      return this._totalVisible;\n    }\n  },\n\n  setTotalVisible: function (totalVisible) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._totalVisiblePostStructureTableDraggee = totalVisible;\n    } else {\n      this._totalVisible = totalVisible;\n    }\n  },\n\n  getMorePending: function () {\n    if (this._isStructureTableDraggingLastElements()) {\n      return this._morePendingPostStructureTableDraggee;\n    } else {\n      return this._morePending;\n    }\n  },\n\n  setMorePending: function (morePending) {\n    if (this._isStructureTableDraggingLastElements()) {\n      this._morePendingPostStructureTableDraggee = morePending;\n    } else {\n      this._morePending = this._morePendingPostStructureTableDraggee =\n        morePending;\n    }\n  },\n\n  getLoadMoreParams: function () {\n    var params = this.base();\n\n    // If we are dragging the last elements on the page,\n    // tell the controller to only load elements positioned after the draggee.\n    if (this._isStructureTableDraggingLastElements()) {\n      params.criteria.positionedAfter =\n        this.structureTableSort.$targetItem.data('id');\n    }\n\n    return params;\n  },\n\n  appendElements: function ($newElements) {\n    this.base($newElements);\n\n    if (this.structureTableSort) {\n      this.structureTableSort.addItems($newElements);\n    }\n\n    Craft.cp.updateResponsiveTables();\n  },\n\n  createElementEditor: function ($element) {\n    Craft.createElementEditor($element.data('type'), $element, {\n      params: {\n        includeTableAttributesForSource: this.elementIndex.sourceKey,\n      },\n      onSaveElement: (response) => {\n        if (response.tableAttributes) {\n          this._updateTableAttributes($element, response.tableAttributes);\n        }\n      },\n      elementIndex: this.elementIndex,\n    });\n  },\n\n  _collapseElement: function ($toggle, force) {\n    if (!force && !$toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.removeClass('expanded');\n\n    // Find and remove the descendant rows\n    var $row = $toggle.parent().parent(),\n      id = $row.data('id'),\n      level = $row.data('level'),\n      $nextRow = $row.next();\n\n    while ($nextRow.length) {\n      if (!Garnish.hasAttr($nextRow, 'data-spinnerrow')) {\n        if ($nextRow.data('level') <= level) {\n          break;\n        }\n\n        if (this.elementSelect) {\n          this.elementSelect.removeItems($nextRow);\n        }\n\n        if (this.structureTableSort) {\n          this.structureTableSort.removeItems($nextRow);\n        }\n\n        this._totalVisible--;\n      }\n\n      var $nextNextRow = $nextRow.next();\n      $nextRow.remove();\n      $nextRow = $nextNextRow;\n    }\n\n    // Remember that this row should be collapsed\n    if (!this.elementIndex.instanceState.collapsedElementIds) {\n      this.elementIndex.instanceState.collapsedElementIds = [];\n    }\n\n    this.elementIndex.instanceState.collapsedElementIds.push(id);\n    this.elementIndex.setInstanceState(\n      'collapsedElementIds',\n      this.elementIndex.instanceState.collapsedElementIds\n    );\n\n    // Bottom of the index might be viewable now\n    this.maybeLoadMore();\n  },\n\n  _expandElement: function ($toggle, force) {\n    if (!force && $toggle.hasClass('expanded')) {\n      return false;\n    }\n\n    $toggle.addClass('expanded');\n\n    // Remove this element from our list of collapsed elements\n    if (this.elementIndex.instanceState.collapsedElementIds) {\n      var $row = $toggle.parent().parent(),\n        id = $row.data('id'),\n        index = $.inArray(\n          id,\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n      if (index !== -1) {\n        this.elementIndex.instanceState.collapsedElementIds.splice(index, 1);\n        this.elementIndex.setInstanceState(\n          'collapsedElementIds',\n          this.elementIndex.instanceState.collapsedElementIds\n        );\n\n        // Add a temporary row\n        var $spinnerRow = this._createSpinnerRowAfter($row);\n\n        // Load the nested elements\n        let data = $.extend(true, {}, this.settings.params);\n        data.criteria.descendantOf = id;\n\n        Craft.sendActionRequest('POST', this.settings.loadMoreElementsAction, {\n          data,\n        })\n          .then((response) => {\n            // Do we even care about this anymore?\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n\n            let $newElements = $(response.data.html);\n\n            // Are there more descendants we didn't get in this batch?\n            let totalVisible = this._totalVisible + $newElements.length;\n            let morePending =\n              this.settings.batchSize &&\n              $newElements.length === this.settings.batchSize;\n\n            if (morePending) {\n              // Remove all the elements after it\n              let $nextRows = $spinnerRow.nextAll();\n\n              if (this.elementSelect) {\n                this.elementSelect.removeItems($nextRows);\n              }\n\n              if (this.structureTableSort) {\n                this.structureTableSort.removeItems($nextRows);\n              }\n\n              $nextRows.remove();\n              totalVisible -= $nextRows.length;\n            } else {\n              // Maintain the current 'more' status\n              morePending = this._morePending;\n            }\n\n            $spinnerRow.replaceWith($newElements);\n            this.thumbLoader.load($newElements);\n\n            if (this.elementIndex.actions || this.settings.selectable) {\n              this.elementSelect.addItems(\n                $newElements.filter(':not(.disabled)')\n              );\n              this.elementIndex.updateActionTriggers();\n            }\n\n            if (this.structureTableSort) {\n              this.structureTableSort.addItems($newElements);\n            }\n\n            Craft.appendHeadHtml(response.data.headHtml);\n            Craft.appendFootHtml(response.data.footHtml);\n            Craft.cp.updateResponsiveTables();\n\n            this.setTotalVisible(totalVisible);\n            this.setMorePending(morePending);\n\n            // Is there room to load more right now?\n            this.maybeLoadMore();\n          })\n          .catch((e) => {\n            Craft.cp.displayError();\n            if (!$spinnerRow.parent().length) {\n              return;\n            }\n          });\n      }\n    }\n  },\n\n  _createSpinnerRowAfter: function ($row) {\n    return $(\n      '<tr data-spinnerrow>' +\n        '<td class=\"centeralign\" colspan=\"' +\n        $row.children().length +\n        '\">' +\n        '<div class=\"spinner\"/>' +\n        '</td>' +\n        '</tr>'\n    ).insertAfter($row);\n  },\n\n  _isStructureTableDraggingLastElements: function () {\n    return (\n      this.structureTableSort &&\n      this.structureTableSort.dragging &&\n      this.structureTableSort.draggingLastElements\n    );\n  },\n\n  _handleSelectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget);\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    // Reverse the sort direction\n    var selectedSortDir = this.elementIndex.getSelectedSortDirection(),\n      newSortDir = selectedSortDir === 'asc' ? 'desc' : 'asc';\n\n    this.elementIndex.setSortDirection(newSortDir);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleUnselectedSortHeaderClick: function (ev) {\n    var $header = $(ev.currentTarget);\n\n    if ($header.hasClass('loading')) {\n      return;\n    }\n\n    var attr = $header.attr('data-attribute');\n\n    this.elementIndex.setSortAttribute(attr);\n    this._handleSortHeaderClick(ev, $header);\n  },\n\n  _handleSortHeaderClick: function (ev, $header) {\n    if (this.$selectedSortHeader) {\n      this.$selectedSortHeader.removeClass('ordered asc desc');\n    }\n\n    $header.removeClass('orderable').addClass('ordered loading');\n    this.elementIndex.storeSortAttributeAndDirection();\n    this.elementIndex.updateElements();\n\n    // No need for two spinners\n    this.elementIndex.setIndexAvailable();\n  },\n\n  _updateTableAttributes: function ($element, tableAttributes) {\n    var $tr = $element.closest('tr');\n\n    for (var attr in tableAttributes) {\n      if (!tableAttributes.hasOwnProperty(attr)) {\n        continue;\n      }\n\n      $tr\n        .children('[data-attr=\"' + attr + '\"]:first')\n        .html(tableAttributes[attr]);\n    }\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tab manager\n */\nCraft.Tabs = Garnish.Base.extend({\n  $container: null,\n  $ul: null,\n  $menuBtn: null,\n  $tabs: null,\n  $selectedTab: null,\n  $focusableTab: null,\n  menu: null,\n\n  init: function (container) {\n    this.$container = $(container);\n    this.$ul = this.$container.find('> ul:first');\n    this.$tabs = this.$ul.find('> li > a');\n    this.$selectedTab = this.$tabs.filter('.sel:first');\n    this.$focusableTab = this.$tabs.filter('[tabindex=0]:first');\n    this.$menuBtn = this.$container.find('> .menubtn:first').menubtn();\n    this.menu = this.$menuBtn.data('menubtn').menu;\n\n    // Is there already a tab manager?\n    if (this.$container.data('tabs')) {\n      console.warn('Double-instantiating a tab manager on an element');\n      this.$container.data('tabs').destroy();\n    }\n\n    this.$container.data('tabs', this);\n\n    for (let i = 0; i < this.$tabs.length; i++) {\n      const $a = this.$tabs.eq(i);\n\n      // Does it link to an anchor?\n      const href = $a.attr('href');\n      if (href && href.charAt(0) === '#') {\n        this.addListener($a, 'keydown', (ev) => {\n          if ([Garnish.SPACE_KEY, Garnish.RETURN_KEY].includes(ev.keyCode)) {\n            ev.preventDefault();\n            this.selectTab(ev.currentTarget);\n          }\n        });\n        this.addListener($a, 'click', (ev) => {\n          ev.preventDefault();\n          const $a = $(ev.currentTarget);\n          this.selectTab(ev.currentTarget);\n          this.makeTabFocusable(ev.currentTarget);\n        });\n\n        if (href.substr(1) === window.LOCATION_HASH) {\n          $initialTab = $a;\n        }\n      }\n\n      this.addListener($a, 'keydown', (ev) => {\n        if (\n          [Garnish.LEFT_KEY, Garnish.RIGHT_KEY].includes(ev.keyCode) &&\n          $.contains(this.$ul[0], ev.currentTarget)\n        ) {\n          let $tab;\n          if (\n            ev.keyCode ===\n            (Craft.orientation === 'ltr' ? Garnish.LEFT_KEY : Garnish.RIGHT_KEY)\n          ) {\n            $tab = $(ev.currentTarget).parent().prev('li').children('a');\n          } else {\n            $tab = $(ev.currentTarget).parent().next('li').children('a');\n          }\n          if ($tab.length) {\n            ev.preventDefault();\n            this.makeTabFocusable($tab);\n            $tab.focus();\n            this.scrollToTab($tab);\n          }\n        }\n      });\n    }\n\n    this.updateMenuBtn();\n\n    Garnish.$win.on('resize', () => {\n      this.updateMenuBtn();\n    });\n\n    // Prevent menu options from updating the URL\n    this.menu.$options.on('click', (ev) => {\n      const $option = $(ev.currentTarget);\n      const href = $option.attr('href');\n      if (href && href.charAt(0) === '#') {\n        ev.preventDefault();\n      }\n    });\n\n    this.menu.on('optionselect', (ev) => {\n      this.selectTab($(ev.selectedOption).data('id'));\n    });\n  },\n\n  selectTab: function (tab) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$selectedTab[0]) {\n      return;\n    }\n\n    this.deselectTab();\n    this.$selectedTab = $tab.addClass('sel');\n    this.makeTabFocusable($tab);\n    this.scrollToTab($tab);\n\n    this.menu.$options.removeClass('sel');\n    this.menu.$options.filter(`[data-id=\"${$tab.data('id')}\"]`).addClass('sel');\n\n    this.trigger('selectTab', {\n      $tab: $tab,\n    });\n\n    $('#content').trigger('scroll');\n  },\n\n  deselectTab: function () {\n    const $tab = this.$selectedTab.removeClass('sel');\n    this.$selectedTab = null;\n\n    this.trigger('deselectTab', {\n      $tab: $tab,\n    });\n  },\n\n  makeTabFocusable: function (tab) {\n    const $tab = this._getTab(tab);\n\n    if ($tab[0] === this.$focusableTab[0]) {\n      return;\n    }\n\n    this.$focusableTab.attr('tabindex', '-1');\n    this.$focusableTab = $tab.attr('tabindex', '0');\n  },\n\n  scrollToTab: function (tab) {\n    const $tab = this._getTab(tab);\n    const scrollLeft = this.$ul.scrollLeft();\n    const tabOffset = $tab.offset().left;\n    const elemScrollOffset = tabOffset - this.$ul.offset().left;\n    let targetScrollLeft = false;\n\n    // Is the tab hidden on the left?\n    if (elemScrollOffset < 0) {\n      targetScrollLeft = scrollLeft + elemScrollOffset - 24;\n    } else {\n      const tabWidth = $tab.outerWidth();\n      const ulWidth = this.$ul.prop('clientWidth');\n\n      // Is it hidden to the right?\n      if (elemScrollOffset + tabWidth > ulWidth) {\n        targetScrollLeft =\n          scrollLeft + (elemScrollOffset - (ulWidth - tabWidth)) + 24;\n      }\n    }\n\n    if (targetScrollLeft !== false) {\n      this.$ul.scrollLeft(targetScrollLeft);\n    }\n  },\n\n  updateMenuBtn: function () {\n    if (\n      Math.floor(this.$ul.prop('scrollWidth') - 48) >\n      this.$container.prop('clientWidth')\n    ) {\n      this.$ul.addClass('scrollable');\n      this.$menuBtn.removeClass('hidden');\n    } else {\n      this.$ul.removeClass('scrollable');\n      this.$menuBtn.addClass('hidden');\n    }\n  },\n\n  _getTab: function (tab) {\n    if (tab instanceof jQuery) {\n      return tab;\n    }\n\n    if (tab instanceof HTMLElement) {\n      return $(tab);\n    }\n\n    if (typeof tab !== 'string') {\n      throw 'Invalid tab ID';\n    }\n\n    const $tab = this.$tabs.filter(`[data-id=\"${tab}\"]`);\n\n    if (!$tab.length) {\n      throw `Invalid tab ID: ${tab}`;\n    }\n\n    return $tab;\n  },\n\n  destroy: function () {\n    this.$container.removeData('tabs');\n    this.base();\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Tag select input\n */\nCraft.TagSelectInput = Craft.BaseElementSelectInput.extend(\n  {\n    searchTimeout: null,\n    searchMenu: null,\n\n    $container: null,\n    $elementsContainer: null,\n    $elements: null,\n    $addTagInput: null,\n    $spinner: null,\n\n    _ignoreBlur: false,\n\n    init: function (settings) {\n      // Normalize the settings\n      // ---------------------------------------------------------------------\n\n      // Are they still passing in a bunch of arguments?\n      if (!$.isPlainObject(settings)) {\n        // Loop through all of the old arguments and apply them to the settings\n        var normalizedSettings = {},\n          args = ['id', 'name', 'tagGroupId', 'sourceElementId'];\n\n        for (var i = 0; i < args.length; i++) {\n          if (typeof arguments[i] !== 'undefined') {\n            normalizedSettings[args[i]] = arguments[i];\n          } else {\n            break;\n          }\n        }\n\n        settings = normalizedSettings;\n      }\n\n      this.base($.extend({}, Craft.TagSelectInput.defaults, settings));\n\n      this.$addTagInput = this.$container.children('.add').children('.text');\n      this.$spinner = this.$addTagInput.next();\n\n      this.addListener(this.$addTagInput, 'input', () => {\n        if (this.searchTimeout) {\n          clearTimeout(this.searchTimeout);\n        }\n\n        this.searchTimeout = setTimeout(this.searchForTags.bind(this), 500);\n      });\n\n      this.addListener(this.$addTagInput, 'keydown', function (ev) {\n        if (ev.keyCode === Garnish.RETURN_KEY) {\n          ev.preventDefault();\n        }\n\n        let $option;\n\n        switch (ev.keyCode) {\n          case Garnish.RETURN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              this.selectTag(this.searchMenu.$options.filter('.hover'));\n            }\n            return;\n          }\n\n          case Garnish.DOWN_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $nextOption = $hoverOption\n                  .parent()\n                  .nextAll()\n                  .find('a:not(.disabled)')\n                  .first();\n                if ($nextOption.length) {\n                  this.focusOption($nextOption);\n                }\n              } else {\n                this.focusOption(this.searchMenu.$options.eq(0));\n              }\n            }\n            return;\n          }\n\n          case Garnish.UP_KEY: {\n            ev.preventDefault();\n            if (this.searchMenu) {\n              let $hoverOption = this.searchMenu.$options.filter('.hover');\n              if ($hoverOption.length) {\n                let $prevOption = $hoverOption\n                  .parent()\n                  .prevAll()\n                  .find('a:not(.disabled)')\n                  .last();\n                if ($prevOption.length) {\n                  this.focusOption($prevOption);\n                }\n              } else {\n                this.focusOption(\n                  this.searchMenu.$options.eq(\n                    this.searchMenu.$options.length - 1\n                  )\n                );\n              }\n            }\n            return;\n          }\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'focus', function () {\n        if (this.searchMenu) {\n          this.searchMenu.show();\n        }\n      });\n\n      this.addListener(this.$addTagInput, 'blur', function () {\n        if (this._ignoreBlur) {\n          this._ignoreBlur = false;\n          return;\n        }\n\n        setTimeout(() => {\n          if (this.searchMenu) {\n            this.searchMenu.hide();\n          }\n        }, 1);\n      });\n    },\n\n    focusOption: function ($option) {\n      this.searchMenu.$options.removeClass('hover');\n      $option.addClass('hover');\n      this.searchMenu.$menuList.attr(\n        'aria-activedescendant',\n        $option.attr('id')\n      );\n    },\n\n    // No \"add\" button\n    getAddElementsBtn: $.noop,\n\n    getElementSortAxis: function () {\n      return null;\n    },\n\n    searchForTags: function () {\n      if (this.searchMenu) {\n        this.killSearchMenu();\n      }\n\n      var val = this.$addTagInput.val();\n\n      if (val) {\n        this.$spinner.removeClass('hidden');\n\n        var excludeIds = [];\n\n        for (var i = 0; i < this.$elements.length; i++) {\n          var id = $(this.$elements[i]).data('id');\n\n          if (id) {\n            excludeIds.push(id);\n          }\n        }\n\n        if (this.settings.sourceElementId) {\n          excludeIds.push(this.settings.sourceElementId);\n        }\n\n        var data = {\n          search: this.$addTagInput.val(),\n          tagGroupId: this.settings.tagGroupId,\n          excludeIds: excludeIds,\n        };\n\n        Craft.postActionRequest(\n          'tags/search-for-tags',\n          data,\n          (response, textStatus) => {\n            // Just in case\n            if (this.searchMenu) {\n              this.killSearchMenu();\n            }\n\n            this.$spinner.addClass('hidden');\n\n            if (textStatus === 'success') {\n              var $menu = $('<div class=\"menu tagmenu\"/>').appendTo(\n                  Garnish.$bod\n                ),\n                $ul = $('<ul/>').appendTo($menu);\n\n              var $li;\n\n              for (var i = 0; i < response.tags.length; i++) {\n                $li = $('<li/>').appendTo($ul);\n\n                $('<a data-icon=\"tag\"/>')\n                  .appendTo($li)\n                  .text(response.tags[i].title)\n                  .data('id', response.tags[i].id)\n                  .addClass(response.tags[i].exclude ? 'disabled' : '');\n              }\n\n              if (!response.exactMatch) {\n                $li = $('<li/>').appendTo($ul);\n                $('<a data-icon=\"plus\"/>').appendTo($li).text(data.search);\n              }\n\n              $ul.find('a:not(.disabled):first').addClass('hover');\n\n              this.searchMenu = new Garnish.Menu($menu, {\n                attachToElement: this.$addTagInput,\n                onOptionSelect: this.selectTag.bind(this),\n              });\n\n              this.addListener($menu, 'mousedown', () => {\n                this._ignoreBlur = true;\n              });\n\n              this.searchMenu.show();\n            }\n          }\n        );\n      } else {\n        this.$spinner.addClass('hidden');\n      }\n    },\n\n    selectTag: function (option) {\n      var $option = $(option);\n\n      if ($option.hasClass('disabled')) {\n        return;\n      }\n\n      var id = $option.data('id');\n      var title = $option.text();\n\n      var $element = $('<div/>', {\n        class: 'element small removable',\n        'data-id': id,\n        'data-site-id': this.settings.targetSiteId,\n        'data-label': title,\n        'data-editable': '1',\n      }).appendTo(this.$elementsContainer);\n\n      var $input = $('<input/>', {\n        type: 'hidden',\n        name: this.settings.name + '[]',\n        value: id,\n      }).appendTo($element);\n\n      $('<a/>', {\n        class: 'delete icon',\n        title: Craft.t('app', 'Remove'),\n      }).appendTo($element);\n\n      var $titleContainer = $('<div/>', {\n        class: 'label',\n      }).appendTo($element);\n\n      $('<span/>', {\n        class: 'title',\n        text: title,\n      }).appendTo($titleContainer);\n\n      var margin = -($element.outerWidth() + 10);\n      this.$addTagInput.css('margin-' + Craft.left, margin + 'px');\n\n      var animateCss = {};\n      animateCss['margin-' + Craft.left] = 0;\n      this.$addTagInput.velocity(animateCss, 'fast');\n\n      this.$elements = this.$elements.add($element);\n\n      this.addElements($element);\n\n      this.killSearchMenu();\n      this.$addTagInput.val('');\n      this.$addTagInput.trigger('focus');\n\n      if (!id) {\n        // We need to create the tag first\n        $element.addClass('loading disabled');\n\n        var data = {\n          groupId: this.settings.tagGroupId,\n          title: title,\n        };\n\n        Craft.postActionRequest(\n          'tags/create-tag',\n          data,\n          (response, textStatus) => {\n            if (textStatus === 'success' && response.success) {\n              $element.attr('data-id', response.id);\n              $input.val(response.id);\n\n              $element.removeClass('loading disabled');\n            } else {\n              this.removeElement($element);\n\n              if (textStatus === 'success') {\n                // Some sort of validation error that still resulted in  a 200 response. Shouldn't be possible though.\n                Craft.cp.displayError(\n                  Craft.t('app', 'A server error occurred.')\n                );\n              }\n            }\n          }\n        );\n      }\n    },\n\n    killSearchMenu: function () {\n      this.searchMenu.hide();\n      this.searchMenu.destroy();\n      this.searchMenu = null;\n    },\n  },\n  {\n    defaults: {\n      tagGroupId: null,\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Thumb Element Index View\n */\nCraft.ThumbsElementIndexView = Craft.BaseElementIndexView.extend({\n  getElementContainer: function () {\n    return this.$container.children('ul');\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\nCraft.ui = {\n  createTextInput: function (config) {\n    config = $.extend(\n      {\n        autocomplete: false,\n      },\n      config\n    );\n    var $input = $('<input/>', {\n      attr: {\n        class: 'text',\n        type: config.type || 'text',\n        inputmode: config.inputmode,\n        id: config.id,\n        size: config.size,\n        name: config.name,\n        value: config.value,\n        maxlength: config.maxlength,\n        autofocus: this.getAutofocusValue(config.autofocus),\n        autocomplete:\n          typeof config.autocomplete === 'boolean'\n            ? config.autocomplete\n              ? 'on'\n              : 'off'\n            : config.autocomplete,\n        disabled: this.getDisabledValue(config.disabled),\n        readonly: config.readonly,\n        title: config.title,\n        placeholder: config.placeholder,\n        step: config.step,\n        min: config.min,\n        max: config.max,\n      },\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n    if (config.placeholder) {\n      $input.addClass('nicetext');\n    }\n    if (config.type === 'password') {\n      $input.addClass('password');\n    }\n    if (config.disabled) {\n      $input.addClass('disabled');\n    }\n    if (!config.size) {\n      $input.addClass('fullwidth');\n    }\n\n    if (config.showCharsLeft && config.maxlength) {\n      $input\n        .attr('data-show-chars-left')\n        .css(\n          'padding-' + (Craft.orientation === 'ltr' ? 'right' : 'left'),\n          7.2 * config.maxlength.toString().length + 14 + 'px'\n        );\n    }\n\n    if (config.placeholder || config.showCharsLeft) {\n      new Garnish.NiceText($input);\n    }\n\n    if (config.type === 'password') {\n      return $('<div class=\"passwordwrapper\"/>').append($input);\n    } else {\n      return $input;\n    }\n  },\n\n  createTextField: function (config) {\n    if (!config.id) {\n      config.id = 'text' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextInput(config), config);\n  },\n\n  createCopyTextInput: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let buttonId = config.buttonId || `${id}-btn`;\n\n    let $container = $('<div/>', {\n      class: 'copytext',\n    });\n\n    let $input = this.createTextInput(\n      $.extend({}, config, {\n        readonly: true,\n      })\n    ).appendTo($container);\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      id: buttonId,\n      class: 'btn',\n      'data-icon': 'clipboard',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n    }).appendTo($container);\n\n    $btn.on('click', () => {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $container.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n    });\n\n    return $container;\n  },\n\n  createCopyTextBtn: function (config) {\n    let id = config.id || 'copytext' + Math.floor(Math.random() * 1000000000);\n    let value = config.value;\n\n    let $btn = $('<div/>', {\n      id,\n      class: 'copytextbtn',\n      role: 'button',\n      title: Craft.t('app', 'Copy to clipboard'),\n      'aria-label': Craft.t('app', 'Copy to clipboard'),\n      tabindex: '0',\n    });\n\n    if (config.class) {\n      $btn.addClass(config.class);\n    }\n\n    let $input = $('<input/>', {\n      value,\n      readonly: true,\n      size: value.length,\n      tabindex: '-1',\n    }).appendTo($btn);\n\n    let $icon = $('<span/>', {\n      'data-icon': 'clipboard',\n      'aria-hidden': 'true',\n    }).appendTo($btn);\n\n    const copyValue = function () {\n      $input[0].select();\n      document.execCommand('copy');\n      Craft.cp.displayNotice(Craft.t('app', 'Copied to clipboard.'));\n      $btn.trigger('copy');\n      $input[0].setSelectionRange(0, 0);\n      $btn.focus();\n    };\n\n    $btn.on('click', () => {\n      copyValue();\n    });\n\n    $btn.on('keydown', (ev) => {\n      if (ev.keyCode === Garnish.SPACE_KEY) {\n        copyValue();\n        ev.preventDefault();\n      }\n    });\n\n    return $btn;\n  },\n\n  createCopyTextField: function (config) {\n    if (!config.id) {\n      config.id = 'copytext' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCopyTextInput(config), config);\n  },\n\n  createCopyTextPrompt: function (config) {\n    let $container = $('<div/>', {\n      class: 'modal fitted',\n    });\n    let $body = $('<div/>', {\n      class: 'body',\n    }).appendTo($container);\n    this.createCopyTextField(\n      $.extend(\n        {\n          size: Math.max(Math.min(config.value.length, 50), 25),\n        },\n        config\n      )\n    ).appendTo($body);\n    let modal = new Garnish.Modal($container, {\n      closeOtherModals: false,\n    });\n    $container.on('copy', () => {\n      modal.hide();\n    });\n    return $container;\n  },\n\n  createTextarea: function (config) {\n    var $textarea = $('<textarea/>', {\n      class: 'text',\n      rows: config.rows || 2,\n      cols: config.cols || 50,\n      id: config.id,\n      name: config.name,\n      maxlength: config.maxlength,\n      autofocus: config.autofocus && !Garnish.isMobileBrowser(true),\n      disabled: !!config.disabled,\n      placeholder: config.placeholder,\n      html: config.value,\n    });\n\n    if (config.showCharsLeft) {\n      $textarea.attr('data-show-chars-left', '');\n    }\n\n    if (config.class) {\n      $textarea.addClass(config.class);\n    }\n\n    if (!config.size) {\n      $textarea.addClass('fullwidth');\n    }\n\n    return $textarea;\n  },\n\n  createTextareaField: function (config) {\n    if (!config.id) {\n      config.id = 'textarea' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTextarea(config), config);\n  },\n\n  createSelect: function (config) {\n    var $container = $('<div/>', {\n      class: 'select',\n    });\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var $select = $('<select/>', {\n      id: config.id,\n      name: config.name,\n      autofocus: config.autofocus && Garnish.isMobileBrowser(true),\n      disabled: config.disabled,\n      'data-target-prefix': config.targetPrefix,\n    }).appendTo($container);\n\n    // Normalize the options into an array\n    if ($.isPlainObject(config.options)) {\n      let options = [];\n      for (var key in config.options) {\n        if (!config.options.hasOwnProperty(key)) {\n          continue;\n        }\n        let option = config.options[key];\n        if ($.isPlainObject(option)) {\n          if (typeof option.optgroup !== 'undefined') {\n            options.push(option);\n          } else {\n            options.push({\n              label: option.label,\n              value: typeof option.value !== 'undefined' ? option.value : key,\n              disabled:\n                typeof option.disabled !== 'undefined'\n                  ? option.disabled\n                  : false,\n            });\n          }\n        } else {\n          options.push({\n            label: option,\n            value: key,\n          });\n        }\n      }\n      config.options = options;\n    }\n\n    var $optgroup = null;\n\n    for (let i = 0; i < config.options.length; i++) {\n      let option = config.options[i];\n\n      // Starting a new <optgroup>?\n      if (typeof option.optgroup !== 'undefined') {\n        $optgroup = $('<optgroup/>', {\n          label: option.label,\n        }).appendTo($select);\n      } else {\n        $('<option/>', {\n          value: option.value,\n          selected: option.value == config.value,\n          disabled:\n            typeof option.disabled !== 'undefined' ? option.disabled : false,\n          html: option.label,\n        }).appendTo($optgroup || $select);\n      }\n    }\n\n    if (config.toggle) {\n      $select.addClass('fieldtoggle');\n      new Craft.FieldToggle($select);\n    }\n\n    return $container;\n  },\n\n  createSelectField: function (config) {\n    if (!config.id) {\n      config.id = 'select' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createSelect(config), config);\n  },\n\n  createCheckbox: function (config) {\n    var id = config.id || 'checkbox' + Math.floor(Math.random() * 1000000000);\n\n    var $input = $('<input/>', {\n      type: 'checkbox',\n      value: typeof config.value !== 'undefined' ? config.value : '1',\n      id: id,\n      class: 'checkbox',\n      name: config.name,\n      checked: config.checked ? 'checked' : null,\n      autofocus: this.getAutofocusValue(config.autofocus),\n      disabled: this.getDisabledValue(config.disabled),\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.class) {\n      $input.addClass(config.class);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $input.addClass('fieldtoggle');\n      new Craft.FieldToggle($input);\n    }\n\n    var $label = $('<label/>', {\n      for: id,\n      html: config.label,\n    });\n\n    // Should we include a hidden input first?\n    if (\n      config.name &&\n      (config.name.length < 3 || config.name.substr(-2) !== '[]')\n    ) {\n      return $([\n        $('<input/>', {\n          type: 'hidden',\n          name: config.name,\n          value: '',\n        })[0],\n        $input[0],\n        $label[0],\n      ]);\n    } else {\n      return $([$input[0], $label[0]]);\n    }\n  },\n\n  createCheckboxField: function (config) {\n    if (!config.id) {\n      config.id = 'checkbox' + Math.floor(Math.random() * 1000000000);\n    }\n\n    var $field = $('<div class=\"field checkboxfield\"/>', {\n      id: `${config.id}-field`,\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n    if (config.instructions) {\n      $field.addClass('has-instructions');\n    }\n\n    this.createCheckbox(config).appendTo($field);\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    return $field;\n  },\n\n  createCheckboxSelect: function (config) {\n    var $container = $('<fieldset class=\"checkbox-select\"/>');\n\n    if (config.class) {\n      $container.addClass(config.class);\n    }\n\n    var allValue, allChecked;\n\n    if (config.showAllOption) {\n      allValue = config.allValue || '*';\n      allChecked = config.values == allValue;\n\n      // Create the \"All\" checkbox\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            id: config.id,\n            class: 'all',\n            label: '<b>' + (config.allLabel || Craft.t('app', 'All')) + '</b>',\n            name: config.name,\n            value: allValue,\n            checked: allChecked,\n            autofocus: config.autofocus,\n          })\n        );\n    } else {\n      allChecked = false;\n    }\n\n    // Create the actual options\n    for (var i = 0; i < config.options.length; i++) {\n      var option = config.options[i];\n\n      if (option.value == allValue) {\n        continue;\n      }\n\n      $('<div/>')\n        .appendTo($container)\n        .append(\n          this.createCheckbox({\n            label: option.label,\n            name: config.name ? config.name + '[]' : null,\n            value: option.value,\n            checked: allChecked || (config.values || []).includes(option.value),\n            disabled: allChecked,\n          })\n        );\n    }\n\n    new Garnish.CheckboxSelect($container);\n\n    return $container;\n  },\n\n  createCheckboxSelectField: function (config) {\n    config.fieldset = true;\n    if (!config.id) {\n      config.id = 'checkboxselect' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createCheckboxSelect(config), config);\n  },\n\n  createLightswitch: function (config) {\n    var value = config.value || '1';\n    var indeterminateValue = config.indeterminateValue || '-';\n\n    var $container = $('<button/>', {\n      type: 'button',\n      class: 'lightswitch',\n      'data-value': value,\n      'data-indeterminate-value': indeterminateValue,\n      id: config.id,\n      role: 'checkbox',\n      'aria-checked': config.on\n        ? 'true'\n        : config.indeterminate\n        ? 'mixed'\n        : 'false',\n      'aria-labelledby': config.labelId,\n      'data-target': config.toggle,\n      'data-reverse-target': config.reverseToggle,\n    });\n\n    if (config.on) {\n      $container.addClass('on');\n    } else if (config.indeterminate) {\n      $container.addClass('indeterminate');\n    }\n\n    if (config.small) {\n      $container.addClass('small');\n    }\n\n    if (config.disabled) {\n      $container.addClass('disabled');\n    }\n\n    $(\n      '<div class=\"lightswitch-container\">' +\n        '<div class=\"handle\"></div>' +\n        '</div>'\n    ).appendTo($container);\n\n    if (config.name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: config.name,\n        value: config.on\n          ? value\n          : config.indeterminate\n          ? indeterminateValue\n          : '',\n        disabled: config.disabled,\n      }).appendTo($container);\n    }\n\n    if (config.toggle || config.reverseToggle) {\n      $container.addClass('fieldtoggle');\n      new Craft.FieldToggle($container);\n    }\n\n    new Craft.LightSwitch($container, {\n      onChange: config.onChange || $.noop,\n    });\n\n    return $container;\n  },\n\n  createLightswitchField: function (config) {\n    if (!config.id) {\n      config.id = 'lightswitch' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createLightswitch(config), config).addClass(\n      'lightswitch-field'\n    );\n  },\n\n  createColorInput: function (config) {\n    const id = config.id || 'color' + Math.floor(Math.random() * 1000000000);\n    const containerId = config.containerId || id + '-container';\n    const name = config.name || null;\n    const value = config.value || null;\n    const small = config.small || false;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      id: containerId,\n      class: 'flex color-container',\n    });\n\n    const $colorPreviewContainer = $('<div/>', {\n      class: 'color static' + (small ? ' small' : ''),\n    }).appendTo($container);\n\n    const $colorPreview = $('<div/>', {\n      class: 'color-preview',\n      style: config.value ? {backgroundColor: config.value} : null,\n    }).appendTo($colorPreviewContainer);\n\n    const $inputContainer = $('<div/>', {\n      class: 'color-input-container',\n    })\n      .append(\n        $('<div/>', {\n          class: 'color-hex-indicator light code',\n          'aria-hidden': 'true',\n          text: '#',\n        })\n      )\n      .appendTo($container);\n\n    const $input = this.createTextInput({\n      id: id,\n      name: name,\n      value: Craft.ltrim(value, '#'),\n      size: 10,\n      class: 'color-input',\n      autofocus: autofocus,\n      disabled: disabled,\n      'aria-label': Craft.t('app', 'Color hex value'),\n    }).appendTo($inputContainer);\n\n    new Craft.ColorInput($container);\n    return $container;\n  },\n\n  createColorField: function (config) {\n    config.fieldset = true;\n    o;\n    if (!config.id) {\n      config.id = 'color' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createColorInput(config), config);\n  },\n\n  createDateInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'date' + Math.floor(Math.random() * 1000000000)) + '-date';\n    const name = config.name || null;\n    const inputName = name ? name + '[date]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'datewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'date' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      value: value\n        ? isMobile\n          ? value.toISOString().split('T')[0]\n          : Craft.formatDate(value)\n        : '',\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"date\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      $input.datetimeinput();\n    } else {\n      $input.datepicker(\n        $.extend(\n          {\n            defaultDate: value || new Date(),\n          },\n          Craft.datepickerOptions\n        )\n      );\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createDateField: function (config) {\n    if (!config.id) {\n      config.id = 'date' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createDateInput(config), config);\n  },\n\n  createDateRangePicker: function (config) {\n    var now = new Date();\n    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n    config = $.extend(\n      {\n        class: '',\n        options: [\n          'today',\n          'thisWeek',\n          'thisMonth',\n          'thisYear',\n          'past7Days',\n          'past30Days',\n          'past90Days',\n          'pastYear',\n        ],\n        onChange: $.noop,\n        selected: null,\n        startDate: null,\n        endDate: null,\n      },\n      config\n    );\n\n    var $menu = $('<div/>', {class: 'menu'});\n    var $ul = $('<ul/>', {class: 'padded'}).appendTo($menu);\n    var $allOption = $('<a/>')\n      .addClass('sel')\n      .text(Craft.t('app', 'All'))\n      .data('handle', 'all');\n\n    $('<li/>').append($allOption).appendTo($ul);\n\n    var option;\n    var selectedOption;\n    for (var i = 0; i < config.options.length; i++) {\n      var handle = config.options[i];\n      switch (handle) {\n        case 'today':\n          option = {\n            label: Craft.t('app', 'Today'),\n            startDate: today,\n            endDate: today,\n          };\n          break;\n        case 'thisWeek':\n          var firstDayOffset = now.getDay() - Craft.datepickerOptions.firstDay;\n          if (firstDayOffset < 0) {\n            firstDayOffset += 7;\n          }\n          option = {\n            label: Craft.t('app', 'This week'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - firstDayOffset\n            ),\n            endDate: today,\n          };\n          break;\n        case 'thisMonth':\n          option = {\n            label: Craft.t('app', 'This month'),\n            startDate: new Date(now.getFullYear(), now.getMonth()),\n            endDate: today,\n          };\n          break;\n        case 'thisYear':\n          option = {\n            label: Craft.t('app', 'This year'),\n            startDate: new Date(now.getFullYear(), 0),\n            endDate: today,\n          };\n          break;\n        case 'past7Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 7}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 7\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past30Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 30}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 30\n            ),\n            endDate: today,\n          };\n          break;\n        case 'past90Days':\n          option = {\n            label: Craft.t('app', 'Past {num} days', {num: 90}),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 90\n            ),\n            endDate: today,\n          };\n          break;\n        case 'pastYear':\n          option = {\n            label: Craft.t('app', 'Past year'),\n            startDate: new Date(\n              now.getFullYear(),\n              now.getMonth(),\n              now.getDate() - 365\n            ),\n            endDate: today,\n          };\n          break;\n      }\n\n      var $li = $('<li/>');\n      var $a = $('<a/>', {text: option.label})\n        .data('handle', handle)\n        .data('startDate', option.startDate)\n        .data('endDate', option.endDate)\n        .data('startTime', option.startDate ? option.startDate.getTime() : null)\n        .data('endTime', option.endDate ? option.endDate.getTime() : null);\n\n      if (config.selected && handle == config.selected) {\n        selectedOption = $a[0];\n      }\n\n      $li.append($a);\n      $li.appendTo($ul);\n    }\n\n    $('<hr/>').appendTo($menu);\n\n    var $flex = $('<div/>', {class: 'flex flex-nowrap padded'}).appendTo($menu);\n    var $startDate = this.createDateField({label: Craft.t('app', 'From')})\n      .appendTo($flex)\n      .find('input');\n    var $endDate = this.createDateField({label: Craft.t('app', 'To')})\n      .appendTo($flex)\n      .find('input');\n\n    // prevent ESC keypresses in the date inputs from closing the menu\n    var $dateInputs = $startDate.add($endDate);\n    $dateInputs.on('keyup', function (ev) {\n      if (\n        ev.keyCode === Garnish.ESC_KEY &&\n        $(this).data('datepicker') &&\n        $(this).data('datepicker').dpDiv.is(':visible')\n      ) {\n        ev.stopPropagation();\n      }\n    });\n\n    // prevent clicks in the datepicker divs from closing the menu\n    if ($startDate.data('datepicker')) {\n      $startDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n    if ($endDate.data('datepicker')) {\n      $endDate.data('datepicker').dpDiv.on('mousedown', function (ev) {\n        ev.stopPropagation();\n      });\n    }\n\n    var menu = new Garnish.Menu($menu, {\n      onOptionSelect: function (option) {\n        var $option = $(option);\n        $btn.text($option.text());\n        menu.setPositionRelativeToAnchor();\n        $menu.find('.sel').removeClass('sel');\n        $option.addClass('sel');\n\n        // Update the start/end dates\n        $startDate.datepicker('setDate', $option.data('startDate'));\n        $endDate.datepicker('setDate', $option.data('endDate'));\n\n        config.onChange(\n          $option.data('startDate') || null,\n          $option.data('endDate') || null,\n          $option.data('handle')\n        );\n      },\n    });\n\n    $dateInputs.on('change', function () {\n      // Do the start & end dates match one of our options?\n      let startDate = $startDate.datepicker('getDate');\n      let endDate = $endDate.datepicker('getDate');\n      let startTime = startDate ? startDate.getTime() : null;\n      let endTime = endDate ? endDate.getTime() : null;\n\n      let $options = $ul.find('a');\n      let $option;\n      let foundOption = false;\n\n      for (let i = 0; i < $options.length; i++) {\n        $option = $options.eq(i);\n        if (\n          startTime === ($option.data('startTime') || null) &&\n          endTime === ($option.data('endTime') || null)\n        ) {\n          menu.selectOption($option[0]);\n          foundOption = true;\n          config.onChange(null, null, $option.data('handle'));\n          break;\n        }\n      }\n\n      if (!foundOption) {\n        $menu.find('.sel').removeClass('sel');\n        $flex.addClass('sel');\n\n        if (!startTime && !endTime) {\n          $btn.text(Craft.t('app', 'All'));\n        } else if (startTime && endTime) {\n          $btn.text($startDate.val() + ' - ' + $endDate.val());\n        } else if (startTime) {\n          $btn.text(Craft.t('app', 'From {date}', {date: $startDate.val()}));\n        } else {\n          $btn.text(Craft.t('app', 'To {date}', {date: $endDate.val()}));\n        }\n        menu.setPositionRelativeToAnchor();\n\n        config.onChange(startDate, endDate, 'custom');\n      }\n    });\n\n    menu.on('hide', function () {\n      $startDate.datepicker('hide');\n      $endDate.datepicker('hide');\n    });\n\n    let btnClasses = 'btn menubtn';\n    if (config.class) {\n      btnClasses = btnClasses + ' ' + config.class;\n    }\n\n    let $btn = $('<button/>', {\n      type: 'button',\n      class: btnClasses,\n      'data-icon': 'date',\n      text: Craft.t('app', 'All'),\n    });\n\n    new Garnish.MenuBtn($btn, menu);\n\n    if (selectedOption) {\n      menu.selectOption(selectedOption);\n    }\n\n    if (config.startDate) {\n      $startDate.datepicker('setDate', config.startDate);\n    }\n\n    if (config.endDate) {\n      $endDate.datepicker('setDate', config.endDate);\n    }\n\n    if (config.startDate || config.endDate) {\n      $dateInputs.trigger('change');\n    }\n\n    return $btn;\n  },\n\n  createTimeInput: function (config) {\n    const isMobile = Garnish.isMobileBrowser();\n    const id =\n      (config.id || 'time' + Math.floor(Math.random() * 1000000000)) + '-time';\n    const name = config.name || null;\n    const inputName = name ? name + '[time]' : null;\n    const value =\n      config.value && typeof config.value.getMonth === 'function'\n        ? config.value\n        : null;\n    const autofocus = config.autofocus && Garnish.isMobileBrowser(true);\n    const disabled = config.disabled || false;\n\n    const $container = $('<div/>', {\n      class: 'timewrapper',\n    });\n\n    const $input = this.createTextInput({\n      id: id,\n      type: isMobile ? 'time' : 'text',\n      class: isMobile && !value ? 'empty-value' : false,\n      name: inputName,\n      placeholder: ' ',\n      autocomplete: false,\n      autofocus: autofocus,\n      disabled: disabled,\n    }).appendTo($container);\n\n    $('<div data-icon=\"time\"></div>').appendTo($container);\n\n    if (name) {\n      $('<input/>', {\n        type: 'hidden',\n        name: name + '[timezone]',\n        val: Craft.timezone,\n      }).appendTo($container);\n    }\n\n    if (isMobile) {\n      if (value) {\n        $input.val(value.toISOString().split('T')[1]);\n      }\n      $input.datetimeinput();\n    } else {\n      $input.timepicker(Craft.timepickerOptions);\n      if (value) {\n        $input.timepicker(\n          'setTime',\n          value.getHours() * 3600 + value.getMinutes() * 60 + value.getSeconds()\n        );\n      }\n    }\n\n    if (config.hasOuterContainer) {\n      return $container;\n    }\n\n    return $('<div class=\"datetimewrapper\"/>').append($container).datetime();\n  },\n\n  createTimeField: function (config) {\n    if (!config.id) {\n      config.id = 'time' + Math.floor(Math.random() * 1000000000);\n    }\n    return this.createField(this.createTimeInput(config), config);\n  },\n\n  createField: function (input, config) {\n    var label =\n        config.label && config.label !== '__blank__' ? config.label : null,\n      siteId = Craft.isMultiSite && config.siteId ? config.siteId : null;\n\n    var $field = $(config.fieldset ? '<fieldset/>' : '<div/>', {\n      class: 'field',\n      id: config.fieldId || (config.id ? config.id + '-field' : null),\n    });\n\n    if (config.first) {\n      $field.addClass('first');\n    }\n\n    if (label) {\n      var $heading = $('<div class=\"heading\"/>').appendTo($field);\n\n      var $label = $(config.fieldset ? '<legend/>' : '<label/>', {\n        id:\n          config.labelId ||\n          (config.id\n            ? `${config.id}-${config.fieldset ? 'legend' : 'label'}`\n            : null),\n        class: config.required ? 'required' : null,\n        for: !config.fieldset && config.id,\n        text: label,\n      }).appendTo($heading);\n    }\n\n    if (config.instructions) {\n      $('<div class=\"instructions\"/>')\n        .text(config.instructions)\n        .appendTo($field);\n    }\n\n    $('<div class=\"input\"/>').append(input).appendTo($field);\n\n    if (config.tip) {\n      const $tip = $('<p class=\"notice has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($tip);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Tip') + ': ')\n        .appendTo($tip);\n      $('<span/>').text(config.tip).appendTo($tip);\n      $tip.appendTo($field);\n    }\n\n    if (config.warning) {\n      const $warning = $('<p class=\"warning has-icon\"/>');\n      $('<span class=\"icon\" aria-hidden=\"true\"/>').appendTo($warning);\n      $('<span class=\"visually-hidden\"/>')\n        .text(Craft.t('app', 'Warning') + ': ')\n        .appendTo($warning);\n      $('<span/>').text(config.warning).appendTo($warning);\n      $warning.appendTo($field);\n    }\n\n    if (config.errors) {\n      this.addErrorsToField($field, config.errors);\n    }\n\n    return $field;\n  },\n\n  createErrorList: function (errors) {\n    var $list = $('<ul class=\"errors\"/>');\n\n    if (errors) {\n      this.addErrorsToList($list, errors);\n    }\n\n    return $list;\n  },\n\n  addErrorsToList: function ($list, errors) {\n    for (var i = 0; i < errors.length; i++) {\n      $('<li/>').text(errors[i]).appendTo($list);\n    }\n  },\n\n  addErrorsToField: function ($field, errors) {\n    if (!errors) {\n      return;\n    }\n\n    $field.addClass('has-errors');\n    $field.children('.input').addClass('errors');\n\n    var $errors = $field.children('ul.errors');\n\n    if (!$errors.length) {\n      $errors = this.createErrorList().appendTo($field);\n    }\n\n    this.addErrorsToList($errors, errors);\n  },\n\n  clearErrorsFromField: function ($field) {\n    $field.removeClass('has-errors');\n    $field.children('.input').removeClass('errors');\n    $field.children('ul.errors').remove();\n  },\n\n  getAutofocusValue: function (autofocus) {\n    return autofocus && !Garnish.isMobileBrowser(true) ? 'autofocus' : null;\n  },\n\n  getDisabledValue: function (disabled) {\n    return disabled ? 'disabled' : null;\n  },\n};\n","/** global: Craft */\n/** global: Garnish */\n/**\n * File Manager.\n */\nCraft.Uploader = Garnish.Base.extend(\n  {\n    uploader: null,\n    allowedKinds: null,\n    $element: null,\n    settings: null,\n    _rejectedFiles: {},\n    _extensionList: null,\n    _totalFileCounter: 0,\n    _validFileCounter: 0,\n\n    init: function ($element, settings) {\n      this._rejectedFiles = {size: [], type: [], limit: []};\n      this.$element = $element;\n      this.allowedKinds = null;\n      this._extensionList = null;\n      this._totalFileCounter = 0;\n      this._validFileCounter = 0;\n\n      settings = $.extend({}, Craft.Uploader.defaults, settings);\n\n      var events = settings.events;\n      delete settings.events;\n\n      if (settings.allowedKinds && settings.allowedKinds.length) {\n        if (typeof settings.allowedKinds === 'string') {\n          settings.allowedKinds = [settings.allowedKinds];\n        }\n\n        this.allowedKinds = settings.allowedKinds;\n        delete settings.allowedKinds;\n      }\n\n      settings.autoUpload = false;\n\n      this.uploader = this.$element.fileupload(settings);\n      for (var event in events) {\n        if (!events.hasOwnProperty(event)) {\n          continue;\n        }\n\n        this.uploader.on(event, events[event]);\n      }\n\n      this.settings = settings;\n\n      this.uploader.on('fileuploadadd', this.onFileAdd.bind(this));\n    },\n\n    /**\n     * Set uploader parameters.\n     */\n    setParams: function (paramObject) {\n      // If CSRF protection isn't enabled, these won't be defined.\n      if (\n        typeof Craft.csrfTokenName !== 'undefined' &&\n        typeof Craft.csrfTokenValue !== 'undefined'\n      ) {\n        // Add the CSRF token\n        paramObject[Craft.csrfTokenName] = Craft.csrfTokenValue;\n      }\n\n      this.uploader.fileupload('option', {formData: paramObject});\n    },\n\n    /**\n     * Get the number of uploads in progress.\n     */\n    getInProgress: function () {\n      return this.uploader.fileupload('active');\n    },\n\n    /**\n     * Return true, if this is the last upload.\n     */\n    isLastUpload: function () {\n      // Processing the last file or not processing at all.\n      return this.getInProgress() < 2;\n    },\n\n    /**\n     * Called on file add.\n     */\n    onFileAdd: function (e, data) {\n      e.stopPropagation();\n\n      var validateExtension = false;\n\n      if (this.allowedKinds) {\n        if (!this._extensionList) {\n          this._createExtensionList();\n        }\n\n        validateExtension = true;\n      }\n\n      // Make sure that file API is there before relying on it\n      data.process().done(() => {\n        var file = data.files[0];\n        var pass = true;\n        if (validateExtension) {\n          var matches = file.name.match(/\\.([a-z0-4_]+)$/i);\n          var fileExtension = matches[1];\n          if (\n            $.inArray(fileExtension.toLowerCase(), this._extensionList) === -1\n          ) {\n            pass = false;\n            this._rejectedFiles.type.push('“' + file.name + '”');\n          }\n        }\n\n        if (file.size > this.settings.maxFileSize) {\n          this._rejectedFiles.size.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        // If the validation has passed for this file up to now, check if we're not hitting any limits\n        if (\n          pass &&\n          typeof this.settings.canAddMoreFiles === 'function' &&\n          !this.settings.canAddMoreFiles(this._validFileCounter)\n        ) {\n          this._rejectedFiles.limit.push('“' + file.name + '”');\n          pass = false;\n        }\n\n        if (pass) {\n          this._validFileCounter++;\n          data.submit();\n        }\n\n        if (++this._totalFileCounter === data.originalFiles.length) {\n          this._totalFileCounter = 0;\n          this._validFileCounter = 0;\n          this.processErrorMessages();\n        }\n      });\n\n      return true;\n    },\n\n    /**\n     * Process error messages.\n     */\n    processErrorMessages: function () {\n      var str;\n\n      if (this._rejectedFiles.type.length) {\n        if (this._rejectedFiles.type.length === 1) {\n          str =\n            'The file {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded. The allowed file kinds are: {kinds}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.type.join(', '),\n          kinds: this.allowedKinds.join(', '),\n        });\n        this._rejectedFiles.type = [];\n        alert(str);\n      }\n\n      if (this._rejectedFiles.size.length) {\n        if (this._rejectedFiles.size.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because it exceeds the maximum upload size of {size}.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because they exceeded the maximum upload size of {size}.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.size.join(', '),\n          size: this.humanFileSize(Craft.maxUploadSize),\n        });\n        this._rejectedFiles.size = [];\n        alert(str);\n      }\n\n      if (this._rejectedFiles.limit.length) {\n        if (this._rejectedFiles.limit.length === 1) {\n          str =\n            'The file {files} could not be uploaded, because the field limit has been reached.';\n        } else {\n          str =\n            'The files {files} could not be uploaded, because the field limit has been reached.';\n        }\n\n        str = Craft.t('app', str, {\n          files: this._rejectedFiles.limit.join(', '),\n        });\n        this._rejectedFiles.limit = [];\n        alert(str);\n      }\n    },\n\n    humanFileSize: function (bytes) {\n      var threshold = 1024;\n\n      if (bytes < threshold) {\n        return bytes + ' B';\n      }\n\n      var units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n\n      var u = -1;\n\n      do {\n        bytes = bytes / threshold;\n        ++u;\n      } while (bytes >= threshold);\n\n      return bytes.toFixed(1) + ' ' + units[u];\n    },\n\n    _createExtensionList: function () {\n      this._extensionList = [];\n\n      for (var i = 0; i < this.allowedKinds.length; i++) {\n        var allowedKind = this.allowedKinds[i];\n\n        if (typeof Craft.fileKinds[allowedKind] !== 'undefined') {\n          for (\n            var j = 0;\n            j < Craft.fileKinds[allowedKind].extensions.length;\n            j++\n          ) {\n            var ext = Craft.fileKinds[allowedKind].extensions[j];\n            this._extensionList.push(ext);\n          }\n        }\n      }\n    },\n\n    destroy: function () {\n      this.$element.fileupload('destroy');\n      this.base();\n    },\n  },\n  {\n    defaults: {\n      dropZone: null,\n      pasteZone: null,\n      fileInput: null,\n      sequentialUploads: true,\n      maxFileSize: Craft.maxUploadSize,\n      allowedKinds: null,\n      events: {},\n      canAddMoreFiles: null,\n      headers: {Accept: 'application/json;q=0.9,*/*;q=0.8'},\n      paramName: 'assets-upload',\n    },\n  }\n);\n","/** global: Craft */\n/** global: Garnish */\n/**\n * Handle Generator\n */\nCraft.UriFormatGenerator = Craft.BaseInputGenerator.extend({\n  generateTargetValue: function (sourceVal) {\n    // Remove HTML tags\n    sourceVal = sourceVal.replace('/<(.*?)>/g', '');\n\n    // Make it lowercase\n    sourceVal = sourceVal.toLowerCase();\n\n    // Convert extended ASCII characters to basic ASCII\n    sourceVal = Craft.asciiString(sourceVal);\n\n    // Handle must start with a letter and end with a letter/number\n    sourceVal = sourceVal.replace(/^[^a-z]+/, '');\n    sourceVal = sourceVal.replace(/[^a-z0-9]+$/, '');\n\n    // Get the \"words\"\n    var words = Craft.filterArray(sourceVal.split(/[^a-z0-9]+/));\n\n    var uriFormat = words.join(Craft.slugWordSeparator);\n\n    if (uriFormat && this.settings.suffix) {\n      uriFormat += this.settings.suffix;\n    }\n\n    return uriFormat;\n  },\n});\n","/** global: Craft */\n/** global: Garnish */\n/**\n * User index class\n */\nCraft.UserIndex = Craft.BaseElementIndex.extend({\n  init: function (elementType, $container, settings) {\n    this.on('selectSource', this.updateUrl.bind(this));\n    this.base(elementType, $container, settings);\n  },\n\n  getDefaultSourceKey: function () {\n    // Did they request a specific group in the URL?\n    if (\n      this.settings.context === 'index' &&\n      typeof defaultSourceSlug !== 'undefined'\n    ) {\n      for (let i = 0; i < this.$sources.length; i++) {\n        const $source = $(this.$sources[i]);\n        if ($source.data('slug') === defaultSourceSlug) {\n          return $source.data('key');\n        }\n      }\n    }\n\n    return this.base();\n  },\n\n  updateUrl: function () {\n    if (this.settings.context === 'index' && typeof history !== 'undefined') {\n      let uri = 'users';\n      const slug = this.$source.data('slug');\n      if (slug) {\n        uri += `/${slug}`;\n      }\n      history.replaceState({}, '', Craft.getUrl(uri));\n    }\n  },\n});\n\n// Register it!\nCraft.registerElementIndexClass('craft\\\\elements\\\\User', Craft.UserIndex);\n","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./charts.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"3790022a\", content, true, {});","// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = require(\"!!../../../../../../node_modules/mini-css-extract-plugin/dist/loader.js??ruleSet[1].rules[3].use[1]!../../../../../../node_modules/css-loader/dist/cjs.js!../../../../../../node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!../../../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./craft.scss\");\nif(content.__esModule) content = content.default;\nif(typeof content === 'string') content = [[module.id, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = require(\"!../../../../../../node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"80058a3c\", content, true, {});","/**\n * Translates the list format produced by css-loader into something\n * easier to manipulate.\n */\nexport default function listToStyles (parentId, list) {\n  var styles = []\n  var newStyles = {}\n  for (var i = 0; i < list.length; i++) {\n    var item = list[i]\n    var id = item[0]\n    var css = item[1]\n    var media = item[2]\n    var sourceMap = item[3]\n    var part = {\n      id: parentId + ':' + i,\n      css: css,\n      media: media,\n      sourceMap: sourceMap\n    }\n    if (!newStyles[id]) {\n      styles.push(newStyles[id] = { id: id, parts: [part] })\n    } else {\n      newStyles[id].parts.push(part)\n    }\n  }\n  return styles\n}\n","/*\n  MIT License http://www.opensource.org/licenses/mit-license.php\n  Author Tobias Koppers @sokra\n  Modified by Evan You @yyx990803\n*/\n\nimport listToStyles from './listToStyles'\n\nvar hasDocument = typeof document !== 'undefined'\n\nif (typeof DEBUG !== 'undefined' && DEBUG) {\n  if (!hasDocument) {\n    throw new Error(\n    'vue-style-loader cannot be used in a non-browser environment. ' +\n    \"Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.\"\n  ) }\n}\n\n/*\ntype StyleObject = {\n  id: number;\n  parts: Array<StyleObjectPart>\n}\n\ntype StyleObjectPart = {\n  css: string;\n  media: string;\n  sourceMap: ?string\n}\n*/\n\nvar stylesInDom = {/*\n  [id: number]: {\n    id: number,\n    refs: number,\n    parts: Array<(obj?: StyleObjectPart) => void>\n  }\n*/}\n\nvar head = hasDocument && (document.head || document.getElementsByTagName('head')[0])\nvar singletonElement = null\nvar singletonCounter = 0\nvar isProduction = false\nvar noop = function () {}\nvar options = null\nvar ssrIdKey = 'data-vue-ssr-id'\n\n// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>\n// tags it will allow on a page\nvar isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\\b/.test(navigator.userAgent.toLowerCase())\n\nexport default function addStylesClient (parentId, list, _isProduction, _options) {\n  isProduction = _isProduction\n\n  options = _options || {}\n\n  var styles = listToStyles(parentId, list)\n  addStylesToDom(styles)\n\n  return function update (newList) {\n    var mayRemove = []\n    for (var i = 0; i < styles.length; i++) {\n      var item = styles[i]\n      var domStyle = stylesInDom[item.id]\n      domStyle.refs--\n      mayRemove.push(domStyle)\n    }\n    if (newList) {\n      styles = listToStyles(parentId, newList)\n      addStylesToDom(styles)\n    } else {\n      styles = []\n    }\n    for (var i = 0; i < mayRemove.length; i++) {\n      var domStyle = mayRemove[i]\n      if (domStyle.refs === 0) {\n        for (var j = 0; j < domStyle.parts.length; j++) {\n          domStyle.parts[j]()\n        }\n        delete stylesInDom[domStyle.id]\n      }\n    }\n  }\n}\n\nfunction addStylesToDom (styles /* Array<StyleObject> */) {\n  for (var i = 0; i < styles.length; i++) {\n    var item = styles[i]\n    var domStyle = stylesInDom[item.id]\n    if (domStyle) {\n      domStyle.refs++\n      for (var j = 0; j < domStyle.parts.length; j++) {\n        domStyle.parts[j](item.parts[j])\n      }\n      for (; j < item.parts.length; j++) {\n        domStyle.parts.push(addStyle(item.parts[j]))\n      }\n      if (domStyle.parts.length > item.parts.length) {\n        domStyle.parts.length = item.parts.length\n      }\n    } else {\n      var parts = []\n      for (var j = 0; j < item.parts.length; j++) {\n        parts.push(addStyle(item.parts[j]))\n      }\n      stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }\n    }\n  }\n}\n\nfunction createStyleElement () {\n  var styleElement = document.createElement('style')\n  styleElement.type = 'text/css'\n  head.appendChild(styleElement)\n  return styleElement\n}\n\nfunction addStyle (obj /* StyleObjectPart */) {\n  var update, remove\n  var styleElement = document.querySelector('style[' + ssrIdKey + '~=\"' + obj.id + '\"]')\n\n  if (styleElement) {\n    if (isProduction) {\n      // has SSR styles and in production mode.\n      // simply do nothing.\n      return noop\n    } else {\n      // has SSR styles but in dev mode.\n      // for some reason Chrome can't handle source map in server-rendered\n      // style tags - source maps in <style> only works if the style tag is\n      // created and inserted dynamically. So we remove the server rendered\n      // styles and inject new ones.\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  if (isOldIE) {\n    // use singleton mode for IE9.\n    var styleIndex = singletonCounter++\n    styleElement = singletonElement || (singletonElement = createStyleElement())\n    update = applyToSingletonTag.bind(null, styleElement, styleIndex, false)\n    remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true)\n  } else {\n    // use multi-style-tag mode in all other cases\n    styleElement = createStyleElement()\n    update = applyToTag.bind(null, styleElement)\n    remove = function () {\n      styleElement.parentNode.removeChild(styleElement)\n    }\n  }\n\n  update(obj)\n\n  return function updateStyle (newObj /* StyleObjectPart */) {\n    if (newObj) {\n      if (newObj.css === obj.css &&\n          newObj.media === obj.media &&\n          newObj.sourceMap === obj.sourceMap) {\n        return\n      }\n      update(obj = newObj)\n    } else {\n      remove()\n    }\n  }\n}\n\nvar replaceText = (function () {\n  var textStore = []\n\n  return function (index, replacement) {\n    textStore[index] = replacement\n    return textStore.filter(Boolean).join('\\n')\n  }\n})()\n\nfunction applyToSingletonTag (styleElement, index, remove, obj) {\n  var css = remove ? '' : obj.css\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = replaceText(index, css)\n  } else {\n    var cssNode = document.createTextNode(css)\n    var childNodes = styleElement.childNodes\n    if (childNodes[index]) styleElement.removeChild(childNodes[index])\n    if (childNodes.length) {\n      styleElement.insertBefore(cssNode, childNodes[index])\n    } else {\n      styleElement.appendChild(cssNode)\n    }\n  }\n}\n\nfunction applyToTag (styleElement, obj) {\n  var css = obj.css\n  var media = obj.media\n  var sourceMap = obj.sourceMap\n\n  if (media) {\n    styleElement.setAttribute('media', media)\n  }\n  if (options.ssrId) {\n    styleElement.setAttribute(ssrIdKey, obj.id)\n  }\n\n  if (sourceMap) {\n    // https://developer.chrome.com/devtools/docs/javascript-debugging\n    // this makes source maps inside style tags work properly in Chrome\n    css += '\\n/*# sourceURL=' + sourceMap.sources[0] + ' */'\n    // http://stackoverflow.com/a/26603875\n    css += '\\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'\n  }\n\n  if (styleElement.styleSheet) {\n    styleElement.styleSheet.cssText = css\n  } else {\n    while (styleElement.firstChild) {\n      styleElement.removeChild(styleElement.firstChild)\n    }\n    styleElement.appendChild(document.createTextNode(css))\n  }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }"],"names":["Craft","AdminTable","Garnish","Base","extend","settings","totalItems","sorter","$noItems","$table","$tbody","$deleteBtns","init","this","setSettings","defaults","allowDeleteAll","minItems","$","noItemsSelector","tableSelector","children","length","sortable","DataTableSorter","onSortChange","reorderItems","bind","find","addListener","updateUI","addRow","row","maxItems","$row","appendTo","$deleteBtn","addItems","add","ids","i","$items","id","attr","idAttribute","push","data","JSON","stringify","postActionRequest","reorderAction","response","textStatus","success","onReorderItems","cp","displayNotice","t","reorderSuccessMessage","displayError","reorderFailMessage","handleDeleteBtnClick","event","target","closest","confirmDeleteItem","deleteItem","name","getItemName","confirm","confirmDeleteMessage","getItemId","deleteAction","handleDeleteItemResponse","removeItems","remove","onDeleteItem","deleteSuccessMessage","deleteFailMessage","escapeHtml","nameAttribute","hide","removeClass","show","addClass","$moveButtons","newItemBtnSelector","noop","AssetEditor","BaseElementEditor","$filenameInput","originalBasename","originalExtension","reloadIndex","element","on","$sidebar","elementIndex","updateElements","input","refreshThumbnail","$element","base","validators","validateExtension","showImageEditor","AssetImageEditor","onSave","load","showImagePreview","startingWidth","startingHeight","PreviewFileModal","selectFilename","selectionStart","_parseFilename","basename","extension","selectionEnd","one","ev","preventDefault","setTimeout","off","oldExt","newExt","originalFilename","val","rtrim","ext","parts","split","pop","join","registerElementEditorClass","Modal","$body","$footer","$imageTools","$buttons","$cancelBtn","$replaceBtn","$saveBtn","$editorContainer","$straighten","$croppingCanvas","$spinnerCanvas","canvas","image","viewport","focalPoint","grid","croppingCanvas","clipper","croppingRectangle","cropperHandles","cropperGrid","croppingShade","imageStraightenAngle","viewportRotation","originalWidth","originalHeight","imageVerticeCoords","zoomRatio","animationInProgress","currentView","assetId","cacheBust","draggingCropper","scalingCropper","draggingFocal","previousMouseX","previousMouseY","shiftKeyHeld","editorHeight","editorWidth","cropperState","scaleFactor","flipData","focalPointState","spinnerInterval","maxImageSize","lastLoadedDimensions","imageIsLoading","mouseMoveEvent","croppingConstraint","constraintOrientation","showingCustomConstraint","renderImage","renderCropper","Date","now","allowDegreeFractions","isImagick","x","y","$container","$bod","type","class","text","allowSavingAsNew","saveImage","removeListener","$shade","getMaxImageSize","loadEditor","browserViewportWidth","$doc","get","documentElement","clientWidth","browserViewportHeight","clientHeight","Math","max","window","devicePixelRatio","html","alert","$tabs","$viewsContainer","$views","innerHeight","innerWidth","_showSpinner","updateSizeAndPosition","fabric","StaticCanvas","width","height","enableRetinaScaling","requestAnimationFrame","renderAll","imageUrl","getActionUrl","size","Image","fromURL","imageObject","set","originX","originY","left","top","getHeight","getWidth","getScaledImageDimensions","_setFittedImageVerticeCoordinates","_repositionEditorElements","focalState","imageDimensions","offsetX","offsetY","focal","focalData","adjustedX","adjustedY","storeFocalPointState","_createFocalPoint","_createViewport","storeCropperState","_addControlListeners","_handleMouseMove","_handleMouseDown","_handleMouseUp","_handleMouseOut","_hideSpinner","first","trigger","_reloadImage","setSrc","css","parent","previousEditorDimensions","setDimensions","currentScaledDimensions","getZoomToFitRatio","previouslyOccupiedArea","_getBoundingRectangle","_repositionCropper","getZoomToCoverRatio","_repositionImage","_repositionViewport","_repositionFocalPoint","_zoomImage","Rect","fill","globalCompositeOperation","sizeFactor","focalX","focalY","deltaX","deltaY","Group","Circle","radius","strokeWidth","stroke","toggleFocalPoint","dimensions","state","currentWidth","ratio","hasOrientationChanged","_","imageRatio","editorRatio","min","round","_handleTabClick","rotateImage","flipImage","straighteningInput","SlideRuleInput","onStart","_showGrid","onChange","slider","straighten","onEnd","_hideGrid","_cleanupFocalPointAfterStraighten","keyCode","SHIFT_KEY","_handleConstraintClick","_handleOrientationClick","_applyCustomConstraint","constraint","currentTarget","$target","siblings","_showCustomConstraint","_hideCustomConstraint","setCroppingConstraint","enforceCroppingConstraint","value","$constraints","$constraint","reverse","filter","click","_getCustomConstraint","w","h","parseFloat","isNaN","_setCustomConstraint","$tab","view","showView","enableSlider","disableSlider","disableCropMode","enableCropMode","zoomFactor","degrees","parseInt","imageZoomRatio","newAngle","angle","scaledImageDimensions","viewportProperties","imageProperties","angleInRadians","PI","newDeltaX","cos","sin","newDeltaY","modifiedDeltaX","modifiedDeltaY","temp","animate","duration","animationDuration","onComplete","cleanAngle","_adjustFocalPointByAngle","_resetFocalPointPosition","axis","editorCenter","setValue","properties","scaleY","scaleX","previousAngle","_adjustEditorElementsOnStraighten","newCenterX","newCenterY","angleDelta","currentZoomRatio","adjustmentRatio","cropperCenterX","cropperCenterY","imageVertices","getImageVerticeCoords","rectangle","_getZoomRatioToFitRectangle","_isCenterInside","opacity","object","containingObject","newFocalX","newFocalY","adjustedFocalX","adjustedFocalY","containingVertices","vertex","rectangleVertices","_getRectangleVertices","verticeIndex","arePointsInsideRectangle","edge","_getEdgeCrossed","rectangleCenter","distanceFromVertexToEdge","abs","sqrt","pow","distanceFromCenterToEdge","$button","hasClass","append","postData","imageRotation","replace","cropData","zoom","end","error","runQueue","scaledWidth","scaledHeight","boundingBox","_getImageBoundingBox","scale","vertScale","horiScale","getCombinedZoomRatio","strokeOptions","gridWidth","gridHeight","xStep","yStep","Line","onFadeOut","destroy","removeAllListeners","_editorModeTransition","cropperData","_showCropper","_hideCropper","targetZoom","inverseZoomFactor","imageOffsetX","imageOffsetY","callback","context","document","getElementById","getContext","start","cW","cH","setInterval","rotation","save","clearRect","translate","rotate","beginPath","moveTo","lineTo","lineWidth","strokeStyle","restore","clearInterval","clipperData","_setupCropperLayer","_redrawCropperElements","backgroundColor","hoverCursor","selection","position","rectangleRatio","rectWidth","rectHeight","lineOptions","gridOptions","pathGroup","Path","cropTextTop","cropTextBackgroundColor","previousImageArea","currentOffset","areaFactor","coordinateSet","a","b","c","d","_isMouseOver","move","handle","_cropperHandleHitTest","pageX","pageY","_handleMouseMoveInternal","_handleFocalDrag","_handleCropperDrag","_handleCropperResize","_setMouseCursor","vertices","dxi","dyi","furthest","furthestDeltas","newX","newY","previousHeight","previousWidth","startingRectangle","_calculateNewCropperSizeByDeltas","cropperDirection","topDelta","leftDelta","change","match","isMobileBrowser","cursor","parentOffset","offset","mouseX","mouseY","lb","rb","tb","bb","topLeft","topRight","bottomRight","bottomLeft","zoomMode","topVerticalSegment","bottomVerticalSegment","rightHorizontalSegment","leftHorizontalSegment","verticalOffset","horizontalOffset","_debug","fabricObj","points","ab","_getVector","bc","scalarAbAb","_getScalarProduct","scalarBcBc","point","ap","bp","scalarAbAp","scalarBcBp","projectsOnAB","projectsOnBC","_getVectorMagnitude","vector","_getAngleBetweenVectors","acos","edgePoints","centerPoint","smallestDiff","edgeCrossed","edgeIndex","toCenter","edgeVector","toVertex","diff","box","proportion","AssetIndex","BaseElementIndex","$includeSubfoldersContainer","$includeSubfoldersCheckbox","showingIncludeSubfoldersCheckbox","$uploadButton","$uploadInput","$progressBar","$folders","uploader","promptHandler","progressBar","_uploadTotalFiles","_uploadFileProgress","_currentUploaderSettings","_assetDrag","_folderDrag","_expandDropTargetFolderTimeout","_tempExpandedFolders","_fileConflictTemplate","choices","title","_folderConflictTemplate","elementType","_initIndexPageMode","$win","$main","modal","_positionProgressBar","initSources","initSource","$source","_createFolderContextMenu","_getSourceLevel","updateDropTargets","deinitSource","contextMenu","parentsUntil","selectable","multiSelect","DragDrop","activeDropTargetClass","helperOpacity","getSelectedElements","has","helper","$file","_getFileDragHelper","dropTargets","$draggee","targets","$sources","eq","hasAttr","onDragStart","_onDragStart","onDropTargetChange","_onDropTargetChange","onDragStop","_onFileDragStop","helperBaseZindex","$draggeeHelper","$helperSidebar","$helperNav","$helperUl","draggedSourceIds","each","key","_getFolderUidFromSourceKey","inArray","_onFolderDragStop","$activeDropTarget","originatingSource","targetFolderId","originalAssetIds","originalAssetId","getElementInfo","setIndexBusy","resetProgressBar","setItemCount","showProgressBar","parameterArray","action","params","folderId","_performBatchRequests","onMoveFinish","responseArray","resetPrompts","conflict","addPrompt","suggestedFilename","prompt","message","setIndexAvailable","hideProgressBar","performAfterMoveActions","sourceSelect","selectItem","_totalVisible","deselectAllElements","_collapseExtraExpandedFolders","getPromptCount","fadeOutHelpers","showBatchPrompts","returnData","newParameterArray","choice","filename","force","apply","returnHelpersToDraggees","folderIds","sort","parentId","requestId","fileMoveList","newSourceKey","transferList","newFolderId","newFolderUid","merge","_performActualFolderMove","folderDeleteList","moveCallback","counter","limit","setInstanceState","refreshSources","_getRootSource","$parent","_getParentSource","_selectSourceByFolderId","$targetSource","_getSourceByKey","$parentSources","parents","$parentSource","selectSource","afterInit","style","addButton","insertBefore","PromptHandler","ProgressBar","options","url","fileInput","dropZone","events","fileuploadstart","_onUploadStart","fileuploadprogressall","_onUploadProgress","fileuploaddone","_onUploadComplete","fileuploadfail","_onUploadFailure","criteria","kind","allowedKinds","Uploader","isIndexBusy","getDefaultSourceKey","defaultSource","defaultSourceParts","volumeSource","toArray","s","subfolderSource","_getChildSources","_expandSource","onSelectSource","sourceKey","setParams","_updateUrl","history","nestedSources","$thisSource","unshift","uri","forEach","$s","replaceState","getUrl","m","startSearching","hideSidebar","floor","random","insertAfter","$search","$subContainer","setSelecetedSourceState","prop","velocity","checked","getSelectedSourceState","marginBottom","stopSearching","getViewParams","includeSubfolders","progress","loaded","total","setProgressPercentage","result","files","doReload","selectElementAfterUpdate","file","isLastUpload","_uploadFollowup","_updateAfterUpload","jqXHR","responseJSON","clearSearch","setSortAttribute","setSortDirection","doFollowup","parameterIndex","followupCallback","incrementProcessedItemCount","updateProgressBar","sourceAssetId","conflictingAssetId","targetFilename","onUpdateElements","_onUpdateElements","getAllElements","newElements","$newElements","removeAllItems","$elements","_onKeyDown","elementSelect","_onElementFocus","SPACE_KEY","shiftKey","openInstance","selfDestruct","$focusedItem","_loadPreview","stopPropagation","item","$outerContainer","$innerContainer","_$firstRowCells","$helperCells","$helperCell","$firstRowCell","$dropTarget","clearTimeout","dropTargetFolder","_hasSubfolders","_isExpanded","_expandFolder","dropTargetFolderId","$excludedSources","_collapseFolder","splice","menuOptions","label","onClick","_createSubfolder","_renameFolder","_deleteFolder","ContextMenu","menuClass","$parentFolder","subfolderName","folderName","_prepareParentForChildren","$subfolder","folderUid","$a","_appendSubfolder","$targetFolder","folder","trim","_cleanUpTree","$label","oldName","newName","sendActionRequest","then","initSourceToggle","$existingChildren","subfolderLabel","folderInserted","$existingChild","before","deinitSourceToggle","scrollTop","windowHeight","finalCallback","activeRequests","parameters","shift","registerElementIndexClass","AssetSelectInput","BaseElementSelectInput","hud","$uploadBtn","arguments","canUpload","_attachUploader","$elementsContainer","createElementEditor","defaultFieldLayoutId","formData","fieldId","sourceElementId","elementId","siteId","$addElementBtn","describedBy","multiple","csrfTokenName","csrfTokenValue","canAddMoreFiles","next","viewMode","$existing","replaceWith","thumbLoader","selectUploadedFile","canAddMoreElements","$newElement","prepend","margin","outerWidth","animateCss","addElements","outerHeight","appendHeadHtml","headHtml","draftEditor","checkForm","slotsTaken","AssetSelectorModal","BaseElementSelectorModal","$selectTransformBtn","_selectedTransform","transforms","createSelectTransformButton","$btnGroup","$primaryButtons","$selectBtn","$menu","$menuList","MenuButton","MenuBtn","onOptionSelect","onSelectTransform","disable","onSelectionChange","$selectedElements","allowTransforms","enable","option","transform","selectImagesWithTransform","transformUrls","imageIdsWithMissingUrls","$item","showFooterSpinner","fetchMissingTransformUrls","hideFooterSpinner","selectElements","info","onSelect","elementInfo","canSelectImageTransforms","registerElementSelectorModalClass","AuthManager","remainingSessionTime","checkRemainingSessionTimer","showLoginModalTimer","decrementLogoutWarningInterval","showingLogoutWarningModal","showingLoginModal","logoutWarningModal","loginModal","$logoutWarningPara","$passwordInput","$passwordSpinner","$loginBtn","$loginErrorPara","submitLoginIfLoggedOut","updateRemainingSessionTime","setCheckRemainingSessionTimer","seconds","checkRemainingSessionTime","extendSession","ajax","dataType","complete","timeout","minSafeSessionTime","showLogoutWarningModal","checkInterval","showLoginModal","submitLogin","hideLogoutWarningModal","hideLoginModal","quickShow","$form","$logoutBtn","$renewSessionBtn","prependTo","autoShow","closeOtherModals","hideOnEsc","hideOnShadeClick","shadeClass","onFadeIn","updateLogoutWarningMessage","decrementLogoutWarning","time","secondsToHumanTimeDuration","quick","quickHide","$inputContainer","$inputsFlexContainer","$passwordContainer","$buttonContainer","$passwordWrapper","PasswordInput","onToggleInput","$newPasswordInput","logout","redirectTo","renewSession","validatePassword","login","clearLoginError","loginName","username","password","showLoginError","shake","deltaNames","initialData","$header","$toolbar","$tabContainer","$editLink","$sidebarBtn","$loadSpinner","$fieldsContainer","$siteSelectContainer","$siteSelect","$siteSpinner","$saveSpinner","slideout","tabManager","showingSidebar","cancelToken","ignoreFailedRequest","initialDeltaValues","isPlainObject","ltr","showSidebar","trapFocusWithin","$siteSelectOuterContainer","$contents","Slideout","containerElement","containerAttributes","method","novalidate","closeOnEsc","closeOnShadeClick","uiLayerManager","registerShortcut","S_KEY","ctrl","saveElement","ESC_KEY","maybeCloseSlideout","onShowHud","onCreateForm","setElementAttribute","attributes","getBaseData","prevalidate","refreshInitialData","Promise","resolve","reject","showLoadSpinner","onBeginLoading","cancel","axios","CancelToken","source","token","includeSites","isMultiSite","showSiteSwitcher","hideLoadSpinner","onEndLoading","updateForm","e","showHeader","hideHeader","switchSite","isDirty","newSiteId","fieldHtml","sites","siteInfo","$option","tabHtml","Tabs","editUrl","sidebarHtml","initUiElements","ElementThumbLoader","hostname","appendFootHtml","footHtml","serialize","setFocusWithin","_closedSidebarStyles","offsetWidth","_openedSidebarStyles","addLayer","removeLayer","isArray","isFunction","call","param","findDeltaData","$title","cpEditUrl","newTitle","elementTypeNames","closeSlideout","onSaveElement","isOpen","close","onHideHud","loadHud","maybeCloseHud","closeHud","reloadForm","initialized","instanceState","sourceStates","sourceStatesStorageKey","searchTimeout","sourceViewModes","sourcesByKey","$visibleSources","$customizeSourcesBtn","customizeSourcesModal","toolbarOffset","searching","searchText","trashed","drafts","$clearSearchBtn","$statusMenuBtn","$statusMenuContainer","statusMenu","status","$siteMenuBtn","siteMenu","$sortMenuBtn","sortMenu","$sortAttributesList","$sortDirectionsList","$scoreSortAttribute","$structureSortAttribute","$viewModeBtnContainer","viewModeBtns","_autoSelectElements","$countSpinner","$countContainer","page","resultSet","totalResults","$exportBtn","actions","actionsHeadHtml","actionsFootHtml","$selectAllContainer","$selectAllCheckbox","showingActionTriggers","exporters","exportersByType","_$detachedToolbarItems","_$triggers","_ignoreFailedRequest","_cancelToken","getDefaultInstanceState","storageKey","getLocalStorage","toolbarSelector","menubtn","menu","_handleStatusChange","$options","_setSite","_handleSiteChange","defaultSiteId","getSiteId","$storedSiteOption","updateElementsIfSearchTextChanged","RETURN_KEY","_handleSortChange","selectDefaultSource","setPage","pageNum","onAfterInit","_createCancelToken","_cancelRequests","getSourceContainer","getSite","_getSourcesInList","Select","multi","allowEmpty","vertical","_handleSourceSelectionChange","getSourceByKey","index","refreshSourcesAction","expandedSources","indexOf","$toggle","_getSourceToggle","removeData","selectedSource","paths","path","getDefaultExpandedSources","addOptions","_updateStructureSortOption","detach","storeInstanceState","setLocalStorage","getSourceState","defaultValue","viewState","storeSortAttributeAndDirection","getSelectedSortAttribute","lastAttr","oldHistory","includes","order","getSelectedSortDirection","orderHistory","location","href","RegExp","pageTrigger","_resetCount","search","batchSize","canHaveDrafts","savedDraftsOnly","draftOf","disabledElementIds","paginated","_isViewPaginated","collapsedElementIds","preservePagination","updateElementsAction","$scrollContainer","_updateView","showActionTriggers","_createTriggers","submitAction","actionParams","selectedElementIds","getSelectedElementIds","_findAction","viewParams","expandPostArray","elementAction","elementIds","download","downloadFromUrl","submitActionsAction","badgeCounts","_updateBadgeCounts","afterAction","actionClass","onAfterAction","hideActionTriggers","updateActionTriggers","totalSelected","getEnabledElements","setStatus","selectOption","getSortAttributeOption","attribute","getSortDirectionOption","dir","getSelectedViewMode","updateSidebarMenuLabel","sortOptions","setStoredSortOptionsForSource","$firstOption","getViewModesForSource","sourceViewMode","$viewModeBtn","className","mode","icon","selectViewMode","doesSourceHaveViewMode","selectSourceByKey","sortAttr","sortDir","getDefaultSort","viewModes","createView","getViewClass","TableElementIndexView","ThumbsElementIndexView","rememberDisabledElementId","forgetDisabledElementId","enableElements","onEnableElements","disableElements","onDisableElements","enableElementsById","makeArray","disableElementsById","getButtonContainer","isShowingSidebar","buttonContainer","createCustomizeSourcesModal","CustomizeSourcesModal","onHide","onSelectSite","elements","$selectedItems","_handleActionTriggerSubmit","getPostData","_handleMenuActionTriggerSubmit","selectedOption","$firstVisibleSource","firstSite","selectNewSource","toString","$heading","$headings","nextUntil","setSiteId","is","_handleSelectionChange","_handleSourceDblClick","_toggleSource","_handleSourceToggleClick","prev","$list","_collapseSource","$childSources","not","_countResults","itemLabel","itemsLabel","last","countLabel","items","$paginationContainer","totalPages","ceil","$prevBtn","$nextBtn","role","tabindex","selectAllElements","checkboxMode","selectElementById","hasOwnProperty","$badge","countElementsAction","count","$btn","triggers","safeMenuActions","destructiveMenuActions","formatInputId","destructive","$menuTrigger","$safeList","_createMenuTriggerList","$destructiveList","$div","_showExportHud","typeOptions","$typeField","ui","createSelectField","$formatField","$typeSelect","formattable","$limitField","createTextField","placeholder","$spinner","HUD","submitting","format","$ul","BaseElementIndexView","$loadingMoreSpinner","$elementContainer","$scroller","loadingMore","_morePending","_handleEnableElements","_handleDisableElements","container","getElementContainer","setTotalVisible","setMorePending","isVerticalList","_handleElementEditing","isTouchCapable","maybeLoadMore","selectElement","selectAll","deselectAll","getTotalVisible","totalVisible","getMorePending","morePending","canLoadMore","loadMore","loadMoreElementsAction","getLoadMoreParams","appendElements","onAppendElements","elementSort","elementEditor","fieldLabel","$addElementBtnContainer","_initialized","normalizedSettings","args","modalStorageKey","getContainer","getFieldLabel","getElementsContainer","getAddElementsBtn","initElementSelect","initElementSort","resetElements","getElements","DragSort","$targetItem","getSelectedItems","ignoreHandleSelector","getElementSortAxis","collapseDraggees","magnetStrength","helperLagBase","resetItemOrder","updateAddElementsBtn","enableAddElementsBtn","disableAddElementsBtn","focusNextLogicalElement","focus","focusLastRemoveBtn","$removeBtns","removeElements","editable","_handleShowElementEditor","removeElement","$nextDeleteBtn","lastElementIndex","onRemoveElements","animateElementAway","right","pause","REMOVE_FX_DURATION","resume","showModal","createModal","createElementSelectorModal","getModalSettings","sources","showSiteMenu","getDisabledElementIds","onModalSelect","onModalHide","triggerElement","modalTitle","modalSettings","allowSelfRelations","slotsLeft","slice","updateDisabledElementsInModal","createNewElement","appendElement","animateElementIntoPlace","onSelectElements","clone","removeText","setElementSize","single","$modalElement","$inputElement","origOffset","destOffset","$helper","zIndex","ADD_FX_DURATION","editorSettings","$sourceToggles","$secondaryButtons","$footerSpinner","$headingId","fullscreen","minGutter","_createElementIndex","updateSelectBtnState","enableSelectBtn","disableSelectBtn","enableCancelBtn","disableCancelBtn","clearMouseUpTimeout","disableElementsOnSelect","hideOnSelect","bodyAction","createElementIndex","Object","assign","indexSettings","touchData","firstTap","secondTap","resizable","onCancel","BaseInputGenerator","listening","startListening","setNewSource","stopListening","onSourceTextChange","updateTarget","onTargetTextChange","activeElement","onFormSubmit","sourceVal","targetVal","generateTargetValue","dispatchEvent","InputEvent","inputType","Event","selectFullValue","CP","authManager","$nav","$navToggle","$globalSidebar","$globalContainer","$mainContainer","$alerts","$crumbs","$breadcrumbList","$breadcrumbItems","$notificationContainer","$primaryForm","$headerContainer","$mainContent","$details","$sidebarContainer","$contentContainer","$edition","$confirmUnloadForms","$deltaForms","$collapsibleTables","isMobile","fixedHeader","breadcrumbListWidth","breadcrumbDisclosureItem","enableQueue","totalJobs","jobInfo","displayedJobInfo","displayedJobInfoUnchanged","trackJobProgressTimeout","jobProgressIcon","checkingForUpdates","forcingRefreshOnUpdatesCheck","includingDetailsOnUpdatesCheck","checkForUpdatesCallbacks","resizeTimeout","$allInstructions","$instructions","updateFixedHeader","ready","handleWindowResize","setSidebarNavAttributes","$errorNotifications","$otherNotifications","delay","notificationDuration","initSpecialForms","initAlerts","shortcuts","redirect","retainScroll","shortcut","submitPrimaryForm","initTabs","scrollY","removeLocalStorage","scrollTo","_handleInputFocus","_handleInputBlur","announcements","hasUnreads","some","unread","contents","group","timestamp","heading","body","onShow","map","serialized","$forms","createForm","submit","confirmUnload","livePreview","inPreviewMode","originalEvent","returnValue","saveShortcut","submitForm","toggleNav","isExpanded","navIsExpanded","disableGlobalSidebarLinks","enableGlobalSidebarLinks","focusableItems","isAlwaysVisible","getComputedStyle","getPropertyValue","toggleSidebar","toggleClass","charAt","menuBtn","undefined","LOCATION_HASH","selectTab","$tabsContainer","$tabsList","$selectedTab","selectedTabIndex","$focusableTab","tab","deselectTab","updateResponsiveTables","handleBreadcrumbVisibility","breadcrumbItemsWrap","orientation","listWidth","getBoundingClientRect","totalItemWidth","finalIndex","visibleItemWidth","shownItems","hiddenItems","disclosureMenu","_i","_$table","_containerWidth","_check","_isCollapsed","headerHeight","displayNotification","$notification","fadedMargin","display","notificationType","fetchAlerts","queueActionRequest","displayAlerts","alerts","$shunnableAlerts","$link","substr","checkForUpdates","forceRefresh","includeDetails","realCallback","_checkForUpdates","updateUtilitiesBadge","callbacks","updateInfo","_getUpdates","_checkForCachedUpdates","cached","onlyIfCached","sendApiRequest","updates","_cacheUpdates","contentType","$utilitiesLink","badgeCount","runQueueAutomatically","trackJobProgress","_trackJobProgressInternal","setJobInfo","jobs","oldInfo","getDisplayedJobInfo","progressLabel","updateJobIcon","statuses","JOB_STATUS_RESERVED","JOB_STATUS_FAILED","JOB_STATUS_WAITING","j","JobProgressIcon","hideFailMode","setDescription","description","setProgress","showFailMode","getCookie","setCookie","maxAge","JOB_STATUS_DONE","$li","$progressLabel","failMode","_$bgCanvas","_$staticCanvas","_$hoverCanvas","_$failCanvas","_staticCtx","_hoverCtx","_canvasSize","_arcPos","_arcRadius","_lineWidth","_arcStartPos","_arcEndPos","_arcStartStepSize","_arcEndStepSize","_arcStep","_arcStepTimeout","_arcAnimateCallback","_progressBar","canAccessQueueManager","$canvasContainer","$labelContainer","_createCanvas","_drawArc","_animateArc","_setArc","color","$canvas","ctx","lineCap","startPos","endPos","arc","closePath","targetStartPos","targetEndPos","_takeNextArcStep","CategoryIndex","editableGroups","$newCategoryBtnGroup","$newCategoryBtn","updateButton","editableCategoryGroups","uid","defaultGroupHandle","selectedSourceHandle","selectedGroup","$menuBtn","_getGroupTriggerHref","_openCreateCategoryModal","getAttribute","menuHtml","site","groupId","newCategoryBtnText","hudTrigger","groupSourceKey","CategorySelectInput","selectedCategoryIds","categoryIds","branchLimit","selectionLabel","$newElementsContainer","filteredElements","$allCategories","_animateCategoryAway","func","charts","DataTable","columns","rows","cellIndex","parseTime","d3","timeParse","Tip","$tip","setContent","setPosition","BaseChart","$chart","chartBaseClass","dataTable","formatLocale","timeFormatLocale","svg","globalSettings","formats","d3Formats","formatLocaleDefinition","d3FormatLocaleDefinition","timeFormatLocaleDefinition","d3TimeFormatLocaleDefinition","select","resize","baseSettings","draw","chartClass","onAfterDrawTicks","tickKey","tick","$tickText","numberFormat","percentFormat","currencyFormat","shortDateFormats","day","month","year","bottom","colors","Area","tip","drawingArea","getChartMargin","translateX","translateY","drawTicks","drawAxes","drawChart","drawTipTriggers","getX","xAxis","axisBottom","tickFormat","getXFormatter","ticks","yAxis","getY","axisLeft","getYFormatter","tickValues","getYTickValues","axisRight","showAxis","tickSizeOuter","gridlines","xLineAxis","tickSize","yLineAxis","line","datum","area","y0","y1","plots","enter","tips","chartMargin","xAxisTickInterval","node","getTotalLength","tipTriggerWidth","$content","$xValue","$yValue","content","values","yTicksMaxWidth","computedTickWidth","formatter","padded","xDomainMin","xDomainMax","xDomain","scaleTime","range","domain","yDomain","getYMaxValue","scaleLinear","utils","getTimeFormatter","getNumberFormatter","maxValue","getDuration","secondsNum","hours","minutes","chartSettings","dataScale","ColorInput","$input","$colorContainer","$colorPreview","$colorInput","createColorInput","handleTextChange","createElement","setAttribute","updateColor","repeat","_browserSupportsColorInputs","doesBrowserSupportColorInputs","rxhtmlTag","jQuery","htmlPrefilter","navHeight","arr","reduce","obj","grouped","thisKey","category","translations","formatMessage","pattern","tokens","_tokenizePattern","_parseToken","pos","depth","chars","open","arg","number","formatNumber","selector","plural","selectorChars","substring","p","formatDate","date","datepicker","datepickerOptions","dateFormat","shortcutText","alt","clientOs","str","escapeRegex","getText","encodeUriComponent","encodeURIComponent","differences","chr","re","setSelectionRange","inputName","baseUrl","anchor","aParams","apos","qpos","pathParam","pathMatch","omitScriptNameInUrls","usePathInfo","scriptName","basePath","endPath","getCpUrl","baseCpUrl","getSiteUrl","baseSiteUrl","actionUrl","getCsrfInput","headers","_actionHeaders","errorThrown","readyState","send","_waitingOnAjax","_ajaxQueue","_postNextActionRequestInQueue","keys","registeredAssetBundles","registeredJsFiles","v","getTime","request","_getApiHeaders","apiHeaders","baseURL","baseApiUrl","apiParams","_apiHeaders","processCraftHeaders","httpProxy","proxy","apiResponse","_processApiHeaders","_loadingApiHeaders","_apiHeaderWaitlist","_rejectApiRequests","clearCachedApiHeaders","XMLHttpRequest","setRequestHeader","responseType","onload","disposition","getResponseHeader","matches","exec","blob","Blob","link","URL","createObjectURL","appendChild","removeChild","stringToArray","oldData","newData","groupedOldParams","_groupParamsByDeltaNames","groupedNewParams","__root__","n","modifiedDeltaNames","concat","withRoot","initialValues","encodeURIComponentExceptEqualChar","o","decodeURIComponent","paramLoop","paramName","serializeParam","subName","expanded","parentElem","chunks","compare","obj1","obj2","sortObjectKeys","Array","getObjectKeys","escapeChars","escaped","ltrim","startsWith","filterArray","filtered","elem","removeFromArray","getLast","uppercaseFirst","toUpperCase","lowercaseFirst","toLowerCase","parseUrl","scheme","host","port","query","hash","isSameHost","requestUrlInfo","urlInfo","showSeconds","secondsInWeek","weeks","days","timeComponents","asciiString","charMap","normalize","char","asciiStr","asciiCharMap","randomString","createErrorList","errors","$existingCss","existingCss","regexp","$existingJs","src","existingJs","infoicon","checkboxselect","fieldtoggle","lightswitch","nicetext","formsubmit","datetime","datetimeinput","_elementIndexClasses","_elementSelectorModalClasses","_elementEditorClasses","systemUid","localStorage","parse","removeItem","cookie","defaultCookieOptions","expires","toUTCString","secure","removeCookie","hasThumb","otherSize","$oldImg","$newImg","sizes","srcset","picturefill","fn","animateLeft","easing","animateRight","$elem","removeAttr","itemSelector","cols","maxCols","minColWidth","fillMode","colClass","snapToGrid","Grid","InfoIcon","CheckboxSelect","FieldToggle","settingName","settingValue","thisSettings","indeterminateValue","LightSwitch","NiceText","$anchor","customTrigger","menuAnchor","$trigger","DisclosureMenu","$wrapper","$inputs","checkValue","hasValue","charsLeftHtml","charsLeft","$elementIndexSourcesContainer","$sourcesContainer","$sourceSettingsContainer","$newHeadingBtn","$footerBtnContainer","$loadingSpinner","sourceSort","updateSourcesOnSave","availableTableAttributes","setContainer","buildModal","addSource","sourceData","$itemLabel","$itemInput","Heading","updateItemLabel","Source","handleNewHeadingBtnClick","scrollContainerToElement","$pendingHeading","$lastSource","$indexSource","getIndexSource","isHeading","appendSource","$extraSources","nextAll","BaseSource","$settingsContainer","isSelected","deselect","createSettings","$settings","headerColHeading","defaultHeaderColHeading","tableAttributes","createTableColumnsField","firstKey","firstLabel","$titleColumnCheckbox","createTableColumnOption","$columnCheckboxes","selectedAttributes","createField","instructions","createCheckbox","disabled","$labelField","$labelInput","handleLabelInputChange","deleteHeading","table","$rows","getHelper","caboose","Y_AXIS","$helperRow","helperClass","$cells","DeleteUserModal","userId","$deleteActionRadios","$deleteSpinner","userSelect","_deleting","idParam","contentSummary","$deleteSubmitBtn","_submitBtnLabel","validateDeleteInputs","withContent","num","validates","handleSubmit","onSubmit","DraftEditor","$revisionBtn","$revisionLabel","$expandSiteStatusesBtn","$statusIcon","$editMetaBtn","metaHud","$nameTextInput","$saveMetaBtn","$siteStatusPane","$globalLightswitch","$siteLightswitches","$addlSiteField","siteIds","newSiteIds","enableAutosave","lastSerializedValue","listeningForChanges","pauseLevel","saving","queue","submittingForm","duplicatedElements","httpStatus","httpError","openingPreview","preview","activatingPreviewToken","activatedPreviewToken","previewTokenQueue","previewLinks","createdProvisionalDraft","autosaveDrafts","siteStatuses","$statusMessage","canEditMultipleSites","previewTargets","enablePreview","$previewBtnContainer","createPreviewLink","createShareMenu","revisionId","serializeForm","isProvisionalDraft","initForProvisionalDraft","draftId","isUnpublishedDraft","initForDraft","canUpdateSource","createDraft","listenForChanges","showStatusHud","BroadcastChannel","onmessage","canonicalId","sourceId","reload","saveDraftAction","statusIcons","stopListeningForChanges","deleteDraftAction","hashedCpEditUrl","provisional","createEditMetaBtn","publishDraftAction","expandSiteStatuses","$enabledForSiteField","_getOtherSupportedSites","_createSiteStatusField","$globalField","createLightswitchField","_showField","siteStatusValues","hasEnabled","hasDisabled","originalEnabledValue","originalSerializedStatus","enabledForSite","_updateGlobalStatus","serializedStatuses","addlSites","_createAddlSiteField","_updateSiteStatuses","$field","overflow","_removeField","allEnabled","allDisabled","turnOn","turnOff","turnIndeterminate","enabled","$lightswitch","$addlSiteSelectContainer","createSelect","$addlSiteSelect","addlSiteInfo","enabledByDefault","bodyHtml","_saveSuccessMessage","_saveFailMessage","hudClass","spinners","statusMessage","getTokenizedPreviewUrl","targetUrl","targetLabel","activatePreviewToken","updatePreviewLinks","updatePreviewLinkHref","isLive","getPreviewTokenParams","previewToken","getPreviewToken","randoParam","asPromise","siteToken","previewUrl","tokenParam","createTokenParams","getPreview","Preview","$statusIcons","openPreview","ensureIsDraftOrRevision","onlyIfChanged","removeActionParams","isPreviewActive","$editor","saveDraft","console","warn","isActive","empty","modifiedFieldNames","preparedData","prepareData","deltaName","_afterSaveRequest","_showFailStatus","docTitle","draftName","revisionMenu","oldId","siteSettings","creator","updatePreviewTargets","checkMetaValues","selectors","modifiedAttributes","$fields","afterUpdate","postMessage","setStatusMessage","deltaCallback","swapDuplicatedElementIds","idsRE","pre","post","newTarget","$previewLink","nextInQueue","showMetaHud","createMetaHud","onMetaHudShow","$hudBody","$nameField","$nameInputContainer","saveMeta","onMetaHudHide","onMetaHudEscape","shakeMetaHud","$hud","handleFormSubmit","autosave","hashedAddAnotherRedirectUrl","DynamicGenerator","EditableTable","baseName","biggestId","$addRowBtn","$tableParent","rowCount","hasMaxRows","hasMinRows","radioCheckboxes","copyDraggeeInputValuesToHelper","updateAllRows","isVisible","initialize","initializeIfVisible","minRows","createRowObj","updateAddRowButton","canAddRow","staticRows","updateRow","canDeleteRow","updateDeleteRowButton","rowId","updateStatusMessage","deleteRow","$tr","onDeleteRow","maxRows","rowIdPrefix","createRow","defaultValues","onAddRow","Row","focusOnPrevRow","tdIndex","blurTd","prevRow","$prevTr","$tds","focusOnNextRow","nextRow","$nextTr","importData","lines","textualColTypes","colId","$cell","col","scope","code","small","createDateInput","createLightswitch","createTimeInput","createTextInput","niceTexts","tds","$textareas","tr","td","$textarea","$checkbox","textareasByColId","onHeightChange","onTextareaHeightChange","radioMode","toggle","applyToggleCheckbox","autopopulate","HandleGenerator","allowNonAlphaStart","onTextareaFocus","onRadioCheckboxChange","checkbox","checkboxColId","neg","checkboxCol","colum","ignoreNextTextareaFocus","handleKeypress","charCode","isCtrlKeyPressed","numericKeyCodes","handlePaste","clipboardData","getData","validateValue","safeValue","tallestTextareaHeight","tdHeight","ElementActionTrigger","maxLevels","newChildUrl","triggerEnabled","activate","updateTrigger","validateSelection","enableTrigger","disableTrigger","valid","batch","handleTriggerActivation","workers","Worker","$thumbs","$thumb","$scrollParent","scrollParent","addToQueue","invisibleThumbs","thumb","active","loadNext","scrollParentOffset","scrollParentHeight","thumbOffset","retryAll","loader","$img","ElevatedSessionForm","inputs","form","getInputPostVal","elevatedSessionManager","fetchingTimeout","stopImmediatePropagation","inputsChanged","$currentInput","requireElevatedSession","ElevatedSessionManager","passwordModal","$submitBtn","$errorPara","minSafeElevatedSessionTimeout","showPasswordModal","$passwordModal","focusPasswordInput","submitPassword","currentPassword","showPasswordError","EntryIndex","publishableSections","$newEntryBtnGroup","$newEntryBtn","section","defaultSectionHandle","selectedSection","_getSectionTriggerHref","_openCreateEntryModal","sectionId","newEntryBtnText","typeId","entryTypes","canPublish","sectionSourceKey","FieldLayoutDesigner","$newTabBtn","$libraryToggle","$selectedLibrary","$fieldLibrary","$uiLibrary","$uiLibraryElements","$fieldSearch","$clearFieldSearchBtn","$fieldGroups","tabGrid","elementDrag","$workspace","$fieldSearchContainer","initTab","elementPlacementInputName","ElementDrag","customizableTabs","tabDrag","TabDrag","customizableUi","$libraryPicker","Listbox","$selectedOption","$matches","$group","$editBtn","onTabOptionSelect","initElement","Element","renameTab","removeTab","$prev","$next","$labelSpan","promptForTabName","getElementPlacementInputName","removeFieldByHandle","removeField","refreshCols","addTab","tabName","elementConfigInputName","designer","$placementInput","$configInput","config","isField","requirable","hasCustomWidth","hasSettings","settingsHtml","isRequired","createSettingsHud","initUi","updatePlacementInput","updateConfigInput","SlidePicker","step","valueLabel","pct","applyHudSettings","serializeArray","updateRequiredClass","required","BaseDrag","Drag","$insertion","showingInsertion","$caboose","findItems","createInsertion","createCaboose","removeCaboose","swapDraggeeWithInsertion","swapInsertionWithDraggee","setMidpoints","getClosestItem","_closestItem","_closestItemMouseDiff","_$item","_midpoint","_mouseDiff","getDist","checkForNewClosestItem","draggeeDisplay","visibility","FX_DURATION","helpers","_showDraggee","onDrag","draggingLibraryElement","draggingField","isDraggeeMandatory","isHoveringOverTab","hitTest","$fieldContainers","$libraryElement","targetPrefix","targetSelector","reverseTargetSelector","_$target","_$reverseTarget","getType","normalizeTargetSelector","findTargets","onToggleChange","nodeName","getToggleVal","boolean","postVal","hideTarget","showTarget","_show","_currentHeight","$t","_targetHeight","totalCols","colGutterDrop","colPctWidth","possibleItemColspans","possibleItemPositionsByColspan","itemPositions","itemColspansByPosition","layouts","layout","itemHeights","leftPadding","_refreshingCols","_refreshColsAfterRefresh","_forceRefreshColsAfterRefresh","handleContainerHeightProxy","setItems","oldHeight","scrollHeight","gutter","itemIndex","tallestItemHeight","colIndex","itemHeight","remainder","itemHeightsByColspan","positionRight","positionLeft","minColspan","maxColspan","colspan","getItemWidthCss","minPosition","maxPosition","colHeights","createLayouts","layoutTotalCols","highestTotalCols","layoutHeights","shortestHeight","shortestLayouts","emptySpaces","emptySpace","colspans","getItemLeftPosCss","positions","isSimpleLayout","positionItems","completeRefreshCols","onRefreshCols","getItemWidth","getItemWidthInPx","getItemLeftPosInPx","prevPositions","prevColspans","prevColHeights","prevEmptySpace","LayoutGenerator","endingCol","affectedColHeights","onItemResize","newHeight","tallestColHeightsByPosition","colHeightsForPosition","tallestColHeight","words","handleCasing","ImageUpload","initImageUpload","containerSelector","uploadAction","postParameters","fileInputSelector","uploadParamName","initButtons","uploadButtonSelector","deleteButtonSelector","refreshImage","onAfterRefreshImage","$icon","previousSibling","nodeType","Node","TEXT_NODE","nodeValue","showHud","showing","closeOtherHUDs","indeterminate","dragger","dragStartMargin","outerContainer","X_AXIS","_onDrag","_onDragStop","muteEvent","changed","prefersReducedMotion","_onSettle","_getOffMargin","_onMouseDown","_onMouseUp","dragging","RIGHT_KEY","LEFT_KEY","_getMargin","mouseDistX","log","selectedOptionIndex","UP_KEY","selectPrev","DOWN_KEY","selectNext","selectedClass","focusClass","LivePreview","$extraFields","$dragHandle","$previewContainer","$iframeContainer","$iframe","$fieldPlaceholder","basePostData","fields","lastPostData","updateIframeInterval","loading","checkAgain","dragStartEditorWidth","_slideInOnIframeLoad","_forceUpdateIframeProxy","_scrollX","_scrollY","_editorWidth","_editorWidthInPx","protocol","previewParams","forceUpdateIframe","extraFields","defaultEditorWidth","moveFieldsBack","editorWidthInPx","inPx","minEditorWidthInPx","exit","$editorHeader","$closeBtn","getIframeWidth","$clone","_getClone","updateIframe","slideIn","createToken","previewAction","updateWidths","$newClone","field","contentWindow","scrollLeft","xhrFields","withCredentials","crossDomain","handleSuccess","handleError","write","onResponse","copyInputValues","$textInput","$showPasswordToggle","showingPassword","passwordInput","initInputFocusEvents","hidePassword","setCurrentInput","updateToggleLabel","showPassword","autocapitalize","togglePassword","onKeyDown","ALT_KEY","onKeyUp","onInputChange","$previewHeader","$targetBtn","$targetMenu","$deviceTypeContainer","$orientationBtn","$refreshBtn","$deviceMask","$devicePreviewContainer","iframeLoaded","$tempInput","activeTarget","currentDeviceType","deviceOrientation","deviceWidth","deviceHeight","deviceMaskDimensions","phone","tablet","iframeHeight","_updateIframeProxy","Pro","switchTarget","_buildDeviceTypeFieldset","_updateRefreshBtn","$radioGroup","$desktopWrapper","$desktopLabel","for","$tabletWrapper","$tabletLabel","$mobileWrapper","$mobileLabel","_activeTarget","_autoRefresh","refresh","previewTarget","_devicePreviewIsActive","updateDevicePreview","_useIframeResizer","previewIframeResizerOptions","resetScroll","sameHost","frameborder","iFrameResize","checkOrigin","scrolling","onInit","iframe","switchDeviceType","$inputWrapper","newDeviceType","switchOrientation","hZoom","wZoom","previewHeight","previewWidth","maskHeight","maskWidth","rotationDeg","marginTop","marginLeft","defaultSettings","_onHide","instance","loadAsset","focusItem","desiredHeight","desiredWidth","containerHeight","containerWidth","_resizeContainer","previewHtml","$innerProgressBar","$progressBarStatus","_itemCount","_processedItemCount","_displaySteps","displaySteps","setProcessedItemCount","fadeTo","incrementItemCount","percentage","$modalContainerDiv","$prompt","$promptApplyToRemainingContainer","$promptApplyToRemainingCheckbox","$promptApplyToRemainingLabel","$pomptChoices","_prompts","_promptBatchCallback","_promptBatchReturnData","_promptBatchNum","_showNextPromptInBatch","remainingInBatch","_showPrompt","_handleBatchPromptSelection","applyToRemaining","choiceData","itemsToGo","_promptCallback","$promptMessage","$promptChoices","$promptButtons","$radioButton","_selectPromptChoice","fadeOut","_cancelPrompt","totalSteps","_min","_max","Number","isInteger","prevAll","triggerEvent","$activeButton","startPositionX","graduationsMin","graduationsMax","slideMin","slideMax","$overlay","$cursor","$graduations","$graduationsUl","_handleResize","_handleTapStart","_handleTapMove","_handleTapEnd","graduationsCalculatedWidth","valueToPosition","touch","startLeft","curX","positionToValue","scaleMin","scaleMax","addModalAttributes","autoOpen","setTriggerElement","_cancelTransitionListeners","addPanel","hideModalBackgroundLayers","removePanel","resetModalBackgroundLayerVisibility","openPanels","panel","updateStyles","totalPanels","SlugGenerator","allowUppercaseInSlug","limitAutoSlugsToAscii","XRegExp","matchChain","slugWordSeparator","Structure","structureDrag","$parents","initToggle","StructureDrag","initNewChildMenus","viewStateKey","$addBtns","onNewChildMenuClick","showMenu","getIndent","level","baseIndent","nestedIndent","addElement","$addBtn","$parentUl","_removeUl","structure","draggeeLevel","$helperLi","$targets","draggeeHeight","$level","cancelDrag","$lis","$closestTarget","closestTargetPos","closestTargetYDiff","closestTargetOffset","closestTargetHeight","targetOffset","targetHeight","targetYMidpoint","targetYDiff","$closestTargetLi","closestTargetLevel","$nextTargetLi","nextTargetLevel","hoveringBetweenRows","draggeeX","targetItemMouseDiffX","$parentLis","$closestParentLi","closestParentLiXDiff","closestParentLevel","$parentLi","parentLiX","parentLiXDiff","parentLevel","onMouseUp","$draggeeParent","moved","$closestSiblings","newLevel","setLevel","structureId","prevId","indent","$childLis","StructureTableSorter","tableView","_basePadding","_helperMargin","_$titleHelperCell","_titleHelperCellOuterWidth","_ancestors","_updateAncestorsFrame","_draggeeLevel","_draggeeLevelDelta","draggingLastElements","_loadingDraggeeLevelDelta","_targetLevel","_targetLevelBounds","_positionChanged","singleHelper","helperSpacingY","findDraggee","$nextRow","nextRowLevel","nextRowLevelDelta","_getAjaxBaseData","delta","drag","canInsertBefore","_getLevelBounds","canInsertAfter","_getAncestors","_setTargetLevelBounds","_updateIndent","onInsertionPointChange","_updateAncestorsBeforeRepaint","levelDiff","padding","_getLevelIndent","$prevRow","prevRowLevel","$spinnerRow","_createSpinnerRowAfter","onPositionChange","_expandElement","onReturnHelpersToDraggees","newDraggeeIndexes","oldDraggeeIndexes","$postDraggeeItems","_minLevel","_maxLevel","forcePositionChange","_mouseDist","realMouseX","mousedownX","_indentationDist","LEVEL_INDENT","_targetLevelMouseDiff","_magnetImpact","MAX_GIVE","_closestLevelMagnetIndent","targetLevel","_level","_$prevRow","cancelAnimationFrame","_updateAncestors","_$ancestor","_newAncestors","HELPER_MARGIN","$selectedSortHeader","structureTableSort","_totalVisiblePostStructureTableDraggee","_morePendingPostStructureTableDraggee","initTableHeaders","_collapseElement","selectedSortAttr","$tableHeaders","selectedSortDir","_handleSelectedSortHeaderClick","_handleUnselectedSortHeaderClick","_isStructureTableDraggingLastElements","positionedAfter","includeTableAttributesForSource","_updateTableAttributes","$nextNextRow","descendantOf","$nextRows","newSortDir","_handleSortHeaderClick","makeTabFocusable","$initialTab","contains","scrollToTab","updateMenuBtn","_getTab","elemScrollOffset","targetScrollLeft","tabWidth","ulWidth","HTMLElement","TagSelectInput","searchMenu","$addTagInput","_ignoreBlur","searchForTags","selectTag","$hoverOption","$nextOption","focusOption","$prevOption","killSearchMenu","excludeIds","tagGroupId","tags","exclude","exactMatch","Menu","attachToElement","targetSiteId","$titleContainer","autocomplete","inputmode","maxlength","autofocus","getAutofocusValue","getDisabledValue","readonly","showCharsLeft","createCopyTextInput","buttonId","execCommand","createCopyTextBtn","copyValue","createCopyTextField","createCopyTextPrompt","createTextarea","createTextareaField","$select","optgroup","$optgroup","selected","reverseToggle","createCheckboxField","createCheckboxSelect","allValue","allChecked","showAllOption","allLabel","createCheckboxSelectField","fieldset","labelId","containerId","$colorPreviewContainer","createColorField","getMonth","toISOString","timezone","defaultDate","hasOuterContainer","createDateField","createDateRangePicker","today","getFullYear","getDate","startDate","endDate","$allOption","firstDayOffset","getDay","firstDay","$flex","$startDate","$endDate","$dateInputs","dpDiv","setPositionRelativeToAnchor","startTime","endTime","foundOption","btnClasses","timepicker","timepickerOptions","getHours","getMinutes","getSeconds","createTimeField","warning","$warning","addErrorsToField","addErrorsToList","$errors","clearErrorsFromField","_rejectedFiles","_extensionList","_totalFileCounter","_validFileCounter","autoUpload","fileupload","onFileAdd","paramObject","getInProgress","_createExtensionList","process","done","pass","fileExtension","maxFileSize","originalFiles","processErrorMessages","kinds","humanFileSize","maxUploadSize","bytes","threshold","u","toFixed","allowedKind","fileKinds","extensions","pasteZone","sequentialUploads","Accept","UriFormatGenerator","uriFormat","suffix","UserIndex","updateUrl","defaultSourceSlug","slug","__esModule","default","module","locals","exports","listToStyles","list","styles","newStyles","part","media","sourceMap","hasDocument","DEBUG","Error","stylesInDom","head","getElementsByTagName","singletonElement","singletonCounter","isProduction","ssrIdKey","isOldIE","navigator","test","userAgent","addStylesClient","_isProduction","_options","addStylesToDom","newList","mayRemove","domStyle","refs","addStyle","createStyleElement","styleElement","update","querySelector","parentNode","styleIndex","applyToSingletonTag","applyToTag","newObj","textStore","replaceText","replacement","Boolean","styleSheet","cssText","cssNode","createTextNode","childNodes","ssrId","btoa","unescape","firstChild","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","definition","defineProperty","enumerable","prototype"],"sourceRoot":""}
\ No newline at end of file

programming_language: R
filename: BaseElementSelectInput.js
change_type: ModificationType.MODIFY
diff: @@ -471,7 +471,7 @@ Craft.BaseElementSelectInput = Garnish.Base.extend(
     createNewElement: function (elementInfo) {
       var $element = elementInfo.$element.clone();
       var removeText = Craft.t('app', 'Remove {label}', {
-        label: elementInfo.label,
+        label: Craft.escapeHtml(elementInfo.label),
       });
       // Make a couple tweaks
       Craft.setElementSize(

programming_language: JavaScript