Program: CWE-79
Project: CVE-2021-32470
Buggy source:
!function(t){var i=/<(?!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(i,"<$1></$2>")},t.extend(Craft,{navHeight:48,index:function(e,i){if(!t.isArray(e))throw"The first argument passed to Craft.index() must be an array.";return e.reduce((t,e,s)=>(t["string"==typeof i?e[i]:i(e,s)]=e,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){let i;if(!1===(i=this._tokenizePattern(t)))throw"Message pattern is invalid.";for(let t=0;t<i.length;t++){let s=i[t];if("object"==typeof s&&!1===(i[t]=this._parseToken(s,e)))throw"Message pattern is invalid."}return i.join("")},_tokenizePattern:function(t){let e,i,s=1;const a=[...t];if(-1===(e=i=a.indexOf("{")))return[t];let n=[a.slice(0,i).join("")];for(;;){let t=a.indexOf("{",i+1),r=a.indexOf("}",i+1);if(-1===t&&(t=!1),-1===r&&(r=!1),!1===t&&!1===r)break;if(!1===t&&(t=a.length),r>t?(s++,i=t):(s--,i=r),0===s&&(n.push(a.slice(e+1,i).join("").split(",",3)),e=i+1,n.push(a.slice(e,t).join("")),e=t),0!==s&&(!1===t||!1===r))break}return 0===s&&n},_parseToken:function(t,e){const i=Craft.trim(t[0]);if(void 0===e[i])return`{${t.join(",")}}`;const s=e[i],a=void 0!==t[1]?Craft.trim(t[1]):"none";switch(a){case"number":let i=void 0!==t[2]?Craft.trim(t[2]):null;if(null!==i&&"integer"!==i)throw"Message format 'number' is only supported for integer values.";let n,r=Craft.formatNumber(s);return null===i&&-1!==(n=(""+s).indexOf("."))&&(r+="."+s.substr(n+1)),r;case"none":return s;case"plural":if(void 0===t[2])return!1;let o=this._tokenizePattern(t[2]);const l=o.length;let h=!1,d=0;for(let t=0;t+1<l;t++){if("object"==typeof o[t]||"object"!=typeof o[t+1])return!1;let e=Craft.trim(o[t++]),i=[...e];if(1===t&&"offset:"===e.substring(0,7)){let t=[...e.replace(/[\n\r\t]/g," ")].indexOf(" ",7);if(-1===t)throw"Message pattern is invalid.";parseInt(Craft.trim(i.slice(7,t).join("")));e=Craft.trim(i.slice(t+1,t+1+i.length).join(""))}(!1===h&&"other"===e||"="===e[0]&&parseInt(i.slice(1,1+i.length).join(""))===s||"one"===e&&s-d==1)&&(h=("string"==typeof o[t]?[o[t]]:o[t]).map(t=>t.replace("#",s-d)).join(","))}if(!1!==h)return this.formatMessage(h,e);break;default:throw`Message format '${a}' is not supported.`}return!1},formatDate:function(e){return"object"!=typeof e&&(e=new Date(e)),t.datepicker.formatDate(Craft.datepickerOptions.dateFormat,e)},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(e){return t("<div/>").text(e).html()},escapeRegex:function(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},getText:function(e){return t("<div/>").html(e).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(e){var i=t(e),s=i.val();if(void 0!==i[0].setSelectionRange){var a=2*s.length;i[0].setSelectionRange(0,a)}else i.val(s)},formatInputId:function(t){return this.rtrim(t.replace(/[\[\]\\]+/g,"-"),"-")},getUrl:function(e,i,s){"string"!=typeof e&&(e="");var a="";if(t.isPlainObject(i)){var n=[];for(var r in i)if(i.hasOwnProperty(r)){var o=i[r];"#"===r?a=o:null!==o&&""!==o&&n.push(r+"="+o)}i=n}i=Garnish.isArray(i)?i.join("&"):Craft.trim(i,"&?");var l=e.indexOf("#");-1!==l&&(a||(a=e.substr(l+1)),e=e.substr(0,l));var h,d=e.indexOf("?");if(-1!==d&&(i=e.substr(d+1)+(i?"&"+i:""),e=e.substr(0,d)),-1!==e.search("://")||"/"===e[0])return e+(i?"?"+i:"")+(a?"#"+a:"");if(e=Craft.trim(e,"/"),s){if(h=s,e&&Craft.pathParam){var c=h.match(new RegExp("[&?]"+Craft.escapeRegex(Craft.pathParam)+"=[^&]+"));c&&(h=h.replace(c[0],Craft.rtrim(c[0],"/")+"/"+e),e="")}}else h=Craft.baseUrl;if(-1!==(d=h.indexOf("?"))&&(i=h.substr(d+1)+(i?"&"+i:""),h=h.substr(0,d)),!Craft.omitScriptNameInUrls&&e)if(Craft.usePathInfo||!Craft.pathParam)-1===h.search(Craft.scriptName)&&(h=Craft.rtrim(h,"/")+"/"+Craft.scriptName);else{if(i&&i.substr(0,Craft.pathParam.length+1)===Craft.pathParam+"="){var u,p=i.indexOf("&");-1!==p?(u=i.substring(2,p),i=i.substr(p+1)):(u=i.substr(2),i=null),e=(u=Craft.rtrim(u))+(e?"/"+e:"")}i=Craft.pathParam+"="+e+(i?"&"+i:""),e=null}return e&&(h=Craft.rtrim(h,"/")+"/"+e),i&&(h+="?"+i),a&&(h+="#"+a),h},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(e,i,s,a){"function"==typeof i&&(a=s,s=i,i={}),(a=a||{}).contentType&&a.contentType.match(/\bjson\b/)&&("object"==typeof i&&(i=JSON.stringify(i)),a.contentType="application/json; charset=utf-8");var n=t.ajax(t.extend({url:Craft.getActionUrl(e),type:"POST",dataType:"json",headers:this._actionHeaders(),data:i,success:s,error:function(t,e,i){4===t.readyState&&(void 0!==Craft.cp?Craft.cp.displayError():alert(Craft.t("app","A server error occurred.")),s&&s(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(){let 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(e,i,s){return new Promise((a,n)=>{(s=s?t.extend({},s):{}).method=e,s.url=Craft.getActionUrl(i),s.headers=t.extend({"X-Requested-With":"XMLHttpRequest"},s.headers||{},this._actionHeaders()),s.params=t.extend({},s.params||{},{v:(new Date).getTime()}),axios.request(s).then(a).catch(n)})},sendApiRequest:function(e,i,s){return new Promise((a,n)=>{let r=(s=s?t.extend({},s):{}).cancelToken||null;this._getApiHeaders(r).then(o=>{s.method=e,s.baseURL=Craft.baseApiUrl,s.url=i,s.headers=t.extend(o,s.headers||{}),s.params=t.extend(Craft.apiParams||{},s.params||{},{v:(new Date).getTime()}),this._apiHeaders||(s.params.processCraftHeaders=1),axios.request(s).then(t=>{this._processApiHeaders(t.headers,r).then(()=>{a(t.data)}).catch(n)}).catch(n)}).catch(n)})},_loadingApiHeaders:!1,_apiHeaders:null,_apiHeaderWaitlist:[],_getApiHeaders:function(t){return new Promise((i,s)=>{this._loadingApiHeaders?this._apiHeaderWaitlist.push([i,s]):this._apiHeaders?i(this._apiHeaders):(this._loadingApiHeaders=!0,this.sendActionRequest("POST","app/api-headers",{cancelToken:t}).then(t=>{this._loadingApiHeaders?i(t.data):s(e)}).catch(t=>{this._rejectApiRequests(s,t)}))})},_processApiHeaders:function(t,i){return new Promise((s,a)=>{this._apiHeaders?s():this.sendActionRequest("POST","app/process-api-response-headers",{data:{headers:t},cancelToken:i}).then(t=>{if(this._loadingApiHeaders)for(this._apiHeaders=t.data,this._loadingApiHeaders=!1,s();this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[0](this._apiHeaders);else a(e)}).catch(t=>{this._rejectApiRequests(a,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((s,a)=>{let n=new XMLHttpRequest;n.open(t,e,!0),"object"==typeof i?(n.setRequestHeader("Content-Type","application/json; charset=UTF-8"),i=JSON.stringify(i)):n.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),n.responseType="blob",n.onload=function(){if(200===n.status){let t=n.getResponseHeader("content-disposition"),e=/"([^"]*)"/.exec(t),i=null!=e&&e[1]?e[1]:"Download",a=n.getResponseHeader("content-type"),r=new Blob([n.response],{type:a}),o=document.createElement("a");o.href=window.URL.createObjectURL(r),o.download=i,document.body.appendChild(o),o.click(),document.body.removeChild(o),s()}else a()}.bind(this),n.send(i)})},stringToArray:function(e){if("string"!=typeof e)return e;for(var i=e.split(","),s=0;s<i.length;s++)i[s]=t.trim(i[s]);return i},findDeltaData:function(t,e,i){i.sort((function(t,e){return t.length===e.length?0:t.length>e.length?1:-1}));for(var s=this._groupParamsByDeltaNames(t.split("&"),i,!1,!0),a=this._groupParamsByDeltaNames(e.split("&"),i,!0,!1),n=a.__root__,r=0;r<i.length;r++)(Craft.inArray(i[r],Craft.modifiedDeltaNames)||"object"==typeof a[i[r]]&&("object"!=typeof s[i[r]]||JSON.stringify(s[i[r]])!==JSON.stringify(a[i[r]])))&&(n=n.concat(a[i[r]])).push("modifiedDeltaNames[]="+i[r]);return n.join("&")},_groupParamsByDeltaNames:function(e,i,s,a){var n,r,o={};s&&(o.__root__=[]);t:for(var l=0;l<e.length;l++){for(n=i.length-1;n>=0;n--)if((r=decodeURIComponent(e[l]).substr(0,i[n].length+1))===i[n]+"="||r===i[n]+"["){void 0===o[i[n]]&&(o[i[n]]=[]),o[i[n]].push(e[l]);continue t}s&&o.__root__.push(e[l])}if(a)for(let e in Craft.initialDeltaValues)Craft.initialDeltaValues.hasOwnProperty(e)&&(o[e]=[encodeURIComponent(e)+"="+t.param(Craft.initialDeltaValues[e])]);return o},expandPostArray:function(t){var e,i={};for(var s in t)if(t.hasOwnProperty(s)){var a,n=t[s],r=s.match(/^(\w+)(\[.*)?/);if(r[2])for(a=r[2].match(/\[[^\[\]]*\]/g),e=0;e<a.length;e++)a[e]=a[e].substring(1,a[e].length-1);else a=[];a.unshift(r[1]);var o=i;for(e=0;e<a.length;e++)e<a.length-1?("object"!=typeof o[a[e]]&&(a[e+1]&&parseInt(a[e+1])!=a[e+1]?o[a[e]]={}:o[a[e]]=[]),o=o[a[e]]):(a[e]||(a[e]=o.length),o[a[e]]=n)}return i},createForm:function(e){var i=t("<form/>",{attr:{method:"post",action:"","accept-charset":"UTF-8"}});if("string"==typeof e)for(var s,a=e.split("&"),n=0;n<a.length;n++)s=a[n].split("=",2),t("<input/>",{type:"hidden",name:decodeURIComponent(s[0]),value:decodeURIComponent(s[1]||"")}).appendTo(i);return i},compare:function(t,e,i){if(typeof t!=typeof e)return!1;if("object"==typeof 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 s in t)if(t.hasOwnProperty(s)&&!Craft.compare(t[s],e[s]))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),t=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(e,i){return t.isPlainObject(i)&&(i=Object.values(i)),i.includes(e)},removeFromArray:function(e,i){var s=t.inArray(e,i);return-1!==s&&(i.splice(s,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=Math.floor(t/604800);t%=604800;var s=Math.floor(t/86400);t%=86400;var a,n=Math.floor(t/3600);t%=3600,e?(a=Math.floor(t/60),t%=60):(a=Math.round(t/60),t=0);var r=[];return i&&r.push(i+" "+(1===i?Craft.t("app","week"):Craft.t("app","weeks"))),s&&r.push(s+" "+(1===s?Craft.t("app","day"):Craft.t("app","days"))),n&&r.push(n+" "+(1===n?Craft.t("app","hour"):Craft.t("app","hours"))),!a&&(e||i||s||n)||r.push(a+" "+(1===a?Craft.t("app","minute"):Craft.t("app","minutes"))),!t&&(!e||i||s||n||a)||r.push(t+" "+(1===t?Craft.t("app","second"):Craft.t("app","seconds"))),r.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(e){for(var i=t(document.createElement("ul")).addClass("errors"),s=0;s<e.length;s++){var a=t(document.createElement("li"));a.appendTo(i),a.html(e[s])}return i},appendHeadHtml:function(e){if(e){var i=t("link[href]");if(i.length){for(var s,a=[],n=0;n<i.length;n++)s=i.eq(n).attr("href").replace(/&/g,"&amp;"),a.push(Craft.escapeRegex(s));var r=new RegExp('<link\\s[^>]*href="(?:'+a.join("|")+')".*?><\/script>',"g");e=e.replace(r,"")}t("head").append(e)}},appendFootHtml:function(e){if(e){var i=t("script[src]");if(i.length){for(var s,a=[],n=0;n<i.length;n++)s=i.eq(n).attr("src").replace(/&/g,"&amp;"),a.push(Craft.escapeRegex(s));var r=new RegExp('<script\\s[^>]*src="(?:'+a.join("|")+')".*?><\/script>',"g");e=e.replace(r,"")}Garnish.$bod.append(e)}},initUiElements:function(e){t(".grid",e).grid(),t(".info",e).infoicon(),t(".checkbox-select",e).checkboxselect(),t(".fieldtoggle",e).fieldtoggle(),t(".lightswitch",e).lightswitch(),t(".nicetext",e).nicetext(),t(".formsubmit",e).formsubmit(),t(".menubtn",e).menubtn(),t(".datetimewrapper",e).datetime(),t("a",e).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===t(this).attr("target")&&t(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(e,i,s){return void 0===s&&t.isPlainObject(i)?(s=i,i=null):"object"!=typeof s&&(s={}),s.elementType||(s.elementType=e),new(void 0!==this._elementEditorClasses[e]?this._elementEditorClasses[e]:Craft.BaseElementEditor)(i,s)},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-${Craft.systemUid}.${t}`)},getCookie:function(t){return document.cookie.replace(new RegExp(`(?:(?:^|.*;\\s*)Craft-${Craft.systemUid}:${t}\\s*\\=\\s*([^;]*).*$)|^.*$`),"$1")},setCookie:function(e,i,s){s=t.extend({},this.defaultCookieOptions,s);let a=`Craft-${Craft.systemUid}:${e}=${encodeURIComponent(i)}`;s.path&&(a+=";path="+s.path),s.domain&&(a+=";domain="+s.domain),s.maxAge?a+=";max-age-in-seconds="+s.maxAge:s.expires&&(a+=";expires="+s.expires.toUTCString()),s.secure&&(a+=";secure"),document.cookie=a},removeCookie:function(t){this.setCookie(t,"",new Date("1970-01-01T00:00:00"))},getElementInfo:function(e){var i=t(e);return i.hasClass("element")||(i=i.find(".element:first")),{id:i.data("id"),siteId:i.data("site-id"),label:i.data("label"),status:i.data("status"),url:i.data("url"),hasThumb:i.hasClass("hasthumb"),$element:i}},setElementSize:function(e,i){var s=t(e);if("small"!==i&&"large"!==i&&(i="small"),!s.hasClass(i)){var a="small"===i?"large":"small";if(s.addClass(i).removeClass(a),s.hasClass("hasthumb")){var n=s.find("> .elementthumb > img"),r=t("<img/>",{sizes:("small"===i?"30":"100")+"px",srcset:n.attr("srcset")||n.attr("data-pfsrcset")});n.replaceWith(r),picturefill({elements:[r[0]]})}}},submitForm:function(e,i){if(void 0===i&&(i={}),!i.confirm||confirm(i.confirm)){if(i.action&&t("<input/>",{type:"hidden",name:"action",val:i.action}).appendTo(e),i.redirect&&t("<input/>",{type:"hidden",name:"redirect",val:i.redirect}).appendTo(e),i.params)for(let s in i.params){let a=i.params[s];t("<input/>",{type:"hidden",name:s,val:a}).appendTo(e)}i.retainScroll&&this.setLocalStorage("scrollY",window.scrollY),e.trigger(t.extend({type:"submit"},i.data))}}}),t.extend(t.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 e=t(this);e.addClass("disabled"),e.data("activatable")&&e.removeAttr("tabindex")}))},enable:function(){return this.each((function(){var e=t(this);e.removeClass("disabled"),e.data("activatable")&&e.attr("tabindex","0")}))},grid:function(){return this.each((function(){var e=t(this),i={};e.data("item-selector")&&(i.itemSelector=e.data("item-selector")),e.data("cols")&&(i.cols=parseInt(e.data("cols"))),e.data("max-cols")&&(i.maxCols=parseInt(e.data("max-cols"))),e.data("min-col-width")&&(i.minColWidth=parseInt(e.data("min-col-width"))),e.data("mode")&&(i.mode=e.data("mode")),e.data("fill-mode")&&(i.fillMode=e.data("fill-mode")),e.data("col-class")&&(i.colClass=e.data("col-class")),e.data("snap-to-grid")&&(i.snapToGrid=!!e.data("snap-to-grid")),new Craft.Grid(this,i)}))},infoicon:function(){return this.each((function(){new Craft.InfoIcon(this)}))},checkboxselect:function(){return this.each((function(){t.data(this,"checkboxselect")||new Garnish.CheckboxSelect(this)}))},fieldtoggle:function(){return this.each((function(){t.data(this,"fieldtoggle")||new Craft.FieldToggle(this)}))},lightswitch:function(e,i,s){return"settings"===e?("string"==typeof i?(e={})[i]=s:e=i,this.each((function(){var i=t.data(this,"lightswitch");i&&i.setSettings(e)}))):(t.isPlainObject(e)||(e={}),this.each((function(){var i=t.extend({},e);Garnish.hasAttr(this,"data-value")&&(i.value=t(this).attr("data-value")),Garnish.hasAttr(this,"data-indeterminate-value")&&(i.indeterminateValue=t(this).attr("data-indeterminate-value")),t.data(this,"lightswitch")||new Craft.LightSwitch(this,i)})))},nicetext:function(){return this.each((function(){t.data(this,"nicetext")||new Garnish.NiceText(this)}))},formsubmit:function(){return this.on("click",(function(e){let i=t(e.currentTarget),s=i.data("params")||{};i.data("param")&&(s[i.data("param")]=i.data("value"));let a=i.data("menu")?i.data("menu").$anchor:i,n=a.attr("data-form")?t("#"+a.attr("data-form")):a.closest("form");Craft.submitForm(n,{confirm:i.data("confirm"),action:i.data("action"),redirect:i.data("redirect"),params:s,data:{customTrigger:i}})}))},menubtn:function(){return this.each((function(){var e=t(this);if(!e.data("menubtn")&&e.next().hasClass("menu")){var i={};e.data("menu-anchor")&&(i.menuAnchor=e.data("menu-anchor")),new Garnish.MenuBtn(e,i)}}))},datetime:function(){return this.each((function(){let e=t(this),i=e.find('input:not([name$="[timezone]"])'),s=()=>{let s=!1;for(let t=0;t<i.length;t++)if(i.eq(t).val()){s=!0;break}if(s){if(!e.children(".clear-btn").length){let s=t("<button/>",{type:"button",class:"clear-btn",title:Craft.t("app","Clear"),"aria-label":Craft.t("app","Clear")}).appendTo(e).on("click",()=>{for(let t=0;t<i.length;t++)i.eq(t).val("");s.remove(),i.first().focus()})}}else e.children(".clear-btn").remove()};i.on("change",s),s()}))}}),Garnish.$doc.ready((function(){Craft.initUiElements()})),Craft.BaseElementEditor=Garnish.Base.extend({$element:null,elementId:null,siteId:null,deltaNames:null,initialData:null,$form:null,$fieldsContainer:null,$cancelBtn:null,$saveBtn:null,$spinner:null,$siteSelect:null,$siteSpinner:null,hud:null,init:function(e,i){void 0===i&&t.isPlainObject(e)&&(i=e,e=null),this.$element=t(e),this.setSettings(i,Craft.BaseElementEditor.defaults),this.loadHud()},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 e=t.extend({},this.settings.params);return this.settings.siteId?e.siteId=this.settings.siteId:this.$element&&this.$element.data("site-id")&&(e.siteId=this.$element.data("site-id")),this.settings.elementId?e.elementId=this.settings.elementId:this.$element&&this.$element.data("id")&&(e.elementId=this.$element.data("id")),this.settings.elementType&&(e.elementType=this.settings.elementType),this.settings.attributes&&(e.attributes=this.settings.attributes),this.settings.prevalidate&&(e.prevalidate=1),e},loadHud:function(){this.onBeginLoading();var e=this.getBaseData();e.includeSites=Craft.isMultiSite&&this.settings.showSiteSwitcher,Craft.postActionRequest("elements/get-editor-html",e,t.proxy(this,"showHud"))},showHud:function(e,i){if(this.onEndLoading(),"success"===i){var s=t();if(e.sites){var a=t('<div class="hud-header"/>');if(1===e.sites.length)t("<h5/>",{text:e.sites[0].name}).appendTo(a);else{var n=t('<div class="select"/>').appendTo(a);this.$siteSelect=t("<select/>").appendTo(n),this.$siteSpinner=t('<div class="spinner hidden"/>').appendTo(a);for(var r=0;r<e.sites.length;r++){var o=e.sites[r];t('<option value="'+o.id+'"'+(o.id==e.siteId?' selected="selected"':"")+">"+o.name+"</option>").appendTo(this.$siteSelect)}this.addListener(this.$siteSelect,"change","switchSite")}s=s.add(a)}this.$form=t("<div/>"),this.$fieldsContainer=t('<div class="fields"/>').appendTo(this.$form),this.updateForm(e,!0),this.onCreateForm(this.$form);var l=t('<div class="hud-footer"/>').appendTo(this.$form),h=t('<div class="buttons right"/>').appendTo(l);if(this.$cancelBtn=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(h),this.$saveBtn=t("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Save")}).appendTo(h),this.$spinner=t('<div class="spinner hidden"/>').appendTo(h),s=s.add(this.$form),this.hud)this.hud.updateBody(s),this.hud.updateSizeAndPosition();else{var d=this.settings.hudTrigger||this.$element;this.hud=new Garnish.HUD(d,s,{bodyClass:"body elementeditor",closeOtherHUDs:!1,hideOnEsc:!1,hideOnShadeClick:!1,onShow:this.onShowHud.bind(this),onHide:this.onHideHud.bind(this),onSubmit:this.saveElement.bind(this)}),Garnish.shortcutManager.registerShortcut(Garnish.ESC_KEY,this.maybeCloseHud.bind(this)),this.hud.addListener(this.hud.$shade,"click",this.maybeCloseHud.bind(this)),this.hud.$hud.data("elementEditor",this),this.hud.$body.attr("novalidate",""),this.hud.on("hide",t.proxy((function(){delete this.hud}),this))}s.find(".text:first").trigger("focus"),this.addListener(this.$cancelBtn,"click",(function(){this.hud.hide()}))}},switchSite:function(){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.reloadForm({siteId:e},t.proxy((function(t){this.$siteSpinner.addClass("hidden"),"success"!==t&&this.$siteSelect.val(this.siteId)}),this)))}else this.$siteSelect.val(this.siteId)},reloadForm:function(e,i){e=t.extend(this.getBaseData(),e),Craft.postActionRequest("elements/get-editor-html",e,t.proxy((function(t,e){"success"===e&&this.updateForm(t,!0),i&&i(e)}),this))},updateForm:function(e,i){this.siteId=e.siteId,this.$fieldsContainer.html(e.html),!1!==i&&(this.deltaNames=e.deltaNames);let s=this.$fieldsContainer.find("> .meta > .field > .instructions");for(let e=0;e<s.length;e++){let i=s.eq(e),a=i.siblings(".heading").children("label");t("<span/>",{class:"info",html:i.children().html()}).appendTo(a),i.remove()}Garnish.requestAnimationFrame(t.proxy((function(){Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),Craft.initUiElements(this.$fieldsContainer),i&&(this.initialData=this.hud.$body.serialize())}),this))},saveElement:function(){var e=this.settings.validators;if(t.isArray(e))for(var i=0;i<e.length;i++)if(t.isFunction(e[i])&&!e[i].call())return!1;this.$spinner.removeClass("hidden");var s=t.param(this.getBaseData())+"&"+this.hud.$body.serialize();s=Craft.findDeltaData(this.initialData,s,this.deltaNames),Craft.postActionRequest("elements/save-element",s,t.proxy((function(t,e){if(this.$spinner.addClass("hidden"),"success"===e)if(t.success){if(this.$element&&this.siteId==this.$element.data("site-id")){var i=this.$element.find(".title"),s=i.find("a");s.length&&t.cpEditUrl?(s.attr("href",t.cpEditUrl),s.text(t.newTitle)):i.text(t.newTitle)}this.settings.elementType&&Craft.elementTypeNames[this.settings.elementType]&&Craft.cp.displayNotice(Craft.t("app","{type} saved.",{type:Craft.elementTypeNames[this.settings.elementType][0]})),this.closeHud(),this.onSaveElement(t)}else this.updateForm(t,!1),Garnish.shake(this.hud.$hud)}),this))},isDirty:function(){return this.hud.$body.serialize()!==this.initialData},maybeCloseHud:function(t){this.hud&&this.hud.showing&&(this.isDirty()&&!confirm("Are you sure you want to close the editor? Any changes will be lost.")||this.closeHud())},closeHud:function(){this.hud&&this.hud.showing&&(this.hud.hide(),delete this.hud)},onShowHud:function(){Garnish.shortcutManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0},this.saveElement.bind(this)),this.settings.onShowHud(),this.trigger("showHud")},onHideHud:function(){this.settings.onHideHud(),this.trigger("hideHud")},onBeginLoading:function(){this.$element&&this.$element.addClass("loading"),this.settings.onBeginLoading(),this.trigger("beginLoading")},onEndLoading:function(){this.$element&&this.$element.removeClass("loading"),this.settings.onEndLoading(),this.trigger("endLoading")},onSaveElement:function(t){this.settings.onSaveElement(t),this.trigger("saveElement",{response:t}),Craft.cp.runQueue()},onCreateForm:function(t){this.settings.onCreateForm(t)}},{defaults:{hudTrigger:null,showSiteSwitcher:!0,elementId:null,elementType:null,siteId:null,attributes:null,params:null,prevalidate:!1,elementIndex:null,onShowHud:t.noop,onHideHud:t.noop,onBeginLoading:t.noop,onEndLoading:t.noop,onCreateForm:t.noop,onSaveElement:t.noop,validators:[]}}),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(e,i,s){if(this.elementType=e,this.$container=i,this.setSettings(s,Craft.BaseElementIndex.defaults),this.instanceState=this.getDefaultInstanceState(),this.sourceStates={},this.settings.storageKey&&t.extend(this.instanceState,Craft.getLocalStorage(this.settings.storageKey),{}),this.sourceStatesStorageKey="BaseElementIndex."+this.elementType+"."+this.settings.context,t.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(),t(".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",t.proxy(this,"_handleStatusChange"))),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",t.proxy(this,"_handleSiteChange")),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",t.proxy((function(){!this.searching&&this.$search.val()?this.startSearching():this.searching&&!this.$search.val()&&this.stopSearching(),this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout(t.proxy(this,"updateElementsIfSearchTextChanged"),500)}),this)),this.addListener(this.$search,"keypress",t.proxy((function(t){t.keyCode===Garnish.RETURN_KEY&&(t.preventDefault(),this.searchTimeout&&clearTimeout(this.searchTimeout),this.updateElementsIfSearchTextChanged())}),this)),this.addListener(this.$clearSearchBtn,"click",t.proxy((function(){this.$search.val(""),this.searchTimeout&&clearTimeout(this.searchTimeout),Garnish.isMobileBrowser(!0)||this.$search.trigger("focus"),this.stopSearching(),this.updateElementsIfSearchTextChanged()}),this)),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",t.proxy(this,"_handleSortChange"))),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(){this._cancelToken&&(this._ignoreFailedRequest=!0,this._cancelToken.cancel(),Garnish.requestAnimationFrame(()=>{this._ignoreFailedRequest=!1}))},getSourceContainer:function(){return this.$sidebar.find("nav > ul")},get $sources(){if(this.sourceSelect)return this.sourceSelect.$items},initSources:function(){var e=this._getSourcesInList(this.getSourceContainer());return 0!==e.length&&(this.sourceSelect||(this.sourceSelect=new Garnish.Select(this.$sidebar.find("nav"),{multi:!1,allowEmpty:!1,vertical:!0,onSelectionChange:t.proxy(this,"_handleSourceSelectionChange")})),this.sourcesByKey={},this._initSources(e),!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(){this.sourceSelect.removeAllItems();var t={context:this.settings.context,elementType:this.elementType};this.setIndexBusy(),Craft.sendActionRequest("POST",this.settings.refreshSourcesAction,{data:t}).then(t=>{this.setIndexAvailable(),this.getSourceContainer().replaceWith(t.data.html),this.initSources(),this.selectDefaultSource()}).catch(()=>{this.setIndexAvailable(),this._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=t('<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")},stopSearching:function(){this.$clearSearchBtn.addClass("hidden"),this.$scoreSortAttribute.detach(),this.searching=!1,this._updateStructureSortOption()},setInstanceState:function(e,i){"object"==typeof e?t.extend(this.instanceState,e):this.instanceState[e]=i,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(e,i){var s=this.getSelectedSourceState();"object"==typeof e?t.extend(s,e):s[e]=i,this.sourceStates[this.instanceState.selectedSource]=s,Craft.setLocalStorage(this.sourceStatesStorageKey,this.sourceStates)},storeSortAttributeAndDirection:function(){var t=this.getSelectedSortAttribute();"score"!==t&&this.setSelecetedSourceState({order:t,sort:this.getSelectedSortDirection()})},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 e={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)&&(e.drafts=this.drafts||null,e.savedDraftsOnly=!0,this.drafts||(e.draftOf=!1)),this.trashed&&(e.trashed=!0),Garnish.hasAttr(this.$source,"data-override-status")||(e.status=this.status),t.extend(e,this.settings.criteria);var i={context:this.settings.context,elementType:this.elementType,source:this.instanceState.selectedSource,criteria:e,disabledElementIds:this.settings.disabledElementIds,viewState:t.extend({},this.getSelectedSourceState()),paginated:this._isViewPaginated()?1:0};return i.viewState.order=this.getSelectedSortAttribute(),i.viewState.sort=this.getSelectedSortDirection(),"structure"===this.getSelectedSortAttribute()&&(void 0===this.instanceState.collapsedElementIds&&(this.instanceState.collapsedElementIds=[]),i.collapsedElementIds=this.instanceState.collapsedElementIds),this.trigger("registerViewParams",{params:i}),i},updateElements:function(t){if(this.initialized){this._cancelRequests(),this.setIndexBusy(),this.view&&(this.view.destroy(),delete this.view),!0!==t&&(this.setPage(1),this._resetCount());var e=this.getViewParams();Craft.sendActionRequest("POST",this.settings.updateElementsAction,{data:e,cancelToken:this._createCancelToken()}).then(t=>{this.setIndexAvailable(),("index"===this.settings.context?Garnish.$scrollContainer:this.$main).scrollTop(0),this._updateView(e,t.data)}).catch(t=>{this.setIndexAvailable(),this._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(e,i){var s=this.view.getSelectedElementIds();if(0!==s.length&&("string"==typeof e&&(e=this._findAction(e)),!e.confirm||confirm(e.confirm))){this._cancelRequests();var a=this.getViewParams();i=i?Craft.expandPostArray(i):{};var n=t.extend(a,e.settings||{},i,{elementAction:e.type,elementIds:s});this.setIndexBusy(),this._autoSelectElements=s,e.download?(Craft.csrfTokenName&&(n[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl(this.settings.submitActionsAction),n).then(t=>{this.setIndexAvailable()}).catch(t=>{this.setIndexAvailable()})):Craft.sendActionRequest("POST",this.settings.submitActionsAction,{data:n,cancelToken:this._createCancelToken()}).then(t=>{this.setIndexAvailable(),t.data.success?(this._resetCount(),this._updateView(a,t.data),t.data.message&&Craft.cp.displayNotice(t.data.message),this.afterAction(e,n)):Craft.cp.displayError(t.data.message)}).catch(()=>{this.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: "+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():t()},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(e){if(!e||!e.length)return!1;if(this.$source&&this.$source[0]&&this.$source[0]===e[0]&&e.data("key")===this.sourceKey)return!1;this.hideActionTriggers(),this.$source=e,this.sourceKey=e.data("key"),this.setInstanceState("selectedSource",this.sourceKey),this.sourceSelect.selectItem(e),Craft.cp.updateSidebarMenuLabel(),this.searching&&(this.searchText=null,this.$search.val(""),this.stopSearching()),this.$sortAttributesList.children("li[data-extra]").remove();let i=this.$source.data("sort-options");if(i)for(let e=0;e<i.length;e++){let s=t("<li/>",{"data-extra":!0}).append(t("<a/>",{text:i[e][0],"data-attr":i[e][1]})).appendTo(this.$sortAttributesList);this.sortMenu.addOptions(s.children())}if(Garnish.hasAttr(this.$source,"data-has-structure")?(this.$structureSortAttribute||(this.$structureSortAttribute=t('<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 s=this.statusMenu.$options.first();this.setStatus(s.data("status"))}if(this.$viewModeBtnContainer&&this.$viewModeBtnContainer.remove(),this.viewModeBtns={},this.viewMode=null,this.sourceViewModes=this.getViewModesForSource(),this.sourceViewModes.length>1){this.$viewModeBtnContainer=t('<div class="btngroup"/>').appendTo(this.$toolbar);for(var a=0;a<this.sourceViewModes.length;a++){let e=this.sourceViewModes[a],i=t("<button/>",{type:"button",class:"btn"+(void 0!==e.className?" "+e.className:""),"data-view":e.mode,"data-icon":e.icon,"aria-label":e.title,title:e.title}).appendTo(this.$viewModeBtnContainer);this.viewModeBtns[e.mode]=i,this.addListener(i,"click",{mode:e.mode},(function(t){this.selectViewMode(t.data.mode),this.updateElements()}))}}var n=this.getSelectedViewMode();return n&&this.doesSourceHaveViewMode(n)||(n=this.viewMode&&this.doesSourceHaveViewMode(this.viewMode)?this.viewMode:this.sourceViewModes[0].mode),this.selectViewMode(n),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 "${t}" not supported.`}},rememberDisabledElementId:function(e){-1===t.inArray(e,this.settings.disabledElementIds)&&this.settings.disabledElementIds.push(e)},forgetDisabledElementId:function(e){var i=t.inArray(e,this.settings.disabledElementIds);-1!==i&&this.settings.disabledElementIds.splice(i,1)},enableElements:function(e){e.removeClass("disabled").parents(".disabled").removeClass("disabled");for(var i=0;i<e.length;i++){var s=t(e[i]).data("id");this.forgetDisabledElementId(s)}this.onEnableElements(e)},disableElements:function(e){e.removeClass("sel").addClass("disabled");for(var i=0;i<e.length;i++){var s=t(e[i]).data("id");this.rememberDisabledElementId(s)}this.onDisableElements(e)},getElementById:function(t){return this.view.getElementById(t)},enableElementsById:function(e){e=t.makeArray(e);for(var i=0;i<e.length;i++){var s=e[i],a=this.getElementById(s);a&&a.length?this.enableElements(a):this.forgetDisabledElementId(s)}},disableElementsById:function(e){e=t.makeArray(e);for(var i=0;i<e.length;i++){var s=e[i],a=this.getElementById(s);a&&a.length?this.disableElements(a):this.rememberDisabledElementId(s)}},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 t(this.settings.buttonContainer);var e=t("#action-button");return e.length||(e=t('<div id="action-button"/>').appendTo(t("#header"))),e},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(e){e.preventDefault();var i=t(e.currentTarget);i.hasClass("disabled")||i.data("custom-handler")||this.submitAction(i.data("action"),Garnish.getPostData(i))},_handleMenuActionTriggerSubmit:function(e){var i=t(e.option);i.hasClass("disabled")||i.data("custom-handler")||this.submitAction(i.data("action"))},_handleStatusChange:function(e){this.statusMenu.$options.removeClass("sel");var i=t(e.selectedOption).addClass("sel");this.$statusMenuBtn.html(i.html()),this.trashed=!1,this.drafts=!1,this.status=null,Garnish.hasAttr(i,"data-trashed")?this.trashed=!0:Garnish.hasAttr(i,"data-drafts")?this.drafts=!0:this.status=i.data("status"),this._updateStructureSortOption(),this.updateElements()},_handleSiteChange:function(e){this.siteMenu.$options.removeClass("sel");var i=t(e.selectedOption).addClass("sel");this.$siteMenuBtn.html(i.html()),this._setSite(i.data("site-id")),this.onSelectSite()},_setSite:function(e){let i=null===this.siteId;var s,a;this.siteId=e,this.$visibleSources=t();for(var n=!(i||this.$source&&this.$source.length),r=0;r<this.$sources.length;r++)void 0===(a=this.$sources.eq(r)).data("sites")||-1!==a.data("sites").toString().split(",").indexOf(e.toString())?(a.parent().removeClass("hidden"),this.$visibleSources=this.$visibleSources.add(a),s||(s=a)):(a.parent().addClass("hidden"),this.$source&&this.$source.get(0)==a.get(0)&&(n=!0));this.initialized&&n&&this.selectSource(s);var o,l=this.getSourceContainer().children(".heading");for(r=0;r<l.length;r++)0!==(o=l.eq(r)).nextUntil(".heading",":not(.hidden)").length?o.removeClass("hidden"):o.addClass("hidden");this.initialized&&("index"===this.settings.context&&Craft.cp.setSiteId(e),this.updateElements())},_handleSortChange:function(e){var i=t(e.selectedOption);i.hasClass("disabled")||i.hasClass("sel")||(i.parent().parent().is(this.$sortAttributesList)?this.setSortAttribute(i.data("attr")):this.setSortDirection(i.data("dir")),this.storeSortAttributeAndDirection(),this.updateElements())},_handleSelectionChange:function(){this.updateActionTriggers(),this.onSelectionChange()},_handleSourceDblClick:function(e){this._toggleSource(t(e.currentTarget)),e.stopPropagation()},_handleSourceToggleClick:function(e){this._toggleSource(t(e.currentTarget).prev("a")),e.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")},_initSources:function(e){for(var i=0;i<e.length;i++)this.initSource(t(e[i]))},_deinitSources:function(e){for(var i=0;i<e.length;i++)this.deinitSource(t(e[i]))},_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");var e=this._getChildSources(t);this._initSources(e);var i=t.data("key");-1===this.instanceState.expandedSources.indexOf(i)&&(this.instanceState.expandedSources.push(i),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");var e=this._getChildSources(t);this._deinitSources(e);var i=this.instanceState.expandedSources.indexOf(t.data("key"));-1!==i&&(this.instanceState.expandedSources.splice(i,1),this.storeInstanceState())},_isViewPaginated:function(){return"index"===this.settings.context&&"structure"!==this.getSelectedSortAttribute()},_updateView:function(e,i){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(e=>{this.$countSpinner.addClass("hidden");let i=Craft.elementTypeNames[this.elementType]?Craft.elementTypeNames[this.elementType][2]:"element",s=Craft.elementTypeNames[this.elementType]?Craft.elementTypeNames[this.elementType][3]:"elements";if(this._isViewPaginated()){let a=Math.min(this.settings.batchSize*(this.page-1)+1,e),n=Math.min(a+(this.settings.batchSize-1),e),r=Craft.t("app","{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}",{first:a,last:n,total:e,item:i,items:s}),o=t('<div class="flex pagination"/>').appendTo(this.$countContainer),l=Math.max(Math.ceil(e/this.settings.batchSize),1),h=t("<div/>",{class:"page-link prev-page"+(this.page>1?"":" disabled"),title:Craft.t("app","Previous Page")}).appendTo(o),d=t("<div/>",{class:"page-link next-page"+(this.page<l?"":" disabled"),title:Craft.t("app","Next Page")}).appendTo(o);t("<div/>",{class:"page-info",text:r}).appendTo(o),this.page>1&&this.addListener(h,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page-1),this.updateElements(!0)})),this.page<l&&this.addListener(d,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page+1),this.updateElements(!0)}))}else{let t=Craft.t("app","{total, number} {total, plural, =1{{item}} other{{items}}}",{total:e,item:i,items:s});this.$countContainer.text(t)}}).catch(()=>{this.$countSpinner.addClass("hidden")})),this.$elements.html(i.html),Craft.appendHeadHtml(i.headHtml),Craft.appendFootHtml(i.footHtml),this.$selectAllContainer=this.$elements.find(".selectallcontainer:first"),i.actions&&i.actions.length?this.$selectAllContainer.length&&(this.actions=i.actions,this.actionsHeadHtml=i.actionsHeadHtml,this.actionsFootHtml=i.actionsFootHtml,this.$selectAllCheckbox=t('<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(e){e.keyCode===Garnish.SPACE_KEY&&(e.preventDefault(),t(e.currentTarget).trigger("click"))}))):(this.$selectAllContainer.siblings().length||this.$selectAllContainer.parent(".header").remove(),this.$selectAllContainer.remove()),this.exporters=i.exporters,this.exportersByType=Craft.index(this.exporters||[],t=>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:e,selectable:s,multiSelect:this.actions||this.settings.multiSelect,checkboxMode:!!this.actions,onSelectionChange:t.proxy(this,"_handleSelectionChange")}),this._autoSelectElements){if(s)for(var a=0;a<this._autoSelectElements.length;a++)this.view.selectElementById(this._autoSelectElements[a]);this._autoSelectElements=null}this.onUpdateElements()},_countResults:function(){return new Promise((t,e)=>{if(null!==this.totalResults)t(this.totalResults);else{var i=this.getViewParams();delete i.criteria.offset,delete i.criteria.limit,null===this.resultSet&&(this.resultSet=Math.floor(1e8*Math.random())),i.resultSet=this.resultSet,Craft.sendActionRequest("POST",this.settings.countElementsAction,{data:i,cancelToken:this._createCancelToken()}).then(i=>{i.data.resultSet==this.resultSet?(this.totalResults=i.data.count,t(i.data.count)):e()}).catch(e)}})},_createTriggers:function(){var e,i,s=[],a=[],n=[];for(e=0;e<this.actions.length;e++){var r=this.actions[e];if(r.trigger){var o=t('<form id="'+Craft.formatInputId(r.type)+'-actiontrigger"/>').data("action",r).append(r.trigger);this.addListener(o,"submit","_handleActionTriggerSubmit"),s.push(o)}else r.destructive?n.push(r):a.push(r)}if(a.length||n.length){var l=t("<form/>");i=t("<button/>",{type:"button",class:"btn menubtn","data-icon":"settings",title:Craft.t("app","Actions")}).appendTo(l);var h=t('<ul class="menu"/>').appendTo(l),d=this._createMenuTriggerList(a,!1),c=this._createMenuTriggerList(n,!0);d&&d.appendTo(h),d&&c&&t("<hr/>").appendTo(h),c&&c.appendTo(h),s.push(l)}for(this._$triggers=t(),e=0;e<s.length;e++){var u=t("<div/>").append(s[e]);this._$triggers=this._$triggers.add(u)}this._$triggers.appendTo(this.$toolbar),Craft.appendHeadHtml(this.actionsHeadHtml),Craft.appendFootHtml(this.actionsFootHtml),Craft.initUiElements(this._$triggers),i&&i.data("menubtn").on("optionSelect",t.proxy(this,"_handleMenuActionTriggerSubmit"))},_showExportHud:function(){this.$exportBtn.addClass("active");for(var e=t("<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);let r=a.find("select");this.addListener(r,"change",()=>{let t=r.val();this.exportersByType[t].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);t("<button/>",{type:"submit",class:"btn submit fullwidth",text:Craft.t("app","Export")}).appendTo(e);var h=t("<div/>",{class:"spinner hidden"}).appendTo(e);new Garnish.HUD(this.$exportBtn,e).on("hide",t.proxy((function(){this.$exportBtn.removeClass("active")}),this));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,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(e,i){if(e&&e.length){for(var s=t("<ul/>"),a=0;a<e.length;a++)t("<li/>").append(t("<a/>",{id:Craft.formatInputId(e[a].type)+"-actiontrigger",class:i?"error":null,data:{action:e[a]},text:e[a].name})).appendTo(s);return s}}},{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:t.noop,onSelectSource:t.noop,onSelectSite:t.noop,onUpdateElements:t.noop,onSelectionChange:t.noop,onEnableElements:t.noop,onDisableElements:t.noop,onAfterAction:t.noop}}),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(e,i,s){this.elementIndex=e,this.$container=t(i),this.setSettings(s,Craft.BaseElementIndexView.defaults),this.$loadingMoreSpinner=t('<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:t.proxy(this,"onSelectionChange")}),this._handleEnableElements=t.proxy((function(t){this.elementSelect.addItems(t.elements)}),this),this._handleDisableElements=t.proxy((function(t){this.elementSelect.removeItems(t.elements)}),this),this.elementIndex.on("enableElements",this._handleEnableElements),this.elementIndex.on("disableElements",this._handleDisableElements)),"index"===this.settings.context&&(this._handleElementEditing=t.proxy((function(e){var i=t(e.target);if("A"!==i.prop("nodeName")){var s;if(i.hasClass("element"))s=i;else if(!(s=i.closest(".element")).length)return;Garnish.hasAttr(s,"data-editable")&&this.createElementEditor(s)}}),this),this.elementIndex.trashed||(this.addListener(this.$elementContainer,"dblclick",this._handleElementEditing),t.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(){let t;try{t=this.getSelectedElements()}catch(t){}let 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(){if(this.getMorePending()&&!this.loadingMore&&this.settings.batchSize){this.loadingMore=!0,this.$loadingMoreSpinner.removeClass("hidden"),this.removeListener(this.$scroller,"scroll");var e=this.getLoadMoreParams();Craft.postActionRequest(this.settings.loadMoreElementsAction,e,t.proxy((function(e,i){if(this.loadingMore=!1,this.$loadingMoreSpinner.addClass("hidden"),"success"===i){var s=t(e.html);this.appendElements(s),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),this.elementSelect&&(this.elementSelect.addItems(s.filter(":not(.disabled)")),this.elementIndex.updateActionTriggers()),this.setTotalVisible(this.getTotalVisible()+s.length),this.setMorePending(s.length==this.settings.batchSize),this.addListener(this.$scroller,"scroll","maybeLoadMore"),this.maybeLoadMore()}}),this))}},getLoadMoreParams:function(){var e=t.extend(!0,{},this.settings.params);return e.criteria.offset=this.getTotalVisible(),e},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:t.noop,onSelectionChange:t.noop}}),Craft.BaseElementSelectInput=Garnish.Base.extend({thumbLoader:null,elementSelect:null,elementSort:null,modal:null,elementEditor:null,$container:null,$elementsContainer:null,$elements:null,$addElementBtn:null,$addElementBtnContainer:null,_initialized:!1,init:function(e){if(!t.isPlainObject(e)){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];e=i}this.setSettings(e,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.$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(()=>{this._initialized=!0})},get totalSelected(){return this.$elements.length},getContainer:function(){return t("#"+this.settings.id)},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(){this.settings.sortable&&(this.elementSort=new Garnish.DragSort({container:this.$elementsContainer,filter:this.settings.selectable?t.proxy((function(){return this.elementSort.$targetItem.hasClass("sel")?this.elementSelect.getSelectedItems():this.elementSort.$targetItem}),this):null,ignoreHandleSelector:".delete",axis:this.getElementSortAxis(),collapseDraggees:!0,magnetStrength:4,helperLagBase:1.5,onSortChange:this.settings.selectable?t.proxy((function(){this.elementSelect.resetItemOrder()}),this):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(){let t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.addClass("hidden")},enableAddElementsBtn:function(){let t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.removeClass("hidden")},resetElements:function(){null!==this.$elements?this.removeElements(this.$elements):this.$elements=t(),this.addElements(this.getElements())},addElements:function(e){this.thumbLoader.load(e),this.settings.selectable&&this.elementSelect.addItems(e),this.settings.sortable&&this.elementSort.addItems(e),this.settings.editable&&(this._handleShowElementEditor=t.proxy((function(e){var i=t(e.currentTarget);!Garnish.hasAttr(i,"data-editable")||i.hasClass("disabled")||i.hasClass("loading")||(this.elementEditor=this.createElementEditor(i))}),this),this.addListener(e,"dblclick",this._handleShowElementEditor),t.isTouchCapable()&&this.addListener(e,"taphold",this._handleShowElementEditor)),e.find(".delete").on("click dblclick",t.proxy((function(e){this.removeElement(t(e.currentTarget).closest(".element")),e.stopPropagation()}),this)),this.$elements=this.$elements.add(e),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)}t.children("input").prop("disabled",!0),this.$elements=this.$elements.not(t),this.updateAddElementsBtn(),this.onRemoveElements()},removeElement:function(t){this.removeElements(t),this.animateElementAway(t,()=>{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,()=>{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 t.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:t.proxy(this,"onModalSelect")},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 t=this.getSelectedElementIds();return!this.settings.allowSelfRelations&&this.settings.sourceElementId&&t.push(this.settings.sourceElementId),this.settings.disabledElementIds&&t.push(...this.settings.disabledElementIds),t},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()},selectElements:function(t){for(let e=0;e<t.length;e++){let 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();return Craft.setElementSize(e,"large"===this.settings.viewMode?"large":"small"),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},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",limit:null,showSiteMenu:!1,modalStorageKey:null,modalSettings:{},onSelectElements:t.noop,onRemoveElements:t.noop,sortable:!0,selectable:!0,editable:!0,prevalidate:!1,editorSettings:{}}}),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(e,i){this.elementType=e,this.setSettings(i,Craft.BaseElementSelectorModal.defaults);var s=t('<div class="modal elementselectormodal"></div>').appendTo(Garnish.$bod),a=t('<div class="body"><div class="spinner big"></div></div>').appendTo(s),n=t('<div class="footer"/>').appendTo(s);this.base(s,this.settings),this.$footerSpinner=t('<div class="spinner hidden"/>').appendTo(n),this.$primaryButtons=t('<div class="buttons right"/>').appendTo(n),this.$secondaryButtons=t('<div class="buttons left secondary-buttons"/>').appendTo(n),this.$cancelBtn=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$primaryButtons),this.$selectBtn=t("<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(e){for(var i=[],s=0;s<e.length;s++){var a=t(e[s]),n=Craft.getElementInfo(a);i.push(n)}return i},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 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("elements/get-modal-body",e,t.proxy((function(e,i){"success"===i&&(this.$body.html(e.html),this.$body.has(".sidebar:not(.hidden)").length&&this.$body.addClass("has-sidebar"),this.elementIndex=Craft.createElementIndex(this.elementType,this.$body,{context:"modal",modal:this,storageKey:this.settings.storageKey,criteria:this.settings.criteria,disabledElementIds:this.settings.disabledElementIds,selectable:!0,multiSelect:this.settings.multiSelect,buttonContainer:this.$secondaryButtons,onSelectionChange:t.proxy(this,"onSelectionChange"),hideSidebar:this.settings.hideSidebar,defaultSiteId:this.settings.defaultSiteId,defaultSource:this.settings.defaultSource}),this.addListener(this.elementIndex.$elements,"doubletap",(function(t,e){e.firstTap.target===e.secondTap.target&&this.selectElements()})))}),this))}},{defaults:{resizable:!0,storageKey:null,sources:null,criteria:null,multiSelect:!1,showSiteMenu:null,disabledElementIds:[],disableElementsOnSelect:!1,hideOnSelect:!0,onCancel:t.noop,onSelect:t.noop,hideSidebar:!1,defaultSiteId:null,defaultSource:null}}),Craft.BaseInputGenerator=Garnish.Base.extend({$source:null,$target:null,$form:null,settings:null,listening:null,timeout:null,init:function(e,i,s){this.$source=t(e),this.$target=t(i),this.$form=this.$source.closest("form"),this.setSettings(s),this.startListening()},setNewSource:function(e){var i=this.listening;this.stopListening(),this.$source=t(e),i&&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(t.proxy(this,"updateTarget"),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(let t=0;t<this.$target.length;t++)this.$target[t].dispatchEvent(new InputEvent("input",{inputType:"insertText"})),this.$target[t].dispatchEvent(new Event("input"));this.$target.is(":focus")&&Craft.selectFullValue(this.$target)}}},generateTargetValue:function(t){return t}}),Craft.AdminTable=Garnish.Base.extend({settings:null,totalItems:null,sorter:null,$noItems:null,$table:null,$tbody:null,$deleteBtns:null,init:function(e){this.setSettings(e,Craft.AdminTable.defaults),this.settings.allowDeleteAll||(this.settings.minItems=1),this.$noItems=t(this.settings.noItemsSelector),this.$table=t(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:t.proxy(this,"reorderItems")})),this.$deleteBtns=this.$table.find(".delete:not(.disabled)"),this.addListener(this.$deleteBtns,"click","handleDeleteBtnClick"),this.updateUI()},addRow:function(e){if(!(this.settings.maxItems&&this.totalItems>=this.settings.maxItems)){var i=t(e).appendTo(this.$tbody),s=i.find(".delete");this.settings.sortable&&this.sorter.addItems(i),this.$deleteBtns=this.$deleteBtns.add(s),this.addListener(s,"click","handleDeleteBtnClick"),this.totalItems++,this.updateUI()}},reorderItems:function(){if(this.settings.sortable){for(var e=[],i=0;i<this.sorter.$items.length;i++){var s=t(this.sorter.$items[i]).attr(this.settings.idAttribute);e.push(s)}var a={ids:JSON.stringify(e)};Craft.postActionRequest(this.settings.reorderAction,a,t.proxy((function(t,i){"success"===i&&(t.success?(this.onReorderItems(e),Craft.cp.displayNotice(Craft.t("app",this.settings.reorderSuccessMessage))):Craft.cp.displayError(Craft.t("app",this.settings.reorderFailMessage)))}),this))}},handleDeleteBtnClick:function(e){if(!(this.settings.minItems&&this.totalItems<=this.settings.minItems)){var i=t(e.target).closest("tr");this.confirmDeleteItem(i)&&this.deleteItem(i)}},confirmDeleteItem:function(t){var e=this.getItemName(t);return confirm(Craft.t("app",this.settings.confirmDeleteMessage,{name:e}))},deleteItem:function(e){var i={id:this.getItemId(e)};Craft.postActionRequest(this.settings.deleteAction,i,t.proxy((function(t,i){"success"===i&&this.handleDeleteItemResponse(t,e)}),this))},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 e=this.$table.find(".move");1===this.totalItems?e.addClass("disabled"):e.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?t(this.settings.newItemBtnSelector).addClass("hidden"):t(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:t.noop,onDeleteItem:t.noop}}),Craft.AssetEditor=Craft.BaseElementEditor.extend({reloadIndex:!1,updateForm:function(t,e){if(this.base(t,e),this.$element.data("id")){var i=this.$fieldsContainer.find("> .meta > .preview-thumb-container.editable");i.length&&this.addListener(i,"click","showImageEditor")}},showImageEditor:function(){new Craft.AssetImageEditor(this.$element.data("id"),{onSave:function(){this.reloadIndex=!0,this.reloadForm()}.bind(this)})},onHideHud:function(){this.reloadIndex&&this.settings.elementIndex?this.settings.elementIndex.updateElements():this.reloadIndex&&this.settings.input&&this.settings.input.refreshThumbnail(this.$element.data("id")),this.base()}}),Craft.registerElementEditorClass("craft\\elements\\Asset",Craft.AssetEditor),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,croppingAreaText: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(e,i){this.cacheBust=Date.now(),this.setSettings(i,Craft.AssetImageEditor.defaults),null===this.settings.allowDegreeFractions&&(this.settings.allowDegreeFractions=Craft.isImagick),this.assetId=e,this.flipData={x:0,y:0},this.$container=t('<form class="modal fitted imageeditor"></form>').appendTo(Garnish.$bod),this.$body=t('<div class="body"></div>').appendTo(this.$container),this.$footer=t('<div class="footer"/>').appendTo(this.$container),this.base(this.$container,this.settings),this.$buttons=t('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=t("<button/>",{type:"button",class:"btn cancel",text:Craft.t("app","Cancel")}).appendTo(this.$buttons),this.$replaceBtn=t("<button/>",{type:"button",class:"btn submit save replace",text:Craft.t("app","Save")}).appendTo(this.$buttons),this.settings.allowSavingAsNew&&(this.$saveBtn=t("<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:e},t.proxy(this,"loadEditor"))},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(e){e.html||alert(Craft.t("app","Could not load the image editor.")),this.$body.html(e.html),this.$tabs=t(".tabs li",this.$body),this.$viewsContainer=t(".views",this.$body),this.$views=t("> div",this.$viewsContainer),this.$imageTools=t(".image-container .image-tools",this.$body),this.$editorContainer=t(".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=t("#cropping-canvas",this.$editorContainer),this.$croppingCanvas.width(this.editorWidth),this.$croppingCanvas.height(this.editorHeight),this.canvas.enableRetinaScaling=!0,this.renderImage=function(){Garnish.requestAnimationFrame(this.canvas.renderAll.bind(this.canvas))}.bind(this);var i=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});fabric.Image.fromURL(i,t.proxy((function(t){this.image=t,this.image.set({originX:"center",originY:"center",left:this.editorWidth/2,top:this.editorHeight/2}),this.canvas.add(this.image),this.originalHeight=this.image.getHeight(),this.originalWidth=this.image.getWidth(),this.zoomRatio=1,this.lastLoadedDimensions=this.getScaledImageDimensions(),this._setFittedImageVerticeCoordinates(),this._repositionEditorElements();var i={imageDimensions:this.getScaledImageDimensions(),offsetX:0,offsetY:0},s=!1;if(e.focalPoint){var a=e.focalPoint,n=i.imageDimensions.width*a.x,r=i.imageDimensions.height*a.y;i.offsetX=n-i.imageDimensions.width/2,i.offsetY=r-i.imageDimensions.height/2,s=!0}this.storeFocalPointState(i),s&&this._createFocalPoint(),this._createViewport(),this.storeCropperState(),this._addControlListeners(),this.addListener(this.$croppingCanvas,"mousemove,touchmove",this._handleMouseMove),this.addListener(this.$croppingCanvas,"mousedown,touchstart",this._handleMouseDown),this.addListener(this.$croppingCanvas,"mouseup,touchend",this._handleMouseUp),this.addListener(this.$croppingCanvas,"mouseout,touchcancel",this._handleMouseOut),this._hideSpinner(),this.renderImage(),this.$tabs.first().trigger("click")}),this))},_reloadImage:function(){if(!this.imageIsLoading){this.imageIsLoading=!0,this.maxImageSize=this.getMaxImageSize();var t=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});this.image.setSrc(t,function(t){this.originalHeight=t.getHeight(),this.originalWidth=t.getWidth(),this.lastLoadedDimensions={width:this.originalHeight,height:this.originalWidth},this.updateSizeAndPosition(),this.renderImage(),this.imageIsLoading=!1}.bind(this))}},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 e={left:this.editorWidth/2,top:this.editorHeight/2};if("crop"===this.currentView)e.width=this.editorWidth,e.height=this.editorHeight;else if(this.cropperState){var i=this.cropperState,s=this.getScaledImageDimensions().width/i.imageDimensions.width;e.width=i.width*s*this.zoomRatio,e.height=i.height*s*this.zoomRatio,this.image.set({left:this.editorWidth/2-i.offsetX*s,top:this.editorHeight/2-i.offsetY*s})}else t.extend(e,this.getScaledImageDimensions());this.viewport.set(e)}},_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(){this.addListener(this.$tabs,"click",this._handleTabClick),this.addListener(t(".focal-point"),"click",this.toggleFocalPoint),this.addListener(t(".rotate-left"),"click",(function(){this.rotateImage(-90)})),this.addListener(t(".rotate-right"),"click",(function(){this.rotateImage(90)})),this.addListener(t(".flip-vertical"),"click",(function(){this.flipImage("y")})),this.addListener(t(".flip-horizontal"),"click",(function(){this.flipImage("x")})),this.straighteningInput=new Craft.SlideRuleInput("slide-rule",{onStart:function(){this._showGrid()}.bind(this),onChange:function(t){this.straighten(t)}.bind(this),onEnd:function(){this._hideGrid(),this._cleanupFocalPointAfterStraighten()}.bind(this)}),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(t(".constraint-buttons .constraint",this.$container),"click",this._handleConstraintClick),this.addListener(t(".orientation input",this.$container),"click",this._handleOrientationClick),this.addListener(t(".constraint-buttons .custom-input input",this.$container),"keyup",this._applyCustomConstraint)},_handleConstraintClick:function(e){var i=t(e.currentTarget).data("constraint"),s=t(e.currentTarget);if(s.siblings().removeClass("active"),s.addClass("active"),"custom"==i)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(i),this.enforceCroppingConstraint()},_handleOrientationClick:function(e){if(e.currentTarget.value!==this.constraintOrientation){this.constraintOrientation=e.currentTarget.value;for(var i=t(".constraint.flip",this.$container),s=0;s<i.length;s++){var a=t(i[s]);a.data("constraint",1/a.data("constraint")),a.html(a.html().split(":").reverse().join(":"))}i.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 e=parseFloat(t(".custom-constraint-w").val()),i=parseFloat(t(".custom-constraint-h").val());return{w:isNaN(e)?0:e,h:isNaN(i)?0:i}},_setCustomConstraint:function(e,i){t(".custom-constraint-w").val(parseFloat(e)),t(".custom-constraint-h").val(parseFloat(i))},_hideCustomConstraint:function(){this.showingCustomConstraint=!1,t(".constraint.custom .custom-input",this.$container).addClass("hidden"),t(".constraint.custom .custom-label",this.$container).removeClass("hidden"),t(".orientation",this.$container).removeClass("hidden")},_showCustomConstraint:function(){this.showingCustomConstraint||(this.showingCustomConstraint=!0,t(".constraint.custom .custom-input",this.$container).removeClass("hidden"),t(".constraint.custom .custom-label",this.$container).addClass("hidden"),t(".orientation",this.$container).addClass("hidden"))},_handleTabClick:function(e){if(!this.animationInProgress){var i=t(e.currentTarget),s=i.data("view");this.$tabs.removeClass("selected"),i.addClass("selected"),this.showView(s)}},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){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 e,i=this.image.angle+t,s=this.getScaledImageDimensions();e=this.hasOrientationChanged()?this.getZoomToCoverRatio({height:s.width,width:s.height}):this.getZoomToCoverRatio(s),this.zoomRatio>e&&(e=this.zoomRatio);var a={angle:90===t?"+=90":"-=90"},n={angle:i,width:s.width*e,height:s.height*e},r=1;this.scaleFactor<1?(r=1/this.scaleFactor,this.scaleFactor=1):(this.viewport.width>this.editorHeight?r=this.editorHeight/this.viewport.width:this.viewport.height>this.editorWidth&&(r=this.editorWidth/this.viewport.height),this.scaleFactor=r),r<1&&(n.width*=r,n.height*=r);var o=this.cropperState,l=o.offsetX,h=o.offsetY,d=t*(Math.PI/180),c=l*Math.cos(d)-h*Math.sin(d),u=l*Math.sin(d)+h*Math.cos(d),p=s.width/o.imageDimensions.width,g=c*p*this.zoomRatio*this.scaleFactor,f=u*p*this.zoomRatio*this.scaleFactor;n.left=this.editorWidth/2-g,n.top=this.editorHeight/2-f,o.offsetX=c,o.offsetY=u;var m=o.width;o.width=o.height,o.height=m,this.storeCropperState(o),this.focalPoint&&this.canvas.remove(this.focalPoint),this.viewport.animate(a,{duration:this.settings.animationDuration,onComplete:function(){var t=this.viewport.height*r;this.viewport.height=this.viewport.width*r,this.viewport.width=t,this.viewport.set({angle:0})}.bind(this)}),this.image.animate(n,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){var e=parseFloat((this.image.angle+360)%360);this.image.set({angle:e}),this.animationInProgress=!1,this.focalPoint?(this._adjustFocalPointByAngle(t),this.straighten(this.straighteningInput),this.canvas.add(this.focalPoint)):this._resetFocalPointPosition()}.bind(this)})}},flipImage:function(t){if(!this.animationInProgress){this.animationInProgress=!0,this.hasOrientationChanged()&&(t="y"===t?"x":"y"),this.focalPoint?this.canvas.remove(this.focalPoint):this._resetFocalPointPosition();var e={x:this.editorWidth/2,y:this.editorHeight/2};this.straighteningInput.setValue(-this.imageStraightenAngle),this.imageStraightenAngle=-this.imageStraightenAngle;var i,s,a={angle:this.viewportRotation+this.imageStraightenAngle},n=this.cropperState,r=this.focalPointState;"y"===t&&this.hasOrientationChanged()||"y"!==t&&!this.hasOrientationChanged()?(n.offsetX=-n.offsetX,r.offsetX=-r.offsetX,s=this.image.left-e.x,a.left=e.x-s):(n.offsetY=-n.offsetY,r.offsetY=-r.offsetY,i=this.image.top-e.y,a.top=e.y-i),"y"===t?(a.scaleY=-1*this.image.scaleY,this.flipData.y=1-this.flipData.y):(a.scaleX=-1*this.image.scaleX,this.flipData.x=1-this.flipData.x),this.storeCropperState(n),this.storeFocalPointState(r),this.image.animate(a,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){this.animationInProgress=!1,this.focalPoint&&(this._adjustFocalPointByAngle(0),this.canvas.add(this.focalPoint))}.bind(this)})}},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(e){var i=t(e.currentTarget);if(i.hasClass("disabled"))return!1;t(".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){this.$buttons.find(".btn").removeClass("disabled").end().find(".spinner").remove(),t.error?alert(t.error):(this.onSave(),this.hide(),Craft.cp.runQueue())}.bind(this))},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(),t("html").addClass("noscroll")},hide:function(){this.removeAllListeners(),this.straighteningInput.removeAllListeners(),t("html").removeClass("noscroll"),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.getScaledImageDimensions();this.zoomRatio=this.getZoomToFitRatio(t);var e={width:this.editorWidth,height:this.editorHeight},i={width:t.width*this.zoomRatio,height:t.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},s=function(){this._setFittedImageVerticeCoordinates();var t=this.cropperState,e=this.getScaledImageDimensions(),i=e.width/t.imageDimensions.width,s={left:this.image.left+t.offsetX*i*this.zoomRatio,top:this.image.top+t.offsetY*i*this.zoomRatio,width:t.width*i*this.zoomRatio,height:t.height*i*this.zoomRatio};this._showCropper(s),this.focalPoint&&(i=e.width/this.focalPointState.imageDimensions.width,this.focalPoint.left=this.image.left+this.focalPointState.offsetX*i*this.zoomRatio,this.focalPoint.top=this.image.top+this.focalPointState.offsetY*i*this.zoomRatio,this.canvas.add(this.focalPoint))}.bind(this);this._editorModeTransition(s,i,e)},disableCropMode:function(){var t={};this._hideCropper();var e=this.getScaledImageDimensions(),i=this.getZoomToCoverRatio(e)*this.scaleFactor,s=i/this.zoomRatio;this.zoomRatio=i;var a={width:e.width*this.zoomRatio,height:e.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},n=(this.clipper.left-this.image.left)*s,r=(this.clipper.top-this.image.top)*s;a.left=this.editorWidth/2-n,a.top=this.editorHeight/2-r,t.height=this.clipper.height*s,t.width=this.clipper.width*s,(!this.focalPoint||this.focalPoint&&!this._isCenterInside(this.focalPoint,this.clipper))&&(this.focalPoint&&this.toggleFocalPoint(),this._resetFocalPointPosition());var o=function(){if(this.focalPoint){var t=this.getScaledImageDimensions().width/this.focalPointState.imageDimensions.width;this.focalPoint.left=this.image.left+this.focalPointState.offsetX*t*this.zoomRatio,this.focalPoint.top=this.image.top+this.focalPointState.offsetY*t*this.zoomRatio,this.canvas.add(this.focalPoint)}}.bind(this);this._editorModeTransition(o,a,t)},_editorModeTransition:function(t,e,i){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(),this.animationInProgress=!1,this.renderImage()}.bind(this)}),this.viewport.animate(i,{duration:this.settings.animationDuration}))},_showSpinner:function(){this.$spinnerCanvas=t('<canvas id="spinner-canvas"></canvas>').appendTo(t(".image",this.$container));var e=document.getElementById("spinner-canvas").getContext("2d"),i=new Date,s=e.canvas.width,a=e.canvas.height;this.spinnerInterval=window.setInterval((function(){var t=parseInt((new Date-i)/1e3*16)/16;e.save(),e.clearRect(0,0,s,a),e.translate(s/2,a/2),e.rotate(2*Math.PI*t);for(var n=0;n<16;n++)e.beginPath(),e.rotate(2*Math.PI/16),e.moveTo(s/10,0),e.lineTo(s/4,0),e.lineWidth=s/30,e.strokeStyle="rgba(255,255,255,"+n/16+")",e.stroke();e.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.remove(this.croppingAreaText),this.croppingCanvas=null,this.renderCropper=null)},_setupCropperLayer:function(e){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(){Garnish.requestAnimationFrame(this.croppingCanvas.renderAll.bind(this.croppingCanvas))}.bind(this),t("#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}),e&&this.clipper.set(e),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.croppingCanvas.remove(this.croppingAreaText)),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.croppingAreaText=new fabric.Textbox(Math.round(this.clipper.width)+" x "+Math.round(this.clipper.height),{left:this.croppingRectangle.left,top:this._redrawCropperElements._.cropTextTop,fontSize:13,fill:"rgb(200,200,200)",backgroundColor:this._redrawCropperElements._.cropTextBackgroundColor,font:"Craft",width:70,height:15,originX:"center",originY:"center",textAlign:"center"}),this.croppingCanvas.add(this.cropperHandles),this.croppingCanvas.add(this.cropperGrid),this.croppingCanvas.add(this.croppingRectangle),this.croppingCanvas.add(this.croppingAreaText)},_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(){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(){this._redrawCropperElements(),this.croppingCanvas.renderAll()}.bind(this),duration:this.settings.animationDuration,onComplete:function(){this._redrawCropperElements(),this.animationInProgress=!1,this.renderCropper(),this.storeCropperState()}.bind(this)}))},_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(e){void 0===this._setMouseCursor._&&(this._setMouseCursor._={}),Garnish.isMobileBrowser(!0)||(this._setMouseCursor._.cursor="default",this._setMouseCursor._.handle=this.croppingCanvas&&this._cropperHandleHitTest(e),this.focalPoint&&this._isMouseOver(e,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(e,this.clipper)&&(this._setMouseCursor._.cursor="move"),t(".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:t.noop,allowDegreeFractions:null}}),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:{},_uploadedAssetIds:[],_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(e,i,s){this.base(e,i,s),"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",t.proxy(this,"_positionProgressBar")))},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(){if(!this._folderDrag){this.settings.selectable=!0,this.settings.multiSelect=!0;var e=t.proxy(this,"_onDragStart"),i=t.proxy(this,"_onDropTargetChange");this._assetDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,filter:t.proxy((function(){return this.view.getSelectedElements().has("div.element[data-movable]")}),this),helper:t.proxy((function(t){return this._getFileDragHelper(t)}),this),dropTargets:t.proxy((function(){var t;t=this._assetDrag.$draggee&&this._assetDrag.$draggee.has(".element[data-peer-file]").length?"data-can-move-peer-files-to":"data-can-move-to";for(var e=[],i=0;i<this.$sources.length;i++){var s=this.$sources.eq(i);Garnish.hasAttr(s,t)&&e.push(s)}return e}),this),onDragStart:e,onDropTargetChange:i,onDragStop:t.proxy(this,"_onFileDragStop"),helperBaseZindex:800}),this._folderDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,filter:t.proxy((function(){for(var e=this.sourceSelect.getSelectedItems(),i=[],s=0;s<e.length;s++){var a=e.eq(s);this._getFolderUidFromSourceKey(a.data("key"))&&(a.hasClass("sel")&&this._getSourceLevel(a)>1&&i.push(a.parent()[0]))}return t(i)}),this),helper:t.proxy((function(e){var i=t('<div class="sidebar" style="padding-top: 0; padding-bottom: 0;"/>'),s=t("<nav/>").appendTo(i),a=t("<ul/>").appendTo(s);return e.appendTo(a).removeClass("expanded"),e.children("a").addClass("sel"),e.css({"padding-top":this._folderDrag.$draggee.css("padding-top"),"padding-right":this._folderDrag.$draggee.css("padding-right"),"padding-bottom":this._folderDrag.$draggee.css("padding-bottom"),"padding-left":this._folderDrag.$draggee.css("padding-left")}),i}),this),dropTargets:t.proxy((function(){var e=[],i=[];this._folderDrag.$draggee.find("a[data-key]").each((function(){i.push(t(this).data("key"))}));for(var s=0;s<this.$sources.length;s++){var a=this.$sources.eq(s),n=a.data("key");this._getFolderUidFromSourceKey(n)&&(Craft.inArray(n,i)||e.push(a))}return e}),this),onDragStart:e,onDropTargetChange:i,onDragStop:t.proxy(this,"_onFolderDragStop")})}},_onFileDragStop:function(){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}});var o=t.proxy((function(a){this.promptHandler.resetPrompts();for(var n=0;n<a.length;n++){var r=a[n];r.conflict&&this.promptHandler.addPrompt({assetId:r.assetId,suggestedFilename:r.suggestedFilename,prompt:{message:r.conflict,choices:this._fileConflictTemplate.choices}}),r.error&&alert(r.error)}this.setIndexAvailable(),this.progressBar.hideProgressBar();var l=!1,h=function(){this.sourceSelect.selectItem(e),this._totalVisible-=this._assetDrag.$draggee.length;for(var a=0;a<s.length;a++)t("[data-id="+s[a]+"]").remove();this.view.deselectAllElements(),this._collapseExtraExpandedFolders(i),l&&this.updateElements()};if(this.promptHandler.getPromptCount()){var d=t.proxy((function(t){for(var e=[],s=0;s<t.length;s++)"cancel"!==t[s].choice?("keepBoth"===t[s].choice&&e.push({action:"assets/move-asset",params:{folderId:i,assetId:t[s].assetId,filename:t[s].suggestedFilename}}),"replace"===t[s].choice&&e.push({action:"assets/move-asset",params:{folderId:i,assetId:t[s].assetId,force:!0}})):l=!0;0===e.length?h.apply(this):(this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(this.promptHandler.getPromptCount()),this.progressBar.showProgressBar(),this._performBatchRequests(e,o))}),this);this._assetDrag.fadeOutHelpers(),this.promptHandler.showBatchPrompts(d)}else h.apply(this),this._assetDrag.fadeOutHelpers()}),this);return void this._performBatchRequests(r,o)}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._assetDrag.returnHelpersToDraggees()},_onFolderDragStop:function(){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="",l=function(e){this.promptHandler.resetPrompts();for(var s=0;s<e.length;s++){var a=e[s];a.success&&(a.transferList&&(r=a.transferList),a.newFolderId&&(o=this._folderDrag.$activeDropTarget.data("key")+"/folder:"+a.newFolderUid)),a.conflict&&(a.prompt={message:a.conflict,choices:this._folderConflictTemplate.choices},this.promptHandler.addPrompt(a)),a.error&&alert(a.error)}if(this.promptHandler.getPromptCount()){var n=t.proxy((function(e){this.promptHandler.resetPrompts();for(var s=[],n={},h=0;h<e.length;h++)"cancel"!==e[h].choice&&("replace"===e[h].choice&&(n.force=!0),"merge"===e[h].choice&&(n.merge=!0),n.folderId=a.folderId,n.parentId=a.parentId,s.push({action:"assets/move-folder",params:n}));0===s.length?t.proxy(this,"_performActualFolderMove",r,i,o)():(this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(this.promptHandler.getPromptCount()),this.progressBar.showProgressBar(),this._performBatchRequests(s,l))}),this);this.promptHandler.showBatchPrompts(n),this.setIndexAvailable(),this.progressBar.hideProgressBar()}else t.proxy(this,"_performActualFolderMove",r,i,o)()}.bind(this);return void this._performBatchRequests(n,l)}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._folderDrag.returnHelpersToDraggees()},_performActualFolderMove:function(t,e,i){this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(1),this.progressBar.showProgressBar();var s=function(t){for(var e=0,s=t.length,a=0;a<t.length;a++)Craft.postActionRequest("assets/delete-folder",{folderId:t[a]},function(){++e===s&&(this.setIndexAvailable(),this.progressBar.hideProgressBar(),this._folderDrag.returnHelpersToDraggees(),this.setInstanceState("selectedSource",i),this.refreshSources())}.bind(this))}.bind(this);if(t.length>0){for(var a=[],n=0;n<t.length;n++)a.push({action:"assets/move-asset",params:t[n]});this._performBatchRequests(a,(function(){s(e)}))}else s(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(e){for(var i=this._getSourceByKey(e),s=i.parent().parents("li"),a=0;a<s.length;a++){var n=t(s[a]);n.hasClass("expanded")||n.children(".toggle").trigger("click")}this.selectSource(i),this.updateElements()},afterInit:function(){this.$uploadButton||(this.$uploadButton=t("<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=t('<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:t.proxy(this,"_onUploadStart"),fileuploadprogressall:t.proxy(this,"_onUploadProgress"),fileuploaddone:t.proxy(this,"_onUploadComplete")},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",t.proxy((function(){this.$uploadButton.hasClass("disabled")||this.isIndexBusy||this.$uploadButton.parent().find("input[name=assets-upload]").trigger("click")}),this)),this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultVolumeHandle)for(var e=0;e<this.$sources.length;e++){var i=t(this.$sources[e]);if(i.data("volume-handle")===defaultVolumeHandle)return i.data("key")}return this.base()},onSelectSource:function(){var t=this._getSourceByKey(this.sourceKey);if(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"),"index"===this.settings.context&&"undefined"!=typeof history){var e="assets",i=this._getRootSource(t);i&&i.data("volume-handle")&&(e+="/"+i.data("volume-handle")),history.replaceState({},"",Craft.getUrl(e))}this.base()},_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 e="includeSubfolders-"+Math.floor(1e9*Math.random());this.$includeSubfoldersContainer=t('<div style="margin-bottom: -25px; opacity: 0;"/>').insertAfter(this.$search);var i=t('<div style="padding-top: 5px;"/>').appendTo(this.$includeSubfoldersContainer);this.$includeSubfoldersCheckbox=t('<input type="checkbox" id="'+e+'" class="checkbox"/>').appendTo(i),t('<label class="light smalltext" for="'+e+'"/>').text(" "+Craft.t("app","Search in subfolders")).appendTo(i),this.addListener(this.$includeSubfoldersCheckbox,"change",(function(){this.setSelecetedSourceState("includeSubfolders",this.$includeSubfoldersCheckbox.prop("checked")),this.updateElements()}))}else this.$includeSubfoldersContainer.velocity("stop");var s=this.getSelectedSourceState("includeSubfolders",!1);this.$includeSubfoldersCheckbox.prop("checked",s),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(e,i){var s=i.result,a=i.files[0].name,n=!0;s.success||s.conflict?(this._uploadedAssetIds.push(s.assetId),s.conflict&&(s.prompt={message:Craft.t("app",s.conflict,{file:s.filename}),choices:this._fileConflictTemplate.choices},this.promptHandler.addPrompt(s)),Craft.cp.runQueue()):(s.error?alert(Craft.t("app","Upload failed. The error message was: “{error}”",{error:s.error})):alert(Craft.t("app","Upload failed for {filename}.",{filename:a})),n=!1),this.uploader.isLastUpload()&&(this.setIndexAvailable(),this.progressBar.hideProgressBar(),this.promptHandler.getPromptCount()?this.promptHandler.showBatchPrompts(t.proxy(this,"_uploadFollowup")):n&&this._updateAfterUpload())},_updateAfterUpload:function(){"index"!==this.settings.context&&(this.setSortAttribute("dateModified"),this.setSortDirection("desc")),this.updateElements()},_uploadFollowup:function(t){this.setIndexBusy(),this.progressBar.resetProgressBar(),this.promptHandler.resetPrompts();var e=function(){this.setIndexAvailable(),this.progressBar.hideProgressBar(),this._updateAfterUpload()}.bind(this);this.progressBar.setItemCount(t.length);var i=function(t,e,s){var a={},n=null,r=function(a,n){"success"===n&&a.assetId?this._uploadedAssetIds.push(a.assetId):a.error&&alert(a.error),e++,this.progressBar.incrementProcessedItemCount(1),this.progressBar.updateProgressBar(),e===t.length?s():i(t,e,s)}.bind(this);"replace"===t[e].choice?(n="assets/replace-file",a.sourceAssetId=t[e].assetId,t[e].conflictingAssetId?a.assetId=t[e].conflictingAssetId:a.targetFilename=t[e].filename):"cancel"===t[e].choice&&(n="assets/delete-asset",a.assetId=t[e].assetId),n?Craft.postActionRequest(n,a,r):r({assetId:t[e].assetId},"success")}.bind(this);this.progressBar.showProgressBar(),i(t,0,e)},onUpdateElements:function(){this._onUpdateElements(!1,this.view.getAllElements()),this.view.on("appendElements",t.proxy((function(t){this._onUpdateElements(!0,t.newElements)}),this)),this.base()},_onUpdateElements:function(t,e){if("index"===this.settings.context&&(t||this._assetDrag.removeAllItems(),this._assetDrag.addItems(e.has("div.element[data-movable]"))),this._uploadedAssetIds.length){if(this.view.settings.selectable)for(var i=0;i<this._uploadedAssetIds.length;i++)this.view.selectElementById(this._uploadedAssetIds[i]);this._uploadedAssetIds=[]}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(e){var i=t(e.item).find(".element");Craft.PreviewFileModal.openInstance&&i.length&&this._loadPreview(i)},_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(e){var i,s;switch(this.getSelectedSourceState("mode")){case"table":i=t('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),s=t('<div class="tableview"/>').appendTo(i);var a=t('<table class="data"/>').appendTo(s),n=t("<tbody/>").appendTo(a);e.appendTo(n),this._$firstRowCells=this.view.$table.children("tbody").children("tr:first").children();for(var r=e.children(),o=0;o<r.length;o++){var l=t(r[o]);if(l.hasClass("checkbox-cell"))l.remove(),i.css("margin-"+Craft.left,19);else{var h=t(this._$firstRowCells[o]),d=h.width();h.width(d),l.width(d)}}return i;case"thumbs":return i=t('<div class="elements thumbviewhelper"/>').appendTo(Garnish.$bod),s=t('<ul class="thumbsview"/>').appendTo(i),e.appendTo(s),i}return t()},_onDropTargetChange:function(e){if(clearTimeout(this._expandDropTargetFolderTimeout),e){var i=e.data("folder-id");i?(this.dropTargetFolder=this._getSourceByKey(i),this._hasSubfolders(this.dropTargetFolder)&&!this._isExpanded(this.dropTargetFolder)&&(this._expandDropTargetFolderTimeout=setTimeout(t.proxy(this,"_expandFolder"),500))):this.dropTargetFolder=null}e&&e[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(e){if(this._getFolderUidFromSourceKey(e.data("key"))){var i=[{label:Craft.t("app","New subfolder"),onClick:t.proxy(this,"_createSubfolder",e)}];"index"===this.settings.context&&this._getSourceLevel(e)>1&&(i.push({label:Craft.t("app","Rename folder"),onClick:t.proxy(this,"_renameFolder",e)}),i.push({label:Craft.t("app","Delete folder"),onClick:t.proxy(this,"_deleteFolder",e)})),new Garnish.ContextMenu(e,i,{menuClass:"menu"})}},_createSubfolder:function(e){var i=prompt(Craft.t("app","Enter the name of the folder"));if(i){var s={parentId:e.data("folder-id"),folderName:i};this.setIndexBusy(),Craft.postActionRequest("assets/create-folder",s,t.proxy((function(i,s){if(this.setIndexAvailable(),"success"===s&&i.success){this._prepareParentForChildren(e);var a=t('<li><a data-key="'+e.data("key")+"/folder:"+i.folderUid+'"'+(Garnish.hasAttr(e,"data-has-thumbs")?" data-has-thumbs":"")+' data-folder-id="'+i.folderId+'"'+(Garnish.hasAttr(e,"data-can-upload")?" data-can-upload":"")+(Garnish.hasAttr(e,"data-can-move-to")?" data-can-move-to":"")+(Garnish.hasAttr(e,"data-can-move-peer-files-to")?" data-can-move-peer-files-to":"")+">"+i.folderName+"</a></li>"),n=a.children("a:first");this._appendSubfolder(e,a),this.initSource(n)}"success"===s&&i.error&&alert(i.error)}),this))}},_deleteFolder:function(e){if(confirm(Craft.t("app","Really delete folder “{folder}”?",{folder:t.trim(e.text())}))){var i={folderId:e.data("folder-id")};this.setIndexBusy(),Craft.postActionRequest("assets/delete-folder",i,t.proxy((function(t,i){if(this.setIndexAvailable(),"success"===i&&t.success){var s=this._getParentSource(e);this.deinitSource(e),e.parent().remove(),this._cleanUpTree(s)}"success"===i&&t.error&&alert(t.error)}),this))}},_renameFolder:function(e){var i=t.trim(e.text()),s=prompt(Craft.t("app","Rename folder"),i);if(s&&s!==i){var a={folderId:e.data("folder-id"),newName:s};this.setIndexBusy(),Craft.postActionRequest("assets/rename-folder",a,t.proxy((function(t,i){this.setIndexAvailable(),"success"===i&&t.success&&(e.text(t.newName),this._getFolderUidFromSourceKey(this.sourceSelect.$selectedItems.data("key"))===this._getFolderUidFromSourceKey(e.data("key"))&&this.updateElements()),"success"===i&&t.error&&alert(t.error)}),this),"json")}},_prepareParentForChildren:function(t){this._hasSubfolders(t)||(t.parent().addClass("expanded").append('<div class="toggle"></div><ul></ul>'),this.initSourceToggle(t))},_appendSubfolder:function(e,i){for(var s=e.siblings("ul").children("li"),a=t.trim(i.children("a:first").text()),n=!1,r=0;r<s.length;r++){var o=t(s[r]);if(t.trim(o.children("a:first").text())>a){o.before(i),n=!0;break}}n||e.siblings("ul").append(i)},_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 e=t(),i=0,s=0;"index"===this.settings.context?(e=this.progressBar.$progressBar.closest("#content"),i=Garnish.$win.scrollTop()):(e=this.progressBar.$progressBar.closest(".main"),i=this.$main.scrollTop());var a=i-e.offset().top,n=Garnish.$win.height();s=e.height()>n?n/2-6+a:e.height()/2-6,"index"!==this.settings.context&&(s=i+(e.height()/2-6)),this.progressBar.$progressBar.css({top:s})},_performBatchRequests:function(t,e){for(var i=[],s=function(s){Craft.postActionRequest(s.action,s.params,function(s,a){this.progressBar.incrementProcessedItemCount(1),this.progressBar.updateProgressBar(),"success"===a&&(i.push(s),Craft.cp.runQueue()),i.length>=t.length&&e(i)}.bind(this))}.bind(this),a=0;a<t.length;a++)s(t[a])}}),Craft.registerElementIndexClass("craft\\elements\\Asset",Craft.AssetIndex),Craft.AssetSelectInput=Craft.BaseElementSelectInput.extend({requestId:0,hud:null,$uploadBtn:null,uploader:null,progressBar:null,originalFilename:"",originalExtension:"",init:function(){arguments.length>0&&"object"==typeof arguments[0]&&(arguments[0].editorSettings={onShowHud:t.proxy(this.resetOriginalFilename,this),onCreateForm:t.proxy(this._renameHelper,this),validators:[t.proxy(this.validateElementForm,this)]}),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(e){var i=t(e.item);Craft.PreviewFileModal.openInstance&&i.length&&this._loadPreview(i)},_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(){this.progressBar=new Craft.ProgressBar(t('<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=t("<button/>",{type:"button",class:"btn dashed","data-icon":"upload",text:1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files")}).insertAfter(this.$addElementBtn),e.fileInput=t("<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=t.proxy(this,"canAddMoreFiles"),e.events={},e.events.fileuploadstart=t.proxy(this,"_onUploadStart"),e.events.fileuploadprogressall=t.proxy(this,"_onUploadProgress"),e.events.fileuploaddone=t.proxy(this,"_onUploadComplete"),this.uploader=new Craft.Uploader(this.$container,e),this.$uploadBtn&&this.$uploadBtn.on("click",t.proxy((function(t){this.$uploadBtn.next("input[type=file]").trigger("click")}),this))},refreshThumbnail:function(e){var i={elementId:e,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=this.$elements.filter('[data-id="'+e+'"]');s.find(".elementthumb").replaceWith(t(i.html).find(".elementthumb")),this.thumbLoader.load(s)}}.bind(this))},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(e,i){if(i.result.error)alert(i.result.error);else{var s={elementId:i.result.assetId,siteId:this.settings.criteria.siteId,size:this.settings.viewMode};Craft.postActionRequest("elements/get-element-html",s,function(e){if(e.error)alert(e.error);else{var i=t(e.html);Craft.appendHeadHtml(e.headHtml),this.selectUploadedFile(Craft.getElementInfo(i))}this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"),window.draftEditor&&window.draftEditor.checkForm())}.bind(this)),Craft.cp.runQueue()}},canAddMoreFiles:function(t){return!this.settings.limit||this.$elements.length+t<this.settings.limit},_parseFilename:function(t){var e=t.split("."),i="";return e.length>1&&(i=e.pop()),{extension:i,baseFileName:e.join(".")}},_renameHelper:function(e){t(".renameHelper",e).on("focus",t.proxy((function(t){var e=t.currentTarget,i=this._parseFilename(e.value);""===this.originalFilename&&""===this.originalExtension&&(this.originalFilename=i.baseFileName,this.originalExtension=i.extension);var s=i.baseFileName.length;if(void 0!==e.selectionStart)e.selectionStart=0,e.selectionEnd=s;else if(document.selection&&document.selection.createRange){e.select();var a=document.selection.createRange();a.collapse(!0),a.moveEnd("character",s),a.moveStart("character",0),a.select()}}),this))},resetOriginalFilename:function(){this.originalFilename="",this.originalExtension=""},validateElementForm:function(){var e=t(".renameHelper",this.elementEditor.hud.$hud.data("elementEditor").$form),i=this._parseFilename(e.val());return i.extension===this.originalExtension||(""===i.extension?this.originalFilename!==i.baseFileName?(e.val(i.baseFileName+"."+this.originalExtension),!0):confirm(Craft.t("app","Are you sure you want to remove the extension “.{ext}”?",{ext:this.originalExtension})):confirm(Craft.t("app","Are you sure you want to change the extension from “.{oldExt}” to “.{newExt}”?",{oldExt:this.originalExtension,newExt:i.extension})))}}),Craft.AssetSelectorModal=Craft.BaseElementSelectorModal.extend({$selectTransformBtn:null,_selectedTransform:null,init:function(e,i){i=t.extend({},Craft.AssetSelectorModal.defaults,i),this.base(e,i),i.transforms.length&&this.createSelectTransformButton(i.transforms)},createSelectTransformButton:function(e){if(e&&e.length){var i=t('<div class="btngroup"/>').appendTo(this.$primaryButtons);this.$selectBtn.appendTo(i),this.$selectTransformBtn=t("<button/>",{type:"button",class:"btn menubtn disabled",text:Craft.t("app","Select transform")}).appendTo(i);for(var s=t('<div class="menu" data-align="right"></div>').insertAfter(this.$selectTransformBtn),a=t("<ul></ul>").appendTo(s),n=0;n<e.length;n++)t('<li><a data-transform="'+e[n].handle+'">'+e[n].name+"</a></li>").appendTo(a);var r=new Garnish.MenuBtn(this.$selectTransformBtn,{onOptionSelect:t.proxy(this,"onSelectTransform")});r.disable(),this.$selectTransformBtn.data("menuButton",r)}},onSelectionChange:function(e){var i=this.elementIndex.getSelectedElements(),s=!1;if(i.length&&this.settings.transforms.length){s=!0;for(var a=0;a<i.length&&t(".element.hasthumb:first",i[a]).length;a++);}var n=null;this.$selectTransformBtn&&(n=this.$selectTransformBtn.data("menuButton")),s?(n&&n.enable(),this.$selectTransformBtn.removeClass("disabled")):this.$selectTransformBtn&&(n&&n.disable(),this.$selectTransformBtn.addClass("disabled")),this.base()},onSelectTransform:function(e){var i=t(e).data("transform");this.selectImagesWithTransform(i)},selectImagesWithTransform:function(e){void 0===Craft.AssetSelectorModal.transformUrls[e]&&(Craft.AssetSelectorModal.transformUrls[e]={});for(var i=this.elementIndex.getSelectedElements(),s=[],a=0;a<i.length;a++){var n=t(i[a]),r=Craft.getElementInfo(n).id;void 0===Craft.AssetSelectorModal.transformUrls[e][r]&&s.push(r)}s.length?(this.showFooterSpinner(),this.fetchMissingTransformUrls(s,e,t.proxy((function(){this.hideFooterSpinner(),this.selectImagesWithTransform(e)}),this))):(this._selectedTransform=e,this.selectElements(),this._selectedTransform=null)},fetchMissingTransformUrls:function(e,i,s){var a=e.pop(),n={assetId:a,handle:i};Craft.postActionRequest("assets/generate-transform",n,t.proxy((function(t,n){Craft.AssetSelectorModal.transformUrls[i][a]=!1,"success"===n&&t.url&&(Craft.AssetSelectorModal.transformUrls[i][a]=t.url),e.length?this.fetchMissingTransformUrls(e,i,s):s()}),this))},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),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(e){this.checkRemainingSessionTimer&&clearTimeout(this.checkRemainingSessionTimer),this.checkRemainingSessionTimer=setTimeout(t.proxy(this,"checkRemainingSessionTime"),1e3*e)},checkRemainingSessionTime:function(e){t.ajax({url:Craft.getActionUrl("users/session-info",e?null:"dontExtendSession=1"),type:"GET",dataType:"json",complete:t.proxy((function(t,e){"success"===e?(void 0!==t.responseJSON.csrfTokenValue&&void 0!==Craft.csrfTokenValue&&(Craft.csrfTokenValue=t.responseJSON.csrfTokenValue),this.updateRemainingSessionTime(t.responseJSON.timeout),this.submitLoginIfLoggedOut=!1):this.updateRemainingSessionTime(-1)}),this)})},updateRemainingSessionTime:function(e){this.remainingSessionTime=parseInt(e),-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(t.proxy(this,"showLoginModal"),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 e;if(this.showingLoginModal?(this.hideLoginModal(!0),e=!0):e=!1,this.showingLogoutWarningModal=!0,!this.logoutWarningModal){let e=t('<form id="logoutwarningmodal" class="modal alert fitted"/>'),i=t('<div class="body"/>').appendTo(e),s=t('<div class="buttons right"/>').appendTo(i),a=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Log out now")}).appendTo(s),n=t("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Keep me logged in")}).appendTo(s);this.$logoutWarningPara=t("<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")}e?this.logoutWarningModal.quickShow():this.logoutWarningModal.show(),this.updateLogoutWarningMessage(),this.decrementLogoutWarningInterval=setInterval(t.proxy(this,"decrementLogoutWarning"),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 e;if(this.showingLogoutWarningModal?(this.hideLogoutWarningModal(!0),e=!0):e=!1,this.showingLoginModal=!0,!this.loginModal){var i=t('<form id="loginmodal" class="modal alert fitted"/>'),s=t('<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=t('<div class="inputcontainer">').appendTo(s),n=t('<div class="flex"/>').appendTo(a),r=t('<div class="flex-grow"/>').appendTo(n),o=t("<div/>").appendTo(n),l=t('<div class="passwordwrapper"/>').appendTo(r);this.$passwordInput=t('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'"/>').appendTo(l),this.$passwordSpinner=t('<div class="spinner hidden"/>').appendTo(a),this.$loginBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Login")}).appendTo(o),this.$loginErrorPara=t('<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:t.proxy((function(){Garnish.isMobileBrowser(!0)||setTimeout(t.proxy((function(){this.$passwordInput.trigger("focus")}),this),100)}),this),onFadeOut:t.proxy((function(){this.$passwordInput.val("")}),this)}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:t.proxy((function(t){this.$passwordInput=t}),this)}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(i,"submit","login")}e?this.loginModal.quickShow():this.loginModal.show()},hideLoginModal:function(t){this.showingLoginModal=!1,this.loginModal&&(t?this.loginModal.quickHide():this.loginModal.hide())},logout:function(){t.get({url:Craft.getActionUrl("users/logout"),dataType:"json",success:t.proxy((function(){Craft.redirectTo("")}),this)})},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 e={loginName:Craft.username,password:this.$passwordInput.val()};Craft.postActionRequest("users/login",e,t.proxy((function(t,e){this.$passwordSpinner.addClass("hidden"),"success"===e?t.success?(this.hideLoginModal(),this.checkRemainingSessionTime()):(this.showLoginError(t.error),Garnish.shake(this.loginModal.$container),Garnish.isMobileBrowser(!0)||this.$passwordInput.trigger("focus")):this.showLoginError()}),this))},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}),Craft.CP=Garnish.Base.extend({authManager:null,$nav:null,$mainContainer:null,$alerts:null,$crumbs:null,$notificationContainer:null,$main:null,$primaryForm:null,$headerContainer:null,$header:null,$mainContent:null,$details:null,$tabsContainer:null,$tabsList:null,$tabs:null,$overflowTabBtn:null,$overflowTabList:null,$selectedTab:null,selectedTabIndex:null,$sidebarContainer:null,$sidebar:null,$contentContainer:null,$edition:null,$confirmUnloadForms:null,$deltaForms:null,$collapsibleTables:null,fixedHeader:!1,enableQueue:!0,totalJobs:0,jobInfo:null,displayedJobInfo:null,displayedJobInfoUnchanged:1,trackJobProgressTimeout:null,jobProgressIcon:null,checkingForUpdates:!1,forcingRefreshOnUpdatesCheck:!1,includingDetailsOnUpdatesCheck:!1,checkForUpdatesCallbacks:null,init:function(){0!==Craft.remainingSessionTime&&(this.authManager=new Craft.AuthManager),this.$nav=t("#nav"),this.$mainContainer=t("#main-container"),this.$alerts=t("#alerts"),this.$crumbs=t("#crumbs"),this.$notificationContainer=t("#notifications"),this.$main=t("#main"),this.$primaryForm=t("#main-form"),this.$headerContainer=t("#header-container"),this.$header=t("#header"),this.$mainContent=t("#main-content"),this.$details=t("#details"),this.$sidebarContainer=t("#sidebar-container"),this.$sidebar=t("#sidebar"),this.$contentContainer=t("#content-container"),this.$collapsibleTables=t("table.collapsible"),this.updateSidebarMenuLabel();let e=this.$details.find(".meta > .field > .instructions");for(let i=0;i<e.length;i++){let s=e.eq(i),a=s.siblings(".heading").children("label");t("<span/>",{class:"info",html:s.children().html()}).appendTo(a),s.remove()}if(this.$header.length&&(this.addListener(Garnish.$win,"scroll","updateFixedHeader"),this.updateFixedHeader()),Garnish.$doc.ready(t.proxy((function(){this.addListener(Garnish.$win,"resize","handleWindowResize"),this.handleWindowResize();var e=this.$notificationContainer.children(".error"),i=this.$notificationContainer.children(":not(.error)");e.delay(2*Craft.CP.notificationDuration).velocity("fadeOut"),i.delay(Craft.CP.notificationDuration).velocity("fadeOut"),Garnish.requestAnimationFrame(t.proxy(this,"initSpecialForms"))}),this)),this.$alerts.length&&this.initAlerts(),this.addListener(t("#nav-toggle"),"click","toggleNav"),this.addListener(t("#sidebar-toggle"),"click","toggleSidebar"),this.$primaryForm.length||(this.$primaryForm=t("form[data-saveshortcut]:first")),this.$primaryForm.length&&Garnish.hasAttr(this.$primaryForm,"data-saveshortcut")){let t=[],e=this.$primaryForm.data("actions");if(void 0===e)t.push([{keyCode:Garnish.S_KEY,ctrl:!0},{redirect:this.$primaryForm.data("saveshortcut-redirect"),retainScroll:Garnish.hasAttr(this.$primaryForm,"saveshortcut-scroll")}]);else for(let i=0;i<e.length;i++){let s=e[i];s.shortcut&&t.push([{keyCode:Garnish.S_KEY,ctrl:!0,shift:!!s.shift},{action:s.action,redirect:s.redirect,confirm:s.confirm,params:s.params,data:s.data,retainScroll:s.retainScroll}])}for(let e=0;e<t.length;e++)Garnish.shortcutManager.registerShortcut(t[e][0],()=>{this.submitPrimaryForm(t[e][1])})}this.initTabs();let i=Craft.getLocalStorage("scrollY");void 0!==i&&(Craft.removeLocalStorage("scrollY"),Garnish.$doc.ready(()=>{Garnish.requestAnimationFrame(()=>{window.scrollTo(0,i)})})),t.isTouchCapable()&&(this.$mainContainer.on("focus","input, textarea, .focusable-input",t.proxy(this,"_handleInputFocus")),this.$mainContainer.on("blur","input, textarea, .focusable-input",t.proxy(this,"_handleInputBlur")))},initSpecialForms:function(){if(this.$confirmUnloadForms=t("form[data-confirm-unload]"),this.$deltaForms=t("form[data-delta]"),this.$confirmUnloadForms.length){for(var e,i,s=this.$confirmUnloadForms.add(this.$deltaForms),a=0;a<s.length;a++)(e=s.eq(a)).data("initialSerializedValue")||(i="function"==typeof e.data("serializer")?e.data("serializer")():e.serialize(),e.data("initialSerializedValue",i)),this.addListener(e,"submit",(function(t){if(Garnish.hasAttr(e,"data-confirm-unload")&&this.removeListener(Garnish.$win,"beforeunload"),Garnish.hasAttr(e,"data-delta")){var i;t.preventDefault(),i="function"==typeof e.data("serializer")?e.data("serializer")():e.serialize();var s=Craft.findDeltaData(e.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"==typeof e&&t.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 e=this.$sidebar.find("a.sel:first"),i=e.children(".label");t("#selected-sidebar-item-label").text(i.length?i.text():e.text()),Garnish.$bod.removeClass("showing-sidebar")},toggleNav:function(){Garnish.$bod.toggleClass("showing-nav")},toggleSidebar:function(){Garnish.$bod.toggleClass("showing-sidebar")},initTabs:function(){if(this.$tabsList=this.$tabs=this.$overflowTabBtn=this.$overflowTabList=this.$selectedTab=this.selectedTabIndex=null,this.$tabsContainer=t("#tabs"),this.$tabsContainer.length){this.$tabsList=this.$tabsContainer.find("> ul"),this.$tabs=this.$tabsList.find("> li"),this.$overflowTabBtn=t("#overflow-tab-btn"),this.$overflowTabBtn.data("menubtn")||new Garnish.MenuBtn(this.$overflowTabBtn),this.$overflowTabList=this.$overflowTabBtn.data("menubtn").menu.$container.find("> ul");for(let t=0;t<this.$tabs.length;t++){const e=this.$tabs.eq(t);this.removeAllListeners(e);const i=e.children("a"),s=i.attr("href");s&&"#"===s.charAt(0)&&(this.addListener(i,"keydown",t=>{[Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)&&(t.preventDefault(),this.selectTab(t.currentTarget),i.focus())}),this.addListener(i,"click",t=>{t.preventDefault(),this.selectTab(t.currentTarget)}),encodeURIComponent(s.substr(1))===document.location.hash.substr(1)&&this.selectTab(i)),!this.$selectedTab&&i.hasClass("sel")&&this._selectTab(i,t)}}else this.$tabsContainer=null},selectTab:function(e){var i=t(e);if(this.$selectedTab){if(this.$selectedTab.get(0)===i.get(0))return;this.deselectTab()}i.addClass("sel");var s=i.attr("href");t(s).removeClass("hidden"),"undefined"!=typeof history&&history.replaceState(void 0,void 0,s),this._selectTab(i,this.$tabs.index(i.parent())),this.updateTabs(),this.$overflowTabBtn.data("menubtn").menu.hide()},_selectTab:function(e,i){if(e===this.$selectedTab)return;this.$selectedTab=e,this.selectedTabIndex=i,0===i?t("#content").addClass("square"):t("#content").removeClass("square"),Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll");let s=e&&e.attr("href");if(s&&"#"===s.charAt(0)){let e=t("#context-btn").menubtn().data("menubtn");if(e)for(let t=0;t<e.menu.$options.length;t++){let i=e.menu.$options[t];i.href&&(i.href=i.href.match(/^[^#]*/)[0]+s)}}},deselectTab:function(){this.$selectedTab&&(this.$selectedTab.removeClass("sel"),"#"===this.$selectedTab.attr("href").charAt(0)&&t(this.$selectedTab.attr("href")).addClass("hidden"),this._selectTab(null,null))},handleWindowResize:function(){this.updateTabs(),this.updateResponsiveTables()},updateTabs:function(){if(this.$tabsContainer){var t,e=Math.floor(this.$tabsContainer.width())-40,i=0,s=!1,a=Garnish.$bod.width()>=768?-12:-7;this.$selectedTab&&(this.$selectedTab.parent("li").appendTo(this.$tabsList),i=Math.ceil(this.$selectedTab.parent("li").width()));for(var n=0;n<this.$tabs.length;n++)if(t=this.$tabs.eq(n).appendTo(this.$tabsList),n!==this.selectedTabIndex&&(i+=Math.ceil(t.width()),(0!==n||this.$selectedTab)&&(i+=a)),n===this.selectedTabIndex||i<=e)t.find("> a").removeAttr("role").removeAttr("tabindex");else{const e=t.appendTo(this.$overflowTabList).find("> a");this.$overflowTabBtn.data("menubtn").menu.addOptions(e),s=!0}s?this.$overflowTabBtn.removeClass("hidden"):this.$overflowTabBtn.addClass("hidden")}},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.$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(e,i){var s=Craft.CP.notificationDuration;"error"===e&&(s*=2);var a=t('<div class="notification '+e+'">'+i+"</div>").appendTo(this.$notificationContainer),n=-a.outerWidth()/2+"px";a.hide().css({opacity:0,"margin-left":n,"margin-right":n}).velocity({opacity:1,"margin-left":"2px","margin-right":"2px"},{display:"inline-block",duration:"fast"}).delay(s).velocity({opacity:0,"margin-left":n,"margin-right":n},{complete:function(){a.remove()}}),this.trigger("displayNotification",{notificationType:e,message:i})},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 e={path:Craft.path};Craft.queueActionRequest("app/get-cp-alerts",e,t.proxy(this,"displayAlerts"))},displayAlerts:function(e){if(this.$alerts.remove(),Garnish.isArray(e)&&e.length){this.$alerts=t('<ul id="alerts"/>').prependTo(t("#page-container"));for(var i=0;i<e.length;i++)t("<li>"+e[i]+"</li>").appendTo(this.$alerts);var s=this.$alerts.outerHeight();this.$alerts.css("margin-top",-s).velocity({"margin-top":0},"fast"),this.initAlerts()}},initAlerts:function(){for(var e=this.$alerts.find('a[class^="shun:"]'),i=0;i<e.length;i++)this.addListener(e[i],"click",t.proxy((function(e){e.preventDefault();var i=t(e.currentTarget),s={message:i.prop("className").substr(5)};Craft.queueActionRequest("app/shun-cp-alert",s,t.proxy((function(t,e){"success"===e&&(t.success?i.parent().remove():this.displayError(t.error))}),this))}),this))},checkForUpdates:function(t,e,i){if("function"==typeof e&&(i=e,e=!1),this.checkingForUpdates&&(!0===t&&!this.forcingRefreshOnUpdatesCheck||!0===e&&!this.includingDetailsOnUpdatesCheck)){var s=i;i=function(){this.checkForUpdates(t,e,s)}.bind(this)}"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(this.updateUtilitiesBadge(),this.checkingForUpdates=!1,Garnish.isArray(this.checkForUpdatesCallbacks)){var e=this.checkForUpdatesCallbacks;this.checkForUpdatesCallbacks=null;for(var i=0;i<e.length;i++)e[i](t)}this.trigger("checkForUpdates",{updateInfo:t})}.bind(this)))},_checkForUpdates:function(t,e){return new Promise(function(i,s){t?this._getUpdates(e).then((function(t){i(t)})):this._checkForCachedUpdates(e).then(function(t){!1!==t.cached&&i(t),this._getUpdates(e).then((function(t){i(t)}))}.bind(this))}.bind(this))},_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){return new Promise(function(e,i){Craft.sendApiRequest("GET","updates").then(function(i){this._cacheUpdates(i,t).then(e)}.bind(this)).catch(function(t){this._cacheUpdates({}).then(e)}.bind(this))}.bind(this))},_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 e=t("#nav-utilities").find("> a:not(.sel)");e.length&&Craft.queueActionRequest("app/get-utilities-badge-count",t.proxy((function(i){var s=e.children(".badge");i.badgeCount?(s.length||(s=t('<span class="badge"/>').appendTo(e)),s.text(i.badgeCount)):s.length&&s.remove()}),this))},runQueue:function(){this.enableQueue&&(Craft.runQueueAutomatically?Craft.queueActionRequest("queue/run",t.proxy((function(t,e){"success"===e&&this.trackJobProgress(!1,!0)}),this)):this.trackJobProgress(!1,!0))},trackJobProgress:function(e,i){if(i&&this.trackJobProgressTimeout&&(clearTimeout(this.trackJobProgressTimeout),this.trackJobProgressTimeout=null),!this.trackJobProgressTimeout&&this.enableQueue)if(!0===e){var s=Math.min(6e4,500*this.displayedJobInfoUnchanged);this.trackJobProgressTimeout=setTimeout(t.proxy(this,"_trackJobProgressInternal"),s)}else this._trackJobProgressInternal()},_trackJobProgressInternal:function(){Craft.queueActionRequest("queue/get-job-info?limit=50&dontExtendSession=1",t.proxy((function(t,e){"success"===e&&(this.trackJobProgressTimeout=null,this.totalJobs=t.total,this.setJobInfo(t.jobs),this.jobInfo.length&&this.trackJobProgress(!0))}),this))},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])return this.jobInfo[i]},updateJobIcon:function(){this.enableQueue&&this.$nav.length&&(this.displayedJobInfo?(this.jobProgressIcon||(this.jobProgressIcon=new s),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(){let 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 s=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=t("<li/>").appendTo(Craft.cp.$nav.children("ul")),this.$a=t("<a/>",{id:"job-icon",href:Craft.canAccessQueueManager?Craft.getUrl("utilities/queue-manager"):null}).appendTo(this.$li),this.$canvasContainer=t('<span class="icon"/>').appendTo(this.$a);var e=t('<span class="label"/>').appendTo(this.$a);this.$label=t("<span/>").appendTo(e),this.$progressLabel=t('<span class="progress-label"/>').appendTo(e).hide();let i=window.devicePixelRatio>1?2:1;this._canvasSize=18*i,this._arcPos=this._canvasSize/2,this._arcRadius=7*i,this._lineWidth=3*i,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(){this._animateArc(0,1,t.proxy((function(){this._$bgCanvas.velocity("fadeOut"),this._animateArc(1,1,t.proxy((function(){this.$a.remove(),this.destroy()}),this))}),this))},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(e,i){var s=t('<canvas id="job-icon-'+e+'" width="'+this._canvasSize+'" height="'+this._canvasSize+'"/>').appendTo(this.$canvasContainer),a=s[0].getContext("2d");return a.strokeStyle=i,a.lineWidth=this._lineWidth,a.lineCap="round",s},_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(t.proxy(this,"_takeNextArcStep"),50):this._arcAnimateCallback&&this._arcAnimateCallback()}});Craft.CategoryIndex=Craft.BaseElementIndex.extend({editableGroups:null,$newCategoryBtnGroup:null,$newCategoryBtn:null,init:function(e,i,s){this.on("selectSource",t.proxy(this,"updateButton")),this.on("selectSite",t.proxy(this,"updateButton")),this.base(e,i,s)},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 e=0;e<this.$sources.length;e++){var i=t(this.$sources[e]);if(i.data("handle")===defaultGroupHandle)return i.data("key")}return this.base()},updateButton:function(){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=t('<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=t('<a class="btn submit add icon" '+i+">"+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=t("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newCategoryBtnGroup))):this.$newCategoryBtn=r=t("<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>")}t(o+="</ul></div>").appendTo(this.$newCategoryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",t.proxy((function(t){this._openCreateCategoryModal(t.option.getAttribute("data-id"))}),this))}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/"+t.handle+"/new";if(this.siteId&&this.siteId!=Craft.primarySiteId)for(var i=0;i<Craft.sites.length;i++)Craft.sites[i].id==this.siteId&&(e+="/"+Craft.sites[i].handle);return'href="'+Craft.getUrl(e)+'"'}return'data-id="'+t.id+'"'},_openCreateCategoryModal:function(e){if(!this.$newCategoryBtn.hasClass("loading")){for(var i,s=0;s<this.editableGroups.length;s++)if(this.editableGroups[s].id==e){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:e},onBeginLoading:t.proxy((function(){this.$newCategoryBtn.addClass("loading")}),this),onEndLoading:t.proxy((function(){this.$newCategoryBtn.removeClass("loading")}),this),onHideHud:t.proxy((function(){this.$newCategoryBtn.removeClass("inactive").text(a)}),this),onSaveElement:t.proxy((function(t){var e="group:"+i.uid;this.sourceKey!==e&&this.selectSourceByKey(e),this.selectElementAfterUpdate(t.id),this.updateElements()}),this)})}}}}),Craft.registerElementIndexClass("craft\\elements\\Category",Craft.CategoryIndex),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(e){this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<e.length;s++)i.push(e[s].id);var a={categoryIds:i,siteId:e[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,t.proxy((function(i,s){if(this.modal.enable(),this.modal.enableCancelBtn(),this.modal.enableSelectBtn(),this.modal.hideFooterSpinner(),"success"===s){var a=t(i.html).children(".elements");this.$elementsContainer.replaceWith(a),this.$elementsContainer=a,this.resetElements();for(var n=[],r=0;r<e.length;r++){var o=e[r],l=this.getElementById(o.id);l&&(this.animateElementIntoPlace(o.$element,l),n.push(o))}this.updateDisabledElementsInModal(),this.modal.hide(),this.onSelectElements(n)}}),this))},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(e,i){var s;i===e.length-1&&(s=t.proxy((function(){var t=e.first().parent().parent(),i=t.parent();i[0]===this.$elementsContainer[0]||t.siblings().length?t.remove():i.remove()}),this));var a=t.proxy((function(){this.animateElementAway(e.eq(i),s)}),this);0===i?a():setTimeout(a,100*i)}}),Craft.charts={},Craft.charts.DataTable=Garnish.Base.extend({columns:null,rows:null,init:function(e){let i=e.columns,s=e.rows;s.forEach(t.proxy((function(e){t.each(e,(function(t){var s;switch(i[t].type){case"date":s=d3.timeParse("%Y-%m-%d"),e[t]=s(e[t]);break;case"datetime":s=d3.timeParse("%Y-%m-%d %H:00:00"),e[t]=s(e[t]);break;case"percent":e[t]=e[t]/100;break;case"number":e[t]=+e[t]}}))}),this)),this.columns=i,this.rows=s}}),Craft.charts.Tip=Garnish.Base.extend({$container:null,$tip:null,init:function(e){this.$container=e,this.$tip=t('<div class="tooltip"></div>').appendTo(this.$container),this.hide()},setContent:function(t){this.$tip.html(t)},setPosition:function(t){this.$tip.css("left",t.left+"px"),this.$tip.css("top",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(e,i){this.$container=e,this.setSettings(Craft.charts.BaseChart.defaults),this.setSettings(i);var s={formats:window.d3Formats,formatLocaleDefinition:window.d3FormatLocaleDefinition,timeFormatLocaleDefinition:window.d3TimeFormatLocaleDefinition};this.setSettings(s),d3.select(window).on("resize",t.proxy((function(){this.resize()}),this))},setSettings:function(e,i){var s=void 0===this.settings?{}:this.settings;this.settings=t.extend(!0,{},s,i,e)},draw:function(e,i){this.setSettings(i),this.dataTable=e,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 s=this.chartBaseClass;this.settings.chartClass&&(s+=" "+this.settings.chartClass),this.$chart=t('<div class="'+s+'" />').appendTo(this.$container)},resize:function(){this.draw(this.dataTable,this.settings)},onAfterDrawTicks:function(){t(".tick",this.$chart).each((function(e,i){var s=t("text",i);s.clone().appendTo(i),s.attr("stroke","#ffffff"),s.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("+s.translateX+","+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, "+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("+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, "+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("+(this.width-0)+", 0)").call(i)):(i=d3.axisRight(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(0, 0)").call(i))}},drawChart:function(){var e=this.getX(!0),i=this.getY();if(this.settings.xAxis.gridlines){var s=d3.axisBottom(e);this.drawingArea.append("g").attr("class","x grid-line").attr("transform","translate(0,"+this.height+")").call(s.tickSize(-this.height,0,0).tickFormat(""))}if(this.settings.yAxis.gridlines){var a=d3.axisLeft(i);this.drawingArea.append("g").attr("class","y grid-line").attr("transform","translate(0 , 0)").call(a.tickSize(-this.width,0).tickFormat("").tickValues(this.getYTickValues()).ticks(2))}var n=d3.line().x((function(t){return e(t[0])})).y((function(t){return i(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",n);var r=d3.area().x((function(t){return e(t[0])})).y0(this.height).y1((function(t){return i(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",r),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",t.proxy((function(t,e){return"plot plot-"+e}),this)).attr("r",4).attr("cx",t.proxy((function(t){return e(t[0])}),this)).attr("cy",t.proxy((function(t){return i(t[1])}),this))},drawTipTriggers:function(){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",t.proxy((function(t){return a(t[0])-s/2}),this)).on("mouseover",t.proxy((function(e,i){this.drawingArea.select(".plot-"+i).attr("r",5);var s=t("<div />"),r=t('<div class="x-value" />').appendTo(s),o=t('<div class="y-value" />').appendTo(s);r.html(this.getXFormatter()(e[0])),o.html(this.getYFormatter()(e[1]));var l=s.get(0);this.tip.setContent(l);var h,d=this.getChartMargin(),c=n(e[1])+24;"rtl"!==this.orientation?(h=a(e[0])+d.left+24,this.$chart.offset().left+h+this.tip.$tip.width()>this.$chart.offset().left+this.$chart.width()-24&&(h=a(e[0])-(this.tip.$tip.width()+24))):h=a(e[0])-(this.tip.$tip.width()+d.left+24);h<0&&(h=a(e[0])+d.left+24);var u={top:c,left:h};this.tip.setPosition(u),this.tip.show()}),this)).on("mouseout",t.proxy((function(t,e){this.drawingArea.select(".plot-"+e).attr("r",4),this.tip.hide()}),this))}},getChartMargin:function(){var e=this.settings.margin,i=this.getYTickValues(),s=0;return t.each(i,t.proxy((function(t,e){var i=8*this.getYFormatter()(e).length;i>s&&(s=i)}),this)),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!==t.noop?this.settings.xAxis.formatter(this):Craft.charts.utils.getTimeFormatter(this.timeFormatLocale,this.settings)},getYFormatter:function(){return this.settings.yAxis.formatter!==t.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:t.noop},yAxis:{gridlines:!0,showAxis:!1,formatter:t.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"+i.hours),i.minutes<10&&(i.minutes="0"+i.minutes),i.seconds<10&&(i.seconds="0"+i.seconds),i.hours+":"+i.minutes+":"+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(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)}}},Craft.ColorInput=Garnish.Base.extend({$container:null,$input:null,$colorContainer:null,$colorPreview:null,$colorInput:null,init:function(e){this.$container=t(e),this.$input=this.$container.children(".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 e=document.createElement("input");e.setAttribute("type","color"),"color"===e.type&&(this.$colorContainer.removeClass("static"),this.$colorInput=t(e).addClass("color-preview-input").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.length&&"#"!==t?("#"!==t[0]&&(t="#"+t,this.$input.val(t)),this.$colorPreview.css("background-color",t),this.$colorInput&&this.$colorInput.val(t)):this.$colorPreview.css("background-color","")}},{_browserSupportsColorInputs:null,doesBrowserSupportColorInputs:function(){return Craft.ColorInput._browserSupportsColorInputs,Craft.ColorInput._browserSupportsColorInputs}}),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(e,i){this.base(),this.setSettings(i,{resizable:!0}),this.elementIndex=e,this.$elementIndexSourcesContainer=this.elementIndex.$sidebar.children("nav").children("ul");var s=t('<form class="modal customize-sources-modal"/>').appendTo(Garnish.$bod);this.$sidebar=t('<div class="cs-sidebar block-types"/>').appendTo(s),this.$sourcesContainer=t('<div class="sources">').appendTo(this.$sidebar),this.$sourceSettingsContainer=t('<div class="source-settings">').appendTo(s),this.$footer=t('<div class="footer"/>').appendTo(s),this.$footerBtnContainer=t('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footerBtnContainer),this.$saveBtn=t("<button/>",{type:"button",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(this.$footerBtnContainer),this.$saveSpinner=t('<div class="spinner hidden"/>').appendTo(this.$footerBtnContainer),this.$newHeadingBtn=t("<button/>",{type:"button",class:"btn submit add icon",text:Craft.t("app","New heading")}).appendTo(t('<div class="buttons left secondary-buttons"/>').appendTo(this.$footer)),this.$loadingSpinner=t('<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,t.proxy((function(t,e){this.$loadingSpinner.remove(),"success"===e&&(this.$saveBtn.removeClass("disabled"),this.buildModal(t))}),this)),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(e){this.availableTableAttributes=e.availableTableAttributes,this.sourceSort=new Garnish.DragSort({handle:".move",axis:"y",onSortChange:t.proxy((function(){this.updateSourcesOnSave=!0}),this)}),this.sources=[];for(var i=0;i<e.sources.length;i++){var s=this.addSource(e.sources[i]);this.sources.push(s)}this.selectedSource||void 0===this.sources[0]||this.sources[0].select()},addSource:function(e){var i,s=t('<div class="customize-sources-item"/>').appendTo(this.$sourcesContainer),a=t('<div class="label"/>').appendTo(s),n=t('<input type="hidden"/>').appendTo(s);return t('<a class="move icon" title="'+Craft.t("app","Reorder")+'" role="button"></a>').appendTo(s),void 0!==e.heading?(s.addClass("heading"),n.attr("name","sourceOrder[][heading]"),(i=new Craft.CustomizeSourcesModal.Heading(this,s,a,n,e)).updateItemLabel(e.heading)):(n.attr("name","sourceOrder[][key]").val(e.key),(i=new Craft.CustomizeSourcesModal.Source(this,s,a,n,e)).updateItemLabel(e.label),(this.elementIndex.sourceKey+"/").substr(0,e.key.length+1)===e.key+"/"&&i.select()),this.sourceSort.addItems(s),i},handleNewHeadingBtnClick:function(){var t=this.addSource({heading:""});Garnish.scrollContainerToElement(this.$sidebar,t.$item),t.select(),this.updateSourcesOnSave=!0},save:function(e){if(e&&e.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,t.proxy((function(t,e){if(this.$saveSpinner.addClass("hidden"),"success"===e&&t.success){if(this.updateSourcesOnSave&&this.$elementIndexSourcesContainer.length){for(var i,s=null,a=0;a<this.sourceSort.$items.length;a++){var n=this.sourceSort.$items.eq(a).data("source"),r=n.getIndexSource();r&&(n.isHeading()?i=r:(i&&(this.appendSource(i,s),s=i,i=null),this.appendSource(r,s),s=r))}if(s){var o=s.nextAll();this.elementIndex.sourceSelect.removeItems(o),o.remove()}}this.selectedSource&&this.selectedSource.sourceData.key&&(this.elementIndex.selectSourceByKey(this.selectedSource.sourceData.key),this.elementIndex.updateElements()),Craft.cp.displayNotice(Craft.t("app","Source settings saved")),this.hide()}else{var l="success"===e&&t.error?t.error:Craft.t("app","A server error occurred.");Craft.cp.displayError(l)}}),this))}},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 t("<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(){let e=t("<div/>").append(Craft.ui.createTextField({label:Craft.t("app","Header Column Heading"),id:"defaultHeaderColHeading"+Math.floor(1e5*Math.random()),name:`sources[${this.sourceData.key}][headerColHeading]`,value:this.sourceData.headerColHeading,placeholder:this.sourceData.defaultHeaderColHeading}));return this.sourceData.tableAttributes.length&&e.append(this.createTableColumnsField()),e},createTableColumnsField:function(){let[e,i]=this.sourceData.tableAttributes[0],s=this.createTableColumnOption(e,i,!0,!0),a=t("<div/>"),n=[e];t('<input type="hidden" name="sources['+this.sourceData.key+'][tableAttributes][]" value=""/>').appendTo(a);for(let t=1;t<this.sourceData.tableAttributes.length;t++){let[e,i]=this.sourceData.tableAttributes[t];a.append(this.createTableColumnOption(e,i,!1,!0)),n.push(e)}let r=this.modal.availableTableAttributes.slice(0);r.push(...this.sourceData.availableTableAttributes);for(let t=0;t<r.length;t++){let[e,i]=r[t];Craft.inArray(e,n)||a.append(this.createTableColumnOption(e,i,!1,!1))}return new Garnish.DragSort(a.children(),{handle:".move",axis:"y"}),Craft.ui.createField(t([s[0],a[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(e,i,s,a){var n=t('<div class="customize-sources-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(i),name:"sources["+this.sourceData.key+"][tableAttributes][]",value:e,checked:a,disabled:s}));return s&&n.children(".move").addClass("disabled"),n},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(){let e=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(e),this.$labelInput=this.$labelField.find(".text"),e.append("<hr/>"),this.$deleteBtn=t('<a class="error delete"/>').text(Craft.t("app","Delete heading")).appendTo(e),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","deleteHeading"),e},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(t.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 e=this.$labelInput?this.$labelInput.val():this.sourceData.heading;return t('<li class="heading"/>').append(t("<span/>").text(e))}}),Craft.DataTableSorter=Garnish.DragSort.extend({$table:null,init:function(e,i){this.$table=t(e);var s=this.$table.children("tbody").children(":not(.filler)");(i=t.extend({},Craft.DataTableSorter.defaults,i)).container=this.$table.children("tbody"),i.helper=t.proxy(this,"getHelper"),i.caboose="<tr/>",i.axis=Garnish.Y_AXIS,i.magnetStrength=4,i.helperLagBase=1.5,this.base(s,i)},getHelper:function(e){var i=t('<div class="'+this.settings.helperClass+'"/>').appendTo(Garnish.$bod),s=t("<table/>").appendTo(i),a=t("<tbody/>").appendTo(s);e.appendTo(a),s.width(this.$table.width()),s.prop("className",this.$table.prop("className"));for(var n=this.$table.find("tr:first").children(),r=e.children(),o=0;o<r.length;o++)t(r[o]).width(t(n[o]).width());return i}},{defaults:{handle:".move",helperClass:"datatablesorthelper"}}),Craft.DeleteUserModal=Garnish.Modal.extend({id:null,userId:null,$deleteActionRadios:null,$deleteSpinner:null,userSelect:null,_deleting:!1,init:function(e,i){this.id=Math.floor(1e9*Math.random()),this.userId=e,i=t.extend(Craft.DeleteUserModal.defaults,i);let s=t('<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+'"/>')+(i.redirect?'<input type="hidden" name="redirect" value="'+i.redirect+'"/>':"")+"</form>").appendTo(Garnish.$bod),a=t('<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(s),n=t('<div class="buttons right"/>').appendTo(a),r=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(n);if(i.contentSummary.length)for(let e=0;e<i.contentSummary.length;e++)a.find("ul").append(t("<li/>",{text:i.contentSummary[e]}));else a.find("ul").remove();var o;if(this.$deleteActionRadios=a.find("input[type=radio]"),this.$deleteSubmitBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:this._submitBtnLabel(!1)}).appendTo(n),this.$deleteSpinner=t('<div class="spinner hidden"/>').appendTo(n),Garnish.isArray(this.userId)){o=["and"];for(let t=0;t<this.userId.length;t++)o.push("not "+this.userId[t])}else o="not "+this.userId;this.userSelect=new Craft.BaseElementSelectInput({id:"transferselect"+this.id,name:"transferContentTo",elementType:"craft\\elements\\User",criteria:{id:o},limit:1,modalSettings:{closeOtherModals:!1},onSelectElements:t.proxy((function(){this.updateSizeAndPosition(),this.$deleteActionRadios.first().prop("checked")?this.validateDeleteInputs():this.$deleteActionRadios.first().trigger("click")}),this),onRemoveElements:t.proxy(this,"validateDeleteInputs"),selectable:!1,editable:!1}),this.addListener(r,"click","hide"),this.addListener(this.$deleteActionRadios,"change","validateDeleteInputs"),this.addListener(s,"submit","handleSubmit"),this.base(s,i)},_submitBtnLabel:function(t){let 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:t.noop,redirect:null}}),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,saveXhr:null,queue:null,submittingForm:!1,duplicatedElements:null,errors:null,openingPreview:!1,preview:null,previewToken:null,createdDraftInPreview:!1,init:function(e){if(this.setSettings(e,Craft.DraftEditor.defaults),this.queue=[],this.duplicatedElements={},this.enableAutosave=Craft.autosaveDrafts,this.siteIds=Object.keys(this.settings.siteStatuses).map(t=>parseInt(t)),this.$revisionBtn=t("#context-btn"),this.$revisionLabel=t("#revision-label"),this.$spinner=t("#revision-spinner"),this.$expandSiteStatusesBtn=t("#expand-status-btn"),this.$statusIcon=t("#revision-status"),this.settings.canEditMultipleSites&&this.addListener(this.$expandSiteStatusesBtn,"click","expandSiteStatuses"),this.settings.previewTargets.length){this.settings.enablePreview&&this.addListener(t("#preview-btn"),"click","openPreview");const e=t("#share-btn");1===this.settings.previewTargets.length?this.addListener(e,"click",(function(){this.openShareLink(this.settings.previewTargets[0].url)})):this.createShareMenu(e)}this.settings.revisionId||(Craft.cp.$primaryForm.data("serializer",function(){return this.serializeForm(!0)}.bind(this)),this.addListener(Craft.cp.$primaryForm,"submit","handleFormSubmit"),this.settings.draftId?this.initForDraft():(this.addListener(t("#save-draft-btn"),"click",function(t){t.preventDefault(),this.createDraft(),this.removeListener(Craft.cp.$primaryForm,"submit.saveShortcut")}.bind(this)),this.settings.canUpdateSource||this.addListener(Craft.cp.$primaryForm,"submit.saveShortcut",function(t){t.saveShortcut&&(t.preventDefault(),this.createDraft(),this.removeListener(Craft.cp.$primaryForm,"submit.saveShortcut"))}.bind(this))))},listenForChanges:function(){this.listeningForChanges||this.pauseLevel>0||!this.enableAutosave||(this.listeningForChanges=!0,this.addListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(e){t(e.target).is(this.statusIcons())||(clearTimeout(this.timeout),["keypress","keyup","change"].includes(e.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())},initForDraft:function(){this.createEditMetaBtn(),this.addListener(this.$statusIcon,"click",function(){this.showStatusHud(this.$statusIcon)}.bind(this)),this.addListener(t("#merge-changes-btn"),"click",this.mergeChanges),Craft.autosaveDrafts&&this.listenForChanges(),this.settings.canUpdateSource&&Garnish.shortcutManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0,alt:!0},()=>{Craft.submitForm(Craft.cp.$primaryForm,{action:this.settings.publishDraftAction,redirect:this.settings.hashedCpEditUrl})},0)},mergeChanges:function(){this.checkForm(),this.saving?this.queue.push(this.mergeChanges.bind(this)):(this.saving=!0,t("#merge-changes-spinner").removeClass("hidden"),Craft.postActionRequest("drafts/merge-source-changes",{elementType:this.settings.elementType,draftId:this.settings.draftId,siteId:this.settings.siteId},(function(e,i){"success"===i?window.location.reload():t("#merge-changes-spinner").addClass("hidden")})))},expandSiteStatuses:function(){this.removeListener(this.$expandSiteStatusesBtn,"click"),this.$expandSiteStatusesBtn.velocity({opacity:0},"fast",function(){this.$expandSiteStatusesBtn.remove()}.bind(this));const e=t(`#enabledForSite-${this.settings.siteId}-field`);if(this.$siteStatusPane=e.parent(),this.settings.revisionId)return void this._getOtherSupportedSites().forEach(t=>this._createSiteStatusField(t));e.addClass("nested");const 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);const s=this.settings.enabled&&!Craft.inArray(!1,this.settings.siteStatuses)?"1":this.settings.enabledForSite?"-":"",a=encodeURIComponent(`enabledForSite[${this.settings.siteId}]`)+"="+(this.settings.enabledForSite?"1":"");this.$siteLightswitches=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this)),this._getOtherSupportedSites().forEach(t=>this._createSiteStatusField(t));let n="enabled="+s;for(let t=0;t<this.$siteLightswitches.length;t++){const e=this.$siteLightswitches.eq(t).data("lightswitch").$input;n+="&"+encodeURIComponent(e.attr("name"))+"="+e.val()}Craft.cp.$primaryForm.data("initialSerializedValue",Craft.cp.$primaryForm.data("initialSerializedValue").replace(a,n)),this.settings.addlSiteIds&&this.settings.addlSiteIds.length&&this._createAddlSiteField(),this.$globalLightswitch.on("change",this._updateSiteStatuses.bind(this)),this._updateGlobalStatus()},_getOtherSupportedSites:function(){return Craft.sites.filter(t=>t.id!=this.settings.siteId&&this.siteIds.includes(t.id))},_showField:function(t){const e=t.height();t.css("overflow","hidden").height(0).velocity({height:e},"fast",()=>{t.css({overflow:"",height:""})})},_removeField:function(t){t.height();t.css("overflow","hidden").velocity({height:0},"fast",()=>{t.remove()})},_updateGlobalStatus:function(){let e=!0,i=!0;this.$siteLightswitches.each((function(){if(t(this).data("lightswitch").on?i=!1:e=!1,!e&&!i)return!1})),e?this.$globalLightswitch.data("lightswitch").turnOn(!0):i?this.$globalLightswitch.data("lightswitch").turnOff(!0):this.$globalLightswitch.data("lightswitch").turnIndeterminate(!0)},_updateSiteStatuses:function(){const e=this.$globalLightswitch.data("lightswitch").on;this.$siteLightswitches.each((function(){e?t(this).data("lightswitch").turnOn(!0):t(this).data("lightswitch").turnOff(!0)}))},_createSiteStatusField:function(t){const e=Craft.ui.createLightswitchField({id:"enabledForSite-"+t.id,label:Craft.t("app","Enabled for {site}",{site:t.name}),name:`enabledForSite[${t.id}]`,on:!this.settings.siteStatuses.hasOwnProperty(t.id)||this.settings.siteStatuses[t.id],disabled:!!this.settings.revisionId});if(this.$addlSiteField?e.insertBefore(this.$addlSiteField):e.appendTo(this.$siteStatusPane),!this.settings.revisionId){e.addClass("nested");const t=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this));this.$siteLightswitches=this.$siteLightswitches.add(t)}return this._showField(e),e},_createAddlSiteField:function(){const t=Craft.sites.filter(t=>!this.siteIds.includes(t.id)&&this.settings.addlSiteIds.includes(t.id));if(!t.length)return;const e=Craft.ui.createSelect({options:[{label:Craft.t("app","Add a site…")},...t.map(t=>({label:t.name,value:t.id}))]}).addClass("fullwidth");this.$addlSiteField=Craft.ui.createField(e,{}).addClass("nested add").appendTo(this.$siteStatusPane);const i=e.find("select");i.on("change",()=>{const t=parseInt(i.val()),e=Craft.sites.find(e=>e.id===t);e&&(this._createSiteStatusField(e),i.val("").find(`option[value="${t}"]`).remove(),null===this.newSiteIds&&(this.newSiteIds=[]),this.siteIds.push(t),this.newSiteIds.push(t),1===i.find("option").length&&this._removeField(this.$addlSiteField))}),this._showField(this.$addlSiteField)},showStatusHud:function(t){let e;null===this.errors?e="<p>"+Craft.t("app","The draft has been saved.")+"</p>":(e='<p class="error">'+Craft.t("app","The draft could not be saved.")+"</p>",this.errors.length&&(e+='<ul class="errors">'+this.errors.map(t=>`<li>${Craft.escapeHtml(t)}</li>`).join("")+"</ul>"));const i=new Garnish.HUD(t,e,{onHide:function(){i.destroy()}})},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},createEditMetaBtn:function(){this.$editMetaBtn=t("<button/>",{type:"button",class:"btn edit icon",title:Craft.t("app","Edit draft settings")}).appendTo(t("#context-btngroup")),this.addListener(this.$editMetaBtn,"click","showMetaHud")},createShareMenu:function(e){e.addClass("menubtn");const i=t("<div/>",{class:"menu"}).insertAfter(e),s=t("<ul/>").appendTo(i);this.settings.previewTargets.forEach(e=>{const i=t("<li/>").appendTo(s),a=t("<a/>",{text:e.label}).appendTo(i);this.addListener(a,"click",()=>{this.openShareLink(e.url)})})},getPreviewToken:function(){return new Promise(function(t,e){this.previewToken?t(this.previewToken):Craft.postActionRequest("preview/create-token",{elementType:this.settings.elementType,sourceId:this.settings.sourceId,siteId:this.settings.siteId,draftId:this.settings.draftId,revisionId:this.settings.revisionId},function(i,s){"success"===s?(this.previewToken=i.token,t(this.previewToken)):e()}.bind(this))}.bind(this))},getTokenizedPreviewUrl:function(t,e){return new Promise(function(i,s){const a={};!e&&this.settings.isLive||(a[e||"x-craft-preview"]=Craft.randomString(10)),this.settings.siteToken&&(a[Craft.siteToken]=this.settings.siteToken),this.settings.isLive?i(Craft.getUrl(t,a)):this.getPreviewToken().then((function(e){a[Craft.tokenParam]=e,i(Craft.getUrl(t,a))})).catch(s)}.bind(this))},openShareLink:function(t){this.getTokenizedPreviewUrl(t).then((function(t){window.open(t)}))},getPreview:function(){return this.preview||(this.preview=new Craft.Preview(this),this.preview.on("open",function(){this.settings.draftId&&Craft.autosaveDrafts||(Craft.autosaveDrafts||(this.enableAutosave=!0),this.listenForChanges())}.bind(this)),this.preview.on("close",function(){if(!this.settings.draftId||!Craft.autosaveDrafts){if(!Craft.autosaveDrafts){this.enableAutosave=!1;const t=this.statusIcons();t.hasClass("checkmark-icon")&&t.addClass("hidden")}this.stopListeningForChanges()}this.createdDraftInPreview&&setTimeout(()=>{this.createDraftNoticeHud(),this.createdDraftInPreview=!1},750)}.bind(this))),this.preview},createDraftNoticeHud:function(){const e=t("<button/>",{class:"btn",type:"button",text:Craft.t("app","Keep it")}),i=t("<button/>",{class:"btn caution",type:"button",text:Craft.t("app","Delete it")}),s=new Garnish.HUD(t("#context-btngroup"),t("<div/>",{class:"readable centeralign"}).append(t("<p/>",{text:Craft.t("app","You’re now editing a draft.")})).append(t("<div/>",{class:"flex flex-nowrap"}).append(e).append(i)),{hideOnEsc:!1,hideOnShadeClick:!1});e.on("click",()=>{s.hide(),s.destroy()}),i.on("click",()=>{confirm(Craft.t("app","Are you sure you want to delete this draft?"))&&Craft.submitForm(Craft.cp.$primaryForm,{action:this.settings.deleteDraftAction,redirect:this.settings.hashedCpEditUrl})})},openPreview:function(){return new Promise(function(t,e){this.openingPreview=!0,this.ensureIsDraftOrRevision(!0).then(function(){this.getPreview().open(),this.openingPreview=!1,t()}.bind(this)).catch(e)}.bind(this))},ensureIsDraftOrRevision:function(t){return new Promise(function(e,i){if(this.settings.draftId||this.settings.revisionId)e();else{if(t&&this.serializeForm(!0)===Craft.cp.$primaryForm.data("initialSerializedValue"))return void e();this.createDraft().then(e).catch(i)}}.bind(this))},serializeForm:function(t){let e=Craft.cp.$primaryForm.serialize();return this.isPreviewActive()&&(e=e.replace("__PREVIEW_FIELDS__=1",this.preview.$editor.serialize())),t&&!this.settings.isUnpublishedDraft&&(e=e.replace(/&action=[^&]*/,""),e=e.replace(/&redirect=[^&]*/,"")),e},checkForm:function(t){if(this.settings.revisionId||!this.settings.draftId&&!this.isPreviewActive()||this.pauseLevel>0)return;clearTimeout(this.timeout),this.timeout=null;const e=this.serializeForm(!0);(t||e!==(this.lastSerializedValue||Craft.cp.$primaryForm.data("initialSerializedValue")))&&this.saveDraft(e)},isPreviewActive:function(){return this.preview&&this.preview.isActive},createDraft:function(){return new Promise(function(t,e){this.saveDraft(this.serializeForm(!0)).then(t).catch(e)}.bind(this))},saveDraft:function(e){return new Promise(function(i,s){if(this.submittingForm)return void s();if(this.saving)return void this.queue.push(function(){this.checkForm()}.bind(this));this.lastSerializedValue=e,this.saving=!0;const a=this.spinners().removeClass("hidden"),n=this.statusIcons().velocity("stop").css("opacity","").removeClass("invisible checkmark-icon alert-icon fade-out").addClass("hidden");this.$saveMetaBtn&&this.$saveMetaBtn.addClass("active"),this.errors=null;const r=Craft.getActionUrl(this.settings.saveDraftAction);this.saveXhr=Craft.postActionRequest(r,this.prepareData(e),function(r,o){if(a.addClass("hidden"),this.$saveMetaBtn&&this.$saveMetaBtn.removeClass("active"),this.saving=!1,"abort"===o)return;if("success"!==o||r.errors)return this.errors=(r?r.errors:null)||[],n.velocity("stop").css("opacity","").removeClass("hidden checkmark-icon").addClass("alert-icon").attr("title",Craft.t("app","The draft could not be saved.")),void s();r.title&&t("#header h1").text(r.title),r.docTitle&&(document.title=r.docTitle),this.$revisionLabel.text(r.draftName),this.settings.draftName=r.draftName;let l=this.$revisionBtn.data("menubtn")?this.$revisionBtn.data("menubtn").menu:null;this.newSiteIds&&(l||(this.$revisionBtn.removeClass("disabled").addClass("menubtn"),new Garnish.MenuBtn(this.$revisionBtn),l=this.$revisionBtn.data("menubtn").menu,l.$container.removeClass("hidden")),this.newSiteIds.forEach(t=>{const e=l.$options.filter(`[data-site-id=${t}]`);e.find(".status").removeClass("disabled").addClass("enabled");e.parent().removeClass("hidden").closest(".site-group").removeClass("hidden")}),l.$container.find(".revision-hr").removeClass("hidden"),this.newSiteIds=null);const h=!this.settings.draftId;if(h){let e;const i=document.location.href.search("#");e=-1!==i?document.location.href.substr(0,i):document.location.href,e+=(e.match(/\?/)?"&":"?")+"draftId="+r.draftId,-1!==i&&(e+=document.location.href.substr(i)),history.replaceState({},"",e),t("#action").remove(),t("<input/>",{id:"action",type:"hidden",name:"action",value:this.settings.saveDraftAction}).appendTo(Craft.cp.$primaryForm),t("#save-draft-btn-container").remove(),t("#save-btn-container").remove();const s=t("#action-buttons");this.settings.canUpdateSource&&t("<button/>",{type:"button",class:"btn secondary formsubmit",text:Craft.t("app","Publish draft"),title:Craft.shortcutText("S",!1,!0),data:{action:this.settings.publishDraftAction,redirect:this.settings.hashedCpEditUrl}}).appendTo(s).formsubmit();const a=t("<div/>",{id:"save-btn-container",class:"btngroup submit"}).appendTo(s);if(t("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Save draft")}).appendTo(a),this.settings.saveDraftAction||this.settings.deleteDraftAction){t("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(a);const e=t("<div/>",{class:"menu",attr:{"data-align":"right"}}).appendTo(a);if(this.settings.saveDraftAction){const i=t("<ul/>").appendTo(e).append(t("<li/>").append(t("<a/>",{class:"formsubmit",data:{action:this.settings.saveDraftAction},text:Craft.t("app","Save and continue editing")}).prepend(t("<span/>",{class:"shortcut",text:Craft.shortcutText("S")}))));this.settings.canUpdateSource&&this.settings.hashedAddAnotherRedirectUrl&&i.append(t("<li/>").append(t("<a/>",{class:"formsubmit",data:{action:this.settings.publishDraftAction,redirect:this.settings.hashedAddAnotherRedirectUrl},text:Craft.t("app","Publish and add another")}))),this.settings.deleteDraftAction&&t("<hr/>").appendTo(e)}this.settings.deleteDraftAction&&t("<ul/>").appendTo(e).append(t("<li/>").append(t("<a/>",{class:"formsubmit error",data:{action:this.settings.deleteDraftAction,redirect:this.settings.hashedCpEditUrl,confirm:Craft.t("app","Are you sure you want to delete this draft?")},text:Craft.t("app","Delete draft")})))}if(Craft.initUiElements(a),this.settings.draftId=r.draftId,this.settings.isLive=!1,this.previewToken=null,this.initForDraft(),l){l.$options.filter(":not(.site-option)").removeClass("sel");let e=l.$container.find(".revision-group-drafts");if(!e.length){const i=t("<h6/>",{text:Craft.t("app","Drafts")}).insertAfter(l.$container.find(".revision-group-current"));e=t("<ul/>",{class:"padded revision-group-drafts"}).insertAfter(i)}const i=t("<li/>").prependTo(e),s=t("<a/>",{class:"sel",html:'<span class="draft-name"></span> <span class="draft-meta light"></span>'}).appendTo(i);l.addOptions(s),l.selectOption(s);const a=l.$options.filter(".site-option[href]");for(let t=0;t<a.length;t++){const e=a.eq(t);e.attr("href",Craft.getUrl(e.attr("href"),{draftId:r.draftId}))}}(this.openingPreview||this.preview&&this.preview.isActive)&&(this.createdDraftInPreview=!0)}l&&(l.$options.filter(".sel").find(".draft-name").text(r.draftName),l.$options.filter(".sel").find(".draft-meta").text("– "+(r.creator?Craft.t("app","saved {timestamp} by {creator}",{timestamp:r.timestamp,creator:r.creator}):Craft.t("app","updated {timestamp}",{timestamp:r.timestamp})))),r.previewTargets&&JSON.stringify(r.previewTargets)!==JSON.stringify(this.settings.previewTargets)&&this.updatePreviewTargets(r.previewTargets),this.afterUpdate(e),h&&this.trigger("createDraft"),this.$nameTextInput&&this.checkMetaValues();for(const t in r.duplicatedElements)t!=this.settings.sourceId&&r.duplicatedElements.hasOwnProperty(t)&&(this.duplicatedElements[t]=r.duplicatedElements[t]);i()}.bind(this))}.bind(this))},prepareData:function(t){t=this.swapDuplicatedElementIds(t),this.settings.draftId&&(t+="&draftId="+this.settings.draftId),null!==this.settings.draftName&&(t+="&draftName="+this.settings.draftName);const e=this.swapDuplicatedElementIds(Craft.cp.$primaryForm.data("initialSerializedValue"));return Craft.findDeltaData(e,t,this.getDeltaNames())},swapDuplicatedElementIds:function(t){const e=Object.keys(this.duplicatedElements).join("|");if(""===e)return t;const i=encodeURIComponent("["),s=encodeURIComponent("]");for(;t!==(t=t.replace(new RegExp(`(&fields${i}[^=]+${s}${i})(${e})(${s})`,"g"),(t,e,i,s)=>e+this.duplicatedElements[i]+s).replace(new RegExp(`(&fields${i}[^=]+=)(${e})\\b`,"g"),(t,e,i)=>e+this.duplicatedElements[i])););return t},getDeltaNames:function(){const t=Craft.deltaNames.slice(0);for(let e=0;e<t.length;e++)for(const i in this.duplicatedElements)this.duplicatedElements.hasOwnProperty(i)&&(t[e]=t[e].replace("]["+i+"]","]["+this.duplicatedElements[i]+"]"));return t},updatePreviewTargets:function(t){t.forEach(t=>{const e=this.settings.previewTargets.find(e=>e.label===t.label);e&&(e.url=t.url)})},afterUpdate:function(t){Craft.cp.$primaryForm.data("initialSerializedValue",t),Craft.initialDeltaValues={};const e=this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden").addClass("checkmark-icon").attr("title",Craft.t("app","The draft has been saved."));this.enableAutosave||e.velocity("stop").velocity({opacity:0},{delay:2e3,complete:()=>{e.addClass("hidden")}}),this.trigger("update"),this.nextInQueue()},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(){const e=t("<div/>"),i=t('<div class="field"><div class="heading"><label for="draft-name">'+Craft.t("app","Draft Name")+"</label></div></div>").appendTo(e),s=t('<div class="input"/>').appendTo(i);this.$nameTextInput=t('<input type="text" class="text fullwidth" id="draft-name"/>').appendTo(s).val(this.settings.draftName);const a=t('<div class="hud-footer flex flex-center"/>').appendTo(e);t('<div class="flex-grow"></div>').appendTo(a),this.$saveMetaBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(a),this.metaHud=new Garnish.HUD(this.$editMetaBtn,e,{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)return;if(this.settings.draftId&&(void 0===t.autosave||t.autosave)&&(t.saveShortcut||t.customTrigger&&t.customTrigger.data("action")===this.settings.saveDraftAction))return void this.checkForm(!0);Craft.cp.$confirmUnloadForms=Craft.cp.$confirmUnloadForms.not(Craft.cp.$primaryForm),this.saving&&this.saveXhr.abort();const e=this.prepareData(this.serializeForm(!1)),i=Craft.createForm(e);i.appendTo(Garnish.$bod),i.submit(),this.submittingForm=!0}},{defaults:{elementType:null,sourceId:null,siteId:null,isUnpublishedDraft:!1,enabled:!1,enabledForSite:!1,isLive:!1,siteStatuses:null,addlSiteIds:[],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:[],siteToken:null}}),Craft.DynamicGenerator=Craft.BaseInputGenerator.extend({callback:t.noop,init:function(t,e,i){this.callback=i,this.base(t,e)},generateTargetValue:function(t){return this.callback(t)}}),Craft.EditableTable=Garnish.Base.extend({initialized:!1,id:null,baseName:null,columns:null,sorter:null,biggestId:-1,$table:null,$tbody:null,$addRowBtn:null,rowCount:0,hasMaxRows:!1,hasMinRows:!1,radioCheckboxes:null,init:function(e,i,s,a){if(this.id=e,this.baseName=i,this.columns=s,this.setSettings(a,Craft.EditableTable.defaults),this.radioCheckboxes={},this.$table=t("#"+e),this.$tbody=this.$table.children("tbody"),this.rowCount=this.$tbody.find("tr").length,this.$table.data("editable-table")&&(Garnish.log("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}),this.isVisible()?this.initialize():setTimeout(t.proxy(this,"initializeIfVisible"),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]);return 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.css("opacity","0.2"),this.$addRowBtn.css("pointer-events","none"))},canDeleteRow:function(){return this.rowCount>this.settings.minRows},deleteRow:function(t){this.canDeleteRow()&&(this.sorter.removeItems(t.$tr),t.$tr.remove(),this.rowCount--,this.updateAddRowButton(),0===this.rowCount&&this.$table.addClass("hidden"),this.settings.onDeleteRow(t.$tr),t.destroy())},canAddRow:function(){return!this.settings.staticRows&&(!this.settings.maxRows||this.rowCount<this.settings.maxRows)},addRow:function(e,i){if(this.canAddRow()){var s=this.settings.rowIdPrefix+(this.biggestId+1),a=this.createRow(s,this.columns,this.baseName,t.extend({},this.settings.defaultValues));i?a.prependTo(this.$tbody):a.appendTo(this.$tbody);var n=this.createRowObj(a);return this.sorter.addItems(a),!1!==e&&a.find("input:visible,textarea:visible,select:visible").first().trigger("focus"),this.rowCount++,this.updateAddRowButton(),this.$table.removeClass("hidden"),this.settings.onAddRow(a),n}},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(e,i,s){var a,n=e.prev("tr");if((a=n.length?n.data("editable-table-row"):this.addRow(!1,!0))&&a.$tds[i])if(t(a.$tds[i]).hasClass("disabled"))n&&this.focusOnPrevRow(n,i,s);else{var r=t("textarea,input.text",a.$tds[i]);r.length&&(t(s).trigger("blur"),r.trigger("focus"))}},focusOnNextRow:function(e,i,s){var a,n=e.next("tr");if((a=n.length?n.data("editable-table-row"):this.addRow(!1))&&a.$tds[i])if(t(a.$tds[i]).hasClass("disabled"))n&&this.focusOnNextRow(n,i,s);else{var r=t("textarea,input.text",a.$tds[i]);r.length&&(t(s).trigger("blur"),r.trigger("focus"))}},importData:function(t,e,i){let s=t.split(/\r?\n|\r/);for(let t=0;t<s.length;t++){let a=s[t].split("\t");for(let t=0;t<a.length;t++){let s=a[t];e.$tds.eq(i+t).find("textarea,input[type!=hidden]").val(s).trigger("input")}let n=e.$tr.next("tr");e=n.length?n.data("editable-table-row"):this.addRow(!1)}}},{textualColTypes:["color","date","email","multiline","number","singleline","template","time","url"],defaults:{rowIdPrefix:"",defaultValues:{},staticRows:!1,minRows:null,maxRows:null,onAddRow:t.noop,onDeleteRow:t.noop},createRow:function(e,i,s,a){var n=t("<tr/>",{"data-id":e});for(var r in i)if(i.hasOwnProperty(r)){var o,l=i[r],h=void 0!==a[r]?a[r]:"";if("heading"===l.type)o=t("<th/>",{scope:"row",class:l.class,html:h});else{var d=s+"["+e+"]["+r+"]";switch(o=t("<td/>",{class:`${l.class} ${l.type}-cell`,width:l.width}),Craft.inArray(l.type,Craft.EditableTable.textualColTypes)&&o.addClass("textual"),l.code&&o.addClass("code"),l.type){case"checkbox":t('<div class="checkbox-wrapper"/>').append(Craft.ui.createCheckbox({name:d,value:l.value||"1",checked:!!h})).appendTo(o);break;case"color":Craft.ui.createColorInput({name:d,value:h,small:!0}).appendTo(o);break;case"date":Craft.ui.createDateInput({name:d,value:h}).appendTo(o);break;case"lightswitch":Craft.ui.createLightswitch({name:d,value:l.value||"1",on:!!h,small:!0}).appendTo(o);break;case"select":Craft.ui.createSelect({name:d,options:l.options,value:h||function(){for(var t in l.options)if(l.options.hasOwnProperty(t)&&l.options[t].default)return void 0!==l.options[t].value?l.options[t].value:t;return null}(),class:"small"}).appendTo(o);break;case"time":Craft.ui.createTimeInput({name:d,value:h}).appendTo(o);break;case"email":case"url":Craft.ui.createTextInput({name:d,value:h,type:l.type,placeholder:l.placeholder||null}).appendTo(o);break;default:t("<textarea/>",{name:d,rows:l.rows||1,val:h,placeholder:l.placeholder}).appendTo(o)}}o.appendTo(n)}return t("<td/>",{class:"thin action"}).append(t("<a/>",{class:"move icon",title:Craft.t("app","Reorder")})).appendTo(n),t("<td/>",{class:"thin action"}).append(t("<a/>",{class:"delete icon",title:Craft.t("app","Delete")})).appendTo(n),n}}),Craft.EditableTable.Row=Garnish.Base.extend({table:null,id:null,niceTexts:null,$tr:null,$tds:null,tds:null,$textareas:null,$deleteBtn:null,init:function(e,i){this.table=e,this.$tr=t(i),this.$tds=this.$tr.children(),this.tds=[],this.id=this.$tr.attr("data-id"),this.$tr.data("editable-table-row",this);var s=parseInt(this.id.substr(this.table.settings.rowIdPrefix.length));s>this.table.biggestId&&(this.table.biggestId=s),this.$textareas=t(),this.niceTexts=[];var a,n,r,o,l,h={},d=0;for(a in this.table.columns)this.table.columns.hasOwnProperty(a)&&(n=this.table.columns[a],r=this.tds[a]=this.$tds[d],Craft.inArray(n.type,Craft.EditableTable.textualColTypes)?(o=t("textarea",r),this.$textareas=this.$textareas.add(o),this.addListener(o,"focus","onTextareaFocus"),this.addListener(o,"mousedown","ignoreNextTextareaFocus"),this.niceTexts.push(new Garnish.NiceText(o,{onHeightChange:t.proxy(this,"onTextareaHeightChange")})),this.addListener(o,"keypress",{tdIndex:d,type:n.type},"handleKeypress"),this.addListener(o,"input",{type:n.type},"validateValue"),o.trigger("input"),"multiline"!==n.type&&this.addListener(o,"paste",{tdIndex:d,type:n.type},"handlePaste"),h[a]=o):"checkbox"===n.type&&(l=t('input[type="checkbox"]',r),n.radioMode&&(void 0===this.table.radioCheckboxes[a]&&(this.table.radioCheckboxes[a]=[]),this.table.radioCheckboxes[a].push(l[0]),this.addListener(l,"change",{colId:a},"onRadioCheckboxChange")),n.toggle&&this.addListener(l,"change",{colId:a},(function(t){this.applyToggleCheckbox(t.data.colId)}))),t(r).hasClass("disabled")||this.addListener(r,"click",{td:r},(function(e){e.target===e.data.td&&t(e.data.td).find("textarea,input,select,.lightswitch").focus()})),d++);for(a in this.onTextareaHeightChange(),this.table.columns)this.table.columns.hasOwnProperty(a)&&"checkbox"===(n=this.table.columns[a]).type&&n.toggle&&this.applyToggleCheckbox(a);for(a in this.table.columns)this.table.columns.hasOwnProperty(a)&&(n=this.table.columns[a]).autopopulate&&void 0!==h[n.autopopulate]&&!h[a].val()&&new Craft.HandleGenerator(h[a],h[n.autopopulate],{allowNonAlphaStart:!0});var c=this.$tr.children().last().find(".delete");this.addListener(c,"click","deleteRow");var u=this.$tr.find("input,textarea,select,.lightswitch");this.addListener(u,"focus",(function(e){t(e.currentTarget).closest("td:not(.disabled)").addClass("focus")})),this.addListener(u,"blur",(function(e){t(e.currentTarget).closest("td").removeClass("focus")}))},onTextareaFocus:function(e){this.onTextareaHeightChange();var i=t(e.currentTarget);i.data("ignoreNextFocus")?i.data("ignoreNextFocus",!1):setTimeout((function(){Craft.selectFullValue(i)}),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(e){for(var i,s,a=this.table.columns[e],n=t('input[type="checkbox"]',this.tds[e]).prop("checked"),r=0;r<a.toggle.length;r++)i=a.toggle[r],this.table.colum,(s="!"===i[0])&&(i=i.substr(1)),n&&!s||!n&&s?t(this.tds[i]).removeClass("disabled").find("textarea, input").prop("disabled",!1):t(this.tds[i]).addClass("disabled").find("textarea, input").prop("disabled",!0)},ignoreNextTextareaFocus:function(e){t.data(e.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){let 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]}),Craft.ElementActionTrigger=Garnish.Base.extend({maxLevels:null,newChildUrl:null,$trigger:null,$selectedItems:null,triggerEnabled:!0,init:function(e){this.setSettings(e,Craft.ElementActionTrigger.defaults),this.$trigger=t("#"+e.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",t.proxy(this,"updateTrigger"))},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}}),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){let e=t.find(".elementthumb");for(let t=0;t<e.length;t++){let i=e.eq(t),s=i.scrollParent();if(this.isVisible(i,s))this.addToQueue(i[0]);else{let t="thumb"+Math.floor(1e6*Math.random());Craft.ElementThumbLoader.invisibleThumbs[t]=[this,i,s],s.on("scroll."+t,{$thumb:i,$scrollParent:s,key:t},t=>{this.isVisible(t.data.$thumb,t.data.$scrollParent)&&(delete Craft.ElementThumbLoader.invisibleThumbs[t.data.key],s.off("scroll."+t.data.key),this.addToQueue(t.data.$thumb[0]))})}}},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){let 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(let t in Craft.ElementThumbLoader.invisibleThumbs){let[e,i,s]=Craft.ElementThumbLoader.invisibleThumbs[t];delete Craft.ElementThumbLoader.invisibleThumbs[t],s.off("scroll."+t),e.load(i.parent())}}}),Craft.ElementThumbLoader.Worker=Garnish.Base.extend({loader:null,active:!1,init:function(t){this.loader=t},loadNext:function(){var e=this.loader.queue.shift();if(void 0!==e){this.active=!0;var i=t(e);if(i.find("img").length)this.loadNext();else{var s=t("<img/>",{sizes:i.attr("data-sizes"),srcset:i.attr("data-srcset"),alt:""});this.addListener(s,"load,error","loadNext"),s.appendTo(i),picturefill({elements:[s[0]]})}}else this.active=!1}}),Craft.ElevatedSessionForm=Garnish.Base.extend({$form:null,inputs:null,init:function(e,i){if(this.$form=t(e),void 0!==i){this.inputs=[],i=t.makeArray(i);for(var s=0;s<i.length;s++)for(var a=t(i[s]),n=0;n<a.length;n++){var r=a.eq(n);this.inputs.push({input:r,val:Garnish.getInputPostVal(r)})}}this.addListener(this.$form,"submit","handleFormSubmit")},handleFormSubmit:function(e){if(Craft.elevatedSessionManager.fetchingTimeout)return e.preventDefault(),void e.stopImmediatePropagation();if(this.inputs){for(var i,s=!1,a=0;a<this.inputs.length;a++)if((i=this.inputs[a].input).data("passwordInput")&&(i=i.data("passwordInput").$currentInput),Garnish.getInputPostVal(i)!==this.inputs[a].val){s=!0;break}if(!s)return}e.preventDefault(),e.stopImmediatePropagation(),Craft.elevatedSessionManager.requireElevatedSession(t.proxy(this,"submitForm"))},submitForm:function(){this.disable(),this.$form.trigger("submit"),this.enable()}}),Craft.ElevatedSessionManager=Garnish.Base.extend({fetchingTimeout:!1,passwordModal:null,$passwordInput:null,$passwordSpinner:null,$submitBtn:null,$errorPara:null,callback:null,requireElevatedSession:function(e){this.callback=e,this.fetchingTimeout=!0,Craft.postActionRequest("users/get-elevated-session-timeout",t.proxy((function(t,e){this.fetchingTimeout=!1,"success"===e&&(!1===t.timeout||t.timeout>=Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout?this.callback():this.showPasswordModal())}),this))},showPasswordModal:function(){if(this.passwordModal)this.passwordModal.show();else{var e=t('<form id="elevatedsessionmodal" class="modal secure fitted"/>'),i=t('<div class="body"><p>'+Craft.t("app","Enter your password to continue.")+"</p></div>").appendTo(e),s=t('<div class="inputcontainer">').appendTo(i),a=t('<div class="flex"/>').appendTo(s),n=t('<div class="flex-grow"/>').appendTo(a),r=t("<td/>").appendTo(a),o=t('<div class="passwordwrapper"/>').appendTo(n);this.$passwordInput=t('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'" autocomplete="current-password"/>').appendTo(o),this.$passwordSpinner=t('<div class="spinner hidden"/>').appendTo(s),this.$submitBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Submit")}).appendTo(r),this.$errorPara=t('<p class="error"/>').appendTo(i),this.passwordModal=new Garnish.Modal(e,{closeOtherModals:!1,onFadeIn:t.proxy((function(){setTimeout(t.proxy(this,"focusPasswordInput"),100)}),this),onFadeOut:t.proxy((function(){this.$passwordInput.val("")}),this)}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:t.proxy((function(t){this.$passwordInput=t}),this)}),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(e){if(e&&e.preventDefault(),this.validatePassword()){this.$passwordSpinner.removeClass("hidden"),this.clearLoginError();var i={currentPassword:this.$passwordInput.val()};Craft.postActionRequest("users/start-elevated-session",i,t.proxy((function(t,e){this.$passwordSpinner.addClass("hidden"),"success"===e?t.success?(this.passwordModal.hide(),this.callback()):(this.showPasswordError(t.message||Craft.t("app","Incorrect password.")),Garnish.shake(this.passwordModal.$container),this.focusPasswordInput()):this.showPasswordError()}),this))}},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,Craft.EntryIndex=Craft.BaseElementIndex.extend({publishableSections:null,$newEntryBtnGroup:null,$newEntryBtn:null,init:function(e,i,s){this.on("selectSource",t.proxy(this,"updateButton")),this.on("selectSite",t.proxy(this,"updateButton")),this.base(e,i,s)},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 e=0;e<this.$sources.length;e++){var i=t(this.$sources[e]);if(i.data("handle")===defaultSectionHandle)return i.data("key")}}return this.base()},updateButton:function(){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=t('<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=t('<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=t("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newEntryBtnGroup))):this.$newEntryBtn=r=t("<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!==t.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>")}t(o+="</ul></div>").appendTo(this.$newEntryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",t.proxy((function(t){this._openCreateEntryModal(t.option.getAttribute("data-id"))}),this))}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/"+t.handle+"/new";let s={};if(this.siteId)for(var i=0;i<Craft.sites.length;i++)Craft.sites[i].id==this.siteId&&(s.site=Craft.sites[i].handle);return'href="'+Craft.getUrl(e,s)+'"'}return'data-id="'+t.id+'"'},_openCreateEntryModal:function(e){if(!this.$newEntryBtn.hasClass("loading")){for(var i,s=0;s<this.publishableSections.length;s++)if(this.publishableSections[s].id==e){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:e,typeId:i.entryTypes[0].id,enabled:i.canPublish?1:0},onBeginLoading:t.proxy((function(){this.$newEntryBtn.addClass("loading")}),this),onEndLoading:t.proxy((function(){this.$newEntryBtn.removeClass("loading")}),this),onHideHud:t.proxy((function(){this.$newEntryBtn.removeClass("inactive").text(a)}),this),onSaveElement:t.proxy((function(t){var e="section:"+i.uid;this.sourceKey!==e&&this.selectSourceByKey(e),this.selectElementAfterUpdate(t.id),this.updateElements()}),this)})}}}}),Craft.registerElementIndexClass("craft\\elements\\Entry",Craft.EntryIndex),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(e,i){this.$container=t(e),this.setSettings(i,Craft.FieldLayoutDesigner.defaults);let 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");let 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});let n=this.$tabContainer.children();for(let e=0;e<n.length;e++)this.initTab(t(n[e]));if(t("<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){let t=this.$sidebar.children(".btngroup");new Craft.Listbox(t,{onChange:t=>{this.$selectedLibrary.addClass("hidden"),this.$selectedLibrary=this[`$${t.data("library")}Library`].removeClass("hidden")}})}this.addListener(this.$fieldSearch,"input",()=>{let t=this.$fieldSearch.val().toLowerCase().replace(/['"]/g,"");if(!t)return this.$fieldLibrary.find(".filtered").removeClass("filtered"),void this.$clearFieldSearchBtn.addClass("hidden");this.$clearFieldSearchBtn.removeClass("hidden");let e=this.$fields.filter(`[data-keywords*="${t}"]`).add(this.$fieldGroups.filter(`[data-name*="${t}"]`).children(".fld-element")).removeClass("filtered");this.$fields.not(e).addClass("filtered");for(let t=0;t<this.$fieldGroups.length;t++){let e=this.$fieldGroups.eq(t);e.find(".fld-element:not(.hidden):not(.filtered)").length?e.removeClass("filtered"):e.addClass("filtered")}}),this.addListener(this.$fieldSearch,"keydown",t=>{t.keyCode===Garnish.ESC_KEY&&this.$fieldSearch.val("").trigger("input")}),this.addListener(this.$clearFieldSearchBtn,"click",()=>{this.$fieldSearch.val("").trigger("input")})},initTab:function(e){if(this.settings.customizableTabs){let i=e.find(".tabs .settings");t('<div class="menu" data-align="center"/>').insertAfter(i).append(t("<ul/>").append(t("<li/>").append(t("<a/>",{"data-action":"rename",text:Craft.t("app","Rename")}))).append(t("<li/>").append(t("<a/>",{"data-action":"remove",text:Craft.t("app","Remove")})))).append(t("<hr/>")).append(t("<ul/>").append(t("<li/>").append(t("<a/>",{"data-action":"moveLeft",text:Craft.t("app","Move to the left")}))).append(t("<li/>").append(t("<a/>",{"data-action":"moveRight",text:Craft.t("app","Move to the right")}))));let s=new Garnish.MenuBtn(i,{onOptionSelect:t.proxy(this,"onTabOptionSelect")});s.menu.on("show",()=>{e.prev(".fld-tab").length?s.menu.$container.find("[data-action=moveLeft]").removeClass("disabled"):s.menu.$container.find("[data-action=moveLeft]").addClass("disabled"),e.next(".fld-tab").length?s.menu.$container.find("[data-action=moveRight]").removeClass("disabled"):s.menu.$container.find("[data-action=moveRight]").addClass("disabled")})}let i=e.children(".fld-tabcontent").children();for(let e=0;e<i.length;e++)this.initElement(t(i[e]))},initElement:function(t){new Craft.FieldLayoutDesigner.Element(this,t)},onTabOptionSelect:function(e){if(!this.settings.customizableTabs)return;let i=t(e),s=i.data("menu").$anchor.parent().parent().parent();switch(i.data("action")){case"rename":this.renameTab(s);break;case"remove":this.removeTab(s);break;case"moveLeft":let t=s.prev(".fld-tab");t.length&&s.insertBefore(t);break;case"moveRight":let e=s.next(".fld-tab");e.length&&s.insertAfter(e)}},renameTab:function(t){if(!this.settings.customizableTabs)return;const 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 prompt(Craft.t("app","Give your tab a name."),t)},removeTab:function(e){if(!this.settings.customizableTabs)return;let i=e.find(".fld-element");for(let e=0;e<i.length;e++){let s=t(i[e]).attr("data-attribute");this.removeFieldByHandle(s)}this.tabGrid.removeItems(e),this.tabDrag.removeItems(e),e.remove()},removeField:function(t){let e=t.attr("data-attribute");t.remove(),this.removeFieldByHandle(e),this.tabGrid.refreshCols(!0)},removeFieldByHandle:function(t){this.$fields.filter(`[data-attribute="${t}"]:first`).removeClass("hidden").closest(".fld-field-group").removeClass("hidden")},addTab:function(){if(!this.settings.customizableTabs)return;const e=this.promptForTabName();if(!e)return;const i=t(`\n<div class="fld-tab">\n  <div class="tabs">\n    <div class="tab sel draggable">\n      <span>${e}</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);this.tabGrid.addItems(i),this.tabDrag.addItems(i),this.initTab(i)},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(e,i){this.designer=e,this.$container=i,this.$container.data("fld-element",this),this.config=this.$container.data("config"),t.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"));let 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=t("<div/>",{class:"hidden"}),this.$editBtn=t("<a/>",{role:"button",tabindex:0,class:"settings icon",title:Craft.t("app","Edit")}),this.$editBtn.on("click",()=>{this.hud?(this.hud.show(),this.hud.updateSizeAndPosition(!0)):this.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(){if(this.$placementInput=t("<input/>",{class:"placement-input",type:"hidden",name:"",value:this.key}).appendTo(this.$container),this.updatePlacementInput(),this.$configInput=t("<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:t=>Craft.t("app","{pct} width",{pct:t+"%"}),onChange:t=>{this.config.width=t,this.updateConfigInput()}}).$container.appendTo(this.$container)}this.hasSettings&&this.$editBtn.appendTo(this.$container)},createSettingsHud:function(t,e){let i=`\n<div class="fld-element-settings">\n  ${t}\n  <div class="hud-footer">\n    <div class="buttons right">\n      <button class="btn submit" type="submit">${Craft.t("app","Apply")}</button>\n      <div class="spinner hidden"></div>\n    </div>\n  </div>\n</div>\n`;if(this.hud=new Garnish.HUD(this.$container,i,{onShow:t=>{Garnish.requestAnimationFrame(()=>{this.hud.$main.find(".text:first").trigger("focus")})},onSubmit:()=>{this.applyHudSettings()}}),Craft.initUiElements(this.hud.$main),this.requirable){Craft.ui.createLightswitchField({label:Craft.t("app","Required"),id:this.key+"-required",name:"required",on:e}).prependTo(this.hud.$main)}this.trigger("createSettingsHud")},applyHudSettings:function(){this.hud.$body.serializeArray().forEach(({name:t,value:e})=>{this.config[t]=e}),this.updateConfigInput();let e=this.hud.$body.find(".spinner").removeClass("hidden");Craft.sendActionRequest("POST","fields/render-layout-element-selector",{data:{config:this.config}}).then(i=>{e.addClass("hidden"),this.$editBtn.detach(),this.$container.html(t(i.data.html).html()),this.initUi(),this.updateRequiredClass(),this.hud.hide()}).catch(t=>{console.error(t),e.addClass("hidden"),this.updateRequiredClass(),this.hud.hide()})},updatePlacementInput:function(){let t=this.$container.closest(".fld-tab").find(".tab span");if(!t.length)return;let 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=t().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=t().add(this.$items.not(this.$draggee).add(this.$insertion)),this.showingInsertion=!0},swapInsertionWithDraggee:function(){this.$insertion.replaceWith(this.$draggee),this.$items=t().add(this.$items.not(this.$insertion).add(this.$draggee)),this.showingInsertion=!1},setMidpoints:function(){for(let e=0;e<this.$items.length;e++){let i=t(this.$items[e]),s=i.offset();i.hasClass("unused")||i.data("midpoint",{left:s.left+i.outerWidth()/2,top:s.top+i.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=t(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&&t.inArray(this.$insertion[0],this.$items)<t.inArray(this.checkForNewClosestItem._closestItem,this.$items)&&-1===t.inArray(this.checkForNewClosestItem._closestItem,this.$caboose)?this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem):this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem),this.$items=t().add(this.$items.add(this.$insertion)),this.showingInsertion=!0,this.designer.tabGrid.refreshCols(!0),this.setMidpoints())},onDragStop:function(){this.showingInsertion&&this.swapInsertionWithDraggee(),this.removeCaboose(),this.designer.tabGrid.refreshCols(!0);let t=this.$draggee.offset();!t||0===t.top&&0===t.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,()=>{this._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(){let e=t('<div class="fld-tab fld-tab-caboose"/>').appendTo(this.designer.$tabContainer);return this.designer.tabGrid.addItems(e),e},removeCaboose:function(){this.base(),this.designer.tabGrid.removeItems(this.$caboose)},createInsertion:function(){let e=this.$draggee.find(".tab");return t(`\n<div class="fld-tab fld-insertion" style="height: ${this.$draggee.height()}px;">\n  <div class="tabs"><div class="tab sel draggable" style="width: ${e.width()}px; height: ${e.height()}px;"></div></div>\n  <div class="fld-tabcontent" style="height: ${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=t().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(let 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(){let e=t(),i=this.designer.$tabContainer.find("> .fld-tab > .fld-tabcontent");for(let s=0;s<i.length;s++)e=e.add(t("<div/>").appendTo(i[s]));return e},createInsertion:function(){return t(`<div class="fld-element fld-insertion" style="height: ${this.$draggee.outerHeight()}px;"/>`)},onDragStop:function(){let t=this.showingInsertion;if(t){if(this.draggingLibraryElement){let t=this.$draggee.clone().removeClass("unused");this.designer.initElement(t),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=t,this.addItems(t)}}else if(!this.draggingLibraryElement){let t=this.draggingField?this.designer.$fields.filter(`[data-attribute="${this.$draggee.data("attribute")}"]:first`):this.designer.$uiLibraryElements.filter(`[data-type="${this.$draggee.data("type").replace(/\\/g,"\\\\")}"]:first`);this.draggingField&&(t.removeClass("hidden"),t.closest(".fld-field-group").removeClass("hidden")),this.removeItems(this.$draggee),this.$draggee=t}this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:this.draggingField||t?"hidden":"visible"}),t&&this.$draggee.data("fld-element").updatePlacementInput()}}),Craft.FieldToggle=Garnish.Base.extend({$toggle:null,targetPrefix:null,targetSelector:null,reverseTargetSelector:null,_$target:null,_$reverseTarget:null,type:null,init:function(e){switch(this.$toggle=t(e),this.$toggle.data("fieldtoggle")&&(Garnish.log("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(){let 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"select";case"A":return"link";case"FIELDSET":return"fieldset"}console.warn("Unexpected field toggle:",this.$toggle[0])},findTargets:function(){if("select"===this.type||"fieldset"===this.type){this.getToggleVal();this._$target=t(this.normalizeTargetSelector(this.targetPrefix+this.getToggleVal()))}else this.targetSelector&&(this._$target=t(this.targetSelector)),this.reverseTargetSelector&&(this._$reverseTarget=t(this.reverseTargetSelector))},getToggleVal:function(){if("checkbox"===this.type)return void 0!==this.$toggle.prop("checked")?this.$toggle.prop("checked"):"true"===this.$toggle.attr("aria-checked");let t;return t="fieldset"===this.type?this.$toggle.find("input:checked:first").val():Garnish.getInputPostVal(this.$toggle),null==t?null:t.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){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(let e=0;e<t.length;e++)(t=>{"SPAN"!==t.prop("nodeName")&&(t.height("auto"),this.showTarget._targetHeight=t.height(),t.css({height:this.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:this.showTarget._targetHeight},"fast",(function(){t.css({height:"",overflow:""})})))})(t.eq(e));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(let e=0;e<t.length;e++)(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))}}}),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(e,i){this.$container=t(e),this.$container.data("grid")&&(Garnish.log("Double-instantiating a grid on an element"),this.$container.data("grid").destroy()),this.$container.data("grid",this),this.setSettings(i,Craft.Grid.defaults),this.handleContainerHeightProxy=t.proxy((function(){this.refreshCols(!1,!0)}),this),this.$items=this.$container.children(this.settings.itemSelector),this.setItems(),this.refreshCols(!0,!1),Garnish.$doc.ready(t.proxy((function(){this.refreshCols(!1,!1)}),this))},addItems:function(e){this.$items=t().add(this.$items.add(e)),this.setItems(),this.refreshCols(!0,!0)},removeItems:function(e){this.$items=t().add(this.$items.not(e)),this.setItems(),this.refreshCols(!0,!0)},resetItemOrder:function(){this.$items=t().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(t(this.$items[this.setItems._.i]));delete this.setItems._},refreshCols:function(e){if(this._refreshingCols)return this._refreshColsAfterRefresh=!0,void(e&&(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===e||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[t.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(){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(t.proxy((function(){this.refreshCols(e)}),this))}},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(e){this.onItemResize._={},e.stopPropagation(),this.onItemResize._.item=t.inArray(e.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()}},{defaults:{itemSelector:".item",cols:null,maxCols:null,minColWidth:320,gutter:14,fillMode:"top",colClass:"col",snapToGrid:null,onRefreshCols:t.noop}}),Craft.Grid.LayoutGenerator=Garnish.Base.extend({grid:null,_:null,init:function(t){this.grid=t},createLayouts:function(e,i,s,a,n){for(this._={},this._.c=0;this._.c<this.grid.possibleItemColspans[e].length;this._.c++){for(this._.colspan=this.grid.possibleItemColspans[e][this._.c],this._.tallestColHeightsByPosition=[],this._.p=0;this._.p<this.grid.possibleItemPositionsByColspan[e][this._.colspan].length;this._.p++){for(this._.position=this.grid.possibleItemPositionsByColspan[e][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(a[this._.col]);this._.tallestColHeightsByPosition[this._.p]=Math.max.apply(null,this._.colHeightsForPosition)}for(this._.p=t.inArray(Math.min.apply(null,this._.tallestColHeightsByPosition),this._.tallestColHeightsByPosition),this._.position=this.grid.possibleItemPositionsByColspan[e][this._.colspan][this._.p],this._.positions=i.slice(0),this._.colspans=s.slice(0),this._.colHeights=a.slice(0),this._.emptySpace=n,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[e][this._.colspan];e===this.grid.items.length-1?this.grid.layouts.push({positions:this._.positions,colspans:this._.colspans,colHeights:this._.colHeights,emptySpace:this._.emptySpace}):this.grid.createLayouts(e+1,this._.positions,this._.colspans,this._.colHeights,this._.emptySpace)}delete this._}}),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(let t=0;t<i.length;t++)"pascal"!==Craft.handleCasing&&0===t?e+=i[t]:e+=i[t].charAt(0).toUpperCase()+i[t].substr(1);return e}}),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=t(this.settings.containerSelector),this.progressBar=new Craft.ProgressBar(t('<div class="progress-shade"></div>').appendTo(this.$container));var e={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&&(e.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),e.events={},e.events.fileuploadstart=t.proxy(this,"_onUploadStart"),e.events.fileuploadprogressall=t.proxy(this,"_onUploadProgress"),e.events.fileuploaddone=t.proxy(this,"_onUploadComplete"),e.events.fileuploadfail=t.proxy(this,"_onUploadError"),this.uploader=new Craft.Uploader(this.$container,e),this.initButtons()},initButtons:function(){this.$container.find(this.settings.uploadButtonSelector).on("click",t.proxy((function(t){this.$container.find(this.settings.fileInputSelector).trigger("click")}),this)),this.$container.find(this.settings.deleteButtonSelector).on("click",t.proxy((function(e){confirm(Craft.t("app","Are you sure you want to delete this image?"))&&(t(e.currentTarget).parent().append('<div class="blocking-modal"></div>'),Craft.postActionRequest(this.settings.deleteAction,this.settings.postParameters,t.proxy((function(t,e){"success"===e&&this.refreshImage(t)}),this)))}),this))},refreshImage:function(e){t(this.settings.containerSelector).replaceWith(e.html),this.settings.onAfterRefreshImage(e),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(e,i){if(i.result.error)alert(i.result.error);else{t(i.result.html);this.refreshImage(i.result)}this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},_onUploadError:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.$container.removeClass("uploading"),this.progressBar.hideProgressBar(),this.progressBar.resetProgressBar())}},{defaults:{postParameters:{},uploadAction:"",deleteAction:"",fileInputSelector:"",onAfterRefreshImage:t.noop,containerSelector:null,uploadButtonSelector:null,deleteButtonSelector:null,uploadParamName:"files"}}),Craft.InfoIcon=Garnish.Base.extend({$icon:null,content:null,hud:null,init:function(e){if(this.$icon=t(e),this.$icon.data("infoicon")?(Garnish.log("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){if(!this.$icon.parent().hasClass("nowrap")){const e=this.$icon[0].previousSibling.nodeValue.match(/[^\s\-]+\s*$/);e&&(this.$icon[0].previousSibling.nodeValue=this.$icon[0].previousSibling.nodeValue.substr(0,e.index),t("<span/>",{class:"nowrap",html:e[0].replace(/\s+$/,"")+" "}).insertAfter(this.$icon[0].previousSibling).append(this.$icon))}}this.addListener(this.$icon,"click",t=>{t.preventDefault(),t.stopPropagation(),this.showHud()}),this.addListener(this.$icon,"keydown",t=>{this.hud&&this.hud.showing||![Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)||(t.preventDefault(),t.stopPropagation(),this.showHud())})},showHud:function(t){this.hud?this.hud.show():(this.hud=new Garnish.HUD(this.$icon,this.content,{hudClass:"hud info-hud",closeOtherHUDs:!1,onShow:()=>{Garnish.shortcutManager.registerShortcut(Garnish.SPACE_KEY,()=>{this.hud.hide()})}}),Craft.initUiElements(this.hud.$body))}}),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(e,i){if(this.$outerContainer=t(e),this.$outerContainer.data("lightswitch")&&(Garnish.log("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(i,Craft.LightSwitch.defaults),this.$innerContainer=this.$outerContainer.find(".lightswitch-container:first"),this.$input=this.$outerContainer.find("input:first"),this.$input.prop("disabled"))return;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:t.proxy(this,"_onDragStart"),onDrag:t.proxy(this,"_onDrag"),onDragStop:t.proxy(this,"_onDragStop")});let s=this.$outerContainer.parent(".lightswitch-inner-container");s.length&&(this.addListener(s.children('span[data-toggle="off"]'),"click",this.turnOff),this.addListener(s.children('span[data-toggle="on"]'),"click",this.turnOn))},turnOn:function(e){var i=!this.on;this.on=!0,this.indeterminate=!1,this.$outerContainer.addClass("dragging");var s={};s["margin-"+Craft.left]=0,this.$innerContainer.velocity("stop").velocity(s,Craft.LightSwitch.animationDuration,t.proxy(this,"_onSettle")),this.$input.val(this.settings.value),this.$outerContainer.addClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","true"),i&&!0!==e&&this.onChange()},turnOff:function(e){var i=this.on||this.indeterminate;this.on=!1,this.indeterminate=!1,this.$outerContainer.addClass("dragging");var s={};s["margin-"+Craft.left]=this._getOffMargin(),this.$innerContainer.velocity("stop").velocity(s,Craft.LightSwitch.animationDuration,t.proxy(this,"_onSettle")),this.$input.val(""),this.$outerContainer.removeClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","false"),i&&!0!==e&&this.onChange()},turnIndeterminate:function(e){var i=!this.indeterminate;this.on=!1,this.indeterminate=!0,this.$outerContainer.addClass("dragging");var s={};s["margin-"+Craft.left]=this._getOffMargin()/2,this.$innerContainer.velocity("stop").velocity(s,Craft.LightSwitch.animationDuration,t.proxy(this,"_onSettle")),this.$input.val(this.settings.indeterminateValue),this.$outerContainer.removeClass("on"),this.$outerContainer.addClass("indeterminate"),this.$outerContainer.attr("aria-checked","mixed"),i&&!0!==e&&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.base(),this.dragger.destroy()},_getOffMargin:function(){return this.small?-10:-12}},{animationDuration:100,defaults:{value:"1",indeterminateValue:"-",onChange:t.noop}}),Craft.Listbox=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,selectedOptionIndex:null,init:function(e,i){this.$container=t(e),this.setSettings(i,Craft.Listbox.defaults),this.$container.data("listbox")&&(Garnish.log("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",t=>{switch(t.keyCode){case Garnish.UP_KEY:this.selectPrev(),t.preventDefault();break;case Garnish.DOWN_KEY:this.selectNext(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.selectPrev():this.selectNext(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.selectNext():this.selectPrev(),t.preventDefault()}}),this.addListener(this.$options,"click",e=>{this.select(this.$options.index(t(e.currentTarget))),e.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)}},{defaults:{selectedClass:"active",focusClass:"focus",onChange:t.noop}}),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,_handleSuccessProxy:null,_handleErrorProxy:null,_forceUpdateIframeProxy:null,_scrollX:null,_scrollY:null,_editorWidth:null,_editorWidthInPx:null,init:function(e){this.setSettings(e,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=t.extend({},this.settings.previewParams),this._handleSuccessProxy=t.proxy(this,"handleSuccess"),this._handleErrorProxy=t.proxy(this,"handleError"),this._forceUpdateIframeProxy=t.proxy(this,"forceUpdateIframe"),this.$extraFields=t(this.settings.extraFields),this.$trigger=t(this.settings.trigger),this.$fieldPlaceholder=t("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.LivePreview.defaultEditorWidth),this.addListener(this.$trigger,"activate","toggle"),Craft.cp.on("beforeSaveShortcut",t.proxy((function(){this.inPreviewMode&&this.moveFieldsBack()}),this))},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(){if(!this.inPreviewMode)if(this.token){if(this.trigger("beforeEnter"),t(document.activeElement).trigger("blur"),!this.$editor){this.$shade=t("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=t("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$iframeContainer=t("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$editorContainer=t("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=t("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=t("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=t("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);t("<div/>",{class:"flex-grow"}).appendTo(e);let s=t("<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:t.proxy(this,"_onDragStart"),onDrag:t.proxy(this,"_onDrag"),onDragStop:t.proxy(this,"_onDragStop")}),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 s=t(this.settings.fields),a=0;a<s.length;a++){var n=t(s[a]),r=this._getClone(n);this.$fieldPlaceholder.insertAfter(n),n.detach(),this.$fieldPlaceholder.replaceWith(r),n.appendTo(this.$editor),this.fields.push({$field:n,$clone:r})}this.updateIframe()?this._slideInOnIframeLoad=!0:this.slideIn(),Garnish.on(Craft.BaseElementEditor,"saveElement",this._forceUpdateIframeProxy),Garnish.on(Craft.AssetImageEditor,"save",this._forceUpdateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.inPreviewMode=!0,this.trigger("enter")}else this.createToken()},createToken:function(){Craft.postActionRequest("live-preview/create-token",{previewAction:this.settings.previewAction},t.proxy((function(t,e){"success"===e&&(this.token=t.token,this.enter())}),this))},save:function(){Craft.cp.submitPrimaryForm()},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){t("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",t.proxy((function(){this.trigger("slideIn"),Garnish.$win.trigger("resize")}),this)),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",t.proxy((function(){this.updateIframeInterval=setInterval(t.proxy(this,"updateIframe"),1e3),this.addListener(Garnish.$bod,"keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&this.exit()}))}),this))},exit:function(){this.inPreviewMode&&(this.trigger("beforeExit"),t("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),this.removeListener(Garnish.$bod,"keyup"),this.updateIframeInterval&&clearInterval(this.updateIframeInterval),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",t.proxy((function(){for(var t=0;t<this.fields.length;t++)this.fields[t].$newClone.remove();this.$editorContainer.hide(),this.trigger("slideOut")}),this)),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",t.proxy((function(){this.$previewContainer.hide()}),this)),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(e){if(e&&(this.lastPostData=null),!this.inPreviewMode)return!1;if(this.loading)return this.checkAgain=!0,!1;var i=t.extend(Garnish.getPostData(this.$editor),Garnish.getPostData(this.$extraFields));if(this.lastPostData&&Craft.compare(i,this.lastPostData,!1))return!1;this.lastPostData=i,this.loading=!0;var s=this.$iframe?t(this.$iframe[0].contentWindow.document):null;return this._scrollX=s?s.scrollLeft():0,this._scrollY=s?s.scrollTop():0,t.ajax({url:this.previewUrl+(-1!==this.previewUrl.indexOf("?")?"&":"?")+Craft.tokenParam+"="+this.token,method:"POST",data:t.extend({},i,this.basePostData),headers:{"X-Craft-Token":this.token},xhrFields:{withCredentials:!0},crossDomain:!0,success:this._handleSuccessProxy,error:this._handleErrorProxy}),!0},forceUpdateIframe:function(){return this.updateIframe(!0)},handleSuccess:function(e){var i=e+'<script type="text/javascript">window.scrollTo('+this._scrollX+", "+this._scrollY+");<\/script>",s=t('<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(t.proxy((function(){s[0].contentWindow.document.open(),s[0].contentWindow.document.write(i),s[0].contentWindow.document.close(),this.onResponse()}),this))},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)},Craft.PasswordInput=Garnish.Base.extend({$passwordWrapper:null,$passwordInput:null,$textInput:null,$currentInput:null,$showPasswordToggle:null,showingPassword:null,init:function(e,i){this.$passwordInput=t(e),this.$passwordWrapper=this.$passwordInput.parent(".passwordwrapper"),this.settings=t.extend({},Craft.PasswordInput.defaults,i),this.$passwordInput.data("passwordInput")&&(Garnish.log("Double-instantiating a password input on an element"),this.$passwordInput.data("passwordInput").destroy()),this.$passwordInput.data("passwordInput",this),this.$showPasswordToggle=t('<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()},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"),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()}},{defaults:{onToggleInput:t.noop}}),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,$deviceMask:null,$devicePreviewContainer:null,$iframe:null,iframeLoaded:!1,$tempInput:null,$fieldPlaceholder:null,isActive:!1,isVisible:!1,activeTarget:0,isDeviceUpdating:!1,deviceAnimationTimeout:null,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(e){this.draftEditor=e,this._updateIframeProxy=t.proxy(this,"updateIframe"),this.$tempInput=t("<input/>",{type:"hidden",name:"__PREVIEW_FIELDS__",value:"1"}),this.$fieldPlaceholder=t("<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(){if(!this.isActive){if(this.isActive=!0,this.trigger("beforeOpen"),t(document.activeElement).trigger("blur"),!this.$editor){this.$shade=t("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=t("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$editorContainer=t("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=t("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=t("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=t("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);if(t("<div/>",{class:"flex-grow"}).appendTo(e),this.$spinner=t("<div/>",{class:"spinner hidden",title:Craft.t("app","Saving")}).appendTo(e),this.$statusIcon=t("<div/>",{class:"invisible"}).appendTo(e),Craft.Pro){if(this.$previewHeader=t("<header/>",{class:"lp-preview-header"}).appendTo(this.$previewContainer),this.draftEditor.settings.previewTargets.length>1){this.$targetBtn=t("<button/>",{type:"button",class:"btn menubtn",text:this.draftEditor.settings.previewTargets[0].label}).appendTo(this.$previewHeader),this.$targetMenu=t("<div/>",{class:"menu lp-target-menu"}).insertAfter(this.$targetBtn);const e=t("<ul/>",{class:"padded"}).appendTo(this.$targetMenu);let i,s;for(let a=0;a<this.draftEditor.settings.previewTargets.length;a++)i=t("<li/>").appendTo(e),s=t("<a/>",{data:{target:a},text:this.draftEditor.settings.previewTargets[a].label,class:0===a?"sel":null}).appendTo(i);new Garnish.MenuBtn(this.$targetBtn,{onOptionSelect:e=>{this.switchTarget(t(e).data("target"))}}),t('<div class="flex-grow"/>').appendTo(this.$previewHeader)}this.$deviceTypeContainer=t("<div/>",{class:"btngroup lp-device-type",role:"listbox","aria-label":Craft.t("app","Device type"),tabindex:"0"}).appendTo(this.$previewHeader),t("<button/>",{type:"button",role:"option",class:"btn lp-device-type-btn--desktop active",title:Craft.t("app","Desktop"),"aria-label":Craft.t("app","Desktop"),"aria-selected":"true",tabindex:"-1",data:{width:"",height:"",deviceType:"desktop"}}).appendTo(this.$deviceTypeContainer),t("<button/>",{type:"button",role:"option",class:"btn lp-device-type-btn--tablet",title:Craft.t("app","Tablet"),"aria-label":Craft.t("app","Tablet"),"aria-selected":"false",tabindex:"-1",data:{width:768,height:1024,deviceType:"tablet"}}).appendTo(this.$deviceTypeContainer),t("<button/>",{type:"button",role:"option",class:"btn lp-device-type-btn--phone",title:Craft.t("app","Mobile"),"aria-label":Craft.t("app","Mobile"),"aria-selected":"false",tabindex:"-1",data:{width:375,height:667,deviceType:"phone"}}).appendTo(this.$deviceTypeContainer),t('<div class="flex-grow"/>').appendTo(this.$previewHeader),this.$orientationBtn=t("<button/>",{type:"button",class:"btn disabled","data-icon":"refresh",disabled:"","aria-hidden":"",text:Craft.t("app","Rotate")}).appendTo(this.$previewHeader),this.addListener(this.$orientationBtn,"click","switchOrientation"),this.deviceOrientation=Craft.getLocalStorage("LivePreview.orientation"),this.addListener(t(".btn",this.$deviceTypeContainer),"click","switchDeviceType"),this.$deviceMask=t("<div/>",{class:"lp-device-mask"})}this.$iframeContainer=t("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$deviceMask&&this.$iframeContainer.append(this.$deviceMask),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",()=>{this.draftEditor.showStatusHud(this.$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 s=t("#content .field").not(t("#content .field .field"));if(s.length){this.$tempInput.insertBefore(s.get(0));for(let e=0;e<s.length;e++){let i=t(s[e]),a=this._getClone(i);this.$fieldPlaceholder.insertAfter(i),i.detach(),this.$fieldPlaceholder.replaceWith(a),i.appendTo(this.$editor),this.fields.push({$field:i,$clone:a})}}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")}},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.trigger("switchTarget",{previewTarget:this.draftEditor.settings.previewTargets[t]})},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){this.isActive&&!this.isVisible&&(t("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",()=>{this.trigger("slideIn"),Garnish.$win.trigger("resize")}),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",()=>{this.addListener(Garnish.$bod,"keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&this.close()}))}),this.isVisible=!0)},close:function(){this.isActive&&this.isVisible&&(this.trigger("beforeClose"),t("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),this.removeListener(Garnish.$bod,"keyup"),this.$tempInput.detach(),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",()=>{for(var t=0;t<this.fields.length;t++)this.fields[t].$newClone.remove();this.$editorContainer.hide(),this.trigger("slideOut")}),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",()=>{this.$previewContainer.hide(),this.resetDevicePreview()}),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")},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(e){if(!this.isActive)return!1;e=!0===e;var i=this.draftEditor.settings.previewTargets[this.activeTarget],s=!(this.draftId===(this.draftId=this.draftEditor.settings.draftId)&&this.$iframe&&!e&&void 0!==i.refresh&&!i.refresh);this.trigger("beforeUpdateIframe",{previewTarget:i,resetScroll:e,refresh:s}),s?this.draftEditor.getTokenizedPreviewUrl(i.url,"x-craft-live-preview").then(i=>{let s;e?this.scrollTop=null:this.iframeLoaded&&this.$iframe&&(this._useIframeResizer()?(this.iframeHeight=this.$iframe.height(),this.scrollTop=this.$iframeContainer.scrollTop()):(s=Craft.isSameHost(i),s&&this.$iframe[0].contentWindow&&(this.scrollTop=t(this.$iframe[0].contentWindow.document).scrollTop()))),this.iframeLoaded=!1;var a=t("<iframe/>",{class:"lp-preview",frameborder:0,src:i});this.$iframe?this.$iframe.replaceWith(a):a.appendTo(this.$iframeContainer),this._devicePreviewIsActive()&&(this.$devicePreviewContainer||(this.$devicePreviewContainer=t("<div/>",{class:"lp-device-preview-container"}),a.wrap('<div class="lp-device-preview-container"></div>'),this.$devicePreviewContainer=this.$iframeContainer.find(".lp-device-preview-container"))),this._useIframeResizer()?(e||null===this.iframeHeight||(a.height(this.iframeHeight),this.$iframeContainer.scrollTop(this.scrollTop)),iFrameResize(t.extend({checkOrigin:!1,scrolling:!0,onInit:t=>{this.iframeLoaded=!0,this.iframeHeight=null,this.scrollTop=null,t.scrolling="no"}},Craft.previewIframeResizerOptions||{}),a[0])):a.on("load",()=>{this.iframeLoaded=!0,!e&&s&&null!==this.scrollTop&&t(a[0].contentWindow.document).scrollTop(this.scrollTop)}),this.url=i,this.$iframe=a,this._devicePreviewIsActive()&&this.updateDevicePreview(),this.trigger("afterUpdateIframe",{previewTarget:this.draftEditor.settings.previewTargets[this.activeTarget],$iframe:this.$iframe}),this.slideIn()}):this.slideIn()},_devicePreviewIsActive:function(){return"desktop"!==this.currentDeviceType},switchDeviceType:function(e){if(this.isDeviceUpdating)return!1;this.$iframeContainer.removeClass("lp-iframe-container--animating");const i=t(e.target),s=i.data("deviceType");if(s===this.currentDeviceType)return!1;this.currentDeviceType=s,this.deviceWidth=i.data("width"),this.deviceHeight=i.data("height"),this.$deviceTypeContainer.find(".btn").removeClass("active").attr("aria-selected","false"),i.addClass("active").attr("aria-selected","true"),"desktop"===this.currentDeviceType?this.resetDevicePreview():(this.$iframeContainer.addClass("lp-iframe-container--updating"),this.updateIframe(),this.updateDevicePreview())},switchOrientation:function(){if(this.isDeviceUpdating||!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--animating"),this.updateDevicePreview()},updateDevicePreview:function(){if(this.isDeviceUpdating)return!1;this.isDeviceUpdating=!0,this.$orientationBtn.removeClass("disabled").removeAttr("disabled").removeAttr("aria-hidden"),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");let e=1,i=1,s=1,a=this.$previewContainer.height()-50-48,n=this.$previewContainer.width()-48,r=this.deviceMaskDimensions[this.currentDeviceType].height,o=this.deviceMaskDimensions[this.currentDeviceType].width;"landscape"===this.deviceOrientation?(n<r&&(e=n/r),a<o&&(i=a/o)):(a<r&&(e=a/r),n<o&&(i=n/o)),s=e,i<e&&(s=i);const l=-100/s/2,h="landscape"===this.deviceOrientation?"-90deg":"0deg";this.$deviceMask.css({width:this.deviceMaskDimensions[this.currentDeviceType].width+"px",height:this.deviceMaskDimensions[this.currentDeviceType].height+"px",transform:"scale("+s+") translate("+l+"%, "+l+"%) rotate("+h+")"}),this.deviceAnimationTimeout&&clearTimeout(this.deviceAnimationTimeout),this.deviceAnimationTimeout=setTimeout(t.proxy((function(){"landscape"===this.deviceOrientation?this.$devicePreviewContainer.css({width:this.deviceHeight+"px",height:this.deviceWidth+"px",transform:"scale("+s+") translate("+l+"%, "+l+"%)",marginTop:0,marginLeft:"-"+12*s+"px"}):this.$devicePreviewContainer.css({width:this.deviceWidth+"px",height:this.deviceHeight+"px",transform:"scale("+s+") translate("+l+"%, "+l+"%)",marginTop:"-"+12*s+"px",marginLeft:0}),this.$iframeContainer.removeClass("lp-iframe-container--animating"),this.$iframeContainer.removeClass("lp-iframe-container--updating"),this.isDeviceUpdating=!1}),this),300)},resetDevicePreview:function(){this.deviceAnimationTimeout&&clearTimeout(this.deviceAnimationTimeout),this.currentDeviceType="desktop",this.$deviceTypeContainer.find(".btn").removeClass("active").attr("aria-selected","false"),this.$deviceTypeContainer.find(".lp-device-type-btn--desktop").addClass("active").attr("aria-selected","true"),this.$orientationBtn.addClass("disabled").attr("disabled","").attr("aria-hidden",""),this.$iframeContainer.removeClass("lp-iframe-container--animating"),this.$iframeContainer.removeClass("lp-iframe-container--has-device-preview"),this.$iframeContainer.removeClass("lp-iframe-container--tablet"),this.$devicePreviewContainer&&(this._useIframeResizer()&&this.$iframe[0].iFrameResizer.removeListeners(),this.$devicePreviewContainer.detach(),this.$devicePreviewContainer=null,this.$iframe=null,this.updateIframe()),this.isDeviceUpdating=!1},_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}),Craft.PreviewFileModal=Garnish.Modal.extend({assetId:null,$spinner:null,elementSelect:null,type:null,loaded:null,requestId:0,init:function(e,i,s){if((s=t.extend(this.defaultSettings,s)).onHide=this._onHide.bind(this),Craft.PreviewFileModal.openInstance){var a=Craft.PreviewFileModal.openInstance;return a.assetId!==e&&(a.loadAsset(e,s.startingWidth,s.startingHeight),a.elementSelect=i),this.destroy()}Craft.PreviewFileModal.openInstance=this,this.elementSelect=i,this.$container=t('<div class="modal previewmodal loading"/>').appendTo(Garnish.$bod),this.base(this.$container,t.extend({resizable:!0},s)),this.$container&&(this.$container.velocity("stop"),this.$container.show().css("opacity",1),this.$shade.velocity("stop"),this.$shade.show().css("opacity",1)),this.loadAsset(e,s.startingWidth,s.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(e,i,s){this.assetId=e,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,i&&s){var r=i/s;n=Math.min(i,Garnish.$win.width()-2*this.settings.minGutter),(n=(a=Math.min(n/r,Garnish.$win.height()-2*this.settings.minGutter))*r)>Math.min(i,Garnish.$win.width()-2*this.settings.minGutter)&&(a=(n=Math.min(i,Garnish.$win.width()-2*this.settings.minGutter))/r)}this._resizeContainer(n,a),this.$spinner=t('<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:e,requestId:this.requestId},function(e,i){if(this.$container.removeClass("loading"),this.$spinner.remove(),this.loaded=!0,"success"===i)if(e.success){if(e.requestId!=this.requestId)return;if(!e.previewHtml)return this.$container.addClass("zilch"),void this.$container.append(t("<p/>",{text:Craft.t("app","No preview available.")}));this.$container.removeClass("zilch"),this.$container.append(e.previewHtml),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml)}else alert(e.error),this.hide()}.bind(this))},_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}}),Craft.ProgressBar=Garnish.Base.extend({$progressBar:null,$innerProgressBar:null,$progressBarStatus:null,_itemCount:0,_processedItemCount:0,_displaySteps:!1,init:function(e,i){i&&(this._displaySteps=!0),this.$progressBar=t('<div class="progressbar pending hidden"/>').appendTo(e),this.$innerProgressBar=t('<div class="progressbar-inner"/>').appendTo(this.$progressBar),this.$progressBarStatus=t('<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(){this.$progressBar.fadeTo("fast",.01,t.proxy((function(){this.$progressBar.addClass("hidden").fadeTo(1,1,t.noop)}),this))},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+"%"))}}),Craft.PromptHandler=Garnish.Base.extend({modal:null,$modalContainerDiv:null,$prompt:null,$promptApplyToRemainingContainer:null,$promptApplyToRemainingCheckbox:null,$promptApplyToRemainingLabel:null,$pomptChoices:null,_prompts:[],_promptBatchCallback:t.noop,_promptBatchReturnData:[],_promptBatchNum:0,resetPrompts:function(){this._prompts=[],this._promptBatchCallback=t.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 e=this._prompts[this._promptBatchNum].prompt,i=this._prompts.length-(this._promptBatchNum+1);this._showPrompt(e.message,e.choices,t.proxy(this,"_handleBatchPromptSelection"),i)},_handleBatchPromptSelection:function(e,i){var s=this._prompts[this._promptBatchNum],a=this._prompts.length-(this._promptBatchNum+1),n=t.extend(s,{choice:e});this._promptBatchReturnData.push(n),a?(this._promptBatchNum++,i?this._handleBatchPromptSelection(e,!0):this._showNextPromptInBatch()):"function"==typeof this._promptBatchCallback&&this._promptBatchCallback(this._promptBatchReturnData)},_showPrompt:function(e,i,s,a){this._promptCallback=s,null===this.modal&&(this.modal=new Garnish.Modal({closeOtherModals:!1})),null===this.$modalContainerDiv&&(this.$modalContainerDiv=t('<div class="modal fitted prompt-modal"></div>').addClass().appendTo(Garnish.$bod)),this.$prompt=t('<div class="body"></div>').appendTo(this.$modalContainerDiv.empty()),this.$promptMessage=t('<p class="prompt-msg"/>').appendTo(this.$prompt),this.$promptChoices=t('<div class="options"></div>').appendTo(this.$prompt),this.$promptApplyToRemainingContainer=t('<label class="assets-applytoremaining"/>').appendTo(this.$prompt).hide(),this.$promptApplyToRemainingCheckbox=t('<input type="checkbox"/>').appendTo(this.$promptApplyToRemainingContainer),this.$promptApplyToRemainingLabel=t("<span/>").appendTo(this.$promptApplyToRemainingContainer),this.$promptButtons=t('<div class="buttons right"/>').appendTo(this.$prompt),this.modal.setContainer(this.$modalContainerDiv),this.$promptMessage.html(e);let n=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$promptButtons),r=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","OK")}).appendTo(this.$promptButtons);for(var o=0;o<i.length;o++){var l=t('<div><label><input type="radio" name="promptAction" value="'+i[o].value+'"/> '+i[o].title+"</label></div>").appendTo(this.$promptChoices).find("input");this.addListener(l,"click",(function(){r.removeClass("disabled")}))}this.addListener(r,"activate",(function(e){var i=t(e.currentTarget).parents(".modal").find("input[name=promptAction]:checked").val(),s=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice(i,s)})),this.addListener(n,"activate",(function(){var t=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice("cancel",t)})),a&&(this.$promptApplyToRemainingContainer.show(),this.$promptApplyToRemainingLabel.html(" "+Craft.t("app","Apply this to the {number} remaining conflicts?",{number:a}))),this.modal.show(),this.modal.removeListener(Garnish.Modal.$shade,"click"),this.addListener(Garnish.Modal.$shade,"click","_cancelPrompt")},_selectPromptChoice:function(e,i){this.$prompt.fadeOut("fast",t.proxy((function(){this.modal.hide(),this._promptCallback(e,i)}),this))},_cancelPrompt:function(){this._selectPromptChoice("cancel",!0)}}),function(t){Craft.SlidePicker=Garnish.Base.extend({min:null,max:null,totalSteps:null,value:null,$container:null,$buttons:null,init:function(e,i){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",t=>{switch(t.keyCode){case Garnish.UP_KEY:this.setValue(this.value+this.settings.step),t.preventDefault();break;case Garnish.DOWN_KEY:this.setValue(this.value-this.settings.step),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.setValue(this.value+this.settings.step):this.setValue(this.value-this.settings.step),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.setValue(this.value-this.settings.step):this.setValue(this.value+this.settings.step),t.preventDefault()}})},refresh:function(){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(let e=this.min;e<=this.max;e+=this.settings.step)this.$buttons=this.$buttons.add(t("<a/>",{title:this.settings.valueLabel(e),data:{value:e}}));if(this.$buttons.appendTo(this.$container),null!==this.value){let t=this.value;this.value=null,this.setValue(t,!1)}this.addListener(this.$buttons,"mouseover",e=>{this.$buttons.removeClass("active-hover last-active-hover"),t(e.currentTarget).addClass("active-hover last-active-hover").prevAll().addClass("active-hover")}),this.addListener(this.$buttons,"mouseout",()=>{this.$buttons.removeClass("active-hover")}),this.addListener(this.$buttons,"click",e=>{this.setValue(t.data(e.currentTarget,"value")),e.stopPropagation(),this.$container.focus()})},setValue:function(t,e){if(t=Math.max(Math.min(t,this.max),this.min),this.value===(this.value=t))return;this.$container.attr({"aria-valuenow":this.value,"aria-valuetext":this.settings.valueLabel(this.value)}),this.$buttons.removeClass("last-active active");let 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),Craft.SlideRuleInput=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,$input:null,value:null,startPositionX:null,init:function(e,i){this.setSettings(i,Craft.SlideRuleInput.defaultSettings),this.value=0,this.graduationsMin=-70,this.graduationsMax=70,this.slideMin=-45,this.slideMax=45,this.$container=t("#"+e),this.$overlay=t('<div class="overlay"></div>').appendTo(this.$container),this.$cursor=t('<div class="cursor"></div>').appendTo(this.$container),this.$graduations=t('<div class="graduations"></div>').appendTo(this.$container),this.$graduationsUl=t("<ul></ul>").appendTo(this.$graduations);for(var s=this.graduationsMin;s<=this.graduationsMax;s++){var a=t('<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",t.proxy(this,"_handleResize")),this.addListener(this.$container,"tapstart",t.proxy(this,"_handleTapStart")),this.addListener(Garnish.$bod,"tapmove",t.proxy(this,"_handleTapMove")),this.addListener(Garnish.$bod,"tapend",t.proxy(this,"_handleTapEnd")),setTimeout(t.proxy((function(){this.graduationsCalculatedWidth=10*(this.$options.length-1),this.$graduationsUl.css("left",-this.graduationsCalculatedWidth/2+this.$container.width()/2)}),this),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(e){var i=this.valueToPosition(e);e<this.slideMin?(e=this.slideMin,i=this.valueToPosition(e)):e>this.slideMax&&(e=this.slideMax,i=this.valueToPosition(e)),this.$graduationsUl.css("left",i),e>=this.slideMin&&e<=this.slideMax&&(this.$options.removeClass("selected"),t.each(this.$options,(function(i,s){t(s).data("graduation")>0&&t(s).data("graduation")<=e&&t(s).addClass("selected"),t(s).data("graduation")<0&&t(s).data("graduation")>=e&&t(s).addClass("selected"),0==t(s).data("graduation")&&t(s).addClass("selected")}))),this.value=e},_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:t.noop,onChange:t.noop,onEnd:t.noop}}),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):""}}),Craft.Structure=Garnish.Base.extend({id:null,$container:null,state:null,structureDrag:null,init:function(e,i,s){this.id=e,this.$container=t(i),this.setSettings(s,Craft.Structure.defaults),this.$container.data("structure")&&(Garnish.log("Double-instantiating a structure on an element"),this.$container.data("structure").destroy()),this.$container.data("structure",this),this.state={},this.settings.storageKey&&t.extend(this.state,Craft.getLocalStorage(this.settings.storageKey,{})),void 0===this.state.collapsedElementIds&&(this.state.collapsedElementIds=[]);for(var a=this.$container.find("ul").prev(".row"),n=0;n<a.length;n++){var r=t(a[n]),o=r.parent(),l=t('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(r);-1!==t.inArray(r.children(".element").data("id"),this.state.collapsedElementIds)&&o.addClass("collapsed"),this.initToggle(l)}this.settings.sortable&&(this.structureDrag=new Craft.StructureDrag(this,this.settings.maxLevels)),this.settings.newChildUrl&&this.initNewChildMenus(this.$container.find(".add"))},initToggle:function(e){e.on("click",t.proxy((function(e){var i=t(e.currentTarget).closest("li"),s=i.children(".row").find(".element:first").data("id"),a=t.inArray(s,this.state.collapsedElementIds);i.hasClass("collapsed")?(i.removeClass("collapsed"),-1!==a&&this.state.collapsedElementIds.splice(a,1)):(i.addClass("collapsed"),-1===a&&this.state.collapsedElementIds.push(s)),this.settings.storageKey&&Craft.setLocalStorage(this.settings.storageKey,this.state)}),this))},initNewChildMenus:function(t){this.addListener(t,"click","onNewChildMenuClick")},onNewChildMenuClick:function(e){var i=t(e.currentTarget);if(!i.data("menubtn")){var s=i.parent().children(".element").data("id"),a=Craft.getUrl(this.settings.newChildUrl,"parentId="+s);t('<div class="menu"><ul><li><a href="'+a+'">'+Craft.t("app","New child")+"</a></li></ul></div>").insertAfter(i),new Garnish.MenuBtn(i).showMenu()}},getIndent:function(t){return Craft.Structure.baseIndent+(t-1)*Craft.Structure.nestedIndent},addElement:function(e){var i=t('<li data-level="1"/>').appendTo(this.$container),s=t('<div class="row" style="margin-'+Craft.left+": -"+Craft.Structure.baseIndent+"px; padding-"+Craft.left+": "+Craft.Structure.baseIndent+'px;">').appendTo(i);if(s.append(e),this.settings.sortable&&(s.append('<a class="move icon" title="'+Craft.t("app","Move")+'"></a>'),this.structureDrag.addItems(i)),this.settings.newChildUrl){var a=t('<a class="add icon" title="'+Craft.t("app","New child")+'"></a>').appendTo(s);this.initNewChildMenus(a)}s.css("margin-bottom",-30),s.velocity({"margin-bottom":0},"fast")},removeElement:function(e){var i,s=e.parent().parent();this.settings.sortable&&this.structureDrag.removeItems(s),s.siblings().length||(i=s.parent()),s.css("visibility","hidden").velocity({marginBottom:-s.height()},"fast",t.proxy((function(){s.remove(),void 0!==i&&this._removeUl(i)}),this))},_removeUl:function(t){t.siblings(".row").children(".toggle").remove(),t.remove()}},{baseIndent:8,nestedIndent:35,defaults:{storageKey:null,sortable:!1,newChildUrl:null,maxLevels:null}}),Craft.StructureDrag=Garnish.Drag.extend({structure:null,maxLevels:null,draggeeLevel:null,$helperLi:null,$targets:null,draggeeHeight:null,init:function(e,i){this.structure=e,this.maxLevels=i,this.$insertion=t('<li class="draginsertion"/>');var s=this.structure.$container.find("li");this.base(s,{handle:".element:first, .move:first",helper:t.proxy(this,"getHelper")})},getHelper:function(e){this.$helperLi=e;var i=t('<ul class="structure draghelper"/>').append(e);return e.css("padding-"+Craft.left,this.$draggee.css("padding-"+Craft.left)),e.find(".move").removeAttr("title"),i},onDragStart:function(){this.$targets=t(),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",t.proxy((function(){this.$draggee.addClass("hidden")}),this)),this.base(),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&this.cancelDrag()}))},findTargets:function(e){for(var i=e.children().not(this.$draggee),s=0;s<i.length;s++){var a=t(i[s]);this.$targets=this.$targets.add(a.children(".row")),a.hasClass("collapsed")||this.findTargets(a.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=t(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=t(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=t(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(){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===t.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=t('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(this._.$closestTarget);this.structure.initToggle(n),a=t("<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",t.proxy((function(){this.$draggee.css("height","auto")}),this)),this.returnHelpersToDraggees(),this.base()},setLevel:function(e,i){e.data("level",i);var s=this.structure.getIndent(i),a={};a["margin-"+Craft.left]="-"+s+"px",a["padding-"+Craft.left]=s+"px",this.$draggee.children(".row").css(a);for(var n=e.children("ul").children(),r=0;r<n.length;r++)this.setLevel(t(n[r]),i+1)}}),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,_updateAncestorsProxy:null,_draggeeLevel:null,_draggeeLevelDelta:null,draggingLastElements:null,_loadingDraggeeLevelDelta:!1,_targetLevel:null,_targetLevelBounds:null,_positionChanged:null,init:function(e,i,s){this.tableView=e,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,s=t.extend({},Craft.StructureTableSorter.defaults,s,{handle:".move",collapseDraggees:!0,singleHelper:!0,helperSpacingY:2,magnetStrength:4,helper:t.proxy(this,"getHelper"),helperLagBase:1.5,axis:Garnish.Y_AXIS}),this.base(i,s)},findDraggee:function(){this._draggeeLevel=this._targetLevel=this.$targetItem.data("level"),this._draggeeLevelDelta=0;for(var e=t(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,t.proxy((function(t,e){"success"===e&&(this._loadingDraggeeLevelDelta=!1,this.dragging&&(this._draggeeLevelDelta=t.delta,this.drag(!1)))}),this))}return e},getHelper:function(e){var i=t('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),s=t('<div class="tableview"/>').appendTo(i),a=t('<table class="data"/>').appendTo(s),n=t("<tbody/>").appendTo(a);e.appendTo(n),this._$firstRowCells=this.tableView.$elementContainer.children("tr:first").children();for(var r=e.children(),o=0;o<r.length;o++){var l=t(r[o]);if(l.hasClass("checkbox-cell"))l.remove();else{var h=t(this._$firstRowCells[o]),d=h[0].getBoundingClientRect().width;if(h.css("width",d+"px"),l.css("width",d+"px"),Garnish.hasAttr(h,"data-titlecell")){this._$titleHelperCell=l;parseInt(h.css("padding-"+Craft.left));this._titleHelperCellOuterWidth=d,l.css("padding-"+Craft.left,this._basePadding)}}}return i},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(){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=t(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,t.proxy((function(t,e){if("success"===e){if(!t.success)return Craft.cp.displayError(Craft.t("app","A server error occurred.")),void this.tableView.elementIndex.updateElements();Craft.cp.displayNotice(Craft.t("app","New position saved.")),this.onPositionChange(),d&&d.parent().length&&(d.remove(),this.tableView._expandElement(h,!0)),Craft.cp.runQueue()}}),this))}},onSortChange:function(){this.tableView.elementSelect&&this.tableView.elementSelect.resetItemOrder(),this._positionChanged=!0,this.base()},onPositionChange:function(){Garnish.requestAnimationFrame(t.proxy((function(){this.trigger("positionChange"),this.settings.onPositionChange()}),this))},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._updateAncestorsProxy||(this._updateAncestorsProxy=t.proxy(this,"_updateAncestors")),this._updateAncestorsFrame=Garnish.requestAnimationFrame(this._updateAncestorsProxy)},_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")&&t('<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:t.noop}}),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(),{onSortChange:t.proxy(this,"_onStructureTableSortChange")}):this.structureTableSort=null,"structure"===this.elementIndex.getSelectedSortAttribute()&&this.addListener(this.$elementContainer,"click",(function(e){var i=t(e.target);i.hasClass("toggle")&&!1===this._collapseElement(i)&&this._expandElement(i)}))},initTableHeaders:function(){for(var e=this.elementIndex.getSelectedSortAttribute(),i=this.$table.children("thead").children().children("[data-attribute]"),s=0;s<i.length;s++){var a=i.eq(s),n=a.attr("data-attribute");if(n===e){this.$selectedSortHeader=a;var r=this.elementIndex.getSelectedSortDirection();a.addClass("ordered "+r).on("click",t.proxy(this,"_handleSelectedSortHeaderClick"))}else{this.elementIndex.getSortAttributeOption(n).length&&a.addClass("orderable").on("click",t.proxy(this,"_handleUnselectedSortHeaderClick"))}}},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(e){Craft.createElementEditor(e.data("type"),e,{params:{includeTableAttributesForSource:this.elementIndex.sourceKey},onSaveElement:t.proxy((function(t){t.tableAttributes&&this._updateTableAttributes(e,t.tableAttributes)}),this),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(e,i){if(!i&&e.hasClass("expanded"))return!1;if(e.addClass("expanded"),this.elementIndex.instanceState.collapsedElementIds){var s=e.parent().parent(),a=s.data("id"),n=t.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=t.extend(!0,{},this.settings.params);o.criteria.descendantOf=a,Craft.postActionRequest("element-indexes/get-more-elements",o,t.proxy((function(e,i){if(r.parent().length&&"success"===i){var s=t(e.html),a=this._totalVisible+s.length,n=this.settings.batchSize&&s.length===this.settings.batchSize;if(n){var o=r.nextAll();this.elementSelect&&this.elementSelect.removeItems(o),this.structureTableSort&&this.structureTableSort.removeItems(o),o.remove(),a-=o.length}else n=this._morePending;r.replaceWith(s),this.thumbLoader.load(s),(this.elementIndex.actions||this.settings.selectable)&&(this.elementSelect.addItems(s.filter(":not(.disabled)")),this.elementIndex.updateActionTriggers()),this.structureTableSort&&this.structureTableSort.addItems(s),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),Craft.cp.updateResponsiveTables(),this.setTotalVisible(a),this.setMorePending(n),this.maybeLoadMore()}}),this))}}},_createSpinnerRowAfter:function(e){return t('<tr data-spinnerrow><td class="centeralign" colspan="'+e.children().length+'"><div class="spinner"/></td></tr>').insertAfter(e)},_isStructureTableDraggingLastElements:function(){return this.structureTableSort&&this.structureTableSort.dragging&&this.structureTableSort.draggingLastElements},_handleSelectedSortHeaderClick:function(e){var i=t(e.currentTarget);if(!i.hasClass("loading")){var s="asc"===this.elementIndex.getSelectedSortDirection()?"desc":"asc";this.elementIndex.setSortDirection(s),this._handleSortHeaderClick(e,i)}},_handleUnselectedSortHeaderClick:function(e){var i=t(e.currentTarget);if(!i.hasClass("loading")){var s=i.attr("data-attribute");this.elementIndex.setSortAttribute(s),this._handleSortHeaderClick(e,i)}},_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])}}),Craft.TagSelectInput=Craft.BaseElementSelectInput.extend({searchTimeout:null,searchMenu:null,$container:null,$elementsContainer:null,$elements:null,$addTagInput:null,$spinner:null,_ignoreBlur:!1,init:function(e){if(!t.isPlainObject(e)){for(var i={},s=["id","name","tagGroupId","sourceElementId"],a=0;a<s.length&&void 0!==arguments[a];a++)i[s[a]]=arguments[a];e=i}this.base(t.extend({},Craft.TagSelectInput.defaults,e)),this.$addTagInput=this.$container.children(".add").children(".text"),this.$spinner=this.$addTagInput.next(),this.addListener(this.$addTagInput,"input",t.proxy((function(){this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout(t.proxy(this,"searchForTags"),500)}),this)),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){let t=this.searchMenu.$options.filter(".hover");if(t.length){let e=t.parent().nextAll().find("a:not(.disabled)").first();e.length&&this.focusOption(e)}else this.focusOption(this.searchMenu.$options.eq(0))}return;case Garnish.UP_KEY:if(t.preventDefault(),this.searchMenu){let t=this.searchMenu.$options.filter(".hover");if(t.length){let e=t.parent().prevAll().find("a:not(.disabled)").last();e.length&&this.focusOption(e)}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(){this._ignoreBlur?this._ignoreBlur=!1:setTimeout(t.proxy((function(){this.searchMenu&&this.searchMenu.hide()}),this),1)}))},focusOption:function(t){this.searchMenu.$options.removeClass("hover"),t.addClass("hover"),this.searchMenu.$menuList.attr("aria-activedescendant",t.attr("id"))},getAddElementsBtn:t.noop,getElementSortAxis:function(){return null},searchForTags:function(){if(this.searchMenu&&this.killSearchMenu(),this.$addTagInput.val()){this.$spinner.removeClass("hidden");for(var e=[],i=0;i<this.$elements.length;i++){var s=t(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,t.proxy((function(e,i){if(this.searchMenu&&this.killSearchMenu(),this.$spinner.addClass("hidden"),"success"===i){for(var s,n=t('<div class="menu tagmenu"/>').appendTo(Garnish.$bod),r=t("<ul/>").appendTo(n),o=0;o<e.tags.length;o++)s=t("<li/>").appendTo(r),t('<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=t("<li/>").appendTo(r),t('<a data-icon="plus"/>').appendTo(s).text(a.search)),r.find("a:not(.disabled):first").addClass("hover"),this.searchMenu=new Garnish.Menu(n,{attachToElement:this.$addTagInput,onOptionSelect:t.proxy(this,"selectTag")}),this.addListener(n,"mousedown",t.proxy((function(){this._ignoreBlur=!0}),this)),this.searchMenu.show()}}),this))}else this.$spinner.addClass("hidden")},selectTag:function(e){var i=t(e);if(!i.hasClass("disabled")){var s=i.data("id"),a=i.text(),n=t("<div/>",{class:"element small removable","data-id":s,"data-site-id":this.settings.targetSiteId,"data-label":a,"data-editable":"1"}).appendTo(this.$elementsContainer),r=t("<input/>",{type:"hidden",name:this.settings.name+"[]",value:s}).appendTo(n);t("<a/>",{class:"delete icon",title:Craft.t("app","Remove")}).appendTo(n);var o=t("<div/>",{class:"label"}).appendTo(n);t("<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,t.proxy((function(t,e){"success"===e&&t.success?(n.attr("data-id",t.id),r.val(t.id),n.removeClass("loading disabled")):(this.removeElement(n),"success"===e&&Craft.cp.displayError(Craft.t("app","A server error occurred.")))}),this))}}},killSearchMenu:function(){this.searchMenu.hide(),this.searchMenu.destroy(),this.searchMenu=null}},{defaults:{tagGroupId:null}}),Craft.ThumbsElementIndexView=Craft.BaseElementIndexView.extend({getElementContainer:function(){return this.$container.children("ul")}}),Craft.ui={createTextInput:function(e){e=t.extend({autocomplete:!1},e);var i=t("<input/>",{attr:{class:"text",type:e.type||"text",inputmode:e.inputmode,id:e.id,size:e.size,name:e.name,value:e.value,maxlength:e.maxlength,autofocus:this.getAutofocusValue(e.autofocus),autocomplete:"boolean"==typeof e.autocomplete?e.autocomplete?"on":"off":e.autocomplete,disabled:this.getDisabledValue(e.disabled),readonly:e.readonly,title:e.title,placeholder:e.placeholder,step:e.step,min:e.min,max:e.max}});return e.class&&i.addClass(e.class),e.placeholder&&i.addClass("nicetext"),"password"===e.type&&i.addClass("password"),e.disabled&&i.addClass("disabled"),e.size||i.addClass("fullwidth"),e.showCharsLeft&&e.maxlength&&i.attr("data-show-chars-left").css("padding-"+("ltr"===Craft.orientation?"right":"left"),7.2*e.maxlength.toString().length+14+"px"),(e.placeholder||e.showCharsLeft)&&new Garnish.NiceText(i),"password"===e.type?t('<div class="passwordwrapper"/>').append(i):i},createTextField:function(t){return t.id||(t.id="text"+Math.floor(1e9*Math.random())),this.createField(this.createTextInput(t),t)},createCopyTextInput:function(e){let i=e.id||"copytext"+Math.floor(1e9*Math.random()),s=e.buttonId||i+"-btn",a=t("<div/>",{class:"copytext"}),n=this.createTextInput(t.extend({},e,{readonly:!0})).appendTo(a);return t("<button/>",{type:"button",id:s,class:"btn","data-icon":"clipboard",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard")}).appendTo(a).on("click",()=>{n[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),a.trigger("copy"),n[0].setSelectionRange(0,0)}),a},createCopyTextField:function(t){return t.id||(t.id="copytext"+Math.floor(1e9*Math.random())),this.createField(this.createCopyTextInput(t),t)},createCopyTextPrompt:function(e){let i=t("<div/>",{class:"modal fitted"}),s=t("<div/>",{class:"body"}).appendTo(i);this.createCopyTextField(t.extend({size:Math.max(Math.min(e.value.length,50),25)},e)).appendTo(s);let a=new Garnish.Modal(i,{closeOtherModals:!1});return i.on("copy",()=>{a.hide()}),i},createTextarea:function(e){var i=t("<textarea/>",{class:"text",rows:e.rows||2,cols:e.cols||50,id:e.id,name:e.name,maxlength:e.maxlength,autofocus:e.autofocus&&!Garnish.isMobileBrowser(!0),disabled:!!e.disabled,placeholder:e.placeholder,html:e.value});return e.showCharsLeft&&i.attr("data-show-chars-left",""),e.class&&i.addClass(e.class),e.size||i.addClass("fullwidth"),i},createTextareaField:function(t){return t.id||(t.id="textarea"+Math.floor(1e9*Math.random())),this.createField(this.createTextarea(t),t)},createSelect:function(e){var i=t("<div/>",{class:"select"});e.class&&i.addClass(e.class);var s=t("<select/>",{id:e.id,name:e.name,autofocus:e.autofocus&&Garnish.isMobileBrowser(!0),disabled:e.disabled,"data-target-prefix":e.targetPrefix}).appendTo(i);if(t.isPlainObject(e.options)){let i=[];for(var a in e.options){if(!e.options.hasOwnProperty(a))continue;let s=e.options[a];t.isPlainObject(s)?void 0!==s.optgroup?i.push(s):i.push({label:s.label,value:void 0!==s.value?s.value:a,disabled:void 0!==s.disabled&&s.disabled}):i.push({label:s,value:a})}e.options=i}var n=null;for(let i=0;i<e.options.length;i++){let a=e.options[i];void 0!==a.optgroup?n=t("<optgroup/>",{label:a.label}).appendTo(s):t("<option/>",{value:a.value,selected:a.value==e.value,disabled:void 0!==a.disabled&&a.disabled,html:a.label}).appendTo(n||s)}return e.toggle&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s)),i},createSelectField:function(t){return t.id||(t.id="select"+Math.floor(1e9*Math.random())),this.createField(this.createSelect(t),t)},createCheckbox:function(e){var i=e.id||"checkbox"+Math.floor(1e9*Math.random()),s=t("<input/>",{type:"checkbox",value:void 0!==e.value?e.value:"1",id:i,class:"checkbox",name:e.name,checked:e.checked?"checked":null,autofocus:this.getAutofocusValue(e.autofocus),disabled:this.getDisabledValue(e.disabled),"data-target":e.toggle,"data-reverse-target":e.reverseToggle});e.class&&s.addClass(e.class),(e.toggle||e.reverseToggle)&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s));var a=t("<label/>",{for:i,html:e.label});return e.name&&(e.name.length<3||"[]"!==e.name.substr(-2))?t([t("<input/>",{type:"hidden",name:e.name,value:""})[0],s[0],a[0]]):t([s[0],a[0]])},createCheckboxField:function(e){e.id||(e.id="checkbox"+Math.floor(1e9*Math.random()));var i=t('<div class="field checkboxfield"/>',{id:e.id+"-field"});return e.first&&i.addClass("first"),e.instructions&&i.addClass("has-instructions"),this.createCheckbox(e).appendTo(i),e.instructions&&t('<div class="instructions"/>').text(e.instructions).appendTo(i),i},createCheckboxSelect:function(e){var i,s,a=t('<fieldset class="checkbox-select"/>');e.class&&a.addClass(e.class),e.showAllOption?(i=e.allValue||"*",s=e.values==i,t("<div/>").appendTo(a).append(this.createCheckbox({id:e.id,class:"all",label:"<b>"+(e.allLabel||Craft.t("app","All"))+"</b>",name:e.name,value:i,checked:s,autofocus:e.autofocus}))):s=!1;for(var n=0;n<e.options.length;n++){var r=e.options[n];r.value!=i&&t("<div/>").appendTo(a).append(this.createCheckbox({label:r.label,name:e.name?e.name+"[]":null,value:r.value,checked:s||(e.values||[]).includes(r.value),disabled:s}))}return new Garnish.CheckboxSelect(a),a},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(e){var i=e.value||"1",s=e.indeterminateValue||"-",a=t("<button/>",{type:"button",class:"lightswitch","data-value":i,"data-indeterminate-value":s,id:e.id,role:"checkbox","aria-checked":e.on?"true":e.indeterminate?"mixed":"false","aria-labelledby":e.labelId,"data-target":e.toggle,"data-reverse-target":e.reverseToggle});return e.on?a.addClass("on"):e.indeterminate&&a.addClass("indeterminate"),e.small&&a.addClass("small"),e.disabled&&a.addClass("disabled"),t('<div class="lightswitch-container"><div class="handle"></div></div>').appendTo(a),e.name&&t("<input/>",{type:"hidden",name:e.name,value:e.on?i:e.indeterminate?s:"",disabled:e.disabled}).appendTo(a),(e.toggle||e.reverseToggle)&&(a.addClass("fieldtoggle"),new Craft.FieldToggle(a)),new Craft.LightSwitch(a,{onChange:e.onChange||t.noop}),a},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(e){var i=e.id||"color"+Math.floor(1e9*Math.random()),s=e.containerId||i+"-container",a=e.name||null,n=e.value||null,r=e.small||!1,o=e.autofocus&&Garnish.isMobileBrowser(!0),l=e.disabled||!1,h=t("<div/>",{id:s,class:"flex color-container"}),d=t("<div/>",{class:"color static"+(r?" small":"")}).appendTo(h);t("<div/>",{class:"color-preview",style:e.value?{backgroundColor:e.value}:null}).appendTo(d),this.createTextInput({id:i,name:a,value:n,size:10,class:"color-input",autofocus:o,disabled:l}).appendTo(h);return new Craft.ColorInput(h),h},createColorField:function(t){return t.id||(t.id="color"+Math.floor(1e9*Math.random())),this.createField(this.createColorInput(t),t)},createDateInput:function(e){var i=(e.id||"date"+Math.floor(1e9*Math.random()))+"-date",s=e.name||null,a=s?s+"[date]":null,n=e.value&&"function"==typeof e.value.getMonth?e.value:null,r=n?Craft.formatDate(n):null,o=e.autofocus&&Garnish.isMobileBrowser(!0),l=e.disabled||!1,h=t("<div/>",{class:"datewrapper"}),d=this.createTextInput({id:i,name:a,value:r,placeholder:" ",autocomplete:!1,autofocus:o,disabled:l}).appendTo(h);return t('<div data-icon="date"></div>').appendTo(h),s&&t("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(h),d.datepicker(t.extend({defaultDate:n||new Date},Craft.datepickerOptions)),h},createDateField:function(t){return t.id||(t.id="date"+Math.floor(1e9*Math.random())),this.createField(this.createDateInput(t),t)},createDateRangePicker:function(e){var i=new Date,s=new Date(i.getFullYear(),i.getMonth(),i.getDate());e=t.extend({class:"",options:["today","thisWeek","thisMonth","thisYear","past7Days","past30Days","past90Days","pastYear"],onChange:t.noop,selected:null,startDate:null,endDate:null},e);var a,n,r=t("<div/>",{class:"menu"}),o=t("<ul/>",{class:"padded"}).appendTo(r),l=t("<a/>").addClass("sel").text(Craft.t("app","All")).data("handle","all");t("<li/>").append(l).appendTo(o);for(var h=0;h<e.options.length;h++){var d=e.options[h];switch(d){case"today":a={label:Craft.t("app","Today"),startDate:s,endDate:s};break;case"thisWeek":var c=i.getDay()-Craft.datepickerOptions.firstDay;c<0&&(c+=7),a={label:Craft.t("app","This week"),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-c),endDate:s};break;case"thisMonth":a={label:Craft.t("app","This month"),startDate:new Date(i.getFullYear(),i.getMonth()),endDate:s};break;case"thisYear":a={label:Craft.t("app","This year"),startDate:new Date(i.getFullYear(),0),endDate:s};break;case"past7Days":a={label:Craft.t("app","Past {num} days",{num:7}),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-7),endDate:s};break;case"past30Days":a={label:Craft.t("app","Past {num} days",{num:30}),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-30),endDate:s};break;case"past90Days":a={label:Craft.t("app","Past {num} days",{num:90}),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-90),endDate:s};break;case"pastYear":a={label:Craft.t("app","Past year"),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-365),endDate:s}}var u=t("<li/>"),p=t("<a/>",{text:a.label}).data("handle",d).data("startDate",a.startDate).data("endDate",a.endDate).data("startTime",a.startDate?a.startDate.getTime():null).data("endTime",a.endDate?a.endDate.getTime():null);e.selected&&d==e.selected&&(n=p[0]),u.append(p),u.appendTo(o)}t("<hr/>").appendTo(r);var g=t("<div/>",{class:"flex flex-nowrap padded"}).appendTo(r),f=this.createDateField({label:Craft.t("app","From")}).appendTo(g).find("input"),m=this.createDateField({label:Craft.t("app","To")}).appendTo(g).find("input"),v=f.add(m);v.on("keyup",(function(e){e.keyCode===Garnish.ESC_KEY&&t(this).data("datepicker").dpDiv.is(":visible")&&e.stopPropagation()})),f.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()})),m.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()}));var C=new Garnish.Menu(r,{onOptionSelect:function(i){var s=t(i);_.text(s.text()),C.setPositionRelativeToAnchor(),r.find(".sel").removeClass("sel"),s.addClass("sel"),f.datepicker("setDate",s.data("startDate")),m.datepicker("setDate",s.data("endDate")),e.onChange(s.data("startDate")||null,s.data("endDate")||null,s.data("handle"))}});v.on("change",(function(){let t,i=f.datepicker("getDate"),s=m.datepicker("getDate"),a=i?i.getTime():null,n=s?s.getTime():null,l=o.find("a"),h=!1;for(let i=0;i<l.length;i++)if(t=l.eq(i),a===(t.data("startTime")||null)&&n===(t.data("endTime")||null)){C.selectOption(t[0]),h=!0,e.onChange(null,null,t.data("handle"));break}h||(r.find(".sel").removeClass("sel"),g.addClass("sel"),a||n?a&&n?_.text(f.val()+" - "+m.val()):a?_.text(Craft.t("app","From {date}",{date:f.val()})):_.text(Craft.t("app","To {date}",{date:m.val()})):_.text(Craft.t("app","All")),C.setPositionRelativeToAnchor(),e.onChange(i,s,"custom"))})),C.on("hide",(function(){f.datepicker("hide"),m.datepicker("hide")}));let b="btn menubtn";e.class&&(b=b+" "+e.class);let _=t("<button/>",{type:"button",class:b,"data-icon":"date",text:Craft.t("app","All")});return new Garnish.MenuBtn(_,C),n&&C.selectOption(n),e.startDate&&f.datepicker("setDate",e.startDate),e.endDate&&m.datepicker("setDate",e.endDate),(e.startDate||e.endDate)&&v.trigger("change"),_},createTimeInput:function(e){var i=(e.id||"time"+Math.floor(1e9*Math.random()))+"-time",s=e.name||null,a=s?s+"[time]":null,n=e.value&&"function"==typeof e.value.getMonth?e.value:null,r=e.autofocus&&Garnish.isMobileBrowser(!0),o=e.disabled||!1,l=t("<div/>",{class:"timewrapper"}),h=this.createTextInput({id:i,name:a,placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return t('<div data-icon="time"></div>').appendTo(l),s&&t("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),h.timepicker(Craft.timepickerOptions),n&&h.timepicker("setTime",3600*n.getHours()+60*n.getMinutes()+n.getSeconds()),l},createTimeField:function(t){return t.id||(t.id="time"+Math.floor(1e9*Math.random())),this.createField(this.createTimeInput(t),t)},createField:function(e,i){var s=i.label&&"__blank__"!==i.label?i.label:null,a=(Craft.isMultiSite&&i.siteId&&i.siteId,t(i.fieldset?"<fieldset/>":"<div/>",{class:"field",id:i.fieldId||(i.id?i.id+"-field":null)}));if(i.first&&a.addClass("first"),s){var n=t('<div class="heading"/>').appendTo(a);t(i.fieldset?"<legend/>":"<label/>",{id:i.labelId||(i.id?`${i.id}-${i.fieldset?"legend":"label"}`:null),class:i.required?"required":null,for:!i.fieldset&&i.id,text:s}).appendTo(n)}return i.instructions&&t('<div class="instructions"/>').text(i.instructions).appendTo(a),t('<div class="input"/>').append(e).appendTo(a),i.warning&&t('<p class="warning"/>').text(i.warning).appendTo(a),i.errors&&this.addErrorsToField(a,i.errors),a},createErrorList:function(e){var i=t('<ul class="errors"/>');return e&&this.addErrorsToList(i,e),i},addErrorsToList:function(e,i){for(var s=0;s<i.length;s++)t("<li/>").text(i[s]).appendTo(e)},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}},Craft.Uploader=Garnish.Base.extend({uploader:null,allowedKinds:null,$element:null,settings:null,_rejectedFiles:{},_extensionList:null,_totalFileCounter:0,_validFileCounter:0,init:function(e,i){this._rejectedFiles={size:[],type:[],limit:[]},this.$element=e,this.allowedKinds=null,this._extensionList=null,this._totalFileCounter=0,this._validFileCounter=0;var s=(i=t.extend({},Craft.Uploader.defaults,i)).events;for(var a in delete i.events,i.allowedKinds&&i.allowedKinds.length&&("string"==typeof i.allowedKinds&&(i.allowedKinds=[i.allowedKinds]),this.allowedKinds=i.allowedKinds,delete i.allowedKinds),i.autoUpload=!1,this.uploader=this.$element.fileupload(i),s)s.hasOwnProperty(a)&&this.uploader.on(a,s[a]);this.settings=i,this.uploader.on("fileuploadadd",t.proxy(this,"onFileAdd"))},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(e,i){e.stopPropagation();var s=!1;return this.allowedKinds&&(this._extensionList||this._createExtensionList(),s=!0),i.process().done(t.proxy((function(){var e=i.files[0],a=!0;if(s){var n=e.name.match(/\.([a-z0-4_]+)$/i)[1];-1===t.inArray(n.toLowerCase(),this._extensionList)&&(a=!1,this._rejectedFiles.type.push("“"+e.name+"”"))}e.size>this.settings.maxFileSize&&(this._rejectedFiles.size.push("“"+e.name+"”"),a=!1),a&&"function"==typeof this.settings.canAddMoreFiles&&!this.settings.canAddMoreFiles(this._validFileCounter)&&(this._rejectedFiles.limit.push("“"+e.name+"”"),a=!1),a&&(this._validFileCounter++,i.submit()),++this._totalFileCounter===i.originalFiles.length&&(this._totalFileCounter=0,this._validFileCounter=0,this.processErrorMessages())}),this)),!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){if(t<1024)return t+" B";var e=-1;do{t/=1024,++e}while(t>=1024);return t.toFixed(1)+" "+["kB","MB","GB","TB","PB","EB","ZB","YB"][e]},_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"}}),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}})}(jQuery);
//# sourceMappingURL=Craft.min.js.map


Fixed version (ground truth):
!function(t){var i=/<(?!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(i,"<$1></$2>")},t.extend(Craft,{navHeight:48,index:function(e,i){if(!t.isArray(e))throw"The first argument passed to Craft.index() must be an array.";return e.reduce((t,e,s)=>(t["string"==typeof i?e[i]:i(e,s)]=e,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){let i;if(!1===(i=this._tokenizePattern(t)))throw"Message pattern is invalid.";for(let t=0;t<i.length;t++){let s=i[t];if("object"==typeof s&&!1===(i[t]=this._parseToken(s,e)))throw"Message pattern is invalid."}return i.join("")},_tokenizePattern:function(t){let e,i,s=1;const a=[...t];if(-1===(e=i=a.indexOf("{")))return[t];let n=[a.slice(0,i).join("")];for(;;){let t=a.indexOf("{",i+1),r=a.indexOf("}",i+1);if(-1===t&&(t=!1),-1===r&&(r=!1),!1===t&&!1===r)break;if(!1===t&&(t=a.length),r>t?(s++,i=t):(s--,i=r),0===s&&(n.push(a.slice(e+1,i).join("").split(",",3)),e=i+1,n.push(a.slice(e,t).join("")),e=t),0!==s&&(!1===t||!1===r))break}return 0===s&&n},_parseToken:function(t,e){const i=Craft.trim(t[0]);if(void 0===e[i])return`{${t.join(",")}}`;const s=e[i],a=void 0!==t[1]?Craft.trim(t[1]):"none";switch(a){case"number":let i=void 0!==t[2]?Craft.trim(t[2]):null;if(null!==i&&"integer"!==i)throw"Message format 'number' is only supported for integer values.";let n,r=Craft.formatNumber(s);return null===i&&-1!==(n=(""+s).indexOf("."))&&(r+="."+s.substr(n+1)),r;case"none":return s;case"plural":if(void 0===t[2])return!1;let o=this._tokenizePattern(t[2]);const l=o.length;let h=!1,d=0;for(let t=0;t+1<l;t++){if("object"==typeof o[t]||"object"!=typeof o[t+1])return!1;let e=Craft.trim(o[t++]),i=[...e];if(1===t&&"offset:"===e.substring(0,7)){let t=[...e.replace(/[\n\r\t]/g," ")].indexOf(" ",7);if(-1===t)throw"Message pattern is invalid.";parseInt(Craft.trim(i.slice(7,t).join("")));e=Craft.trim(i.slice(t+1,t+1+i.length).join(""))}(!1===h&&"other"===e||"="===e[0]&&parseInt(i.slice(1,1+i.length).join(""))===s||"one"===e&&s-d==1)&&(h=("string"==typeof o[t]?[o[t]]:o[t]).map(t=>t.replace("#",s-d)).join(","))}if(!1!==h)return this.formatMessage(h,e);break;default:throw`Message format '${a}' is not supported.`}return!1},formatDate:function(e){return"object"!=typeof e&&(e=new Date(e)),t.datepicker.formatDate(Craft.datepickerOptions.dateFormat,e)},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(e){return t("<div/>").text(e).html()},escapeRegex:function(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},getText:function(e){return t("<div/>").html(e).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(e){var i=t(e),s=i.val();if(void 0!==i[0].setSelectionRange){var a=2*s.length;i[0].setSelectionRange(0,a)}else i.val(s)},formatInputId:function(t){return this.rtrim(t.replace(/[\[\]\\]+/g,"-"),"-")},getUrl:function(e,i,s){"string"!=typeof e&&(e="");var a="";if(t.isPlainObject(i)){var n=[];for(var r in i)if(i.hasOwnProperty(r)){var o=i[r];"#"===r?a=o:null!==o&&""!==o&&n.push(r+"="+o)}i=n}i=Garnish.isArray(i)?i.join("&"):Craft.trim(i,"&?");var l=e.indexOf("#");-1!==l&&(a||(a=e.substr(l+1)),e=e.substr(0,l));var h,d=e.indexOf("?");if(-1!==d&&(i=e.substr(d+1)+(i?"&"+i:""),e=e.substr(0,d)),-1!==e.search("://")||"/"===e[0])return e+(i?"?"+i:"")+(a?"#"+a:"");if(e=Craft.trim(e,"/"),s){if(h=s,e&&Craft.pathParam){var c=h.match(new RegExp("[&?]"+Craft.escapeRegex(Craft.pathParam)+"=[^&]+"));c&&(h=h.replace(c[0],Craft.rtrim(c[0],"/")+"/"+e),e="")}}else h=Craft.baseUrl;if(-1!==(d=h.indexOf("?"))&&(i=h.substr(d+1)+(i?"&"+i:""),h=h.substr(0,d)),!Craft.omitScriptNameInUrls&&e)if(Craft.usePathInfo||!Craft.pathParam)-1===h.search(Craft.scriptName)&&(h=Craft.rtrim(h,"/")+"/"+Craft.scriptName);else{if(i&&i.substr(0,Craft.pathParam.length+1)===Craft.pathParam+"="){var u,p=i.indexOf("&");-1!==p?(u=i.substring(2,p),i=i.substr(p+1)):(u=i.substr(2),i=null),e=(u=Craft.rtrim(u))+(e?"/"+e:"")}i=Craft.pathParam+"="+e+(i?"&"+i:""),e=null}return e&&(h=Craft.rtrim(h,"/")+"/"+e),i&&(h+="?"+i),a&&(h+="#"+a),h},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(e,i,s,a){"function"==typeof i&&(a=s,s=i,i={}),(a=a||{}).contentType&&a.contentType.match(/\bjson\b/)&&("object"==typeof i&&(i=JSON.stringify(i)),a.contentType="application/json; charset=utf-8");var n=t.ajax(t.extend({url:Craft.getActionUrl(e),type:"POST",dataType:"json",headers:this._actionHeaders(),data:i,success:s,error:function(t,e,i){4===t.readyState&&(void 0!==Craft.cp?Craft.cp.displayError():alert(Craft.t("app","A server error occurred.")),s&&s(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(){let 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(e,i,s){return new Promise((a,n)=>{(s=s?t.extend({},s):{}).method=e,s.url=Craft.getActionUrl(i),s.headers=t.extend({"X-Requested-With":"XMLHttpRequest"},s.headers||{},this._actionHeaders()),s.params=t.extend({},s.params||{},{v:(new Date).getTime()}),axios.request(s).then(a).catch(n)})},sendApiRequest:function(e,i,s){return new Promise((a,n)=>{let r=(s=s?t.extend({},s):{}).cancelToken||null;this._getApiHeaders(r).then(o=>{s.method=e,s.baseURL=Craft.baseApiUrl,s.url=i,s.headers=t.extend(o,s.headers||{}),s.params=t.extend(Craft.apiParams||{},s.params||{},{v:(new Date).getTime()}),this._apiHeaders||(s.params.processCraftHeaders=1),axios.request(s).then(t=>{this._processApiHeaders(t.headers,r).then(()=>{a(t.data)}).catch(n)}).catch(n)}).catch(n)})},_loadingApiHeaders:!1,_apiHeaders:null,_apiHeaderWaitlist:[],_getApiHeaders:function(t){return new Promise((i,s)=>{this._loadingApiHeaders?this._apiHeaderWaitlist.push([i,s]):this._apiHeaders?i(this._apiHeaders):(this._loadingApiHeaders=!0,this.sendActionRequest("POST","app/api-headers",{cancelToken:t}).then(t=>{this._loadingApiHeaders?i(t.data):s(e)}).catch(t=>{this._rejectApiRequests(s,t)}))})},_processApiHeaders:function(t,i){return new Promise((s,a)=>{this._apiHeaders?s():this.sendActionRequest("POST","app/process-api-response-headers",{data:{headers:t},cancelToken:i}).then(t=>{if(this._loadingApiHeaders)for(this._apiHeaders=t.data,this._loadingApiHeaders=!1,s();this._apiHeaderWaitlist.length;)this._apiHeaderWaitlist.shift()[0](this._apiHeaders);else a(e)}).catch(t=>{this._rejectApiRequests(a,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((s,a)=>{let n=new XMLHttpRequest;n.open(t,e,!0),"object"==typeof i?(n.setRequestHeader("Content-Type","application/json; charset=UTF-8"),i=JSON.stringify(i)):n.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),n.responseType="blob",n.onload=function(){if(200===n.status){let t=n.getResponseHeader("content-disposition"),e=/"([^"]*)"/.exec(t),i=null!=e&&e[1]?e[1]:"Download",a=n.getResponseHeader("content-type"),r=new Blob([n.response],{type:a}),o=document.createElement("a");o.href=window.URL.createObjectURL(r),o.download=i,document.body.appendChild(o),o.click(),document.body.removeChild(o),s()}else a()}.bind(this),n.send(i)})},stringToArray:function(e){if("string"!=typeof e)return e;for(var i=e.split(","),s=0;s<i.length;s++)i[s]=t.trim(i[s]);return i},findDeltaData:function(t,e,i){i.sort((function(t,e){return t.length===e.length?0:t.length>e.length?1:-1}));for(var s=this._groupParamsByDeltaNames(t.split("&"),i,!1,!0),a=this._groupParamsByDeltaNames(e.split("&"),i,!0,!1),n=a.__root__,r=0;r<i.length;r++)(Craft.inArray(i[r],Craft.modifiedDeltaNames)||"object"==typeof a[i[r]]&&("object"!=typeof s[i[r]]||JSON.stringify(s[i[r]])!==JSON.stringify(a[i[r]])))&&(n=n.concat(a[i[r]])).push("modifiedDeltaNames[]="+i[r]);return n.join("&")},_groupParamsByDeltaNames:function(e,i,s,a){var n,r,o={};s&&(o.__root__=[]);t:for(var l=0;l<e.length;l++){for(n=i.length-1;n>=0;n--)if((r=decodeURIComponent(e[l]).substr(0,i[n].length+1))===i[n]+"="||r===i[n]+"["){void 0===o[i[n]]&&(o[i[n]]=[]),o[i[n]].push(e[l]);continue t}s&&o.__root__.push(e[l])}if(a)for(let e in Craft.initialDeltaValues)Craft.initialDeltaValues.hasOwnProperty(e)&&(o[e]=[encodeURIComponent(e)+"="+t.param(Craft.initialDeltaValues[e])]);return o},expandPostArray:function(t){var e,i={};for(var s in t)if(t.hasOwnProperty(s)){var a,n=t[s],r=s.match(/^(\w+)(\[.*)?/);if(r[2])for(a=r[2].match(/\[[^\[\]]*\]/g),e=0;e<a.length;e++)a[e]=a[e].substring(1,a[e].length-1);else a=[];a.unshift(r[1]);var o=i;for(e=0;e<a.length;e++)e<a.length-1?("object"!=typeof o[a[e]]&&(a[e+1]&&parseInt(a[e+1])!=a[e+1]?o[a[e]]={}:o[a[e]]=[]),o=o[a[e]]):(a[e]||(a[e]=o.length),o[a[e]]=n)}return i},createForm:function(e){var i=t("<form/>",{attr:{method:"post",action:"","accept-charset":"UTF-8"}});if("string"==typeof e)for(var s,a=e.split("&"),n=0;n<a.length;n++)s=a[n].split("=",2),t("<input/>",{type:"hidden",name:decodeURIComponent(s[0]),value:decodeURIComponent(s[1]||"")}).appendTo(i);return i},compare:function(t,e,i){if(typeof t!=typeof e)return!1;if("object"==typeof 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 s in t)if(t.hasOwnProperty(s)&&!Craft.compare(t[s],e[s]))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),t=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(e,i){return t.isPlainObject(i)&&(i=Object.values(i)),i.includes(e)},removeFromArray:function(e,i){var s=t.inArray(e,i);return-1!==s&&(i.splice(s,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=Math.floor(t/604800);t%=604800;var s=Math.floor(t/86400);t%=86400;var a,n=Math.floor(t/3600);t%=3600,e?(a=Math.floor(t/60),t%=60):(a=Math.round(t/60),t=0);var r=[];return i&&r.push(i+" "+(1===i?Craft.t("app","week"):Craft.t("app","weeks"))),s&&r.push(s+" "+(1===s?Craft.t("app","day"):Craft.t("app","days"))),n&&r.push(n+" "+(1===n?Craft.t("app","hour"):Craft.t("app","hours"))),!a&&(e||i||s||n)||r.push(a+" "+(1===a?Craft.t("app","minute"):Craft.t("app","minutes"))),!t&&(!e||i||s||n||a)||r.push(t+" "+(1===t?Craft.t("app","second"):Craft.t("app","seconds"))),r.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(e){for(var i=t(document.createElement("ul")).addClass("errors"),s=0;s<e.length;s++){var a=t(document.createElement("li"));a.appendTo(i),a.html(e[s])}return i},appendHeadHtml:function(e){if(e){var i=t("link[href]");if(i.length){for(var s,a=[],n=0;n<i.length;n++)s=i.eq(n).attr("href").replace(/&/g,"&amp;"),a.push(Craft.escapeRegex(s));var r=new RegExp('<link\\s[^>]*href="(?:'+a.join("|")+')".*?><\/script>',"g");e=e.replace(r,"")}t("head").append(e)}},appendFootHtml:function(e){if(e){var i=t("script[src]");if(i.length){for(var s,a=[],n=0;n<i.length;n++)s=i.eq(n).attr("src").replace(/&/g,"&amp;"),a.push(Craft.escapeRegex(s));var r=new RegExp('<script\\s[^>]*src="(?:'+a.join("|")+')".*?><\/script>',"g");e=e.replace(r,"")}Garnish.$bod.append(e)}},initUiElements:function(e){t(".grid",e).grid(),t(".info",e).infoicon(),t(".checkbox-select",e).checkboxselect(),t(".fieldtoggle",e).fieldtoggle(),t(".lightswitch",e).lightswitch(),t(".nicetext",e).nicetext(),t(".formsubmit",e).formsubmit(),t(".menubtn",e).menubtn(),t(".datetimewrapper",e).datetime(),t("a",e).each((function(){this.hostname.length&&this.hostname!==location.hostname&&void 0===t(this).attr("target")&&t(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(e,i,s){return void 0===s&&t.isPlainObject(i)?(s=i,i=null):"object"!=typeof s&&(s={}),s.elementType||(s.elementType=e),new(void 0!==this._elementEditorClasses[e]?this._elementEditorClasses[e]:Craft.BaseElementEditor)(i,s)},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-${Craft.systemUid}.${t}`)},getCookie:function(t){return document.cookie.replace(new RegExp(`(?:(?:^|.*;\\s*)Craft-${Craft.systemUid}:${t}\\s*\\=\\s*([^;]*).*$)|^.*$`),"$1")},setCookie:function(e,i,s){s=t.extend({},this.defaultCookieOptions,s);let a=`Craft-${Craft.systemUid}:${e}=${encodeURIComponent(i)}`;s.path&&(a+=";path="+s.path),s.domain&&(a+=";domain="+s.domain),s.maxAge?a+=";max-age-in-seconds="+s.maxAge:s.expires&&(a+=";expires="+s.expires.toUTCString()),s.secure&&(a+=";secure"),document.cookie=a},removeCookie:function(t){this.setCookie(t,"",new Date("1970-01-01T00:00:00"))},getElementInfo:function(e){var i=t(e);return i.hasClass("element")||(i=i.find(".element:first")),{id:i.data("id"),siteId:i.data("site-id"),label:i.data("label"),status:i.data("status"),url:i.data("url"),hasThumb:i.hasClass("hasthumb"),$element:i}},setElementSize:function(e,i){var s=t(e);if("small"!==i&&"large"!==i&&(i="small"),!s.hasClass(i)){var a="small"===i?"large":"small";if(s.addClass(i).removeClass(a),s.hasClass("hasthumb")){var n=s.find("> .elementthumb > img"),r=t("<img/>",{sizes:("small"===i?"30":"100")+"px",srcset:n.attr("srcset")||n.attr("data-pfsrcset")});n.replaceWith(r),picturefill({elements:[r[0]]})}}},submitForm:function(e,i){if(void 0===i&&(i={}),!i.confirm||confirm(i.confirm)){if(i.action&&t("<input/>",{type:"hidden",name:"action",val:i.action}).appendTo(e),i.redirect&&t("<input/>",{type:"hidden",name:"redirect",val:i.redirect}).appendTo(e),i.params)for(let s in i.params){let a=i.params[s];t("<input/>",{type:"hidden",name:s,val:a}).appendTo(e)}i.retainScroll&&this.setLocalStorage("scrollY",window.scrollY),e.trigger(t.extend({type:"submit"},i.data))}}}),t.extend(t.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 e=t(this);e.addClass("disabled"),e.data("activatable")&&e.removeAttr("tabindex")}))},enable:function(){return this.each((function(){var e=t(this);e.removeClass("disabled"),e.data("activatable")&&e.attr("tabindex","0")}))},grid:function(){return this.each((function(){var e=t(this),i={};e.data("item-selector")&&(i.itemSelector=e.data("item-selector")),e.data("cols")&&(i.cols=parseInt(e.data("cols"))),e.data("max-cols")&&(i.maxCols=parseInt(e.data("max-cols"))),e.data("min-col-width")&&(i.minColWidth=parseInt(e.data("min-col-width"))),e.data("mode")&&(i.mode=e.data("mode")),e.data("fill-mode")&&(i.fillMode=e.data("fill-mode")),e.data("col-class")&&(i.colClass=e.data("col-class")),e.data("snap-to-grid")&&(i.snapToGrid=!!e.data("snap-to-grid")),new Craft.Grid(this,i)}))},infoicon:function(){return this.each((function(){new Craft.InfoIcon(this)}))},checkboxselect:function(){return this.each((function(){t.data(this,"checkboxselect")||new Garnish.CheckboxSelect(this)}))},fieldtoggle:function(){return this.each((function(){t.data(this,"fieldtoggle")||new Craft.FieldToggle(this)}))},lightswitch:function(e,i,s){return"settings"===e?("string"==typeof i?(e={})[i]=s:e=i,this.each((function(){var i=t.data(this,"lightswitch");i&&i.setSettings(e)}))):(t.isPlainObject(e)||(e={}),this.each((function(){var i=t.extend({},e);Garnish.hasAttr(this,"data-value")&&(i.value=t(this).attr("data-value")),Garnish.hasAttr(this,"data-indeterminate-value")&&(i.indeterminateValue=t(this).attr("data-indeterminate-value")),t.data(this,"lightswitch")||new Craft.LightSwitch(this,i)})))},nicetext:function(){return this.each((function(){t.data(this,"nicetext")||new Garnish.NiceText(this)}))},formsubmit:function(){return this.on("click",(function(e){let i=t(e.currentTarget),s=i.data("params")||{};i.data("param")&&(s[i.data("param")]=i.data("value"));let a=i.data("menu")?i.data("menu").$anchor:i,n=a.attr("data-form")?t("#"+a.attr("data-form")):a.closest("form");Craft.submitForm(n,{confirm:i.data("confirm"),action:i.data("action"),redirect:i.data("redirect"),params:s,data:{customTrigger:i}})}))},menubtn:function(){return this.each((function(){var e=t(this);if(!e.data("menubtn")&&e.next().hasClass("menu")){var i={};e.data("menu-anchor")&&(i.menuAnchor=e.data("menu-anchor")),new Garnish.MenuBtn(e,i)}}))},datetime:function(){return this.each((function(){let e=t(this),i=e.find('input:not([name$="[timezone]"])'),s=()=>{let s=!1;for(let t=0;t<i.length;t++)if(i.eq(t).val()){s=!0;break}if(s){if(!e.children(".clear-btn").length){let s=t("<button/>",{type:"button",class:"clear-btn",title:Craft.t("app","Clear"),"aria-label":Craft.t("app","Clear")}).appendTo(e).on("click",()=>{for(let t=0;t<i.length;t++)i.eq(t).val("");s.remove(),i.first().focus()})}}else e.children(".clear-btn").remove()};i.on("change",s),s()}))}}),Garnish.$doc.ready((function(){Craft.initUiElements()})),Craft.BaseElementEditor=Garnish.Base.extend({$element:null,elementId:null,siteId:null,deltaNames:null,initialData:null,$form:null,$fieldsContainer:null,$cancelBtn:null,$saveBtn:null,$spinner:null,$siteSelect:null,$siteSpinner:null,hud:null,init:function(e,i){void 0===i&&t.isPlainObject(e)&&(i=e,e=null),this.$element=t(e),this.setSettings(i,Craft.BaseElementEditor.defaults),this.loadHud()},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 e=t.extend({},this.settings.params);return this.settings.siteId?e.siteId=this.settings.siteId:this.$element&&this.$element.data("site-id")&&(e.siteId=this.$element.data("site-id")),this.settings.elementId?e.elementId=this.settings.elementId:this.$element&&this.$element.data("id")&&(e.elementId=this.$element.data("id")),this.settings.elementType&&(e.elementType=this.settings.elementType),this.settings.attributes&&(e.attributes=this.settings.attributes),this.settings.prevalidate&&(e.prevalidate=1),e},loadHud:function(){this.onBeginLoading();var e=this.getBaseData();e.includeSites=Craft.isMultiSite&&this.settings.showSiteSwitcher,Craft.postActionRequest("elements/get-editor-html",e,t.proxy(this,"showHud"))},showHud:function(e,i){if(this.onEndLoading(),"success"===i){var s=t();if(e.sites){var a=t('<div class="hud-header"/>');if(1===e.sites.length)t("<h5/>",{text:e.sites[0].name}).appendTo(a);else{var n=t('<div class="select"/>').appendTo(a);this.$siteSelect=t("<select/>").appendTo(n),this.$siteSpinner=t('<div class="spinner hidden"/>').appendTo(a);for(var r=0;r<e.sites.length;r++){var o=e.sites[r];t('<option value="'+o.id+'"'+(o.id==e.siteId?' selected="selected"':"")+">"+o.name+"</option>").appendTo(this.$siteSelect)}this.addListener(this.$siteSelect,"change","switchSite")}s=s.add(a)}this.$form=t("<div/>"),this.$fieldsContainer=t('<div class="fields"/>').appendTo(this.$form),this.updateForm(e,!0),this.onCreateForm(this.$form);var l=t('<div class="hud-footer"/>').appendTo(this.$form),h=t('<div class="buttons right"/>').appendTo(l);if(this.$cancelBtn=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(h),this.$saveBtn=t("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Save")}).appendTo(h),this.$spinner=t('<div class="spinner hidden"/>').appendTo(h),s=s.add(this.$form),this.hud)this.hud.updateBody(s),this.hud.updateSizeAndPosition();else{var d=this.settings.hudTrigger||this.$element;this.hud=new Garnish.HUD(d,s,{bodyClass:"body elementeditor",closeOtherHUDs:!1,hideOnEsc:!1,hideOnShadeClick:!1,onShow:this.onShowHud.bind(this),onHide:this.onHideHud.bind(this),onSubmit:this.saveElement.bind(this)}),Garnish.shortcutManager.registerShortcut(Garnish.ESC_KEY,this.maybeCloseHud.bind(this)),this.hud.addListener(this.hud.$shade,"click",this.maybeCloseHud.bind(this)),this.hud.$hud.data("elementEditor",this),this.hud.$body.attr("novalidate",""),this.hud.on("hide",t.proxy((function(){delete this.hud}),this))}s.find(".text:first").trigger("focus"),this.addListener(this.$cancelBtn,"click",(function(){this.hud.hide()}))}},switchSite:function(){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.reloadForm({siteId:e},t.proxy((function(t){this.$siteSpinner.addClass("hidden"),"success"!==t&&this.$siteSelect.val(this.siteId)}),this)))}else this.$siteSelect.val(this.siteId)},reloadForm:function(e,i){e=t.extend(this.getBaseData(),e),Craft.postActionRequest("elements/get-editor-html",e,t.proxy((function(t,e){"success"===e&&this.updateForm(t,!0),i&&i(e)}),this))},updateForm:function(e,i){this.siteId=e.siteId,this.$fieldsContainer.html(e.html),!1!==i&&(this.deltaNames=e.deltaNames);let s=this.$fieldsContainer.find("> .meta > .field > .instructions");for(let e=0;e<s.length;e++){let i=s.eq(e),a=i.siblings(".heading").children("label");t("<span/>",{class:"info",html:i.children().html()}).appendTo(a),i.remove()}Garnish.requestAnimationFrame(t.proxy((function(){Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),Craft.initUiElements(this.$fieldsContainer),i&&(this.initialData=this.hud.$body.serialize())}),this))},saveElement:function(){var e=this.settings.validators;if(t.isArray(e))for(var i=0;i<e.length;i++)if(t.isFunction(e[i])&&!e[i].call())return!1;this.$spinner.removeClass("hidden");var s=t.param(this.getBaseData())+"&"+this.hud.$body.serialize();s=Craft.findDeltaData(this.initialData,s,this.deltaNames),Craft.postActionRequest("elements/save-element",s,t.proxy((function(t,e){if(this.$spinner.addClass("hidden"),"success"===e)if(t.success){if(this.$element&&this.siteId==this.$element.data("site-id")){var i=this.$element.find(".title"),s=i.find("a");s.length&&t.cpEditUrl?(s.attr("href",t.cpEditUrl),s.text(t.newTitle)):i.text(t.newTitle)}this.settings.elementType&&Craft.elementTypeNames[this.settings.elementType]&&Craft.cp.displayNotice(Craft.t("app","{type} saved.",{type:Craft.elementTypeNames[this.settings.elementType][0]})),this.closeHud(),this.onSaveElement(t)}else this.updateForm(t,!1),Garnish.shake(this.hud.$hud)}),this))},isDirty:function(){return this.hud.$body.serialize()!==this.initialData},maybeCloseHud:function(t){this.hud&&this.hud.showing&&(this.isDirty()&&!confirm("Are you sure you want to close the editor? Any changes will be lost.")||this.closeHud())},closeHud:function(){this.hud&&this.hud.showing&&(this.hud.hide(),delete this.hud)},onShowHud:function(){Garnish.shortcutManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0},this.saveElement.bind(this)),this.settings.onShowHud(),this.trigger("showHud")},onHideHud:function(){this.settings.onHideHud(),this.trigger("hideHud")},onBeginLoading:function(){this.$element&&this.$element.addClass("loading"),this.settings.onBeginLoading(),this.trigger("beginLoading")},onEndLoading:function(){this.$element&&this.$element.removeClass("loading"),this.settings.onEndLoading(),this.trigger("endLoading")},onSaveElement:function(t){this.settings.onSaveElement(t),this.trigger("saveElement",{response:t}),Craft.cp.runQueue()},onCreateForm:function(t){this.settings.onCreateForm(t)}},{defaults:{hudTrigger:null,showSiteSwitcher:!0,elementId:null,elementType:null,siteId:null,attributes:null,params:null,prevalidate:!1,elementIndex:null,onShowHud:t.noop,onHideHud:t.noop,onBeginLoading:t.noop,onEndLoading:t.noop,onCreateForm:t.noop,onSaveElement:t.noop,validators:[]}}),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(e,i,s){if(this.elementType=e,this.$container=i,this.setSettings(s,Craft.BaseElementIndex.defaults),this.instanceState=this.getDefaultInstanceState(),this.sourceStates={},this.settings.storageKey&&t.extend(this.instanceState,Craft.getLocalStorage(this.settings.storageKey),{}),this.sourceStatesStorageKey="BaseElementIndex."+this.elementType+"."+this.settings.context,t.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(),t(".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",t.proxy(this,"_handleStatusChange"))),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",t.proxy(this,"_handleSiteChange")),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",t.proxy((function(){!this.searching&&this.$search.val()?this.startSearching():this.searching&&!this.$search.val()&&this.stopSearching(),this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout(t.proxy(this,"updateElementsIfSearchTextChanged"),500)}),this)),this.addListener(this.$search,"keypress",t.proxy((function(t){t.keyCode===Garnish.RETURN_KEY&&(t.preventDefault(),this.searchTimeout&&clearTimeout(this.searchTimeout),this.updateElementsIfSearchTextChanged())}),this)),this.addListener(this.$clearSearchBtn,"click",t.proxy((function(){this.$search.val(""),this.searchTimeout&&clearTimeout(this.searchTimeout),Garnish.isMobileBrowser(!0)||this.$search.trigger("focus"),this.stopSearching(),this.updateElementsIfSearchTextChanged()}),this)),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",t.proxy(this,"_handleSortChange"))),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(){this._cancelToken&&(this._ignoreFailedRequest=!0,this._cancelToken.cancel(),Garnish.requestAnimationFrame(()=>{this._ignoreFailedRequest=!1}))},getSourceContainer:function(){return this.$sidebar.find("nav > ul")},get $sources(){if(this.sourceSelect)return this.sourceSelect.$items},initSources:function(){var e=this._getSourcesInList(this.getSourceContainer());return 0!==e.length&&(this.sourceSelect||(this.sourceSelect=new Garnish.Select(this.$sidebar.find("nav"),{multi:!1,allowEmpty:!1,vertical:!0,onSelectionChange:t.proxy(this,"_handleSourceSelectionChange")})),this.sourcesByKey={},this._initSources(e),!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(){this.sourceSelect.removeAllItems();var t={context:this.settings.context,elementType:this.elementType};this.setIndexBusy(),Craft.sendActionRequest("POST",this.settings.refreshSourcesAction,{data:t}).then(t=>{this.setIndexAvailable(),this.getSourceContainer().replaceWith(t.data.html),this.initSources(),this.selectDefaultSource()}).catch(()=>{this.setIndexAvailable(),this._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=t('<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")},stopSearching:function(){this.$clearSearchBtn.addClass("hidden"),this.$scoreSortAttribute.detach(),this.searching=!1,this._updateStructureSortOption()},setInstanceState:function(e,i){"object"==typeof e?t.extend(this.instanceState,e):this.instanceState[e]=i,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(e,i){var s=this.getSelectedSourceState();"object"==typeof e?t.extend(s,e):s[e]=i,this.sourceStates[this.instanceState.selectedSource]=s,Craft.setLocalStorage(this.sourceStatesStorageKey,this.sourceStates)},storeSortAttributeAndDirection:function(){var t=this.getSelectedSortAttribute();"score"!==t&&this.setSelecetedSourceState({order:t,sort:this.getSelectedSortDirection()})},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 e={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)&&(e.drafts=this.drafts||null,e.savedDraftsOnly=!0,this.drafts||(e.draftOf=!1)),this.trashed&&(e.trashed=!0),Garnish.hasAttr(this.$source,"data-override-status")||(e.status=this.status),t.extend(e,this.settings.criteria);var i={context:this.settings.context,elementType:this.elementType,source:this.instanceState.selectedSource,criteria:e,disabledElementIds:this.settings.disabledElementIds,viewState:t.extend({},this.getSelectedSourceState()),paginated:this._isViewPaginated()?1:0};return i.viewState.order=this.getSelectedSortAttribute(),i.viewState.sort=this.getSelectedSortDirection(),"structure"===this.getSelectedSortAttribute()&&(void 0===this.instanceState.collapsedElementIds&&(this.instanceState.collapsedElementIds=[]),i.collapsedElementIds=this.instanceState.collapsedElementIds),this.trigger("registerViewParams",{params:i}),i},updateElements:function(t){if(this.initialized){this._cancelRequests(),this.setIndexBusy(),this.view&&(this.view.destroy(),delete this.view),!0!==t&&(this.setPage(1),this._resetCount());var e=this.getViewParams();Craft.sendActionRequest("POST",this.settings.updateElementsAction,{data:e,cancelToken:this._createCancelToken()}).then(t=>{this.setIndexAvailable(),("index"===this.settings.context?Garnish.$scrollContainer:this.$main).scrollTop(0),this._updateView(e,t.data)}).catch(t=>{this.setIndexAvailable(),this._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(e,i){var s=this.view.getSelectedElementIds();if(0!==s.length&&("string"==typeof e&&(e=this._findAction(e)),!e.confirm||confirm(e.confirm))){this._cancelRequests();var a=this.getViewParams();i=i?Craft.expandPostArray(i):{};var n=t.extend(a,e.settings||{},i,{elementAction:e.type,elementIds:s});this.setIndexBusy(),this._autoSelectElements=s,e.download?(Craft.csrfTokenName&&(n[Craft.csrfTokenName]=Craft.csrfTokenValue),Craft.downloadFromUrl("POST",Craft.getActionUrl(this.settings.submitActionsAction),n).then(t=>{this.setIndexAvailable()}).catch(t=>{this.setIndexAvailable()})):Craft.sendActionRequest("POST",this.settings.submitActionsAction,{data:n,cancelToken:this._createCancelToken()}).then(t=>{this.setIndexAvailable(),t.data.success?(this._resetCount(),this._updateView(a,t.data),t.data.message&&Craft.cp.displayNotice(t.data.message),this.afterAction(e,n)):Craft.cp.displayError(t.data.message)}).catch(()=>{this.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: "+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():t()},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(e){if(!e||!e.length)return!1;if(this.$source&&this.$source[0]&&this.$source[0]===e[0]&&e.data("key")===this.sourceKey)return!1;this.hideActionTriggers(),this.$source=e,this.sourceKey=e.data("key"),this.setInstanceState("selectedSource",this.sourceKey),this.sourceSelect.selectItem(e),Craft.cp.updateSidebarMenuLabel(),this.searching&&(this.searchText=null,this.$search.val(""),this.stopSearching()),this.$sortAttributesList.children("li[data-extra]").remove();let i=this.$source.data("sort-options");if(i)for(let e=0;e<i.length;e++){let s=t("<li/>",{"data-extra":!0}).append(t("<a/>",{text:i[e][0],"data-attr":i[e][1]})).appendTo(this.$sortAttributesList);this.sortMenu.addOptions(s.children())}if(Garnish.hasAttr(this.$source,"data-has-structure")?(this.$structureSortAttribute||(this.$structureSortAttribute=t('<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 s=this.statusMenu.$options.first();this.setStatus(s.data("status"))}if(this.$viewModeBtnContainer&&this.$viewModeBtnContainer.remove(),this.viewModeBtns={},this.viewMode=null,this.sourceViewModes=this.getViewModesForSource(),this.sourceViewModes.length>1){this.$viewModeBtnContainer=t('<div class="btngroup"/>').appendTo(this.$toolbar);for(var a=0;a<this.sourceViewModes.length;a++){let e=this.sourceViewModes[a],i=t("<button/>",{type:"button",class:"btn"+(void 0!==e.className?" "+e.className:""),"data-view":e.mode,"data-icon":e.icon,"aria-label":e.title,title:e.title}).appendTo(this.$viewModeBtnContainer);this.viewModeBtns[e.mode]=i,this.addListener(i,"click",{mode:e.mode},(function(t){this.selectViewMode(t.data.mode),this.updateElements()}))}}var n=this.getSelectedViewMode();return n&&this.doesSourceHaveViewMode(n)||(n=this.viewMode&&this.doesSourceHaveViewMode(this.viewMode)?this.viewMode:this.sourceViewModes[0].mode),this.selectViewMode(n),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 "${t}" not supported.`}},rememberDisabledElementId:function(e){-1===t.inArray(e,this.settings.disabledElementIds)&&this.settings.disabledElementIds.push(e)},forgetDisabledElementId:function(e){var i=t.inArray(e,this.settings.disabledElementIds);-1!==i&&this.settings.disabledElementIds.splice(i,1)},enableElements:function(e){e.removeClass("disabled").parents(".disabled").removeClass("disabled");for(var i=0;i<e.length;i++){var s=t(e[i]).data("id");this.forgetDisabledElementId(s)}this.onEnableElements(e)},disableElements:function(e){e.removeClass("sel").addClass("disabled");for(var i=0;i<e.length;i++){var s=t(e[i]).data("id");this.rememberDisabledElementId(s)}this.onDisableElements(e)},getElementById:function(t){return this.view.getElementById(t)},enableElementsById:function(e){e=t.makeArray(e);for(var i=0;i<e.length;i++){var s=e[i],a=this.getElementById(s);a&&a.length?this.enableElements(a):this.forgetDisabledElementId(s)}},disableElementsById:function(e){e=t.makeArray(e);for(var i=0;i<e.length;i++){var s=e[i],a=this.getElementById(s);a&&a.length?this.disableElements(a):this.rememberDisabledElementId(s)}},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 t(this.settings.buttonContainer);var e=t("#action-button");return e.length||(e=t('<div id="action-button"/>').appendTo(t("#header"))),e},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(e){e.preventDefault();var i=t(e.currentTarget);i.hasClass("disabled")||i.data("custom-handler")||this.submitAction(i.data("action"),Garnish.getPostData(i))},_handleMenuActionTriggerSubmit:function(e){var i=t(e.option);i.hasClass("disabled")||i.data("custom-handler")||this.submitAction(i.data("action"))},_handleStatusChange:function(e){this.statusMenu.$options.removeClass("sel");var i=t(e.selectedOption).addClass("sel");this.$statusMenuBtn.html(i.html()),this.trashed=!1,this.drafts=!1,this.status=null,Garnish.hasAttr(i,"data-trashed")?this.trashed=!0:Garnish.hasAttr(i,"data-drafts")?this.drafts=!0:this.status=i.data("status"),this._updateStructureSortOption(),this.updateElements()},_handleSiteChange:function(e){this.siteMenu.$options.removeClass("sel");var i=t(e.selectedOption).addClass("sel");this.$siteMenuBtn.html(i.html()),this._setSite(i.data("site-id")),this.onSelectSite()},_setSite:function(e){let i=null===this.siteId;var s,a;this.siteId=e,this.$visibleSources=t();for(var n=!(i||this.$source&&this.$source.length),r=0;r<this.$sources.length;r++)void 0===(a=this.$sources.eq(r)).data("sites")||-1!==a.data("sites").toString().split(",").indexOf(e.toString())?(a.parent().removeClass("hidden"),this.$visibleSources=this.$visibleSources.add(a),s||(s=a)):(a.parent().addClass("hidden"),this.$source&&this.$source.get(0)==a.get(0)&&(n=!0));this.initialized&&n&&this.selectSource(s);var o,l=this.getSourceContainer().children(".heading");for(r=0;r<l.length;r++)0!==(o=l.eq(r)).nextUntil(".heading",":not(.hidden)").length?o.removeClass("hidden"):o.addClass("hidden");this.initialized&&("index"===this.settings.context&&Craft.cp.setSiteId(e),this.updateElements())},_handleSortChange:function(e){var i=t(e.selectedOption);i.hasClass("disabled")||i.hasClass("sel")||(i.parent().parent().is(this.$sortAttributesList)?this.setSortAttribute(i.data("attr")):this.setSortDirection(i.data("dir")),this.storeSortAttributeAndDirection(),this.updateElements())},_handleSelectionChange:function(){this.updateActionTriggers(),this.onSelectionChange()},_handleSourceDblClick:function(e){this._toggleSource(t(e.currentTarget)),e.stopPropagation()},_handleSourceToggleClick:function(e){this._toggleSource(t(e.currentTarget).prev("a")),e.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")},_initSources:function(e){for(var i=0;i<e.length;i++)this.initSource(t(e[i]))},_deinitSources:function(e){for(var i=0;i<e.length;i++)this.deinitSource(t(e[i]))},_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");var e=this._getChildSources(t);this._initSources(e);var i=t.data("key");-1===this.instanceState.expandedSources.indexOf(i)&&(this.instanceState.expandedSources.push(i),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");var e=this._getChildSources(t);this._deinitSources(e);var i=this.instanceState.expandedSources.indexOf(t.data("key"));-1!==i&&(this.instanceState.expandedSources.splice(i,1),this.storeInstanceState())},_isViewPaginated:function(){return"index"===this.settings.context&&"structure"!==this.getSelectedSortAttribute()},_updateView:function(e,i){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(e=>{this.$countSpinner.addClass("hidden");let i=Craft.elementTypeNames[this.elementType]?Craft.elementTypeNames[this.elementType][2]:"element",s=Craft.elementTypeNames[this.elementType]?Craft.elementTypeNames[this.elementType][3]:"elements";if(this._isViewPaginated()){let a=Math.min(this.settings.batchSize*(this.page-1)+1,e),n=Math.min(a+(this.settings.batchSize-1),e),r=Craft.t("app","{first, number}-{last, number} of {total, number} {total, plural, =1{{item}} other{{items}}}",{first:a,last:n,total:e,item:i,items:s}),o=t('<div class="flex pagination"/>').appendTo(this.$countContainer),l=Math.max(Math.ceil(e/this.settings.batchSize),1),h=t("<div/>",{class:"page-link prev-page"+(this.page>1?"":" disabled"),title:Craft.t("app","Previous Page")}).appendTo(o),d=t("<div/>",{class:"page-link next-page"+(this.page<l?"":" disabled"),title:Craft.t("app","Next Page")}).appendTo(o);t("<div/>",{class:"page-info",text:r}).appendTo(o),this.page>1&&this.addListener(h,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page-1),this.updateElements(!0)})),this.page<l&&this.addListener(d,"click",(function(){this.removeListener(h,"click"),this.removeListener(d,"click"),this.setPage(this.page+1),this.updateElements(!0)}))}else{let t=Craft.t("app","{total, number} {total, plural, =1{{item}} other{{items}}}",{total:e,item:i,items:s});this.$countContainer.text(t)}}).catch(()=>{this.$countSpinner.addClass("hidden")})),this.$elements.html(i.html),Craft.appendHeadHtml(i.headHtml),Craft.appendFootHtml(i.footHtml),this.$selectAllContainer=this.$elements.find(".selectallcontainer:first"),i.actions&&i.actions.length?this.$selectAllContainer.length&&(this.actions=i.actions,this.actionsHeadHtml=i.actionsHeadHtml,this.actionsFootHtml=i.actionsFootHtml,this.$selectAllCheckbox=t('<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(e){e.keyCode===Garnish.SPACE_KEY&&(e.preventDefault(),t(e.currentTarget).trigger("click"))}))):(this.$selectAllContainer.siblings().length||this.$selectAllContainer.parent(".header").remove(),this.$selectAllContainer.remove()),this.exporters=i.exporters,this.exportersByType=Craft.index(this.exporters||[],t=>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:e,selectable:s,multiSelect:this.actions||this.settings.multiSelect,checkboxMode:!!this.actions,onSelectionChange:t.proxy(this,"_handleSelectionChange")}),this._autoSelectElements){if(s)for(var a=0;a<this._autoSelectElements.length;a++)this.view.selectElementById(this._autoSelectElements[a]);this._autoSelectElements=null}this.onUpdateElements()},_countResults:function(){return new Promise((t,e)=>{if(null!==this.totalResults)t(this.totalResults);else{var i=this.getViewParams();delete i.criteria.offset,delete i.criteria.limit,null===this.resultSet&&(this.resultSet=Math.floor(1e8*Math.random())),i.resultSet=this.resultSet,Craft.sendActionRequest("POST",this.settings.countElementsAction,{data:i,cancelToken:this._createCancelToken()}).then(i=>{i.data.resultSet==this.resultSet?(this.totalResults=i.data.count,t(i.data.count)):e()}).catch(e)}})},_createTriggers:function(){var e,i,s=[],a=[],n=[];for(e=0;e<this.actions.length;e++){var r=this.actions[e];if(r.trigger){var o=t('<form id="'+Craft.formatInputId(r.type)+'-actiontrigger"/>').data("action",r).append(r.trigger);this.addListener(o,"submit","_handleActionTriggerSubmit"),s.push(o)}else r.destructive?n.push(r):a.push(r)}if(a.length||n.length){var l=t("<form/>");i=t("<button/>",{type:"button",class:"btn menubtn","data-icon":"settings",title:Craft.t("app","Actions")}).appendTo(l);var h=t('<ul class="menu"/>').appendTo(l),d=this._createMenuTriggerList(a,!1),c=this._createMenuTriggerList(n,!0);d&&d.appendTo(h),d&&c&&t("<hr/>").appendTo(h),c&&c.appendTo(h),s.push(l)}for(this._$triggers=t(),e=0;e<s.length;e++){var u=t("<div/>").append(s[e]);this._$triggers=this._$triggers.add(u)}this._$triggers.appendTo(this.$toolbar),Craft.appendHeadHtml(this.actionsHeadHtml),Craft.appendFootHtml(this.actionsFootHtml),Craft.initUiElements(this._$triggers),i&&i.data("menubtn").on("optionSelect",t.proxy(this,"_handleMenuActionTriggerSubmit"))},_showExportHud:function(){this.$exportBtn.addClass("active");for(var e=t("<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);let r=a.find("select");this.addListener(r,"change",()=>{let t=r.val();this.exportersByType[t].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);t("<button/>",{type:"submit",class:"btn submit fullwidth",text:Craft.t("app","Export")}).appendTo(e);var h=t("<div/>",{class:"spinner hidden"}).appendTo(e);new Garnish.HUD(this.$exportBtn,e).on("hide",t.proxy((function(){this.$exportBtn.removeClass("active")}),this));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,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(e,i){if(e&&e.length){for(var s=t("<ul/>"),a=0;a<e.length;a++)t("<li/>").append(t("<a/>",{id:Craft.formatInputId(e[a].type)+"-actiontrigger",class:i?"error":null,data:{action:e[a]},text:e[a].name})).appendTo(s);return s}}},{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:t.noop,onSelectSource:t.noop,onSelectSite:t.noop,onUpdateElements:t.noop,onSelectionChange:t.noop,onEnableElements:t.noop,onDisableElements:t.noop,onAfterAction:t.noop}}),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(e,i,s){this.elementIndex=e,this.$container=t(i),this.setSettings(s,Craft.BaseElementIndexView.defaults),this.$loadingMoreSpinner=t('<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:t.proxy(this,"onSelectionChange")}),this._handleEnableElements=t.proxy((function(t){this.elementSelect.addItems(t.elements)}),this),this._handleDisableElements=t.proxy((function(t){this.elementSelect.removeItems(t.elements)}),this),this.elementIndex.on("enableElements",this._handleEnableElements),this.elementIndex.on("disableElements",this._handleDisableElements)),"index"===this.settings.context&&(this._handleElementEditing=t.proxy((function(e){var i=t(e.target);if("A"!==i.prop("nodeName")){var s;if(i.hasClass("element"))s=i;else if(!(s=i.closest(".element")).length)return;Garnish.hasAttr(s,"data-editable")&&this.createElementEditor(s)}}),this),this.elementIndex.trashed||(this.addListener(this.$elementContainer,"dblclick",this._handleElementEditing),t.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(){let t;try{t=this.getSelectedElements()}catch(t){}let 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(){if(this.getMorePending()&&!this.loadingMore&&this.settings.batchSize){this.loadingMore=!0,this.$loadingMoreSpinner.removeClass("hidden"),this.removeListener(this.$scroller,"scroll");var e=this.getLoadMoreParams();Craft.postActionRequest(this.settings.loadMoreElementsAction,e,t.proxy((function(e,i){if(this.loadingMore=!1,this.$loadingMoreSpinner.addClass("hidden"),"success"===i){var s=t(e.html);this.appendElements(s),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),this.elementSelect&&(this.elementSelect.addItems(s.filter(":not(.disabled)")),this.elementIndex.updateActionTriggers()),this.setTotalVisible(this.getTotalVisible()+s.length),this.setMorePending(s.length==this.settings.batchSize),this.addListener(this.$scroller,"scroll","maybeLoadMore"),this.maybeLoadMore()}}),this))}},getLoadMoreParams:function(){var e=t.extend(!0,{},this.settings.params);return e.criteria.offset=this.getTotalVisible(),e},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:t.noop,onSelectionChange:t.noop}}),Craft.BaseElementSelectInput=Garnish.Base.extend({thumbLoader:null,elementSelect:null,elementSort:null,modal:null,elementEditor:null,$container:null,$elementsContainer:null,$elements:null,$addElementBtn:null,$addElementBtnContainer:null,_initialized:!1,init:function(e){if(!t.isPlainObject(e)){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];e=i}this.setSettings(e,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.$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(()=>{this._initialized=!0})},get totalSelected(){return this.$elements.length},getContainer:function(){return t("#"+this.settings.id)},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(){this.settings.sortable&&(this.elementSort=new Garnish.DragSort({container:this.$elementsContainer,filter:this.settings.selectable?t.proxy((function(){return this.elementSort.$targetItem.hasClass("sel")?this.elementSelect.getSelectedItems():this.elementSort.$targetItem}),this):null,ignoreHandleSelector:".delete",axis:this.getElementSortAxis(),collapseDraggees:!0,magnetStrength:4,helperLagBase:1.5,onSortChange:this.settings.selectable?t.proxy((function(){this.elementSelect.resetItemOrder()}),this):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(){let t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.addClass("hidden")},enableAddElementsBtn:function(){let t=this.$addElementBtnContainer||this.$addElementBtn;t&&t.removeClass("hidden")},resetElements:function(){null!==this.$elements?this.removeElements(this.$elements):this.$elements=t(),this.addElements(this.getElements())},addElements:function(e){this.thumbLoader.load(e),this.settings.selectable&&this.elementSelect.addItems(e),this.settings.sortable&&this.elementSort.addItems(e),this.settings.editable&&(this._handleShowElementEditor=t.proxy((function(e){var i=t(e.currentTarget);!Garnish.hasAttr(i,"data-editable")||i.hasClass("disabled")||i.hasClass("loading")||(this.elementEditor=this.createElementEditor(i))}),this),this.addListener(e,"dblclick",this._handleShowElementEditor),t.isTouchCapable()&&this.addListener(e,"taphold",this._handleShowElementEditor)),e.find(".delete").on("click dblclick",t.proxy((function(e){this.removeElement(t(e.currentTarget).closest(".element")),e.stopPropagation()}),this)),this.$elements=this.$elements.add(e),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)}t.children("input").prop("disabled",!0),this.$elements=this.$elements.not(t),this.updateAddElementsBtn(),this.onRemoveElements()},removeElement:function(t){this.removeElements(t),this.animateElementAway(t,()=>{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,()=>{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 t.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:t.proxy(this,"onModalSelect")},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 t=this.getSelectedElementIds();return!this.settings.allowSelfRelations&&this.settings.sourceElementId&&t.push(this.settings.sourceElementId),this.settings.disabledElementIds&&t.push(...this.settings.disabledElementIds),t},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()},selectElements:function(t){for(let e=0;e<t.length;e++){let 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();return Craft.setElementSize(e,"large"===this.settings.viewMode?"large":"small"),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},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",limit:null,showSiteMenu:!1,modalStorageKey:null,modalSettings:{},onSelectElements:t.noop,onRemoveElements:t.noop,sortable:!0,selectable:!0,editable:!0,prevalidate:!1,editorSettings:{}}}),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(e,i){this.elementType=e,this.setSettings(i,Craft.BaseElementSelectorModal.defaults);var s=t('<div class="modal elementselectormodal"></div>').appendTo(Garnish.$bod),a=t('<div class="body"><div class="spinner big"></div></div>').appendTo(s),n=t('<div class="footer"/>').appendTo(s);this.base(s,this.settings),this.$footerSpinner=t('<div class="spinner hidden"/>').appendTo(n),this.$primaryButtons=t('<div class="buttons right"/>').appendTo(n),this.$secondaryButtons=t('<div class="buttons left secondary-buttons"/>').appendTo(n),this.$cancelBtn=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$primaryButtons),this.$selectBtn=t("<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(e){for(var i=[],s=0;s<e.length;s++){var a=t(e[s]),n=Craft.getElementInfo(a);i.push(n)}return i},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 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("elements/get-modal-body",e,t.proxy((function(e,i){"success"===i&&(this.$body.html(e.html),this.$body.has(".sidebar:not(.hidden)").length&&this.$body.addClass("has-sidebar"),this.elementIndex=Craft.createElementIndex(this.elementType,this.$body,{context:"modal",modal:this,storageKey:this.settings.storageKey,criteria:this.settings.criteria,disabledElementIds:this.settings.disabledElementIds,selectable:!0,multiSelect:this.settings.multiSelect,buttonContainer:this.$secondaryButtons,onSelectionChange:t.proxy(this,"onSelectionChange"),hideSidebar:this.settings.hideSidebar,defaultSiteId:this.settings.defaultSiteId,defaultSource:this.settings.defaultSource}),this.addListener(this.elementIndex.$elements,"doubletap",(function(t,e){e.firstTap.target===e.secondTap.target&&this.selectElements()})))}),this))}},{defaults:{resizable:!0,storageKey:null,sources:null,criteria:null,multiSelect:!1,showSiteMenu:null,disabledElementIds:[],disableElementsOnSelect:!1,hideOnSelect:!0,onCancel:t.noop,onSelect:t.noop,hideSidebar:!1,defaultSiteId:null,defaultSource:null}}),Craft.BaseInputGenerator=Garnish.Base.extend({$source:null,$target:null,$form:null,settings:null,listening:null,timeout:null,init:function(e,i,s){this.$source=t(e),this.$target=t(i),this.$form=this.$source.closest("form"),this.setSettings(s),this.startListening()},setNewSource:function(e){var i=this.listening;this.stopListening(),this.$source=t(e),i&&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(t.proxy(this,"updateTarget"),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(let t=0;t<this.$target.length;t++)this.$target[t].dispatchEvent(new InputEvent("input",{inputType:"insertText"})),this.$target[t].dispatchEvent(new Event("input"));this.$target.is(":focus")&&Craft.selectFullValue(this.$target)}}},generateTargetValue:function(t){return t}}),Craft.AdminTable=Garnish.Base.extend({settings:null,totalItems:null,sorter:null,$noItems:null,$table:null,$tbody:null,$deleteBtns:null,init:function(e){this.setSettings(e,Craft.AdminTable.defaults),this.settings.allowDeleteAll||(this.settings.minItems=1),this.$noItems=t(this.settings.noItemsSelector),this.$table=t(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:t.proxy(this,"reorderItems")})),this.$deleteBtns=this.$table.find(".delete:not(.disabled)"),this.addListener(this.$deleteBtns,"click","handleDeleteBtnClick"),this.updateUI()},addRow:function(e){if(!(this.settings.maxItems&&this.totalItems>=this.settings.maxItems)){var i=t(e).appendTo(this.$tbody),s=i.find(".delete");this.settings.sortable&&this.sorter.addItems(i),this.$deleteBtns=this.$deleteBtns.add(s),this.addListener(s,"click","handleDeleteBtnClick"),this.totalItems++,this.updateUI()}},reorderItems:function(){if(this.settings.sortable){for(var e=[],i=0;i<this.sorter.$items.length;i++){var s=t(this.sorter.$items[i]).attr(this.settings.idAttribute);e.push(s)}var a={ids:JSON.stringify(e)};Craft.postActionRequest(this.settings.reorderAction,a,t.proxy((function(t,i){"success"===i&&(t.success?(this.onReorderItems(e),Craft.cp.displayNotice(Craft.t("app",this.settings.reorderSuccessMessage))):Craft.cp.displayError(Craft.t("app",this.settings.reorderFailMessage)))}),this))}},handleDeleteBtnClick:function(e){if(!(this.settings.minItems&&this.totalItems<=this.settings.minItems)){var i=t(e.target).closest("tr");this.confirmDeleteItem(i)&&this.deleteItem(i)}},confirmDeleteItem:function(t){var e=this.getItemName(t);return confirm(Craft.t("app",this.settings.confirmDeleteMessage,{name:e}))},deleteItem:function(e){var i={id:this.getItemId(e)};Craft.postActionRequest(this.settings.deleteAction,i,t.proxy((function(t,i){"success"===i&&this.handleDeleteItemResponse(t,e)}),this))},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 e=this.$table.find(".move");1===this.totalItems?e.addClass("disabled"):e.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?t(this.settings.newItemBtnSelector).addClass("hidden"):t(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:t.noop,onDeleteItem:t.noop}}),Craft.AssetEditor=Craft.BaseElementEditor.extend({reloadIndex:!1,updateForm:function(t,e){if(this.base(t,e),this.$element.data("id")){var i=this.$fieldsContainer.find("> .meta > .preview-thumb-container.editable");i.length&&this.addListener(i,"click","showImageEditor")}},showImageEditor:function(){new Craft.AssetImageEditor(this.$element.data("id"),{onSave:function(){this.reloadIndex=!0,this.reloadForm()}.bind(this)})},onHideHud:function(){this.reloadIndex&&this.settings.elementIndex?this.settings.elementIndex.updateElements():this.reloadIndex&&this.settings.input&&this.settings.input.refreshThumbnail(this.$element.data("id")),this.base()}}),Craft.registerElementEditorClass("craft\\elements\\Asset",Craft.AssetEditor),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,croppingAreaText: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(e,i){this.cacheBust=Date.now(),this.setSettings(i,Craft.AssetImageEditor.defaults),null===this.settings.allowDegreeFractions&&(this.settings.allowDegreeFractions=Craft.isImagick),this.assetId=e,this.flipData={x:0,y:0},this.$container=t('<form class="modal fitted imageeditor"></form>').appendTo(Garnish.$bod),this.$body=t('<div class="body"></div>').appendTo(this.$container),this.$footer=t('<div class="footer"/>').appendTo(this.$container),this.base(this.$container,this.settings),this.$buttons=t('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=t("<button/>",{type:"button",class:"btn cancel",text:Craft.t("app","Cancel")}).appendTo(this.$buttons),this.$replaceBtn=t("<button/>",{type:"button",class:"btn submit save replace",text:Craft.t("app","Save")}).appendTo(this.$buttons),this.settings.allowSavingAsNew&&(this.$saveBtn=t("<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:e},t.proxy(this,"loadEditor"))},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(e){e.html||alert(Craft.t("app","Could not load the image editor.")),this.$body.html(e.html),this.$tabs=t(".tabs li",this.$body),this.$viewsContainer=t(".views",this.$body),this.$views=t("> div",this.$viewsContainer),this.$imageTools=t(".image-container .image-tools",this.$body),this.$editorContainer=t(".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=t("#cropping-canvas",this.$editorContainer),this.$croppingCanvas.width(this.editorWidth),this.$croppingCanvas.height(this.editorHeight),this.canvas.enableRetinaScaling=!0,this.renderImage=function(){Garnish.requestAnimationFrame(this.canvas.renderAll.bind(this.canvas))}.bind(this);var i=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});fabric.Image.fromURL(i,t.proxy((function(t){this.image=t,this.image.set({originX:"center",originY:"center",left:this.editorWidth/2,top:this.editorHeight/2}),this.canvas.add(this.image),this.originalHeight=this.image.getHeight(),this.originalWidth=this.image.getWidth(),this.zoomRatio=1,this.lastLoadedDimensions=this.getScaledImageDimensions(),this._setFittedImageVerticeCoordinates(),this._repositionEditorElements();var i={imageDimensions:this.getScaledImageDimensions(),offsetX:0,offsetY:0},s=!1;if(e.focalPoint){var a=e.focalPoint,n=i.imageDimensions.width*a.x,r=i.imageDimensions.height*a.y;i.offsetX=n-i.imageDimensions.width/2,i.offsetY=r-i.imageDimensions.height/2,s=!0}this.storeFocalPointState(i),s&&this._createFocalPoint(),this._createViewport(),this.storeCropperState(),this._addControlListeners(),this.addListener(this.$croppingCanvas,"mousemove,touchmove",this._handleMouseMove),this.addListener(this.$croppingCanvas,"mousedown,touchstart",this._handleMouseDown),this.addListener(this.$croppingCanvas,"mouseup,touchend",this._handleMouseUp),this.addListener(this.$croppingCanvas,"mouseout,touchcancel",this._handleMouseOut),this._hideSpinner(),this.renderImage(),this.$tabs.first().trigger("click")}),this))},_reloadImage:function(){if(!this.imageIsLoading){this.imageIsLoading=!0,this.maxImageSize=this.getMaxImageSize();var t=Craft.getActionUrl("assets/edit-image",{assetId:this.assetId,size:this.maxImageSize,cacheBust:this.cacheBust});this.image.setSrc(t,function(t){this.originalHeight=t.getHeight(),this.originalWidth=t.getWidth(),this.lastLoadedDimensions={width:this.originalHeight,height:this.originalWidth},this.updateSizeAndPosition(),this.renderImage(),this.imageIsLoading=!1}.bind(this))}},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 e={left:this.editorWidth/2,top:this.editorHeight/2};if("crop"===this.currentView)e.width=this.editorWidth,e.height=this.editorHeight;else if(this.cropperState){var i=this.cropperState,s=this.getScaledImageDimensions().width/i.imageDimensions.width;e.width=i.width*s*this.zoomRatio,e.height=i.height*s*this.zoomRatio,this.image.set({left:this.editorWidth/2-i.offsetX*s,top:this.editorHeight/2-i.offsetY*s})}else t.extend(e,this.getScaledImageDimensions());this.viewport.set(e)}},_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(){this.addListener(this.$tabs,"click",this._handleTabClick),this.addListener(t(".focal-point"),"click",this.toggleFocalPoint),this.addListener(t(".rotate-left"),"click",(function(){this.rotateImage(-90)})),this.addListener(t(".rotate-right"),"click",(function(){this.rotateImage(90)})),this.addListener(t(".flip-vertical"),"click",(function(){this.flipImage("y")})),this.addListener(t(".flip-horizontal"),"click",(function(){this.flipImage("x")})),this.straighteningInput=new Craft.SlideRuleInput("slide-rule",{onStart:function(){this._showGrid()}.bind(this),onChange:function(t){this.straighten(t)}.bind(this),onEnd:function(){this._hideGrid(),this._cleanupFocalPointAfterStraighten()}.bind(this)}),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(t(".constraint-buttons .constraint",this.$container),"click",this._handleConstraintClick),this.addListener(t(".orientation input",this.$container),"click",this._handleOrientationClick),this.addListener(t(".constraint-buttons .custom-input input",this.$container),"keyup",this._applyCustomConstraint)},_handleConstraintClick:function(e){var i=t(e.currentTarget).data("constraint"),s=t(e.currentTarget);if(s.siblings().removeClass("active"),s.addClass("active"),"custom"==i)return this._showCustomConstraint(),void this._applyCustomConstraint();this._hideCustomConstraint(),this.setCroppingConstraint(i),this.enforceCroppingConstraint()},_handleOrientationClick:function(e){if(e.currentTarget.value!==this.constraintOrientation){this.constraintOrientation=e.currentTarget.value;for(var i=t(".constraint.flip",this.$container),s=0;s<i.length;s++){var a=t(i[s]);a.data("constraint",1/a.data("constraint")),a.html(a.html().split(":").reverse().join(":"))}i.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 e=parseFloat(t(".custom-constraint-w").val()),i=parseFloat(t(".custom-constraint-h").val());return{w:isNaN(e)?0:e,h:isNaN(i)?0:i}},_setCustomConstraint:function(e,i){t(".custom-constraint-w").val(parseFloat(e)),t(".custom-constraint-h").val(parseFloat(i))},_hideCustomConstraint:function(){this.showingCustomConstraint=!1,t(".constraint.custom .custom-input",this.$container).addClass("hidden"),t(".constraint.custom .custom-label",this.$container).removeClass("hidden"),t(".orientation",this.$container).removeClass("hidden")},_showCustomConstraint:function(){this.showingCustomConstraint||(this.showingCustomConstraint=!0,t(".constraint.custom .custom-input",this.$container).removeClass("hidden"),t(".constraint.custom .custom-label",this.$container).addClass("hidden"),t(".orientation",this.$container).addClass("hidden"))},_handleTabClick:function(e){if(!this.animationInProgress){var i=t(e.currentTarget),s=i.data("view");this.$tabs.removeClass("selected"),i.addClass("selected"),this.showView(s)}},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){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 e,i=this.image.angle+t,s=this.getScaledImageDimensions();e=this.hasOrientationChanged()?this.getZoomToCoverRatio({height:s.width,width:s.height}):this.getZoomToCoverRatio(s),this.zoomRatio>e&&(e=this.zoomRatio);var a={angle:90===t?"+=90":"-=90"},n={angle:i,width:s.width*e,height:s.height*e},r=1;this.scaleFactor<1?(r=1/this.scaleFactor,this.scaleFactor=1):(this.viewport.width>this.editorHeight?r=this.editorHeight/this.viewport.width:this.viewport.height>this.editorWidth&&(r=this.editorWidth/this.viewport.height),this.scaleFactor=r),r<1&&(n.width*=r,n.height*=r);var o=this.cropperState,l=o.offsetX,h=o.offsetY,d=t*(Math.PI/180),c=l*Math.cos(d)-h*Math.sin(d),u=l*Math.sin(d)+h*Math.cos(d),p=s.width/o.imageDimensions.width,g=c*p*this.zoomRatio*this.scaleFactor,f=u*p*this.zoomRatio*this.scaleFactor;n.left=this.editorWidth/2-g,n.top=this.editorHeight/2-f,o.offsetX=c,o.offsetY=u;var m=o.width;o.width=o.height,o.height=m,this.storeCropperState(o),this.focalPoint&&this.canvas.remove(this.focalPoint),this.viewport.animate(a,{duration:this.settings.animationDuration,onComplete:function(){var t=this.viewport.height*r;this.viewport.height=this.viewport.width*r,this.viewport.width=t,this.viewport.set({angle:0})}.bind(this)}),this.image.animate(n,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){var e=parseFloat((this.image.angle+360)%360);this.image.set({angle:e}),this.animationInProgress=!1,this.focalPoint?(this._adjustFocalPointByAngle(t),this.straighten(this.straighteningInput),this.canvas.add(this.focalPoint)):this._resetFocalPointPosition()}.bind(this)})}},flipImage:function(t){if(!this.animationInProgress){this.animationInProgress=!0,this.hasOrientationChanged()&&(t="y"===t?"x":"y"),this.focalPoint?this.canvas.remove(this.focalPoint):this._resetFocalPointPosition();var e={x:this.editorWidth/2,y:this.editorHeight/2};this.straighteningInput.setValue(-this.imageStraightenAngle),this.imageStraightenAngle=-this.imageStraightenAngle;var i,s,a={angle:this.viewportRotation+this.imageStraightenAngle},n=this.cropperState,r=this.focalPointState;"y"===t&&this.hasOrientationChanged()||"y"!==t&&!this.hasOrientationChanged()?(n.offsetX=-n.offsetX,r.offsetX=-r.offsetX,s=this.image.left-e.x,a.left=e.x-s):(n.offsetY=-n.offsetY,r.offsetY=-r.offsetY,i=this.image.top-e.y,a.top=e.y-i),"y"===t?(a.scaleY=-1*this.image.scaleY,this.flipData.y=1-this.flipData.y):(a.scaleX=-1*this.image.scaleX,this.flipData.x=1-this.flipData.x),this.storeCropperState(n),this.storeFocalPointState(r),this.image.animate(a,{onChange:this.canvas.renderAll.bind(this.canvas),duration:this.settings.animationDuration,onComplete:function(){this.animationInProgress=!1,this.focalPoint&&(this._adjustFocalPointByAngle(0),this.canvas.add(this.focalPoint))}.bind(this)})}},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(e){var i=t(e.currentTarget);if(i.hasClass("disabled"))return!1;t(".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){this.$buttons.find(".btn").removeClass("disabled").end().find(".spinner").remove(),t.error?alert(t.error):(this.onSave(),this.hide(),Craft.cp.runQueue())}.bind(this))},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(),t("html").addClass("noscroll")},hide:function(){this.removeAllListeners(),this.straighteningInput.removeAllListeners(),t("html").removeClass("noscroll"),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.getScaledImageDimensions();this.zoomRatio=this.getZoomToFitRatio(t);var e={width:this.editorWidth,height:this.editorHeight},i={width:t.width*this.zoomRatio,height:t.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},s=function(){this._setFittedImageVerticeCoordinates();var t=this.cropperState,e=this.getScaledImageDimensions(),i=e.width/t.imageDimensions.width,s={left:this.image.left+t.offsetX*i*this.zoomRatio,top:this.image.top+t.offsetY*i*this.zoomRatio,width:t.width*i*this.zoomRatio,height:t.height*i*this.zoomRatio};this._showCropper(s),this.focalPoint&&(i=e.width/this.focalPointState.imageDimensions.width,this.focalPoint.left=this.image.left+this.focalPointState.offsetX*i*this.zoomRatio,this.focalPoint.top=this.image.top+this.focalPointState.offsetY*i*this.zoomRatio,this.canvas.add(this.focalPoint))}.bind(this);this._editorModeTransition(s,i,e)},disableCropMode:function(){var t={};this._hideCropper();var e=this.getScaledImageDimensions(),i=this.getZoomToCoverRatio(e)*this.scaleFactor,s=i/this.zoomRatio;this.zoomRatio=i;var a={width:e.width*this.zoomRatio,height:e.height*this.zoomRatio,left:this.editorWidth/2,top:this.editorHeight/2},n=(this.clipper.left-this.image.left)*s,r=(this.clipper.top-this.image.top)*s;a.left=this.editorWidth/2-n,a.top=this.editorHeight/2-r,t.height=this.clipper.height*s,t.width=this.clipper.width*s,(!this.focalPoint||this.focalPoint&&!this._isCenterInside(this.focalPoint,this.clipper))&&(this.focalPoint&&this.toggleFocalPoint(),this._resetFocalPointPosition());var o=function(){if(this.focalPoint){var t=this.getScaledImageDimensions().width/this.focalPointState.imageDimensions.width;this.focalPoint.left=this.image.left+this.focalPointState.offsetX*t*this.zoomRatio,this.focalPoint.top=this.image.top+this.focalPointState.offsetY*t*this.zoomRatio,this.canvas.add(this.focalPoint)}}.bind(this);this._editorModeTransition(o,a,t)},_editorModeTransition:function(t,e,i){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(),this.animationInProgress=!1,this.renderImage()}.bind(this)}),this.viewport.animate(i,{duration:this.settings.animationDuration}))},_showSpinner:function(){this.$spinnerCanvas=t('<canvas id="spinner-canvas"></canvas>').appendTo(t(".image",this.$container));var e=document.getElementById("spinner-canvas").getContext("2d"),i=new Date,s=e.canvas.width,a=e.canvas.height;this.spinnerInterval=window.setInterval((function(){var t=parseInt((new Date-i)/1e3*16)/16;e.save(),e.clearRect(0,0,s,a),e.translate(s/2,a/2),e.rotate(2*Math.PI*t);for(var n=0;n<16;n++)e.beginPath(),e.rotate(2*Math.PI/16),e.moveTo(s/10,0),e.lineTo(s/4,0),e.lineWidth=s/30,e.strokeStyle="rgba(255,255,255,"+n/16+")",e.stroke();e.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.remove(this.croppingAreaText),this.croppingCanvas=null,this.renderCropper=null)},_setupCropperLayer:function(e){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(){Garnish.requestAnimationFrame(this.croppingCanvas.renderAll.bind(this.croppingCanvas))}.bind(this),t("#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}),e&&this.clipper.set(e),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.croppingCanvas.remove(this.croppingAreaText)),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.croppingAreaText=new fabric.Textbox(Math.round(this.clipper.width)+" x "+Math.round(this.clipper.height),{left:this.croppingRectangle.left,top:this._redrawCropperElements._.cropTextTop,fontSize:13,fill:"rgb(200,200,200)",backgroundColor:this._redrawCropperElements._.cropTextBackgroundColor,font:"Craft",width:70,height:15,originX:"center",originY:"center",textAlign:"center"}),this.croppingCanvas.add(this.cropperHandles),this.croppingCanvas.add(this.cropperGrid),this.croppingCanvas.add(this.croppingRectangle),this.croppingCanvas.add(this.croppingAreaText)},_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(){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(){this._redrawCropperElements(),this.croppingCanvas.renderAll()}.bind(this),duration:this.settings.animationDuration,onComplete:function(){this._redrawCropperElements(),this.animationInProgress=!1,this.renderCropper(),this.storeCropperState()}.bind(this)}))},_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(e){void 0===this._setMouseCursor._&&(this._setMouseCursor._={}),Garnish.isMobileBrowser(!0)||(this._setMouseCursor._.cursor="default",this._setMouseCursor._.handle=this.croppingCanvas&&this._cropperHandleHitTest(e),this.focalPoint&&this._isMouseOver(e,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(e,this.clipper)&&(this._setMouseCursor._.cursor="move"),t(".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:t.noop,allowDegreeFractions:null}}),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:{},_uploadedAssetIds:[],_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(e,i,s){this.base(e,i,s),"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",t.proxy(this,"_positionProgressBar")))},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(){if(!this._folderDrag){this.settings.selectable=!0,this.settings.multiSelect=!0;var e=t.proxy(this,"_onDragStart"),i=t.proxy(this,"_onDropTargetChange");this._assetDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,filter:t.proxy((function(){return this.view.getSelectedElements().has("div.element[data-movable]")}),this),helper:t.proxy((function(t){return this._getFileDragHelper(t)}),this),dropTargets:t.proxy((function(){var t;t=this._assetDrag.$draggee&&this._assetDrag.$draggee.has(".element[data-peer-file]").length?"data-can-move-peer-files-to":"data-can-move-to";for(var e=[],i=0;i<this.$sources.length;i++){var s=this.$sources.eq(i);Garnish.hasAttr(s,t)&&e.push(s)}return e}),this),onDragStart:e,onDropTargetChange:i,onDragStop:t.proxy(this,"_onFileDragStop"),helperBaseZindex:800}),this._folderDrag=new Garnish.DragDrop({activeDropTargetClass:"sel",helperOpacity:.75,filter:t.proxy((function(){for(var e=this.sourceSelect.getSelectedItems(),i=[],s=0;s<e.length;s++){var a=e.eq(s);this._getFolderUidFromSourceKey(a.data("key"))&&(a.hasClass("sel")&&this._getSourceLevel(a)>1&&i.push(a.parent()[0]))}return t(i)}),this),helper:t.proxy((function(e){var i=t('<div class="sidebar" style="padding-top: 0; padding-bottom: 0;"/>'),s=t("<nav/>").appendTo(i),a=t("<ul/>").appendTo(s);return e.appendTo(a).removeClass("expanded"),e.children("a").addClass("sel"),e.css({"padding-top":this._folderDrag.$draggee.css("padding-top"),"padding-right":this._folderDrag.$draggee.css("padding-right"),"padding-bottom":this._folderDrag.$draggee.css("padding-bottom"),"padding-left":this._folderDrag.$draggee.css("padding-left")}),i}),this),dropTargets:t.proxy((function(){var e=[],i=[];this._folderDrag.$draggee.find("a[data-key]").each((function(){i.push(t(this).data("key"))}));for(var s=0;s<this.$sources.length;s++){var a=this.$sources.eq(s),n=a.data("key");this._getFolderUidFromSourceKey(n)&&(Craft.inArray(n,i)||e.push(a))}return e}),this),onDragStart:e,onDropTargetChange:i,onDragStop:t.proxy(this,"_onFolderDragStop")})}},_onFileDragStop:function(){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}});var o=t.proxy((function(a){this.promptHandler.resetPrompts();for(var n=0;n<a.length;n++){var r=a[n];r.conflict&&this.promptHandler.addPrompt({assetId:r.assetId,suggestedFilename:r.suggestedFilename,prompt:{message:r.conflict,choices:this._fileConflictTemplate.choices}}),r.error&&alert(r.error)}this.setIndexAvailable(),this.progressBar.hideProgressBar();var l=!1,h=function(){this.sourceSelect.selectItem(e),this._totalVisible-=this._assetDrag.$draggee.length;for(var a=0;a<s.length;a++)t("[data-id="+s[a]+"]").remove();this.view.deselectAllElements(),this._collapseExtraExpandedFolders(i),l&&this.updateElements()};if(this.promptHandler.getPromptCount()){var d=t.proxy((function(t){for(var e=[],s=0;s<t.length;s++)"cancel"!==t[s].choice?("keepBoth"===t[s].choice&&e.push({action:"assets/move-asset",params:{folderId:i,assetId:t[s].assetId,filename:t[s].suggestedFilename}}),"replace"===t[s].choice&&e.push({action:"assets/move-asset",params:{folderId:i,assetId:t[s].assetId,force:!0}})):l=!0;0===e.length?h.apply(this):(this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(this.promptHandler.getPromptCount()),this.progressBar.showProgressBar(),this._performBatchRequests(e,o))}),this);this._assetDrag.fadeOutHelpers(),this.promptHandler.showBatchPrompts(d)}else h.apply(this),this._assetDrag.fadeOutHelpers()}),this);return void this._performBatchRequests(r,o)}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._assetDrag.returnHelpersToDraggees()},_onFolderDragStop:function(){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="",l=function(e){this.promptHandler.resetPrompts();for(var s=0;s<e.length;s++){var a=e[s];a.success&&(a.transferList&&(r=a.transferList),a.newFolderId&&(o=this._folderDrag.$activeDropTarget.data("key")+"/folder:"+a.newFolderUid)),a.conflict&&(a.prompt={message:a.conflict,choices:this._folderConflictTemplate.choices},this.promptHandler.addPrompt(a)),a.error&&alert(a.error)}if(this.promptHandler.getPromptCount()){var n=t.proxy((function(e){this.promptHandler.resetPrompts();for(var s=[],n={},h=0;h<e.length;h++)"cancel"!==e[h].choice&&("replace"===e[h].choice&&(n.force=!0),"merge"===e[h].choice&&(n.merge=!0),n.folderId=a.folderId,n.parentId=a.parentId,s.push({action:"assets/move-folder",params:n}));0===s.length?t.proxy(this,"_performActualFolderMove",r,i,o)():(this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(this.promptHandler.getPromptCount()),this.progressBar.showProgressBar(),this._performBatchRequests(s,l))}),this);this.promptHandler.showBatchPrompts(n),this.setIndexAvailable(),this.progressBar.hideProgressBar()}else t.proxy(this,"_performActualFolderMove",r,i,o)()}.bind(this);return void this._performBatchRequests(n,l)}}else this.$source.addClass("sel"),this._collapseExtraExpandedFolders();this._folderDrag.returnHelpersToDraggees()},_performActualFolderMove:function(t,e,i){this.setIndexBusy(),this.progressBar.resetProgressBar(),this.progressBar.setItemCount(1),this.progressBar.showProgressBar();var s=function(t){for(var e=0,s=t.length,a=0;a<t.length;a++)Craft.postActionRequest("assets/delete-folder",{folderId:t[a]},function(){++e===s&&(this.setIndexAvailable(),this.progressBar.hideProgressBar(),this._folderDrag.returnHelpersToDraggees(),this.setInstanceState("selectedSource",i),this.refreshSources())}.bind(this))}.bind(this);if(t.length>0){for(var a=[],n=0;n<t.length;n++)a.push({action:"assets/move-asset",params:t[n]});this._performBatchRequests(a,(function(){s(e)}))}else s(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(e){for(var i=this._getSourceByKey(e),s=i.parent().parents("li"),a=0;a<s.length;a++){var n=t(s[a]);n.hasClass("expanded")||n.children(".toggle").trigger("click")}this.selectSource(i),this.updateElements()},afterInit:function(){this.$uploadButton||(this.$uploadButton=t("<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=t('<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:t.proxy(this,"_onUploadStart"),fileuploadprogressall:t.proxy(this,"_onUploadProgress"),fileuploaddone:t.proxy(this,"_onUploadComplete")},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",t.proxy((function(){this.$uploadButton.hasClass("disabled")||this.isIndexBusy||this.$uploadButton.parent().find("input[name=assets-upload]").trigger("click")}),this)),this.base()},getDefaultSourceKey:function(){if("index"===this.settings.context&&"undefined"!=typeof defaultVolumeHandle)for(var e=0;e<this.$sources.length;e++){var i=t(this.$sources[e]);if(i.data("volume-handle")===defaultVolumeHandle)return i.data("key")}return this.base()},onSelectSource:function(){var t=this._getSourceByKey(this.sourceKey);if(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"),"index"===this.settings.context&&"undefined"!=typeof history){var e="assets",i=this._getRootSource(t);i&&i.data("volume-handle")&&(e+="/"+i.data("volume-handle")),history.replaceState({},"",Craft.getUrl(e))}this.base()},_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 e="includeSubfolders-"+Math.floor(1e9*Math.random());this.$includeSubfoldersContainer=t('<div style="margin-bottom: -25px; opacity: 0;"/>').insertAfter(this.$search);var i=t('<div style="padding-top: 5px;"/>').appendTo(this.$includeSubfoldersContainer);this.$includeSubfoldersCheckbox=t('<input type="checkbox" id="'+e+'" class="checkbox"/>').appendTo(i),t('<label class="light smalltext" for="'+e+'"/>').text(" "+Craft.t("app","Search in subfolders")).appendTo(i),this.addListener(this.$includeSubfoldersCheckbox,"change",(function(){this.setSelecetedSourceState("includeSubfolders",this.$includeSubfoldersCheckbox.prop("checked")),this.updateElements()}))}else this.$includeSubfoldersContainer.velocity("stop");var s=this.getSelectedSourceState("includeSubfolders",!1);this.$includeSubfoldersCheckbox.prop("checked",s),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(e,i){var s=i.result,a=i.files[0].name,n=!0;s.success||s.conflict?(this._uploadedAssetIds.push(s.assetId),s.conflict&&(s.prompt={message:Craft.t("app",s.conflict,{file:s.filename}),choices:this._fileConflictTemplate.choices},this.promptHandler.addPrompt(s)),Craft.cp.runQueue()):(s.error?alert(Craft.t("app","Upload failed. The error message was: “{error}”",{error:s.error})):alert(Craft.t("app","Upload failed for {filename}.",{filename:a})),n=!1),this.uploader.isLastUpload()&&(this.setIndexAvailable(),this.progressBar.hideProgressBar(),this.promptHandler.getPromptCount()?this.promptHandler.showBatchPrompts(t.proxy(this,"_uploadFollowup")):n&&this._updateAfterUpload())},_updateAfterUpload:function(){"index"!==this.settings.context&&(this.setSortAttribute("dateModified"),this.setSortDirection("desc")),this.updateElements()},_uploadFollowup:function(t){this.setIndexBusy(),this.progressBar.resetProgressBar(),this.promptHandler.resetPrompts();var e=function(){this.setIndexAvailable(),this.progressBar.hideProgressBar(),this._updateAfterUpload()}.bind(this);this.progressBar.setItemCount(t.length);var i=function(t,e,s){var a={},n=null,r=function(a,n){"success"===n&&a.assetId?this._uploadedAssetIds.push(a.assetId):a.error&&alert(a.error),e++,this.progressBar.incrementProcessedItemCount(1),this.progressBar.updateProgressBar(),e===t.length?s():i(t,e,s)}.bind(this);"replace"===t[e].choice?(n="assets/replace-file",a.sourceAssetId=t[e].assetId,t[e].conflictingAssetId?a.assetId=t[e].conflictingAssetId:a.targetFilename=t[e].filename):"cancel"===t[e].choice&&(n="assets/delete-asset",a.assetId=t[e].assetId),n?Craft.postActionRequest(n,a,r):r({assetId:t[e].assetId},"success")}.bind(this);this.progressBar.showProgressBar(),i(t,0,e)},onUpdateElements:function(){this._onUpdateElements(!1,this.view.getAllElements()),this.view.on("appendElements",t.proxy((function(t){this._onUpdateElements(!0,t.newElements)}),this)),this.base()},_onUpdateElements:function(t,e){if("index"===this.settings.context&&(t||this._assetDrag.removeAllItems(),this._assetDrag.addItems(e.has("div.element[data-movable]"))),this._uploadedAssetIds.length){if(this.view.settings.selectable)for(var i=0;i<this._uploadedAssetIds.length;i++)this.view.selectElementById(this._uploadedAssetIds[i]);this._uploadedAssetIds=[]}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(e){var i=t(e.item).find(".element");Craft.PreviewFileModal.openInstance&&i.length&&this._loadPreview(i)},_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(e){var i,s;switch(this.getSelectedSourceState("mode")){case"table":i=t('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),s=t('<div class="tableview"/>').appendTo(i);var a=t('<table class="data"/>').appendTo(s),n=t("<tbody/>").appendTo(a);e.appendTo(n),this._$firstRowCells=this.view.$table.children("tbody").children("tr:first").children();for(var r=e.children(),o=0;o<r.length;o++){var l=t(r[o]);if(l.hasClass("checkbox-cell"))l.remove(),i.css("margin-"+Craft.left,19);else{var h=t(this._$firstRowCells[o]),d=h.width();h.width(d),l.width(d)}}return i;case"thumbs":return i=t('<div class="elements thumbviewhelper"/>').appendTo(Garnish.$bod),s=t('<ul class="thumbsview"/>').appendTo(i),e.appendTo(s),i}return t()},_onDropTargetChange:function(e){if(clearTimeout(this._expandDropTargetFolderTimeout),e){var i=e.data("folder-id");i?(this.dropTargetFolder=this._getSourceByKey(i),this._hasSubfolders(this.dropTargetFolder)&&!this._isExpanded(this.dropTargetFolder)&&(this._expandDropTargetFolderTimeout=setTimeout(t.proxy(this,"_expandFolder"),500))):this.dropTargetFolder=null}e&&e[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(e){if(this._getFolderUidFromSourceKey(e.data("key"))){var i=[{label:Craft.t("app","New subfolder"),onClick:t.proxy(this,"_createSubfolder",e)}];"index"===this.settings.context&&this._getSourceLevel(e)>1&&(i.push({label:Craft.t("app","Rename folder"),onClick:t.proxy(this,"_renameFolder",e)}),i.push({label:Craft.t("app","Delete folder"),onClick:t.proxy(this,"_deleteFolder",e)})),new Garnish.ContextMenu(e,i,{menuClass:"menu"})}},_createSubfolder:function(e){var i=prompt(Craft.t("app","Enter the name of the folder"));if(i){var s={parentId:e.data("folder-id"),folderName:i};this.setIndexBusy(),Craft.postActionRequest("assets/create-folder",s,t.proxy((function(i,s){if(this.setIndexAvailable(),"success"===s&&i.success){this._prepareParentForChildren(e);var a=t('<li><a data-key="'+e.data("key")+"/folder:"+i.folderUid+'"'+(Garnish.hasAttr(e,"data-has-thumbs")?" data-has-thumbs":"")+' data-folder-id="'+i.folderId+'"'+(Garnish.hasAttr(e,"data-can-upload")?" data-can-upload":"")+(Garnish.hasAttr(e,"data-can-move-to")?" data-can-move-to":"")+(Garnish.hasAttr(e,"data-can-move-peer-files-to")?" data-can-move-peer-files-to":"")+">"+i.folderName+"</a></li>"),n=a.children("a:first");this._appendSubfolder(e,a),this.initSource(n)}"success"===s&&i.error&&alert(i.error)}),this))}},_deleteFolder:function(e){if(confirm(Craft.t("app","Really delete folder “{folder}”?",{folder:t.trim(e.text())}))){var i={folderId:e.data("folder-id")};this.setIndexBusy(),Craft.postActionRequest("assets/delete-folder",i,t.proxy((function(t,i){if(this.setIndexAvailable(),"success"===i&&t.success){var s=this._getParentSource(e);this.deinitSource(e),e.parent().remove(),this._cleanUpTree(s)}"success"===i&&t.error&&alert(t.error)}),this))}},_renameFolder:function(e){var i=t.trim(e.text()),s=prompt(Craft.t("app","Rename folder"),i);if(s&&s!==i){var a={folderId:e.data("folder-id"),newName:s};this.setIndexBusy(),Craft.postActionRequest("assets/rename-folder",a,t.proxy((function(t,i){this.setIndexAvailable(),"success"===i&&t.success&&(e.text(t.newName),this._getFolderUidFromSourceKey(this.sourceSelect.$selectedItems.data("key"))===this._getFolderUidFromSourceKey(e.data("key"))&&this.updateElements()),"success"===i&&t.error&&alert(t.error)}),this),"json")}},_prepareParentForChildren:function(t){this._hasSubfolders(t)||(t.parent().addClass("expanded").append('<div class="toggle"></div><ul></ul>'),this.initSourceToggle(t))},_appendSubfolder:function(e,i){for(var s=e.siblings("ul").children("li"),a=t.trim(i.children("a:first").text()),n=!1,r=0;r<s.length;r++){var o=t(s[r]);if(t.trim(o.children("a:first").text())>a){o.before(i),n=!0;break}}n||e.siblings("ul").append(i)},_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 e=t(),i=0,s=0;"index"===this.settings.context?(e=this.progressBar.$progressBar.closest("#content"),i=Garnish.$win.scrollTop()):(e=this.progressBar.$progressBar.closest(".main"),i=this.$main.scrollTop());var a=i-e.offset().top,n=Garnish.$win.height();s=e.height()>n?n/2-6+a:e.height()/2-6,"index"!==this.settings.context&&(s=i+(e.height()/2-6)),this.progressBar.$progressBar.css({top:s})},_performBatchRequests:function(t,e){for(var i=[],s=function(s){Craft.postActionRequest(s.action,s.params,function(s,a){this.progressBar.incrementProcessedItemCount(1),this.progressBar.updateProgressBar(),"success"===a&&(i.push(s),Craft.cp.runQueue()),i.length>=t.length&&e(i)}.bind(this))}.bind(this),a=0;a<t.length;a++)s(t[a])}}),Craft.registerElementIndexClass("craft\\elements\\Asset",Craft.AssetIndex),Craft.AssetSelectInput=Craft.BaseElementSelectInput.extend({requestId:0,hud:null,$uploadBtn:null,uploader:null,progressBar:null,originalFilename:"",originalExtension:"",init:function(){arguments.length>0&&"object"==typeof arguments[0]&&(arguments[0].editorSettings={onShowHud:t.proxy(this.resetOriginalFilename,this),onCreateForm:t.proxy(this._renameHelper,this),validators:[t.proxy(this.validateElementForm,this)]}),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(e){var i=t(e.item);Craft.PreviewFileModal.openInstance&&i.length&&this._loadPreview(i)},_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(){this.progressBar=new Craft.ProgressBar(t('<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=t("<button/>",{type:"button",class:"btn dashed","data-icon":"upload",text:1==this.settings.limit?Craft.t("app","Upload a file"):Craft.t("app","Upload files")}).insertAfter(this.$addElementBtn),e.fileInput=t("<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=t.proxy(this,"canAddMoreFiles"),e.events={},e.events.fileuploadstart=t.proxy(this,"_onUploadStart"),e.events.fileuploadprogressall=t.proxy(this,"_onUploadProgress"),e.events.fileuploaddone=t.proxy(this,"_onUploadComplete"),this.uploader=new Craft.Uploader(this.$container,e),this.$uploadBtn&&this.$uploadBtn.on("click",t.proxy((function(t){this.$uploadBtn.next("input[type=file]").trigger("click")}),this))},refreshThumbnail:function(e){var i={elementId:e,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=this.$elements.filter('[data-id="'+e+'"]');s.find(".elementthumb").replaceWith(t(i.html).find(".elementthumb")),this.thumbLoader.load(s)}}.bind(this))},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(e,i){if(i.result.error)alert(i.result.error);else{var s={elementId:i.result.assetId,siteId:this.settings.criteria.siteId,size:this.settings.viewMode};Craft.postActionRequest("elements/get-element-html",s,function(e){if(e.error)alert(e.error);else{var i=t(e.html);Craft.appendHeadHtml(e.headHtml),this.selectUploadedFile(Craft.getElementInfo(i))}this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"),window.draftEditor&&window.draftEditor.checkForm())}.bind(this)),Craft.cp.runQueue()}},canAddMoreFiles:function(t){return!this.settings.limit||this.$elements.length+t<this.settings.limit},_parseFilename:function(t){var e=t.split("."),i="";return e.length>1&&(i=e.pop()),{extension:i,baseFileName:e.join(".")}},_renameHelper:function(e){t(".renameHelper",e).on("focus",t.proxy((function(t){var e=t.currentTarget,i=this._parseFilename(e.value);""===this.originalFilename&&""===this.originalExtension&&(this.originalFilename=i.baseFileName,this.originalExtension=i.extension);var s=i.baseFileName.length;if(void 0!==e.selectionStart)e.selectionStart=0,e.selectionEnd=s;else if(document.selection&&document.selection.createRange){e.select();var a=document.selection.createRange();a.collapse(!0),a.moveEnd("character",s),a.moveStart("character",0),a.select()}}),this))},resetOriginalFilename:function(){this.originalFilename="",this.originalExtension=""},validateElementForm:function(){var e=t(".renameHelper",this.elementEditor.hud.$hud.data("elementEditor").$form),i=this._parseFilename(e.val());return i.extension===this.originalExtension||(""===i.extension?this.originalFilename!==i.baseFileName?(e.val(i.baseFileName+"."+this.originalExtension),!0):confirm(Craft.t("app","Are you sure you want to remove the extension “.{ext}”?",{ext:this.originalExtension})):confirm(Craft.t("app","Are you sure you want to change the extension from “.{oldExt}” to “.{newExt}”?",{oldExt:this.originalExtension,newExt:i.extension})))}}),Craft.AssetSelectorModal=Craft.BaseElementSelectorModal.extend({$selectTransformBtn:null,_selectedTransform:null,init:function(e,i){i=t.extend({},Craft.AssetSelectorModal.defaults,i),this.base(e,i),i.transforms.length&&this.createSelectTransformButton(i.transforms)},createSelectTransformButton:function(e){if(e&&e.length){var i=t('<div class="btngroup"/>').appendTo(this.$primaryButtons);this.$selectBtn.appendTo(i),this.$selectTransformBtn=t("<button/>",{type:"button",class:"btn menubtn disabled",text:Craft.t("app","Select transform")}).appendTo(i);for(var s=t('<div class="menu" data-align="right"></div>').insertAfter(this.$selectTransformBtn),a=t("<ul></ul>").appendTo(s),n=0;n<e.length;n++)t('<li><a data-transform="'+e[n].handle+'">'+e[n].name+"</a></li>").appendTo(a);var r=new Garnish.MenuBtn(this.$selectTransformBtn,{onOptionSelect:t.proxy(this,"onSelectTransform")});r.disable(),this.$selectTransformBtn.data("menuButton",r)}},onSelectionChange:function(e){var i=this.elementIndex.getSelectedElements(),s=!1;if(i.length&&this.settings.transforms.length){s=!0;for(var a=0;a<i.length&&t(".element.hasthumb:first",i[a]).length;a++);}var n=null;this.$selectTransformBtn&&(n=this.$selectTransformBtn.data("menuButton")),s?(n&&n.enable(),this.$selectTransformBtn.removeClass("disabled")):this.$selectTransformBtn&&(n&&n.disable(),this.$selectTransformBtn.addClass("disabled")),this.base()},onSelectTransform:function(e){var i=t(e).data("transform");this.selectImagesWithTransform(i)},selectImagesWithTransform:function(e){void 0===Craft.AssetSelectorModal.transformUrls[e]&&(Craft.AssetSelectorModal.transformUrls[e]={});for(var i=this.elementIndex.getSelectedElements(),s=[],a=0;a<i.length;a++){var n=t(i[a]),r=Craft.getElementInfo(n).id;void 0===Craft.AssetSelectorModal.transformUrls[e][r]&&s.push(r)}s.length?(this.showFooterSpinner(),this.fetchMissingTransformUrls(s,e,t.proxy((function(){this.hideFooterSpinner(),this.selectImagesWithTransform(e)}),this))):(this._selectedTransform=e,this.selectElements(),this._selectedTransform=null)},fetchMissingTransformUrls:function(e,i,s){var a=e.pop(),n={assetId:a,handle:i};Craft.postActionRequest("assets/generate-transform",n,t.proxy((function(t,n){Craft.AssetSelectorModal.transformUrls[i][a]=!1,"success"===n&&t.url&&(Craft.AssetSelectorModal.transformUrls[i][a]=t.url),e.length?this.fetchMissingTransformUrls(e,i,s):s()}),this))},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),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(e){this.checkRemainingSessionTimer&&clearTimeout(this.checkRemainingSessionTimer),this.checkRemainingSessionTimer=setTimeout(t.proxy(this,"checkRemainingSessionTime"),1e3*e)},checkRemainingSessionTime:function(e){t.ajax({url:Craft.getActionUrl("users/session-info",e?null:"dontExtendSession=1"),type:"GET",dataType:"json",complete:t.proxy((function(t,e){"success"===e?(void 0!==t.responseJSON.csrfTokenValue&&void 0!==Craft.csrfTokenValue&&(Craft.csrfTokenValue=t.responseJSON.csrfTokenValue),this.updateRemainingSessionTime(t.responseJSON.timeout),this.submitLoginIfLoggedOut=!1):this.updateRemainingSessionTime(-1)}),this)})},updateRemainingSessionTime:function(e){this.remainingSessionTime=parseInt(e),-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(t.proxy(this,"showLoginModal"),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 e;if(this.showingLoginModal?(this.hideLoginModal(!0),e=!0):e=!1,this.showingLogoutWarningModal=!0,!this.logoutWarningModal){let e=t('<form id="logoutwarningmodal" class="modal alert fitted"/>'),i=t('<div class="body"/>').appendTo(e),s=t('<div class="buttons right"/>').appendTo(i),a=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Log out now")}).appendTo(s),n=t("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Keep me logged in")}).appendTo(s);this.$logoutWarningPara=t("<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")}e?this.logoutWarningModal.quickShow():this.logoutWarningModal.show(),this.updateLogoutWarningMessage(),this.decrementLogoutWarningInterval=setInterval(t.proxy(this,"decrementLogoutWarning"),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 e;if(this.showingLogoutWarningModal?(this.hideLogoutWarningModal(!0),e=!0):e=!1,this.showingLoginModal=!0,!this.loginModal){var i=t('<form id="loginmodal" class="modal alert fitted"/>'),s=t('<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=t('<div class="inputcontainer">').appendTo(s),n=t('<div class="flex"/>').appendTo(a),r=t('<div class="flex-grow"/>').appendTo(n),o=t("<div/>").appendTo(n),l=t('<div class="passwordwrapper"/>').appendTo(r);this.$passwordInput=t('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'"/>').appendTo(l),this.$passwordSpinner=t('<div class="spinner hidden"/>').appendTo(a),this.$loginBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Login")}).appendTo(o),this.$loginErrorPara=t('<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:t.proxy((function(){Garnish.isMobileBrowser(!0)||setTimeout(t.proxy((function(){this.$passwordInput.trigger("focus")}),this),100)}),this),onFadeOut:t.proxy((function(){this.$passwordInput.val("")}),this)}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:t.proxy((function(t){this.$passwordInput=t}),this)}),this.addListener(this.$passwordInput,"input","validatePassword"),this.addListener(i,"submit","login")}e?this.loginModal.quickShow():this.loginModal.show()},hideLoginModal:function(t){this.showingLoginModal=!1,this.loginModal&&(t?this.loginModal.quickHide():this.loginModal.hide())},logout:function(){t.get({url:Craft.getActionUrl("users/logout"),dataType:"json",success:t.proxy((function(){Craft.redirectTo("")}),this)})},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 e={loginName:Craft.username,password:this.$passwordInput.val()};Craft.postActionRequest("users/login",e,t.proxy((function(t,e){this.$passwordSpinner.addClass("hidden"),"success"===e?t.success?(this.hideLoginModal(),this.checkRemainingSessionTime()):(this.showLoginError(t.error),Garnish.shake(this.loginModal.$container),Garnish.isMobileBrowser(!0)||this.$passwordInput.trigger("focus")):this.showLoginError()}),this))},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}),Craft.CP=Garnish.Base.extend({authManager:null,$nav:null,$mainContainer:null,$alerts:null,$crumbs:null,$notificationContainer:null,$main:null,$primaryForm:null,$headerContainer:null,$header:null,$mainContent:null,$details:null,$tabsContainer:null,$tabsList:null,$tabs:null,$overflowTabBtn:null,$overflowTabList:null,$selectedTab:null,selectedTabIndex:null,$sidebarContainer:null,$sidebar:null,$contentContainer:null,$edition:null,$confirmUnloadForms:null,$deltaForms:null,$collapsibleTables:null,fixedHeader:!1,enableQueue:!0,totalJobs:0,jobInfo:null,displayedJobInfo:null,displayedJobInfoUnchanged:1,trackJobProgressTimeout:null,jobProgressIcon:null,checkingForUpdates:!1,forcingRefreshOnUpdatesCheck:!1,includingDetailsOnUpdatesCheck:!1,checkForUpdatesCallbacks:null,init:function(){0!==Craft.remainingSessionTime&&(this.authManager=new Craft.AuthManager),this.$nav=t("#nav"),this.$mainContainer=t("#main-container"),this.$alerts=t("#alerts"),this.$crumbs=t("#crumbs"),this.$notificationContainer=t("#notifications"),this.$main=t("#main"),this.$primaryForm=t("#main-form"),this.$headerContainer=t("#header-container"),this.$header=t("#header"),this.$mainContent=t("#main-content"),this.$details=t("#details"),this.$sidebarContainer=t("#sidebar-container"),this.$sidebar=t("#sidebar"),this.$contentContainer=t("#content-container"),this.$collapsibleTables=t("table.collapsible"),this.updateSidebarMenuLabel();let e=this.$details.find(".meta > .field > .instructions");for(let i=0;i<e.length;i++){let s=e.eq(i),a=s.siblings(".heading").children("label");t("<span/>",{class:"info",html:s.children().html()}).appendTo(a),s.remove()}if(this.$header.length&&(this.addListener(Garnish.$win,"scroll","updateFixedHeader"),this.updateFixedHeader()),Garnish.$doc.ready(t.proxy((function(){this.addListener(Garnish.$win,"resize","handleWindowResize"),this.handleWindowResize();var e=this.$notificationContainer.children(".error"),i=this.$notificationContainer.children(":not(.error)");e.delay(2*Craft.CP.notificationDuration).velocity("fadeOut"),i.delay(Craft.CP.notificationDuration).velocity("fadeOut"),Garnish.requestAnimationFrame(t.proxy(this,"initSpecialForms"))}),this)),this.$alerts.length&&this.initAlerts(),this.addListener(t("#nav-toggle"),"click","toggleNav"),this.addListener(t("#sidebar-toggle"),"click","toggleSidebar"),this.$primaryForm.length||(this.$primaryForm=t("form[data-saveshortcut]:first")),this.$primaryForm.length&&Garnish.hasAttr(this.$primaryForm,"data-saveshortcut")){let t=[],e=this.$primaryForm.data("actions");if(void 0===e)t.push([{keyCode:Garnish.S_KEY,ctrl:!0},{redirect:this.$primaryForm.data("saveshortcut-redirect"),retainScroll:Garnish.hasAttr(this.$primaryForm,"saveshortcut-scroll")}]);else for(let i=0;i<e.length;i++){let s=e[i];s.shortcut&&t.push([{keyCode:Garnish.S_KEY,ctrl:!0,shift:!!s.shift},{action:s.action,redirect:s.redirect,confirm:s.confirm,params:s.params,data:s.data,retainScroll:s.retainScroll}])}for(let e=0;e<t.length;e++)Garnish.shortcutManager.registerShortcut(t[e][0],()=>{this.submitPrimaryForm(t[e][1])})}this.initTabs();let i=Craft.getLocalStorage("scrollY");void 0!==i&&(Craft.removeLocalStorage("scrollY"),Garnish.$doc.ready(()=>{Garnish.requestAnimationFrame(()=>{window.scrollTo(0,i)})})),t.isTouchCapable()&&(this.$mainContainer.on("focus","input, textarea, .focusable-input",t.proxy(this,"_handleInputFocus")),this.$mainContainer.on("blur","input, textarea, .focusable-input",t.proxy(this,"_handleInputBlur")))},initSpecialForms:function(){if(this.$confirmUnloadForms=t("form[data-confirm-unload]"),this.$deltaForms=t("form[data-delta]"),this.$confirmUnloadForms.length){for(var e,i,s=this.$confirmUnloadForms.add(this.$deltaForms),a=0;a<s.length;a++)(e=s.eq(a)).data("initialSerializedValue")||(i="function"==typeof e.data("serializer")?e.data("serializer")():e.serialize(),e.data("initialSerializedValue",i)),this.addListener(e,"submit",(function(t){if(Garnish.hasAttr(e,"data-confirm-unload")&&this.removeListener(Garnish.$win,"beforeunload"),Garnish.hasAttr(e,"data-delta")){var i;t.preventDefault(),i="function"==typeof e.data("serializer")?e.data("serializer")():e.serialize();var s=Craft.findDeltaData(e.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"==typeof e&&t.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 e=this.$sidebar.find("a.sel:first"),i=e.children(".label");t("#selected-sidebar-item-label").text(i.length?i.text():e.text()),Garnish.$bod.removeClass("showing-sidebar")},toggleNav:function(){Garnish.$bod.toggleClass("showing-nav")},toggleSidebar:function(){Garnish.$bod.toggleClass("showing-sidebar")},initTabs:function(){if(this.$tabsList=this.$tabs=this.$overflowTabBtn=this.$overflowTabList=this.$selectedTab=this.selectedTabIndex=null,this.$tabsContainer=t("#tabs"),this.$tabsContainer.length){this.$tabsList=this.$tabsContainer.find("> ul"),this.$tabs=this.$tabsList.find("> li"),this.$overflowTabBtn=t("#overflow-tab-btn"),this.$overflowTabBtn.data("menubtn")||new Garnish.MenuBtn(this.$overflowTabBtn),this.$overflowTabList=this.$overflowTabBtn.data("menubtn").menu.$container.find("> ul");for(let t=0;t<this.$tabs.length;t++){const e=this.$tabs.eq(t);this.removeAllListeners(e);const i=e.children("a"),s=i.attr("href");s&&"#"===s.charAt(0)&&(this.addListener(i,"keydown",t=>{[Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)&&(t.preventDefault(),this.selectTab(t.currentTarget),i.focus())}),this.addListener(i,"click",t=>{t.preventDefault(),this.selectTab(t.currentTarget)}),encodeURIComponent(s.substr(1))===document.location.hash.substr(1)&&this.selectTab(i)),!this.$selectedTab&&i.hasClass("sel")&&this._selectTab(i,t)}}else this.$tabsContainer=null},selectTab:function(e){var i=t(e);if(this.$selectedTab){if(this.$selectedTab.get(0)===i.get(0))return;this.deselectTab()}i.addClass("sel");var s=i.attr("href");t(s).removeClass("hidden"),"undefined"!=typeof history&&history.replaceState(void 0,void 0,s),this._selectTab(i,this.$tabs.index(i.parent())),this.updateTabs(),this.$overflowTabBtn.data("menubtn").menu.hide()},_selectTab:function(e,i){if(e===this.$selectedTab)return;this.$selectedTab=e,this.selectedTabIndex=i,0===i?t("#content").addClass("square"):t("#content").removeClass("square"),Garnish.$win.trigger("resize"),Garnish.$doc.trigger("scroll");let s=e&&e.attr("href");if(s&&"#"===s.charAt(0)){let e=t("#context-btn").menubtn().data("menubtn");if(e)for(let t=0;t<e.menu.$options.length;t++){let i=e.menu.$options[t];i.href&&(i.href=i.href.match(/^[^#]*/)[0]+s)}}},deselectTab:function(){this.$selectedTab&&(this.$selectedTab.removeClass("sel"),"#"===this.$selectedTab.attr("href").charAt(0)&&t(this.$selectedTab.attr("href")).addClass("hidden"),this._selectTab(null,null))},handleWindowResize:function(){this.updateTabs(),this.updateResponsiveTables()},updateTabs:function(){if(this.$tabsContainer){var t,e=Math.floor(this.$tabsContainer.width())-40,i=0,s=!1,a=Garnish.$bod.width()>=768?-12:-7;this.$selectedTab&&(this.$selectedTab.parent("li").appendTo(this.$tabsList),i=Math.ceil(this.$selectedTab.parent("li").width()));for(var n=0;n<this.$tabs.length;n++)if(t=this.$tabs.eq(n).appendTo(this.$tabsList),n!==this.selectedTabIndex&&(i+=Math.ceil(t.width()),(0!==n||this.$selectedTab)&&(i+=a)),n===this.selectedTabIndex||i<=e)t.find("> a").removeAttr("role").removeAttr("tabindex");else{const e=t.appendTo(this.$overflowTabList).find("> a");this.$overflowTabBtn.data("menubtn").menu.addOptions(e),s=!0}s?this.$overflowTabBtn.removeClass("hidden"):this.$overflowTabBtn.addClass("hidden")}},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.$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(e,i){var s=Craft.CP.notificationDuration;"error"===e&&(s*=2);var a=t('<div class="notification '+e+'">'+i+"</div>").appendTo(this.$notificationContainer),n=-a.outerWidth()/2+"px";a.hide().css({opacity:0,"margin-left":n,"margin-right":n}).velocity({opacity:1,"margin-left":"2px","margin-right":"2px"},{display:"inline-block",duration:"fast"}).delay(s).velocity({opacity:0,"margin-left":n,"margin-right":n},{complete:function(){a.remove()}}),this.trigger("displayNotification",{notificationType:e,message:i})},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 e={path:Craft.path};Craft.queueActionRequest("app/get-cp-alerts",e,t.proxy(this,"displayAlerts"))},displayAlerts:function(e){if(this.$alerts.remove(),Garnish.isArray(e)&&e.length){this.$alerts=t('<ul id="alerts"/>').prependTo(t("#page-container"));for(var i=0;i<e.length;i++)t("<li>"+e[i]+"</li>").appendTo(this.$alerts);var s=this.$alerts.outerHeight();this.$alerts.css("margin-top",-s).velocity({"margin-top":0},"fast"),this.initAlerts()}},initAlerts:function(){for(var e=this.$alerts.find('a[class^="shun:"]'),i=0;i<e.length;i++)this.addListener(e[i],"click",t.proxy((function(e){e.preventDefault();var i=t(e.currentTarget),s={message:i.prop("className").substr(5)};Craft.queueActionRequest("app/shun-cp-alert",s,t.proxy((function(t,e){"success"===e&&(t.success?i.parent().remove():this.displayError(t.error))}),this))}),this))},checkForUpdates:function(t,e,i){if("function"==typeof e&&(i=e,e=!1),this.checkingForUpdates&&(!0===t&&!this.forcingRefreshOnUpdatesCheck||!0===e&&!this.includingDetailsOnUpdatesCheck)){var s=i;i=function(){this.checkForUpdates(t,e,s)}.bind(this)}"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(this.updateUtilitiesBadge(),this.checkingForUpdates=!1,Garnish.isArray(this.checkForUpdatesCallbacks)){var e=this.checkForUpdatesCallbacks;this.checkForUpdatesCallbacks=null;for(var i=0;i<e.length;i++)e[i](t)}this.trigger("checkForUpdates",{updateInfo:t})}.bind(this)))},_checkForUpdates:function(t,e){return new Promise(function(i,s){t?this._getUpdates(e).then((function(t){i(t)})):this._checkForCachedUpdates(e).then(function(t){!1!==t.cached&&i(t),this._getUpdates(e).then((function(t){i(t)}))}.bind(this))}.bind(this))},_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){return new Promise(function(e,i){Craft.sendApiRequest("GET","updates").then(function(i){this._cacheUpdates(i,t).then(e)}.bind(this)).catch(function(t){this._cacheUpdates({}).then(e)}.bind(this))}.bind(this))},_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 e=t("#nav-utilities").find("> a:not(.sel)");e.length&&Craft.queueActionRequest("app/get-utilities-badge-count",t.proxy((function(i){var s=e.children(".badge");i.badgeCount?(s.length||(s=t('<span class="badge"/>').appendTo(e)),s.text(i.badgeCount)):s.length&&s.remove()}),this))},runQueue:function(){this.enableQueue&&(Craft.runQueueAutomatically?Craft.queueActionRequest("queue/run",t.proxy((function(t,e){"success"===e&&this.trackJobProgress(!1,!0)}),this)):this.trackJobProgress(!1,!0))},trackJobProgress:function(e,i){if(i&&this.trackJobProgressTimeout&&(clearTimeout(this.trackJobProgressTimeout),this.trackJobProgressTimeout=null),!this.trackJobProgressTimeout&&this.enableQueue)if(!0===e){var s=Math.min(6e4,500*this.displayedJobInfoUnchanged);this.trackJobProgressTimeout=setTimeout(t.proxy(this,"_trackJobProgressInternal"),s)}else this._trackJobProgressInternal()},_trackJobProgressInternal:function(){Craft.queueActionRequest("queue/get-job-info?limit=50&dontExtendSession=1",t.proxy((function(t,e){"success"===e&&(this.trackJobProgressTimeout=null,this.totalJobs=t.total,this.setJobInfo(t.jobs),this.jobInfo.length&&this.trackJobProgress(!0))}),this))},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])return this.jobInfo[i]},updateJobIcon:function(){this.enableQueue&&this.$nav.length&&(this.displayedJobInfo?(this.jobProgressIcon||(this.jobProgressIcon=new s),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(){let 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 s=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=t("<li/>").appendTo(Craft.cp.$nav.children("ul")),this.$a=t("<a/>",{id:"job-icon",href:Craft.canAccessQueueManager?Craft.getUrl("utilities/queue-manager"):null}).appendTo(this.$li),this.$canvasContainer=t('<span class="icon"/>').appendTo(this.$a);var e=t('<span class="label"/>').appendTo(this.$a);this.$label=t("<span/>").appendTo(e),this.$progressLabel=t('<span class="progress-label"/>').appendTo(e).hide();let i=window.devicePixelRatio>1?2:1;this._canvasSize=18*i,this._arcPos=this._canvasSize/2,this._arcRadius=7*i,this._lineWidth=3*i,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(){this._animateArc(0,1,t.proxy((function(){this._$bgCanvas.velocity("fadeOut"),this._animateArc(1,1,t.proxy((function(){this.$a.remove(),this.destroy()}),this))}),this))},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(e,i){var s=t('<canvas id="job-icon-'+e+'" width="'+this._canvasSize+'" height="'+this._canvasSize+'"/>').appendTo(this.$canvasContainer),a=s[0].getContext("2d");return a.strokeStyle=i,a.lineWidth=this._lineWidth,a.lineCap="round",s},_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(t.proxy(this,"_takeNextArcStep"),50):this._arcAnimateCallback&&this._arcAnimateCallback()}});Craft.CategoryIndex=Craft.BaseElementIndex.extend({editableGroups:null,$newCategoryBtnGroup:null,$newCategoryBtn:null,init:function(e,i,s){this.on("selectSource",t.proxy(this,"updateButton")),this.on("selectSite",t.proxy(this,"updateButton")),this.base(e,i,s)},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 e=0;e<this.$sources.length;e++){var i=t(this.$sources[e]);if(i.data("handle")===defaultGroupHandle)return i.data("key")}return this.base()},updateButton:function(){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=t('<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=t('<a class="btn submit add icon" '+i+">"+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=t("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newCategoryBtnGroup))):this.$newCategoryBtn=r=t("<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>")}t(o+="</ul></div>").appendTo(this.$newCategoryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",t.proxy((function(t){this._openCreateCategoryModal(t.option.getAttribute("data-id"))}),this))}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/"+t.handle+"/new";if(this.siteId&&this.siteId!=Craft.primarySiteId)for(var i=0;i<Craft.sites.length;i++)Craft.sites[i].id==this.siteId&&(e+="/"+Craft.sites[i].handle);return'href="'+Craft.getUrl(e)+'"'}return'data-id="'+t.id+'"'},_openCreateCategoryModal:function(e){if(!this.$newCategoryBtn.hasClass("loading")){for(var i,s=0;s<this.editableGroups.length;s++)if(this.editableGroups[s].id==e){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:e},onBeginLoading:t.proxy((function(){this.$newCategoryBtn.addClass("loading")}),this),onEndLoading:t.proxy((function(){this.$newCategoryBtn.removeClass("loading")}),this),onHideHud:t.proxy((function(){this.$newCategoryBtn.removeClass("inactive").text(a)}),this),onSaveElement:t.proxy((function(t){var e="group:"+i.uid;this.sourceKey!==e&&this.selectSourceByKey(e),this.selectElementAfterUpdate(t.id),this.updateElements()}),this)})}}}}),Craft.registerElementIndexClass("craft\\elements\\Category",Craft.CategoryIndex),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(e){this.modal.disable(),this.modal.disableCancelBtn(),this.modal.disableSelectBtn(),this.modal.showFooterSpinner();for(var i=this.getSelectedElementIds(),s=0;s<e.length;s++)i.push(e[s].id);var a={categoryIds:i,siteId:e[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,t.proxy((function(i,s){if(this.modal.enable(),this.modal.enableCancelBtn(),this.modal.enableSelectBtn(),this.modal.hideFooterSpinner(),"success"===s){var a=t(i.html).children(".elements");this.$elementsContainer.replaceWith(a),this.$elementsContainer=a,this.resetElements();for(var n=[],r=0;r<e.length;r++){var o=e[r],l=this.getElementById(o.id);l&&(this.animateElementIntoPlace(o.$element,l),n.push(o))}this.updateDisabledElementsInModal(),this.modal.hide(),this.onSelectElements(n)}}),this))},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(e,i){var s;i===e.length-1&&(s=t.proxy((function(){var t=e.first().parent().parent(),i=t.parent();i[0]===this.$elementsContainer[0]||t.siblings().length?t.remove():i.remove()}),this));var a=t.proxy((function(){this.animateElementAway(e.eq(i),s)}),this);0===i?a():setTimeout(a,100*i)}}),Craft.charts={},Craft.charts.DataTable=Garnish.Base.extend({columns:null,rows:null,init:function(e){let i=e.columns,s=e.rows;s.forEach(t.proxy((function(e){t.each(e,(function(t){var s;switch(i[t].type){case"date":s=d3.timeParse("%Y-%m-%d"),e[t]=s(e[t]);break;case"datetime":s=d3.timeParse("%Y-%m-%d %H:00:00"),e[t]=s(e[t]);break;case"percent":e[t]=e[t]/100;break;case"number":e[t]=+e[t]}}))}),this)),this.columns=i,this.rows=s}}),Craft.charts.Tip=Garnish.Base.extend({$container:null,$tip:null,init:function(e){this.$container=e,this.$tip=t('<div class="tooltip"></div>').appendTo(this.$container),this.hide()},setContent:function(t){this.$tip.html(t)},setPosition:function(t){this.$tip.css("left",t.left+"px"),this.$tip.css("top",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(e,i){this.$container=e,this.setSettings(Craft.charts.BaseChart.defaults),this.setSettings(i);var s={formats:window.d3Formats,formatLocaleDefinition:window.d3FormatLocaleDefinition,timeFormatLocaleDefinition:window.d3TimeFormatLocaleDefinition};this.setSettings(s),d3.select(window).on("resize",t.proxy((function(){this.resize()}),this))},setSettings:function(e,i){var s=void 0===this.settings?{}:this.settings;this.settings=t.extend(!0,{},s,i,e)},draw:function(e,i){this.setSettings(i),this.dataTable=e,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 s=this.chartBaseClass;this.settings.chartClass&&(s+=" "+this.settings.chartClass),this.$chart=t('<div class="'+s+'" />').appendTo(this.$container)},resize:function(){this.draw(this.dataTable,this.settings)},onAfterDrawTicks:function(){t(".tick",this.$chart).each((function(e,i){var s=t("text",i);s.clone().appendTo(i),s.attr("stroke","#ffffff"),s.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("+s.translateX+","+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, "+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("+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, "+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("+(this.width-0)+", 0)").call(i)):(i=d3.axisRight(s).ticks(0),this.drawingArea.append("g").attr("class","y axis").attr("transform","translate(0, 0)").call(i))}},drawChart:function(){var e=this.getX(!0),i=this.getY();if(this.settings.xAxis.gridlines){var s=d3.axisBottom(e);this.drawingArea.append("g").attr("class","x grid-line").attr("transform","translate(0,"+this.height+")").call(s.tickSize(-this.height,0,0).tickFormat(""))}if(this.settings.yAxis.gridlines){var a=d3.axisLeft(i);this.drawingArea.append("g").attr("class","y grid-line").attr("transform","translate(0 , 0)").call(a.tickSize(-this.width,0).tickFormat("").tickValues(this.getYTickValues()).ticks(2))}var n=d3.line().x((function(t){return e(t[0])})).y((function(t){return i(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",n);var r=d3.area().x((function(t){return e(t[0])})).y0(this.height).y1((function(t){return i(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",r),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",t.proxy((function(t,e){return"plot plot-"+e}),this)).attr("r",4).attr("cx",t.proxy((function(t){return e(t[0])}),this)).attr("cy",t.proxy((function(t){return i(t[1])}),this))},drawTipTriggers:function(){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",t.proxy((function(t){return a(t[0])-s/2}),this)).on("mouseover",t.proxy((function(e,i){this.drawingArea.select(".plot-"+i).attr("r",5);var s=t("<div />"),r=t('<div class="x-value" />').appendTo(s),o=t('<div class="y-value" />').appendTo(s);r.html(this.getXFormatter()(e[0])),o.html(this.getYFormatter()(e[1]));var l=s.get(0);this.tip.setContent(l);var h,d=this.getChartMargin(),c=n(e[1])+24;"rtl"!==this.orientation?(h=a(e[0])+d.left+24,this.$chart.offset().left+h+this.tip.$tip.width()>this.$chart.offset().left+this.$chart.width()-24&&(h=a(e[0])-(this.tip.$tip.width()+24))):h=a(e[0])-(this.tip.$tip.width()+d.left+24);h<0&&(h=a(e[0])+d.left+24);var u={top:c,left:h};this.tip.setPosition(u),this.tip.show()}),this)).on("mouseout",t.proxy((function(t,e){this.drawingArea.select(".plot-"+e).attr("r",4),this.tip.hide()}),this))}},getChartMargin:function(){var e=this.settings.margin,i=this.getYTickValues(),s=0;return t.each(i,t.proxy((function(t,e){var i=8*this.getYFormatter()(e).length;i>s&&(s=i)}),this)),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!==t.noop?this.settings.xAxis.formatter(this):Craft.charts.utils.getTimeFormatter(this.timeFormatLocale,this.settings)},getYFormatter:function(){return this.settings.yAxis.formatter!==t.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:t.noop},yAxis:{gridlines:!0,showAxis:!1,formatter:t.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"+i.hours),i.minutes<10&&(i.minutes="0"+i.minutes),i.seconds<10&&(i.seconds="0"+i.seconds),i.hours+":"+i.minutes+":"+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(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)}}},Craft.ColorInput=Garnish.Base.extend({$container:null,$input:null,$colorContainer:null,$colorPreview:null,$colorInput:null,init:function(e){this.$container=t(e),this.$input=this.$container.children(".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 e=document.createElement("input");e.setAttribute("type","color"),"color"===e.type&&(this.$colorContainer.removeClass("static"),this.$colorInput=t(e).addClass("color-preview-input").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.length&&"#"!==t?("#"!==t[0]&&(t="#"+t,this.$input.val(t)),this.$colorPreview.css("background-color",t),this.$colorInput&&this.$colorInput.val(t)):this.$colorPreview.css("background-color","")}},{_browserSupportsColorInputs:null,doesBrowserSupportColorInputs:function(){return Craft.ColorInput._browserSupportsColorInputs,Craft.ColorInput._browserSupportsColorInputs}}),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(e,i){this.base(),this.setSettings(i,{resizable:!0}),this.elementIndex=e,this.$elementIndexSourcesContainer=this.elementIndex.$sidebar.children("nav").children("ul");var s=t('<form class="modal customize-sources-modal"/>').appendTo(Garnish.$bod);this.$sidebar=t('<div class="cs-sidebar block-types"/>').appendTo(s),this.$sourcesContainer=t('<div class="sources">').appendTo(this.$sidebar),this.$sourceSettingsContainer=t('<div class="source-settings">').appendTo(s),this.$footer=t('<div class="footer"/>').appendTo(s),this.$footerBtnContainer=t('<div class="buttons right"/>').appendTo(this.$footer),this.$cancelBtn=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$footerBtnContainer),this.$saveBtn=t("<button/>",{type:"button",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(this.$footerBtnContainer),this.$saveSpinner=t('<div class="spinner hidden"/>').appendTo(this.$footerBtnContainer),this.$newHeadingBtn=t("<button/>",{type:"button",class:"btn submit add icon",text:Craft.t("app","New heading")}).appendTo(t('<div class="buttons left secondary-buttons"/>').appendTo(this.$footer)),this.$loadingSpinner=t('<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,t.proxy((function(t,e){this.$loadingSpinner.remove(),"success"===e&&(this.$saveBtn.removeClass("disabled"),this.buildModal(t))}),this)),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(e){this.availableTableAttributes=e.availableTableAttributes,this.sourceSort=new Garnish.DragSort({handle:".move",axis:"y",onSortChange:t.proxy((function(){this.updateSourcesOnSave=!0}),this)}),this.sources=[];for(var i=0;i<e.sources.length;i++){var s=this.addSource(e.sources[i]);this.sources.push(s)}this.selectedSource||void 0===this.sources[0]||this.sources[0].select()},addSource:function(e){var i,s=t('<div class="customize-sources-item"/>').appendTo(this.$sourcesContainer),a=t('<div class="label"/>').appendTo(s),n=t('<input type="hidden"/>').appendTo(s);return t('<a class="move icon" title="'+Craft.t("app","Reorder")+'" role="button"></a>').appendTo(s),void 0!==e.heading?(s.addClass("heading"),n.attr("name","sourceOrder[][heading]"),(i=new Craft.CustomizeSourcesModal.Heading(this,s,a,n,e)).updateItemLabel(e.heading)):(n.attr("name","sourceOrder[][key]").val(e.key),(i=new Craft.CustomizeSourcesModal.Source(this,s,a,n,e)).updateItemLabel(e.label),(this.elementIndex.sourceKey+"/").substr(0,e.key.length+1)===e.key+"/"&&i.select()),this.sourceSort.addItems(s),i},handleNewHeadingBtnClick:function(){var t=this.addSource({heading:""});Garnish.scrollContainerToElement(this.$sidebar,t.$item),t.select(),this.updateSourcesOnSave=!0},save:function(e){if(e&&e.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,t.proxy((function(t,e){if(this.$saveSpinner.addClass("hidden"),"success"===e&&t.success){if(this.updateSourcesOnSave&&this.$elementIndexSourcesContainer.length){for(var i,s=null,a=0;a<this.sourceSort.$items.length;a++){var n=this.sourceSort.$items.eq(a).data("source"),r=n.getIndexSource();r&&(n.isHeading()?i=r:(i&&(this.appendSource(i,s),s=i,i=null),this.appendSource(r,s),s=r))}if(s){var o=s.nextAll();this.elementIndex.sourceSelect.removeItems(o),o.remove()}}this.selectedSource&&this.selectedSource.sourceData.key&&(this.elementIndex.selectSourceByKey(this.selectedSource.sourceData.key),this.elementIndex.updateElements()),Craft.cp.displayNotice(Craft.t("app","Source settings saved")),this.hide()}else{var l="success"===e&&t.error?t.error:Craft.t("app","A server error occurred.");Craft.cp.displayError(l)}}),this))}},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 t("<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(){let e=t("<div/>").append(Craft.ui.createTextField({label:Craft.t("app","Header Column Heading"),id:"defaultHeaderColHeading"+Math.floor(1e5*Math.random()),name:`sources[${this.sourceData.key}][headerColHeading]`,value:this.sourceData.headerColHeading,placeholder:this.sourceData.defaultHeaderColHeading}));return this.sourceData.tableAttributes.length&&e.append(this.createTableColumnsField()),e},createTableColumnsField:function(){let[e,i]=this.sourceData.tableAttributes[0],s=this.createTableColumnOption(e,i,!0,!0),a=t("<div/>"),n=[e];t('<input type="hidden" name="sources['+this.sourceData.key+'][tableAttributes][]" value=""/>').appendTo(a);for(let t=1;t<this.sourceData.tableAttributes.length;t++){let[e,i]=this.sourceData.tableAttributes[t];a.append(this.createTableColumnOption(e,i,!1,!0)),n.push(e)}let r=this.modal.availableTableAttributes.slice(0);r.push(...this.sourceData.availableTableAttributes);for(let t=0;t<r.length;t++){let[e,i]=r[t];Craft.inArray(e,n)||a.append(this.createTableColumnOption(e,i,!1,!1))}return new Garnish.DragSort(a.children(),{handle:".move",axis:"y"}),Craft.ui.createField(t([s[0],a[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(e,i,s,a){var n=t('<div class="customize-sources-table-column"/>').append('<div class="icon move"/>').append(Craft.ui.createCheckbox({label:Craft.escapeHtml(i),name:"sources["+this.sourceData.key+"][tableAttributes][]",value:e,checked:a,disabled:s}));return s&&n.children(".move").addClass("disabled"),n},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(){let e=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(e),this.$labelInput=this.$labelField.find(".text"),e.append("<hr/>"),this.$deleteBtn=t('<a class="error delete"/>').text(Craft.t("app","Delete heading")).appendTo(e),this.addListener(this.$labelInput,"input","handleLabelInputChange"),this.addListener(this.$deleteBtn,"click","deleteHeading"),e},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(t.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 e=this.$labelInput?this.$labelInput.val():this.sourceData.heading;return t('<li class="heading"/>').append(t("<span/>").text(e))}}),Craft.DataTableSorter=Garnish.DragSort.extend({$table:null,init:function(e,i){this.$table=t(e);var s=this.$table.children("tbody").children(":not(.filler)");(i=t.extend({},Craft.DataTableSorter.defaults,i)).container=this.$table.children("tbody"),i.helper=t.proxy(this,"getHelper"),i.caboose="<tr/>",i.axis=Garnish.Y_AXIS,i.magnetStrength=4,i.helperLagBase=1.5,this.base(s,i)},getHelper:function(e){var i=t('<div class="'+this.settings.helperClass+'"/>').appendTo(Garnish.$bod),s=t("<table/>").appendTo(i),a=t("<tbody/>").appendTo(s);e.appendTo(a),s.width(this.$table.width()),s.prop("className",this.$table.prop("className"));for(var n=this.$table.find("tr:first").children(),r=e.children(),o=0;o<r.length;o++)t(r[o]).width(t(n[o]).width());return i}},{defaults:{handle:".move",helperClass:"datatablesorthelper"}}),Craft.DeleteUserModal=Garnish.Modal.extend({id:null,userId:null,$deleteActionRadios:null,$deleteSpinner:null,userSelect:null,_deleting:!1,init:function(e,i){this.id=Math.floor(1e9*Math.random()),this.userId=e,i=t.extend(Craft.DeleteUserModal.defaults,i);let s=t('<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+'"/>')+(i.redirect?'<input type="hidden" name="redirect" value="'+i.redirect+'"/>':"")+"</form>").appendTo(Garnish.$bod),a=t('<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(s),n=t('<div class="buttons right"/>').appendTo(a),r=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(n);if(i.contentSummary.length)for(let e=0;e<i.contentSummary.length;e++)a.find("ul").append(t("<li/>",{text:i.contentSummary[e]}));else a.find("ul").remove();var o;if(this.$deleteActionRadios=a.find("input[type=radio]"),this.$deleteSubmitBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:this._submitBtnLabel(!1)}).appendTo(n),this.$deleteSpinner=t('<div class="spinner hidden"/>').appendTo(n),Garnish.isArray(this.userId)){o=["and"];for(let t=0;t<this.userId.length;t++)o.push("not "+this.userId[t])}else o="not "+this.userId;this.userSelect=new Craft.BaseElementSelectInput({id:"transferselect"+this.id,name:"transferContentTo",elementType:"craft\\elements\\User",criteria:{id:o},limit:1,modalSettings:{closeOtherModals:!1},onSelectElements:t.proxy((function(){this.updateSizeAndPosition(),this.$deleteActionRadios.first().prop("checked")?this.validateDeleteInputs():this.$deleteActionRadios.first().trigger("click")}),this),onRemoveElements:t.proxy(this,"validateDeleteInputs"),selectable:!1,editable:!1}),this.addListener(r,"click","hide"),this.addListener(this.$deleteActionRadios,"change","validateDeleteInputs"),this.addListener(s,"submit","handleSubmit"),this.base(s,i)},_submitBtnLabel:function(t){let 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:t.noop,redirect:null}}),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,saveXhr:null,queue:null,submittingForm:!1,duplicatedElements:null,errors:null,openingPreview:!1,preview:null,previewToken:null,createdDraftInPreview:!1,init:function(e){if(this.setSettings(e,Craft.DraftEditor.defaults),this.queue=[],this.duplicatedElements={},this.enableAutosave=Craft.autosaveDrafts,this.siteIds=Object.keys(this.settings.siteStatuses).map(t=>parseInt(t)),this.$revisionBtn=t("#context-btn"),this.$revisionLabel=t("#revision-label"),this.$spinner=t("#revision-spinner"),this.$expandSiteStatusesBtn=t("#expand-status-btn"),this.$statusIcon=t("#revision-status"),this.settings.canEditMultipleSites&&this.addListener(this.$expandSiteStatusesBtn,"click","expandSiteStatuses"),this.settings.previewTargets.length){this.settings.enablePreview&&this.addListener(t("#preview-btn"),"click","openPreview");const e=t("#share-btn");1===this.settings.previewTargets.length?this.addListener(e,"click",(function(){this.openShareLink(this.settings.previewTargets[0].url)})):this.createShareMenu(e)}this.settings.revisionId||(Craft.cp.$primaryForm.data("serializer",function(){return this.serializeForm(!0)}.bind(this)),this.addListener(Craft.cp.$primaryForm,"submit","handleFormSubmit"),this.settings.draftId?this.initForDraft():(this.addListener(t("#save-draft-btn"),"click",function(t){t.preventDefault(),this.createDraft(),this.removeListener(Craft.cp.$primaryForm,"submit.saveShortcut")}.bind(this)),this.settings.canUpdateSource||this.addListener(Craft.cp.$primaryForm,"submit.saveShortcut",function(t){t.saveShortcut&&(t.preventDefault(),this.createDraft(),this.removeListener(Craft.cp.$primaryForm,"submit.saveShortcut"))}.bind(this))))},listenForChanges:function(){this.listeningForChanges||this.pauseLevel>0||!this.enableAutosave||(this.listeningForChanges=!0,this.addListener(Garnish.$bod,"keypress,keyup,change,focus,blur,click,mousedown,mouseup",(function(e){t(e.target).is(this.statusIcons())||(clearTimeout(this.timeout),["keypress","keyup","change"].includes(e.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())},initForDraft:function(){this.createEditMetaBtn(),this.addListener(this.$statusIcon,"click",function(){this.showStatusHud(this.$statusIcon)}.bind(this)),this.addListener(t("#merge-changes-btn"),"click",this.mergeChanges),Craft.autosaveDrafts&&this.listenForChanges(),this.settings.canUpdateSource&&Garnish.shortcutManager.registerShortcut({keyCode:Garnish.S_KEY,ctrl:!0,alt:!0},()=>{Craft.submitForm(Craft.cp.$primaryForm,{action:this.settings.publishDraftAction,redirect:this.settings.hashedCpEditUrl})},0)},mergeChanges:function(){this.checkForm(),this.saving?this.queue.push(this.mergeChanges.bind(this)):(this.saving=!0,t("#merge-changes-spinner").removeClass("hidden"),Craft.postActionRequest("drafts/merge-source-changes",{elementType:this.settings.elementType,draftId:this.settings.draftId,siteId:this.settings.siteId},(function(e,i){"success"===i?window.location.reload():t("#merge-changes-spinner").addClass("hidden")})))},expandSiteStatuses:function(){this.removeListener(this.$expandSiteStatusesBtn,"click"),this.$expandSiteStatusesBtn.velocity({opacity:0},"fast",function(){this.$expandSiteStatusesBtn.remove()}.bind(this));const e=t(`#enabledForSite-${this.settings.siteId}-field`);if(this.$siteStatusPane=e.parent(),this.settings.revisionId)return void this._getOtherSupportedSites().forEach(t=>this._createSiteStatusField(t));e.addClass("nested");const 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);const s=this.settings.enabled&&!Craft.inArray(!1,this.settings.siteStatuses)?"1":this.settings.enabledForSite?"-":"",a=encodeURIComponent(`enabledForSite[${this.settings.siteId}]`)+"="+(this.settings.enabledForSite?"1":"");this.$siteLightswitches=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this)),this._getOtherSupportedSites().forEach(t=>this._createSiteStatusField(t));let n="enabled="+s;for(let t=0;t<this.$siteLightswitches.length;t++){const e=this.$siteLightswitches.eq(t).data("lightswitch").$input;n+="&"+encodeURIComponent(e.attr("name"))+"="+e.val()}Craft.cp.$primaryForm.data("initialSerializedValue",Craft.cp.$primaryForm.data("initialSerializedValue").replace(a,n)),this.settings.addlSiteIds&&this.settings.addlSiteIds.length&&this._createAddlSiteField(),this.$globalLightswitch.on("change",this._updateSiteStatuses.bind(this)),this._updateGlobalStatus()},_getOtherSupportedSites:function(){return Craft.sites.filter(t=>t.id!=this.settings.siteId&&this.siteIds.includes(t.id))},_showField:function(t){const e=t.height();t.css("overflow","hidden").height(0).velocity({height:e},"fast",()=>{t.css({overflow:"",height:""})})},_removeField:function(t){t.height();t.css("overflow","hidden").velocity({height:0},"fast",()=>{t.remove()})},_updateGlobalStatus:function(){let e=!0,i=!0;this.$siteLightswitches.each((function(){if(t(this).data("lightswitch").on?i=!1:e=!1,!e&&!i)return!1})),e?this.$globalLightswitch.data("lightswitch").turnOn(!0):i?this.$globalLightswitch.data("lightswitch").turnOff(!0):this.$globalLightswitch.data("lightswitch").turnIndeterminate(!0)},_updateSiteStatuses:function(){const e=this.$globalLightswitch.data("lightswitch").on;this.$siteLightswitches.each((function(){e?t(this).data("lightswitch").turnOn(!0):t(this).data("lightswitch").turnOff(!0)}))},_createSiteStatusField:function(t){const e=Craft.ui.createLightswitchField({id:"enabledForSite-"+t.id,label:Craft.t("app","Enabled for {site}",{site:t.name}),name:`enabledForSite[${t.id}]`,on:!this.settings.siteStatuses.hasOwnProperty(t.id)||this.settings.siteStatuses[t.id],disabled:!!this.settings.revisionId});if(this.$addlSiteField?e.insertBefore(this.$addlSiteField):e.appendTo(this.$siteStatusPane),!this.settings.revisionId){e.addClass("nested");const t=e.find(".lightswitch").on("change",this._updateGlobalStatus.bind(this));this.$siteLightswitches=this.$siteLightswitches.add(t)}return this._showField(e),e},_createAddlSiteField:function(){const t=Craft.sites.filter(t=>!this.siteIds.includes(t.id)&&this.settings.addlSiteIds.includes(t.id));if(!t.length)return;const e=Craft.ui.createSelect({options:[{label:Craft.t("app","Add a site…")},...t.map(t=>({label:t.name,value:t.id}))]}).addClass("fullwidth");this.$addlSiteField=Craft.ui.createField(e,{}).addClass("nested add").appendTo(this.$siteStatusPane);const i=e.find("select");i.on("change",()=>{const t=parseInt(i.val()),e=Craft.sites.find(e=>e.id===t);e&&(this._createSiteStatusField(e),i.val("").find(`option[value="${t}"]`).remove(),null===this.newSiteIds&&(this.newSiteIds=[]),this.siteIds.push(t),this.newSiteIds.push(t),1===i.find("option").length&&this._removeField(this.$addlSiteField))}),this._showField(this.$addlSiteField)},showStatusHud:function(t){let e;null===this.errors?e="<p>"+Craft.t("app","The draft has been saved.")+"</p>":(e='<p class="error">'+Craft.t("app","The draft could not be saved.")+"</p>",this.errors.length&&(e+='<ul class="errors">'+this.errors.map(t=>`<li>${Craft.escapeHtml(t)}</li>`).join("")+"</ul>"));const i=new Garnish.HUD(t,e,{onHide:function(){i.destroy()}})},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},createEditMetaBtn:function(){this.$editMetaBtn=t("<button/>",{type:"button",class:"btn edit icon",title:Craft.t("app","Edit draft settings")}).appendTo(t("#context-btngroup")),this.addListener(this.$editMetaBtn,"click","showMetaHud")},createShareMenu:function(e){e.addClass("menubtn");const i=t("<div/>",{class:"menu"}).insertAfter(e),s=t("<ul/>").appendTo(i);this.settings.previewTargets.forEach(e=>{const i=t("<li/>").appendTo(s),a=t("<a/>",{text:e.label}).appendTo(i);this.addListener(a,"click",()=>{this.openShareLink(e.url)})})},getPreviewToken:function(){return new Promise(function(t,e){this.previewToken?t(this.previewToken):Craft.postActionRequest("preview/create-token",{elementType:this.settings.elementType,sourceId:this.settings.sourceId,siteId:this.settings.siteId,draftId:this.settings.draftId,revisionId:this.settings.revisionId},function(i,s){"success"===s?(this.previewToken=i.token,t(this.previewToken)):e()}.bind(this))}.bind(this))},getTokenizedPreviewUrl:function(t,e){return new Promise(function(i,s){const a={};!e&&this.settings.isLive||(a[e||"x-craft-preview"]=Craft.randomString(10)),this.settings.siteToken&&(a[Craft.siteToken]=this.settings.siteToken),this.settings.isLive?i(Craft.getUrl(t,a)):this.getPreviewToken().then((function(e){a[Craft.tokenParam]=e,i(Craft.getUrl(t,a))})).catch(s)}.bind(this))},openShareLink:function(t){this.getTokenizedPreviewUrl(t).then((function(t){window.open(t)}))},getPreview:function(){return this.preview||(this.preview=new Craft.Preview(this),this.preview.on("open",function(){this.settings.draftId&&Craft.autosaveDrafts||(Craft.autosaveDrafts||(this.enableAutosave=!0),this.listenForChanges())}.bind(this)),this.preview.on("close",function(){if(!this.settings.draftId||!Craft.autosaveDrafts){if(!Craft.autosaveDrafts){this.enableAutosave=!1;const t=this.statusIcons();t.hasClass("checkmark-icon")&&t.addClass("hidden")}this.stopListeningForChanges()}this.createdDraftInPreview&&setTimeout(()=>{this.createDraftNoticeHud(),this.createdDraftInPreview=!1},750)}.bind(this))),this.preview},createDraftNoticeHud:function(){const e=t("<button/>",{class:"btn",type:"button",text:Craft.t("app","Keep it")}),i=t("<button/>",{class:"btn caution",type:"button",text:Craft.t("app","Delete it")}),s=new Garnish.HUD(t("#context-btngroup"),t("<div/>",{class:"readable centeralign"}).append(t("<p/>",{text:Craft.t("app","You’re now editing a draft.")})).append(t("<div/>",{class:"flex flex-nowrap"}).append(e).append(i)),{hideOnEsc:!1,hideOnShadeClick:!1});e.on("click",()=>{s.hide(),s.destroy()}),i.on("click",()=>{confirm(Craft.t("app","Are you sure you want to delete this draft?"))&&Craft.submitForm(Craft.cp.$primaryForm,{action:this.settings.deleteDraftAction,redirect:this.settings.hashedCpEditUrl})})},openPreview:function(){return new Promise(function(t,e){this.openingPreview=!0,this.ensureIsDraftOrRevision(!0).then(function(){this.getPreview().open(),this.openingPreview=!1,t()}.bind(this)).catch(e)}.bind(this))},ensureIsDraftOrRevision:function(t){return new Promise(function(e,i){if(this.settings.draftId||this.settings.revisionId)e();else{if(t&&this.serializeForm(!0)===Craft.cp.$primaryForm.data("initialSerializedValue"))return void e();this.createDraft().then(e).catch(i)}}.bind(this))},serializeForm:function(t){let e=Craft.cp.$primaryForm.serialize();return this.isPreviewActive()&&(e=e.replace("__PREVIEW_FIELDS__=1",this.preview.$editor.serialize())),t&&!this.settings.isUnpublishedDraft&&(e=e.replace(/&action=[^&]*/,""),e=e.replace(/&redirect=[^&]*/,"")),e},checkForm:function(t){if(this.settings.revisionId||!this.settings.draftId&&!this.isPreviewActive()||this.pauseLevel>0)return;clearTimeout(this.timeout),this.timeout=null;const e=this.serializeForm(!0);(t||e!==(this.lastSerializedValue||Craft.cp.$primaryForm.data("initialSerializedValue")))&&this.saveDraft(e)},isPreviewActive:function(){return this.preview&&this.preview.isActive},createDraft:function(){return new Promise(function(t,e){this.saveDraft(this.serializeForm(!0)).then(t).catch(e)}.bind(this))},saveDraft:function(e){return new Promise(function(i,s){if(this.submittingForm)return void s();if(this.saving)return void this.queue.push(function(){this.checkForm()}.bind(this));this.lastSerializedValue=e,this.saving=!0;const a=this.spinners().removeClass("hidden"),n=this.statusIcons().velocity("stop").css("opacity","").removeClass("invisible checkmark-icon alert-icon fade-out").addClass("hidden");this.$saveMetaBtn&&this.$saveMetaBtn.addClass("active"),this.errors=null;const r=Craft.getActionUrl(this.settings.saveDraftAction);this.saveXhr=Craft.postActionRequest(r,this.prepareData(e),function(r,o){if(a.addClass("hidden"),this.$saveMetaBtn&&this.$saveMetaBtn.removeClass("active"),this.saving=!1,"abort"===o)return;if("success"!==o||r.errors)return this.errors=(r?r.errors:null)||[],n.velocity("stop").css("opacity","").removeClass("hidden checkmark-icon").addClass("alert-icon").attr("title",Craft.t("app","The draft could not be saved.")),void s();r.title&&t("#header h1").text(r.title),r.docTitle&&(document.title=r.docTitle),this.$revisionLabel.text(r.draftName),this.settings.draftName=r.draftName;let l=this.$revisionBtn.data("menubtn")?this.$revisionBtn.data("menubtn").menu:null;this.newSiteIds&&(l||(this.$revisionBtn.removeClass("disabled").addClass("menubtn"),new Garnish.MenuBtn(this.$revisionBtn),l=this.$revisionBtn.data("menubtn").menu,l.$container.removeClass("hidden")),this.newSiteIds.forEach(t=>{const e=l.$options.filter(`[data-site-id=${t}]`);e.find(".status").removeClass("disabled").addClass("enabled");e.parent().removeClass("hidden").closest(".site-group").removeClass("hidden")}),l.$container.find(".revision-hr").removeClass("hidden"),this.newSiteIds=null);const h=!this.settings.draftId;if(h){let e;const i=document.location.href.search("#");e=-1!==i?document.location.href.substr(0,i):document.location.href,e+=(e.match(/\?/)?"&":"?")+"draftId="+r.draftId,-1!==i&&(e+=document.location.href.substr(i)),history.replaceState({},"",e),t("#action").remove(),t("<input/>",{id:"action",type:"hidden",name:"action",value:this.settings.saveDraftAction}).appendTo(Craft.cp.$primaryForm),t("#save-draft-btn-container").remove(),t("#save-btn-container").remove();const s=t("#action-buttons");this.settings.canUpdateSource&&t("<button/>",{type:"button",class:"btn secondary formsubmit",text:Craft.t("app","Publish draft"),title:Craft.shortcutText("S",!1,!0),data:{action:this.settings.publishDraftAction,redirect:this.settings.hashedCpEditUrl}}).appendTo(s).formsubmit();const a=t("<div/>",{id:"save-btn-container",class:"btngroup submit"}).appendTo(s);if(t("<button/>",{type:"submit",class:"btn submit",text:Craft.t("app","Save draft")}).appendTo(a),this.settings.saveDraftAction||this.settings.deleteDraftAction){t("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(a);const e=t("<div/>",{class:"menu",attr:{"data-align":"right"}}).appendTo(a);if(this.settings.saveDraftAction){const i=t("<ul/>").appendTo(e).append(t("<li/>").append(t("<a/>",{class:"formsubmit",data:{action:this.settings.saveDraftAction},text:Craft.t("app","Save and continue editing")}).prepend(t("<span/>",{class:"shortcut",text:Craft.shortcutText("S")}))));this.settings.canUpdateSource&&this.settings.hashedAddAnotherRedirectUrl&&i.append(t("<li/>").append(t("<a/>",{class:"formsubmit",data:{action:this.settings.publishDraftAction,redirect:this.settings.hashedAddAnotherRedirectUrl},text:Craft.t("app","Publish and add another")}))),this.settings.deleteDraftAction&&t("<hr/>").appendTo(e)}this.settings.deleteDraftAction&&t("<ul/>").appendTo(e).append(t("<li/>").append(t("<a/>",{class:"formsubmit error",data:{action:this.settings.deleteDraftAction,redirect:this.settings.hashedCpEditUrl,confirm:Craft.t("app","Are you sure you want to delete this draft?")},text:Craft.t("app","Delete draft")})))}if(Craft.initUiElements(a),this.settings.draftId=r.draftId,this.settings.isLive=!1,this.previewToken=null,this.initForDraft(),l){l.$options.filter(":not(.site-option)").removeClass("sel");let e=l.$container.find(".revision-group-drafts");if(!e.length){const i=t("<h6/>",{text:Craft.t("app","Drafts")}).insertAfter(l.$container.find(".revision-group-current"));e=t("<ul/>",{class:"padded revision-group-drafts"}).insertAfter(i)}const i=t("<li/>").prependTo(e),s=t("<a/>",{class:"sel",html:'<span class="draft-name"></span> <span class="draft-meta light"></span>'}).appendTo(i);l.addOptions(s),l.selectOption(s);const a=l.$options.filter(".site-option[href]");for(let t=0;t<a.length;t++){const e=a.eq(t);e.attr("href",Craft.getUrl(e.attr("href"),{draftId:r.draftId}))}}(this.openingPreview||this.preview&&this.preview.isActive)&&(this.createdDraftInPreview=!0)}l&&(l.$options.filter(".sel").find(".draft-name").text(r.draftName),l.$options.filter(".sel").find(".draft-meta").text("– "+(r.creator?Craft.t("app","saved {timestamp} by {creator}",{timestamp:r.timestamp,creator:r.creator}):Craft.t("app","updated {timestamp}",{timestamp:r.timestamp})))),r.previewTargets&&JSON.stringify(r.previewTargets)!==JSON.stringify(this.settings.previewTargets)&&this.updatePreviewTargets(r.previewTargets),this.afterUpdate(e),h&&this.trigger("createDraft"),this.$nameTextInput&&this.checkMetaValues();for(const t in r.duplicatedElements)t!=this.settings.sourceId&&r.duplicatedElements.hasOwnProperty(t)&&(this.duplicatedElements[t]=r.duplicatedElements[t]);i()}.bind(this))}.bind(this))},prepareData:function(t){t=this.swapDuplicatedElementIds(t),this.settings.draftId&&(t+="&draftId="+this.settings.draftId),null!==this.settings.draftName&&(t+="&draftName="+this.settings.draftName);const e=this.swapDuplicatedElementIds(Craft.cp.$primaryForm.data("initialSerializedValue"));return Craft.findDeltaData(e,t,this.getDeltaNames())},swapDuplicatedElementIds:function(t){const e=Object.keys(this.duplicatedElements).join("|");if(""===e)return t;const i=encodeURIComponent("["),s=encodeURIComponent("]");for(;t!==(t=t.replace(new RegExp(`(&fields${i}[^=]+${s}${i})(${e})(${s})`,"g"),(t,e,i,s)=>e+this.duplicatedElements[i]+s).replace(new RegExp(`(&fields${i}[^=]+=)(${e})\\b`,"g"),(t,e,i)=>e+this.duplicatedElements[i])););return t},getDeltaNames:function(){const t=Craft.deltaNames.slice(0);for(let e=0;e<t.length;e++)for(const i in this.duplicatedElements)this.duplicatedElements.hasOwnProperty(i)&&(t[e]=t[e].replace("]["+i+"]","]["+this.duplicatedElements[i]+"]"));return t},updatePreviewTargets:function(t){t.forEach(t=>{const e=this.settings.previewTargets.find(e=>e.label===t.label);e&&(e.url=t.url)})},afterUpdate:function(t){Craft.cp.$primaryForm.data("initialSerializedValue",t),Craft.initialDeltaValues={};const e=this.statusIcons().velocity("stop").css("opacity","").removeClass("hidden").addClass("checkmark-icon").attr("title",Craft.t("app","The draft has been saved."));this.enableAutosave||e.velocity("stop").velocity({opacity:0},{delay:2e3,complete:()=>{e.addClass("hidden")}}),this.trigger("update"),this.nextInQueue()},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(){const e=t("<div/>"),i=t('<div class="field"><div class="heading"><label for="draft-name">'+Craft.t("app","Draft Name")+"</label></div></div>").appendTo(e),s=t('<div class="input"/>').appendTo(i);this.$nameTextInput=t('<input type="text" class="text fullwidth" id="draft-name"/>').appendTo(s).val(this.settings.draftName);const a=t('<div class="hud-footer flex flex-center"/>').appendTo(e);t('<div class="flex-grow"></div>').appendTo(a),this.$saveMetaBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Save")}).appendTo(a),this.metaHud=new Garnish.HUD(this.$editMetaBtn,e,{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)return;if(this.settings.draftId&&(void 0===t.autosave||t.autosave)&&(t.saveShortcut||t.customTrigger&&t.customTrigger.data("action")===this.settings.saveDraftAction))return void this.checkForm(!0);Craft.cp.$confirmUnloadForms=Craft.cp.$confirmUnloadForms.not(Craft.cp.$primaryForm),this.saving&&this.saveXhr.abort();const e=this.prepareData(this.serializeForm(!1)),i=Craft.createForm(e);i.appendTo(Garnish.$bod),i.submit(),this.submittingForm=!0}},{defaults:{elementType:null,sourceId:null,siteId:null,isUnpublishedDraft:!1,enabled:!1,enabledForSite:!1,isLive:!1,siteStatuses:null,addlSiteIds:[],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:[],siteToken:null}}),Craft.DynamicGenerator=Craft.BaseInputGenerator.extend({callback:t.noop,init:function(t,e,i){this.callback=i,this.base(t,e)},generateTargetValue:function(t){return this.callback(t)}}),Craft.EditableTable=Garnish.Base.extend({initialized:!1,id:null,baseName:null,columns:null,sorter:null,biggestId:-1,$table:null,$tbody:null,$addRowBtn:null,rowCount:0,hasMaxRows:!1,hasMinRows:!1,radioCheckboxes:null,init:function(e,i,s,a){if(this.id=e,this.baseName=i,this.columns=s,this.setSettings(a,Craft.EditableTable.defaults),this.radioCheckboxes={},this.$table=t("#"+e),this.$tbody=this.$table.children("tbody"),this.rowCount=this.$tbody.find("tr").length,this.$table.data("editable-table")&&(Garnish.log("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}),this.isVisible()?this.initialize():setTimeout(t.proxy(this,"initializeIfVisible"),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]);return 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.css("opacity","0.2"),this.$addRowBtn.css("pointer-events","none"))},canDeleteRow:function(){return this.rowCount>this.settings.minRows},deleteRow:function(t){this.canDeleteRow()&&(this.sorter.removeItems(t.$tr),t.$tr.remove(),this.rowCount--,this.updateAddRowButton(),0===this.rowCount&&this.$table.addClass("hidden"),this.settings.onDeleteRow(t.$tr),t.destroy())},canAddRow:function(){return!this.settings.staticRows&&(!this.settings.maxRows||this.rowCount<this.settings.maxRows)},addRow:function(e,i){if(this.canAddRow()){var s=this.settings.rowIdPrefix+(this.biggestId+1),a=this.createRow(s,this.columns,this.baseName,t.extend({},this.settings.defaultValues));i?a.prependTo(this.$tbody):a.appendTo(this.$tbody);var n=this.createRowObj(a);return this.sorter.addItems(a),!1!==e&&a.find("input:visible,textarea:visible,select:visible").first().trigger("focus"),this.rowCount++,this.updateAddRowButton(),this.$table.removeClass("hidden"),this.settings.onAddRow(a),n}},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(e,i,s){var a,n=e.prev("tr");if((a=n.length?n.data("editable-table-row"):this.addRow(!1,!0))&&a.$tds[i])if(t(a.$tds[i]).hasClass("disabled"))n&&this.focusOnPrevRow(n,i,s);else{var r=t("textarea,input.text",a.$tds[i]);r.length&&(t(s).trigger("blur"),r.trigger("focus"))}},focusOnNextRow:function(e,i,s){var a,n=e.next("tr");if((a=n.length?n.data("editable-table-row"):this.addRow(!1))&&a.$tds[i])if(t(a.$tds[i]).hasClass("disabled"))n&&this.focusOnNextRow(n,i,s);else{var r=t("textarea,input.text",a.$tds[i]);r.length&&(t(s).trigger("blur"),r.trigger("focus"))}},importData:function(t,e,i){let s=t.split(/\r?\n|\r/);for(let t=0;t<s.length;t++){let a=s[t].split("\t");for(let t=0;t<a.length;t++){let s=a[t];e.$tds.eq(i+t).find("textarea,input[type!=hidden]").val(s).trigger("input")}let n=e.$tr.next("tr");e=n.length?n.data("editable-table-row"):this.addRow(!1)}}},{textualColTypes:["color","date","email","multiline","number","singleline","template","time","url"],defaults:{rowIdPrefix:"",defaultValues:{},staticRows:!1,minRows:null,maxRows:null,onAddRow:t.noop,onDeleteRow:t.noop},createRow:function(e,i,s,a){var n=t("<tr/>",{"data-id":e});for(var r in i)if(i.hasOwnProperty(r)){var o,l=i[r],h=void 0!==a[r]?a[r]:"";if("heading"===l.type)o=t("<th/>",{scope:"row",class:l.class,html:h});else{var d=s+"["+e+"]["+r+"]";switch(o=t("<td/>",{class:`${l.class} ${l.type}-cell`,width:l.width}),Craft.inArray(l.type,Craft.EditableTable.textualColTypes)&&o.addClass("textual"),l.code&&o.addClass("code"),l.type){case"checkbox":t('<div class="checkbox-wrapper"/>').append(Craft.ui.createCheckbox({name:d,value:l.value||"1",checked:!!h})).appendTo(o);break;case"color":Craft.ui.createColorInput({name:d,value:h,small:!0}).appendTo(o);break;case"date":Craft.ui.createDateInput({name:d,value:h}).appendTo(o);break;case"lightswitch":Craft.ui.createLightswitch({name:d,value:l.value||"1",on:!!h,small:!0}).appendTo(o);break;case"select":Craft.ui.createSelect({name:d,options:l.options,value:h||function(){for(var t in l.options)if(l.options.hasOwnProperty(t)&&l.options[t].default)return void 0!==l.options[t].value?l.options[t].value:t;return null}(),class:"small"}).appendTo(o);break;case"time":Craft.ui.createTimeInput({name:d,value:h}).appendTo(o);break;case"email":case"url":Craft.ui.createTextInput({name:d,value:h,type:l.type,placeholder:l.placeholder||null}).appendTo(o);break;default:t("<textarea/>",{name:d,rows:l.rows||1,val:h,placeholder:l.placeholder}).appendTo(o)}}o.appendTo(n)}return t("<td/>",{class:"thin action"}).append(t("<a/>",{class:"move icon",title:Craft.t("app","Reorder")})).appendTo(n),t("<td/>",{class:"thin action"}).append(t("<a/>",{class:"delete icon",title:Craft.t("app","Delete")})).appendTo(n),n}}),Craft.EditableTable.Row=Garnish.Base.extend({table:null,id:null,niceTexts:null,$tr:null,$tds:null,tds:null,$textareas:null,$deleteBtn:null,init:function(e,i){this.table=e,this.$tr=t(i),this.$tds=this.$tr.children(),this.tds=[],this.id=this.$tr.attr("data-id"),this.$tr.data("editable-table-row",this);var s=parseInt(this.id.substr(this.table.settings.rowIdPrefix.length));s>this.table.biggestId&&(this.table.biggestId=s),this.$textareas=t(),this.niceTexts=[];var a,n,r,o,l,h={},d=0;for(a in this.table.columns)this.table.columns.hasOwnProperty(a)&&(n=this.table.columns[a],r=this.tds[a]=this.$tds[d],Craft.inArray(n.type,Craft.EditableTable.textualColTypes)?(o=t("textarea",r),this.$textareas=this.$textareas.add(o),this.addListener(o,"focus","onTextareaFocus"),this.addListener(o,"mousedown","ignoreNextTextareaFocus"),this.niceTexts.push(new Garnish.NiceText(o,{onHeightChange:t.proxy(this,"onTextareaHeightChange")})),this.addListener(o,"keypress",{tdIndex:d,type:n.type},"handleKeypress"),this.addListener(o,"input",{type:n.type},"validateValue"),o.trigger("input"),"multiline"!==n.type&&this.addListener(o,"paste",{tdIndex:d,type:n.type},"handlePaste"),h[a]=o):"checkbox"===n.type&&(l=t('input[type="checkbox"]',r),n.radioMode&&(void 0===this.table.radioCheckboxes[a]&&(this.table.radioCheckboxes[a]=[]),this.table.radioCheckboxes[a].push(l[0]),this.addListener(l,"change",{colId:a},"onRadioCheckboxChange")),n.toggle&&this.addListener(l,"change",{colId:a},(function(t){this.applyToggleCheckbox(t.data.colId)}))),t(r).hasClass("disabled")||this.addListener(r,"click",{td:r},(function(e){e.target===e.data.td&&t(e.data.td).find("textarea,input,select,.lightswitch").focus()})),d++);for(a in this.onTextareaHeightChange(),this.table.columns)this.table.columns.hasOwnProperty(a)&&"checkbox"===(n=this.table.columns[a]).type&&n.toggle&&this.applyToggleCheckbox(a);for(a in this.table.columns)this.table.columns.hasOwnProperty(a)&&(n=this.table.columns[a]).autopopulate&&void 0!==h[n.autopopulate]&&!h[a].val()&&new Craft.HandleGenerator(h[a],h[n.autopopulate],{allowNonAlphaStart:!0});var c=this.$tr.children().last().find(".delete");this.addListener(c,"click","deleteRow");var u=this.$tr.find("input,textarea,select,.lightswitch");this.addListener(u,"focus",(function(e){t(e.currentTarget).closest("td:not(.disabled)").addClass("focus")})),this.addListener(u,"blur",(function(e){t(e.currentTarget).closest("td").removeClass("focus")}))},onTextareaFocus:function(e){this.onTextareaHeightChange();var i=t(e.currentTarget);i.data("ignoreNextFocus")?i.data("ignoreNextFocus",!1):setTimeout((function(){Craft.selectFullValue(i)}),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(e){for(var i,s,a=this.table.columns[e],n=t('input[type="checkbox"]',this.tds[e]).prop("checked"),r=0;r<a.toggle.length;r++)i=a.toggle[r],this.table.colum,(s="!"===i[0])&&(i=i.substr(1)),n&&!s||!n&&s?t(this.tds[i]).removeClass("disabled").find("textarea, input").prop("disabled",!1):t(this.tds[i]).addClass("disabled").find("textarea, input").prop("disabled",!0)},ignoreNextTextareaFocus:function(e){t.data(e.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){let 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]}),Craft.ElementActionTrigger=Garnish.Base.extend({maxLevels:null,newChildUrl:null,$trigger:null,$selectedItems:null,triggerEnabled:!0,init:function(e){this.setSettings(e,Craft.ElementActionTrigger.defaults),this.$trigger=t("#"+e.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",t.proxy(this,"updateTrigger"))},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}}),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){let e=t.find(".elementthumb");for(let t=0;t<e.length;t++){let i=e.eq(t),s=i.scrollParent();if(this.isVisible(i,s))this.addToQueue(i[0]);else{let t="thumb"+Math.floor(1e6*Math.random());Craft.ElementThumbLoader.invisibleThumbs[t]=[this,i,s],s.on("scroll."+t,{$thumb:i,$scrollParent:s,key:t},t=>{this.isVisible(t.data.$thumb,t.data.$scrollParent)&&(delete Craft.ElementThumbLoader.invisibleThumbs[t.data.key],s.off("scroll."+t.data.key),this.addToQueue(t.data.$thumb[0]))})}}},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){let 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(let t in Craft.ElementThumbLoader.invisibleThumbs){let[e,i,s]=Craft.ElementThumbLoader.invisibleThumbs[t];delete Craft.ElementThumbLoader.invisibleThumbs[t],s.off("scroll."+t),e.load(i.parent())}}}),Craft.ElementThumbLoader.Worker=Garnish.Base.extend({loader:null,active:!1,init:function(t){this.loader=t},loadNext:function(){var e=this.loader.queue.shift();if(void 0!==e){this.active=!0;var i=t(e);if(i.find("img").length)this.loadNext();else{var s=t("<img/>",{sizes:i.attr("data-sizes"),srcset:i.attr("data-srcset"),alt:""});this.addListener(s,"load,error","loadNext"),s.appendTo(i),picturefill({elements:[s[0]]})}}else this.active=!1}}),Craft.ElevatedSessionForm=Garnish.Base.extend({$form:null,inputs:null,init:function(e,i){if(this.$form=t(e),void 0!==i){this.inputs=[],i=t.makeArray(i);for(var s=0;s<i.length;s++)for(var a=t(i[s]),n=0;n<a.length;n++){var r=a.eq(n);this.inputs.push({input:r,val:Garnish.getInputPostVal(r)})}}this.addListener(this.$form,"submit","handleFormSubmit")},handleFormSubmit:function(e){if(Craft.elevatedSessionManager.fetchingTimeout)return e.preventDefault(),void e.stopImmediatePropagation();if(this.inputs){for(var i,s=!1,a=0;a<this.inputs.length;a++)if((i=this.inputs[a].input).data("passwordInput")&&(i=i.data("passwordInput").$currentInput),Garnish.getInputPostVal(i)!==this.inputs[a].val){s=!0;break}if(!s)return}e.preventDefault(),e.stopImmediatePropagation(),Craft.elevatedSessionManager.requireElevatedSession(t.proxy(this,"submitForm"))},submitForm:function(){this.disable(),this.$form.trigger("submit"),this.enable()}}),Craft.ElevatedSessionManager=Garnish.Base.extend({fetchingTimeout:!1,passwordModal:null,$passwordInput:null,$passwordSpinner:null,$submitBtn:null,$errorPara:null,callback:null,requireElevatedSession:function(e){this.callback=e,this.fetchingTimeout=!0,Craft.postActionRequest("users/get-elevated-session-timeout",t.proxy((function(t,e){this.fetchingTimeout=!1,"success"===e&&(!1===t.timeout||t.timeout>=Craft.ElevatedSessionManager.minSafeElevatedSessionTimeout?this.callback():this.showPasswordModal())}),this))},showPasswordModal:function(){if(this.passwordModal)this.passwordModal.show();else{var e=t('<form id="elevatedsessionmodal" class="modal secure fitted"/>'),i=t('<div class="body"><p>'+Craft.t("app","Enter your password to continue.")+"</p></div>").appendTo(e),s=t('<div class="inputcontainer">').appendTo(i),a=t('<div class="flex"/>').appendTo(s),n=t('<div class="flex-grow"/>').appendTo(a),r=t("<td/>").appendTo(a),o=t('<div class="passwordwrapper"/>').appendTo(n);this.$passwordInput=t('<input type="password" class="text password fullwidth" placeholder="'+Craft.t("app","Password")+'" autocomplete="current-password"/>').appendTo(o),this.$passwordSpinner=t('<div class="spinner hidden"/>').appendTo(s),this.$submitBtn=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","Submit")}).appendTo(r),this.$errorPara=t('<p class="error"/>').appendTo(i),this.passwordModal=new Garnish.Modal(e,{closeOtherModals:!1,onFadeIn:t.proxy((function(){setTimeout(t.proxy(this,"focusPasswordInput"),100)}),this),onFadeOut:t.proxy((function(){this.$passwordInput.val("")}),this)}),new Craft.PasswordInput(this.$passwordInput,{onToggleInput:t.proxy((function(t){this.$passwordInput=t}),this)}),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(e){if(e&&e.preventDefault(),this.validatePassword()){this.$passwordSpinner.removeClass("hidden"),this.clearLoginError();var i={currentPassword:this.$passwordInput.val()};Craft.postActionRequest("users/start-elevated-session",i,t.proxy((function(t,e){this.$passwordSpinner.addClass("hidden"),"success"===e?t.success?(this.passwordModal.hide(),this.callback()):(this.showPasswordError(t.message||Craft.t("app","Incorrect password.")),Garnish.shake(this.passwordModal.$container),this.focusPasswordInput()):this.showPasswordError()}),this))}},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,Craft.EntryIndex=Craft.BaseElementIndex.extend({publishableSections:null,$newEntryBtnGroup:null,$newEntryBtn:null,init:function(e,i,s){this.on("selectSource",t.proxy(this,"updateButton")),this.on("selectSite",t.proxy(this,"updateButton")),this.base(e,i,s)},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 e=0;e<this.$sources.length;e++){var i=t(this.$sources[e]);if(i.data("handle")===defaultSectionHandle)return i.data("key")}}return this.base()},updateButton:function(){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=t('<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=t('<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=t("<button/>",{type:"button",class:"btn submit menubtn"}).appendTo(this.$newEntryBtnGroup))):this.$newEntryBtn=r=t("<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!==t.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>")}t(o+="</ul></div>").appendTo(this.$newEntryBtnGroup);var h=new Garnish.MenuBtn(r);"index"!==this.settings.context&&h.on("optionSelect",t.proxy((function(t){this._openCreateEntryModal(t.option.getAttribute("data-id"))}),this))}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/"+t.handle+"/new";let s={};if(this.siteId)for(var i=0;i<Craft.sites.length;i++)Craft.sites[i].id==this.siteId&&(s.site=Craft.sites[i].handle);return'href="'+Craft.getUrl(e,s)+'"'}return'data-id="'+t.id+'"'},_openCreateEntryModal:function(e){if(!this.$newEntryBtn.hasClass("loading")){for(var i,s=0;s<this.publishableSections.length;s++)if(this.publishableSections[s].id==e){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:e,typeId:i.entryTypes[0].id,enabled:i.canPublish?1:0},onBeginLoading:t.proxy((function(){this.$newEntryBtn.addClass("loading")}),this),onEndLoading:t.proxy((function(){this.$newEntryBtn.removeClass("loading")}),this),onHideHud:t.proxy((function(){this.$newEntryBtn.removeClass("inactive").text(a)}),this),onSaveElement:t.proxy((function(t){var e="section:"+i.uid;this.sourceKey!==e&&this.selectSourceByKey(e),this.selectElementAfterUpdate(t.id),this.updateElements()}),this)})}}}}),Craft.registerElementIndexClass("craft\\elements\\Entry",Craft.EntryIndex),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(e,i){this.$container=t(e),this.setSettings(i,Craft.FieldLayoutDesigner.defaults);let 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");let 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});let n=this.$tabContainer.children();for(let e=0;e<n.length;e++)this.initTab(t(n[e]));if(t("<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){let t=this.$sidebar.children(".btngroup");new Craft.Listbox(t,{onChange:t=>{this.$selectedLibrary.addClass("hidden"),this.$selectedLibrary=this[`$${t.data("library")}Library`].removeClass("hidden")}})}this.addListener(this.$fieldSearch,"input",()=>{let t=this.$fieldSearch.val().toLowerCase().replace(/['"]/g,"");if(!t)return this.$fieldLibrary.find(".filtered").removeClass("filtered"),void this.$clearFieldSearchBtn.addClass("hidden");this.$clearFieldSearchBtn.removeClass("hidden");let e=this.$fields.filter(`[data-keywords*="${t}"]`).add(this.$fieldGroups.filter(`[data-name*="${t}"]`).children(".fld-element")).removeClass("filtered");this.$fields.not(e).addClass("filtered");for(let t=0;t<this.$fieldGroups.length;t++){let e=this.$fieldGroups.eq(t);e.find(".fld-element:not(.hidden):not(.filtered)").length?e.removeClass("filtered"):e.addClass("filtered")}}),this.addListener(this.$fieldSearch,"keydown",t=>{t.keyCode===Garnish.ESC_KEY&&this.$fieldSearch.val("").trigger("input")}),this.addListener(this.$clearFieldSearchBtn,"click",()=>{this.$fieldSearch.val("").trigger("input")})},initTab:function(e){if(this.settings.customizableTabs){let i=e.find(".tabs .settings");t('<div class="menu" data-align="center"/>').insertAfter(i).append(t("<ul/>").append(t("<li/>").append(t("<a/>",{"data-action":"rename",text:Craft.t("app","Rename")}))).append(t("<li/>").append(t("<a/>",{"data-action":"remove",text:Craft.t("app","Remove")})))).append(t("<hr/>")).append(t("<ul/>").append(t("<li/>").append(t("<a/>",{"data-action":"moveLeft",text:Craft.t("app","Move to the left")}))).append(t("<li/>").append(t("<a/>",{"data-action":"moveRight",text:Craft.t("app","Move to the right")}))));let s=new Garnish.MenuBtn(i,{onOptionSelect:t.proxy(this,"onTabOptionSelect")});s.menu.on("show",()=>{e.prev(".fld-tab").length?s.menu.$container.find("[data-action=moveLeft]").removeClass("disabled"):s.menu.$container.find("[data-action=moveLeft]").addClass("disabled"),e.next(".fld-tab").length?s.menu.$container.find("[data-action=moveRight]").removeClass("disabled"):s.menu.$container.find("[data-action=moveRight]").addClass("disabled")})}let i=e.children(".fld-tabcontent").children();for(let e=0;e<i.length;e++)this.initElement(t(i[e]))},initElement:function(t){new Craft.FieldLayoutDesigner.Element(this,t)},onTabOptionSelect:function(e){if(!this.settings.customizableTabs)return;let i=t(e),s=i.data("menu").$anchor.parent().parent().parent();switch(i.data("action")){case"rename":this.renameTab(s);break;case"remove":this.removeTab(s);break;case"moveLeft":let t=s.prev(".fld-tab");t.length&&s.insertBefore(t);break;case"moveRight":let e=s.next(".fld-tab");e.length&&s.insertAfter(e)}},renameTab:function(t){if(!this.settings.customizableTabs)return;const 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(e){if(!this.settings.customizableTabs)return;let i=e.find(".fld-element");for(let e=0;e<i.length;e++){let s=t(i[e]).attr("data-attribute");this.removeFieldByHandle(s)}this.tabGrid.removeItems(e),this.tabDrag.removeItems(e),e.remove()},removeField:function(t){let e=t.attr("data-attribute");t.remove(),this.removeFieldByHandle(e),this.tabGrid.refreshCols(!0)},removeFieldByHandle:function(t){this.$fields.filter(`[data-attribute="${t}"]:first`).removeClass("hidden").closest(".fld-field-group").removeClass("hidden")},addTab:function(){if(!this.settings.customizableTabs)return;const e=this.promptForTabName();if(!e)return;const i=t(`\n<div class="fld-tab">\n  <div class="tabs">\n    <div class="tab sel draggable">\n      <span>${e}</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);this.tabGrid.addItems(i),this.tabDrag.addItems(i),this.initTab(i)},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(e,i){this.designer=e,this.$container=i,this.$container.data("fld-element",this),this.config=this.$container.data("config"),t.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"));let 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=t("<div/>",{class:"hidden"}),this.$editBtn=t("<a/>",{role:"button",tabindex:0,class:"settings icon",title:Craft.t("app","Edit")}),this.$editBtn.on("click",()=>{this.hud?(this.hud.show(),this.hud.updateSizeAndPosition(!0)):this.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(){if(this.$placementInput=t("<input/>",{class:"placement-input",type:"hidden",name:"",value:this.key}).appendTo(this.$container),this.updatePlacementInput(),this.$configInput=t("<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:t=>Craft.t("app","{pct} width",{pct:t+"%"}),onChange:t=>{this.config.width=t,this.updateConfigInput()}}).$container.appendTo(this.$container)}this.hasSettings&&this.$editBtn.appendTo(this.$container)},createSettingsHud:function(t,e){let i=`\n<div class="fld-element-settings">\n  ${t}\n  <div class="hud-footer">\n    <div class="buttons right">\n      <button class="btn submit" type="submit">${Craft.t("app","Apply")}</button>\n      <div class="spinner hidden"></div>\n    </div>\n  </div>\n</div>\n`;if(this.hud=new Garnish.HUD(this.$container,i,{onShow:t=>{Garnish.requestAnimationFrame(()=>{this.hud.$main.find(".text:first").trigger("focus")})},onSubmit:()=>{this.applyHudSettings()}}),Craft.initUiElements(this.hud.$main),this.requirable){Craft.ui.createLightswitchField({label:Craft.t("app","Required"),id:this.key+"-required",name:"required",on:e}).prependTo(this.hud.$main)}this.trigger("createSettingsHud")},applyHudSettings:function(){this.hud.$body.serializeArray().forEach(({name:t,value:e})=>{this.config[t]=e}),this.updateConfigInput();let e=this.hud.$body.find(".spinner").removeClass("hidden");Craft.sendActionRequest("POST","fields/render-layout-element-selector",{data:{config:this.config}}).then(i=>{e.addClass("hidden"),this.$editBtn.detach(),this.$container.html(t(i.data.html).html()),this.initUi(),this.updateRequiredClass(),this.hud.hide()}).catch(t=>{console.error(t),e.addClass("hidden"),this.updateRequiredClass(),this.hud.hide()})},updatePlacementInput:function(){let t=this.$container.closest(".fld-tab").find(".tab span");if(!t.length)return;let 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=t().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=t().add(this.$items.not(this.$draggee).add(this.$insertion)),this.showingInsertion=!0},swapInsertionWithDraggee:function(){this.$insertion.replaceWith(this.$draggee),this.$items=t().add(this.$items.not(this.$insertion).add(this.$draggee)),this.showingInsertion=!1},setMidpoints:function(){for(let e=0;e<this.$items.length;e++){let i=t(this.$items[e]),s=i.offset();i.hasClass("unused")||i.data("midpoint",{left:s.left+i.outerWidth()/2,top:s.top+i.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=t(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&&t.inArray(this.$insertion[0],this.$items)<t.inArray(this.checkForNewClosestItem._closestItem,this.$items)&&-1===t.inArray(this.checkForNewClosestItem._closestItem,this.$caboose)?this.$insertion.insertAfter(this.checkForNewClosestItem._closestItem):this.$insertion.insertBefore(this.checkForNewClosestItem._closestItem),this.$items=t().add(this.$items.add(this.$insertion)),this.showingInsertion=!0,this.designer.tabGrid.refreshCols(!0),this.setMidpoints())},onDragStop:function(){this.showingInsertion&&this.swapInsertionWithDraggee(),this.removeCaboose(),this.designer.tabGrid.refreshCols(!0);let t=this.$draggee.offset();!t||0===t.top&&0===t.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,()=>{this._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(){let e=t('<div class="fld-tab fld-tab-caboose"/>').appendTo(this.designer.$tabContainer);return this.designer.tabGrid.addItems(e),e},removeCaboose:function(){this.base(),this.designer.tabGrid.removeItems(this.$caboose)},createInsertion:function(){let e=this.$draggee.find(".tab");return t(`\n<div class="fld-tab fld-insertion" style="height: ${this.$draggee.height()}px;">\n  <div class="tabs"><div class="tab sel draggable" style="width: ${e.width()}px; height: ${e.height()}px;"></div></div>\n  <div class="fld-tabcontent" style="height: ${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=t().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(let 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(){let e=t(),i=this.designer.$tabContainer.find("> .fld-tab > .fld-tabcontent");for(let s=0;s<i.length;s++)e=e.add(t("<div/>").appendTo(i[s]));return e},createInsertion:function(){return t(`<div class="fld-element fld-insertion" style="height: ${this.$draggee.outerHeight()}px;"/>`)},onDragStop:function(){let t=this.showingInsertion;if(t){if(this.draggingLibraryElement){let t=this.$draggee.clone().removeClass("unused");this.designer.initElement(t),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=t,this.addItems(t)}}else if(!this.draggingLibraryElement){let t=this.draggingField?this.designer.$fields.filter(`[data-attribute="${this.$draggee.data("attribute")}"]:first`):this.designer.$uiLibraryElements.filter(`[data-type="${this.$draggee.data("type").replace(/\\/g,"\\\\")}"]:first`);this.draggingField&&(t.removeClass("hidden"),t.closest(".fld-field-group").removeClass("hidden")),this.removeItems(this.$draggee),this.$draggee=t}this.base(),this.$draggee.css({display:this.draggeeDisplay,visibility:this.draggingField||t?"hidden":"visible"}),t&&this.$draggee.data("fld-element").updatePlacementInput()}}),Craft.FieldToggle=Garnish.Base.extend({$toggle:null,targetPrefix:null,targetSelector:null,reverseTargetSelector:null,_$target:null,_$reverseTarget:null,type:null,init:function(e){switch(this.$toggle=t(e),this.$toggle.data("fieldtoggle")&&(Garnish.log("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(){let 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"select";case"A":return"link";case"FIELDSET":return"fieldset"}console.warn("Unexpected field toggle:",this.$toggle[0])},findTargets:function(){if("select"===this.type||"fieldset"===this.type){this.getToggleVal();this._$target=t(this.normalizeTargetSelector(this.targetPrefix+this.getToggleVal()))}else this.targetSelector&&(this._$target=t(this.targetSelector)),this.reverseTargetSelector&&(this._$reverseTarget=t(this.reverseTargetSelector))},getToggleVal:function(){if("checkbox"===this.type)return void 0!==this.$toggle.prop("checked")?this.$toggle.prop("checked"):"true"===this.$toggle.attr("aria-checked");let t;return t="fieldset"===this.type?this.$toggle.find("input:checked:first").val():Garnish.getInputPostVal(this.$toggle),null==t?null:t.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){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(let e=0;e<t.length;e++)(t=>{"SPAN"!==t.prop("nodeName")&&(t.height("auto"),this.showTarget._targetHeight=t.height(),t.css({height:this.showTarget._currentHeight,overflow:"hidden"}),t.velocity("stop"),t.velocity({height:this.showTarget._targetHeight},"fast",(function(){t.css({height:"",overflow:""})})))})(t.eq(e));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(let e=0;e<t.length;e++)(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))}}}),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(e,i){this.$container=t(e),this.$container.data("grid")&&(Garnish.log("Double-instantiating a grid on an element"),this.$container.data("grid").destroy()),this.$container.data("grid",this),this.setSettings(i,Craft.Grid.defaults),this.handleContainerHeightProxy=t.proxy((function(){this.refreshCols(!1,!0)}),this),this.$items=this.$container.children(this.settings.itemSelector),this.setItems(),this.refreshCols(!0,!1),Garnish.$doc.ready(t.proxy((function(){this.refreshCols(!1,!1)}),this))},addItems:function(e){this.$items=t().add(this.$items.add(e)),this.setItems(),this.refreshCols(!0,!0)},removeItems:function(e){this.$items=t().add(this.$items.not(e)),this.setItems(),this.refreshCols(!0,!0)},resetItemOrder:function(){this.$items=t().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(t(this.$items[this.setItems._.i]));delete this.setItems._},refreshCols:function(e){if(this._refreshingCols)return this._refreshColsAfterRefresh=!0,void(e&&(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===e||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[t.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(){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(t.proxy((function(){this.refreshCols(e)}),this))}},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(e){this.onItemResize._={},e.stopPropagation(),this.onItemResize._.item=t.inArray(e.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()}},{defaults:{itemSelector:".item",cols:null,maxCols:null,minColWidth:320,gutter:14,fillMode:"top",colClass:"col",snapToGrid:null,onRefreshCols:t.noop}}),Craft.Grid.LayoutGenerator=Garnish.Base.extend({grid:null,_:null,init:function(t){this.grid=t},createLayouts:function(e,i,s,a,n){for(this._={},this._.c=0;this._.c<this.grid.possibleItemColspans[e].length;this._.c++){for(this._.colspan=this.grid.possibleItemColspans[e][this._.c],this._.tallestColHeightsByPosition=[],this._.p=0;this._.p<this.grid.possibleItemPositionsByColspan[e][this._.colspan].length;this._.p++){for(this._.position=this.grid.possibleItemPositionsByColspan[e][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(a[this._.col]);this._.tallestColHeightsByPosition[this._.p]=Math.max.apply(null,this._.colHeightsForPosition)}for(this._.p=t.inArray(Math.min.apply(null,this._.tallestColHeightsByPosition),this._.tallestColHeightsByPosition),this._.position=this.grid.possibleItemPositionsByColspan[e][this._.colspan][this._.p],this._.positions=i.slice(0),this._.colspans=s.slice(0),this._.colHeights=a.slice(0),this._.emptySpace=n,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[e][this._.colspan];e===this.grid.items.length-1?this.grid.layouts.push({positions:this._.positions,colspans:this._.colspans,colHeights:this._.colHeights,emptySpace:this._.emptySpace}):this.grid.createLayouts(e+1,this._.positions,this._.colspans,this._.colHeights,this._.emptySpace)}delete this._}}),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(let t=0;t<i.length;t++)"pascal"!==Craft.handleCasing&&0===t?e+=i[t]:e+=i[t].charAt(0).toUpperCase()+i[t].substr(1);return e}}),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=t(this.settings.containerSelector),this.progressBar=new Craft.ProgressBar(t('<div class="progress-shade"></div>').appendTo(this.$container));var e={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&&(e.formData[Craft.csrfTokenName]=Craft.csrfTokenValue),e.events={},e.events.fileuploadstart=t.proxy(this,"_onUploadStart"),e.events.fileuploadprogressall=t.proxy(this,"_onUploadProgress"),e.events.fileuploaddone=t.proxy(this,"_onUploadComplete"),e.events.fileuploadfail=t.proxy(this,"_onUploadError"),this.uploader=new Craft.Uploader(this.$container,e),this.initButtons()},initButtons:function(){this.$container.find(this.settings.uploadButtonSelector).on("click",t.proxy((function(t){this.$container.find(this.settings.fileInputSelector).trigger("click")}),this)),this.$container.find(this.settings.deleteButtonSelector).on("click",t.proxy((function(e){confirm(Craft.t("app","Are you sure you want to delete this image?"))&&(t(e.currentTarget).parent().append('<div class="blocking-modal"></div>'),Craft.postActionRequest(this.settings.deleteAction,this.settings.postParameters,t.proxy((function(t,e){"success"===e&&this.refreshImage(t)}),this)))}),this))},refreshImage:function(e){t(this.settings.containerSelector).replaceWith(e.html),this.settings.onAfterRefreshImage(e),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(e,i){if(i.result.error)alert(i.result.error);else{t(i.result.html);this.refreshImage(i.result)}this.uploader.isLastUpload()&&(this.progressBar.hideProgressBar(),this.$container.removeClass("uploading"))},_onUploadError:function(t,e){e.jqXHR.responseJSON.error&&(alert(e.jqXHR.responseJSON.error),this.$container.removeClass("uploading"),this.progressBar.hideProgressBar(),this.progressBar.resetProgressBar())}},{defaults:{postParameters:{},uploadAction:"",deleteAction:"",fileInputSelector:"",onAfterRefreshImage:t.noop,containerSelector:null,uploadButtonSelector:null,deleteButtonSelector:null,uploadParamName:"files"}}),Craft.InfoIcon=Garnish.Base.extend({$icon:null,content:null,hud:null,init:function(e){if(this.$icon=t(e),this.$icon.data("infoicon")?(Garnish.log("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){if(!this.$icon.parent().hasClass("nowrap")){const e=this.$icon[0].previousSibling.nodeValue.match(/[^\s\-]+\s*$/);e&&(this.$icon[0].previousSibling.nodeValue=this.$icon[0].previousSibling.nodeValue.substr(0,e.index),t("<span/>",{class:"nowrap",html:e[0].replace(/\s+$/,"")+" "}).insertAfter(this.$icon[0].previousSibling).append(this.$icon))}}this.addListener(this.$icon,"click",t=>{t.preventDefault(),t.stopPropagation(),this.showHud()}),this.addListener(this.$icon,"keydown",t=>{this.hud&&this.hud.showing||![Garnish.SPACE_KEY,Garnish.RETURN_KEY].includes(t.keyCode)||(t.preventDefault(),t.stopPropagation(),this.showHud())})},showHud:function(t){this.hud?this.hud.show():(this.hud=new Garnish.HUD(this.$icon,this.content,{hudClass:"hud info-hud",closeOtherHUDs:!1,onShow:()=>{Garnish.shortcutManager.registerShortcut(Garnish.SPACE_KEY,()=>{this.hud.hide()})}}),Craft.initUiElements(this.hud.$body))}}),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(e,i){if(this.$outerContainer=t(e),this.$outerContainer.data("lightswitch")&&(Garnish.log("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(i,Craft.LightSwitch.defaults),this.$innerContainer=this.$outerContainer.find(".lightswitch-container:first"),this.$input=this.$outerContainer.find("input:first"),this.$input.prop("disabled"))return;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:t.proxy(this,"_onDragStart"),onDrag:t.proxy(this,"_onDrag"),onDragStop:t.proxy(this,"_onDragStop")});let s=this.$outerContainer.parent(".lightswitch-inner-container");s.length&&(this.addListener(s.children('span[data-toggle="off"]'),"click",this.turnOff),this.addListener(s.children('span[data-toggle="on"]'),"click",this.turnOn))},turnOn:function(e){var i=!this.on;this.on=!0,this.indeterminate=!1,this.$outerContainer.addClass("dragging");var s={};s["margin-"+Craft.left]=0,this.$innerContainer.velocity("stop").velocity(s,Craft.LightSwitch.animationDuration,t.proxy(this,"_onSettle")),this.$input.val(this.settings.value),this.$outerContainer.addClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","true"),i&&!0!==e&&this.onChange()},turnOff:function(e){var i=this.on||this.indeterminate;this.on=!1,this.indeterminate=!1,this.$outerContainer.addClass("dragging");var s={};s["margin-"+Craft.left]=this._getOffMargin(),this.$innerContainer.velocity("stop").velocity(s,Craft.LightSwitch.animationDuration,t.proxy(this,"_onSettle")),this.$input.val(""),this.$outerContainer.removeClass("on"),this.$outerContainer.removeClass("indeterminate"),this.$outerContainer.attr("aria-checked","false"),i&&!0!==e&&this.onChange()},turnIndeterminate:function(e){var i=!this.indeterminate;this.on=!1,this.indeterminate=!0,this.$outerContainer.addClass("dragging");var s={};s["margin-"+Craft.left]=this._getOffMargin()/2,this.$innerContainer.velocity("stop").velocity(s,Craft.LightSwitch.animationDuration,t.proxy(this,"_onSettle")),this.$input.val(this.settings.indeterminateValue),this.$outerContainer.removeClass("on"),this.$outerContainer.addClass("indeterminate"),this.$outerContainer.attr("aria-checked","mixed"),i&&!0!==e&&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.base(),this.dragger.destroy()},_getOffMargin:function(){return this.small?-10:-12}},{animationDuration:100,defaults:{value:"1",indeterminateValue:"-",onChange:t.noop}}),Craft.Listbox=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,selectedOptionIndex:null,init:function(e,i){this.$container=t(e),this.setSettings(i,Craft.Listbox.defaults),this.$container.data("listbox")&&(Garnish.log("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",t=>{switch(t.keyCode){case Garnish.UP_KEY:this.selectPrev(),t.preventDefault();break;case Garnish.DOWN_KEY:this.selectNext(),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.selectPrev():this.selectNext(),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.selectNext():this.selectPrev(),t.preventDefault()}}),this.addListener(this.$options,"click",e=>{this.select(this.$options.index(t(e.currentTarget))),e.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)}},{defaults:{selectedClass:"active",focusClass:"focus",onChange:t.noop}}),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,_handleSuccessProxy:null,_handleErrorProxy:null,_forceUpdateIframeProxy:null,_scrollX:null,_scrollY:null,_editorWidth:null,_editorWidthInPx:null,init:function(e){this.setSettings(e,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=t.extend({},this.settings.previewParams),this._handleSuccessProxy=t.proxy(this,"handleSuccess"),this._handleErrorProxy=t.proxy(this,"handleError"),this._forceUpdateIframeProxy=t.proxy(this,"forceUpdateIframe"),this.$extraFields=t(this.settings.extraFields),this.$trigger=t(this.settings.trigger),this.$fieldPlaceholder=t("<div/>"),this.editorWidth=Craft.getLocalStorage("LivePreview.editorWidth",Craft.LivePreview.defaultEditorWidth),this.addListener(this.$trigger,"activate","toggle"),Craft.cp.on("beforeSaveShortcut",t.proxy((function(){this.inPreviewMode&&this.moveFieldsBack()}),this))},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(){if(!this.inPreviewMode)if(this.token){if(this.trigger("beforeEnter"),t(document.activeElement).trigger("blur"),!this.$editor){this.$shade=t("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=t("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$iframeContainer=t("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$editorContainer=t("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=t("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=t("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=t("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);t("<div/>",{class:"flex-grow"}).appendTo(e);let s=t("<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:t.proxy(this,"_onDragStart"),onDrag:t.proxy(this,"_onDrag"),onDragStop:t.proxy(this,"_onDragStop")}),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 s=t(this.settings.fields),a=0;a<s.length;a++){var n=t(s[a]),r=this._getClone(n);this.$fieldPlaceholder.insertAfter(n),n.detach(),this.$fieldPlaceholder.replaceWith(r),n.appendTo(this.$editor),this.fields.push({$field:n,$clone:r})}this.updateIframe()?this._slideInOnIframeLoad=!0:this.slideIn(),Garnish.on(Craft.BaseElementEditor,"saveElement",this._forceUpdateIframeProxy),Garnish.on(Craft.AssetImageEditor,"save",this._forceUpdateIframeProxy),Craft.ElementThumbLoader.retryAll(),this.inPreviewMode=!0,this.trigger("enter")}else this.createToken()},createToken:function(){Craft.postActionRequest("live-preview/create-token",{previewAction:this.settings.previewAction},t.proxy((function(t,e){"success"===e&&(this.token=t.token,this.enter())}),this))},save:function(){Craft.cp.submitPrimaryForm()},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){t("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",t.proxy((function(){this.trigger("slideIn"),Garnish.$win.trigger("resize")}),this)),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",t.proxy((function(){this.updateIframeInterval=setInterval(t.proxy(this,"updateIframe"),1e3),this.addListener(Garnish.$bod,"keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&this.exit()}))}),this))},exit:function(){this.inPreviewMode&&(this.trigger("beforeExit"),t("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),this.removeListener(Garnish.$bod,"keyup"),this.updateIframeInterval&&clearInterval(this.updateIframeInterval),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",t.proxy((function(){for(var t=0;t<this.fields.length;t++)this.fields[t].$newClone.remove();this.$editorContainer.hide(),this.trigger("slideOut")}),this)),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",t.proxy((function(){this.$previewContainer.hide()}),this)),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(e){if(e&&(this.lastPostData=null),!this.inPreviewMode)return!1;if(this.loading)return this.checkAgain=!0,!1;var i=t.extend(Garnish.getPostData(this.$editor),Garnish.getPostData(this.$extraFields));if(this.lastPostData&&Craft.compare(i,this.lastPostData,!1))return!1;this.lastPostData=i,this.loading=!0;var s=this.$iframe?t(this.$iframe[0].contentWindow.document):null;return this._scrollX=s?s.scrollLeft():0,this._scrollY=s?s.scrollTop():0,t.ajax({url:this.previewUrl+(-1!==this.previewUrl.indexOf("?")?"&":"?")+Craft.tokenParam+"="+this.token,method:"POST",data:t.extend({},i,this.basePostData),headers:{"X-Craft-Token":this.token},xhrFields:{withCredentials:!0},crossDomain:!0,success:this._handleSuccessProxy,error:this._handleErrorProxy}),!0},forceUpdateIframe:function(){return this.updateIframe(!0)},handleSuccess:function(e){var i=e+'<script type="text/javascript">window.scrollTo('+this._scrollX+", "+this._scrollY+");<\/script>",s=t('<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(t.proxy((function(){s[0].contentWindow.document.open(),s[0].contentWindow.document.write(i),s[0].contentWindow.document.close(),this.onResponse()}),this))},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)},Craft.PasswordInput=Garnish.Base.extend({$passwordWrapper:null,$passwordInput:null,$textInput:null,$currentInput:null,$showPasswordToggle:null,showingPassword:null,init:function(e,i){this.$passwordInput=t(e),this.$passwordWrapper=this.$passwordInput.parent(".passwordwrapper"),this.settings=t.extend({},Craft.PasswordInput.defaults,i),this.$passwordInput.data("passwordInput")&&(Garnish.log("Double-instantiating a password input on an element"),this.$passwordInput.data("passwordInput").destroy()),this.$passwordInput.data("passwordInput",this),this.$showPasswordToggle=t('<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()},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"),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()}},{defaults:{onToggleInput:t.noop}}),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,$deviceMask:null,$devicePreviewContainer:null,$iframe:null,iframeLoaded:!1,$tempInput:null,$fieldPlaceholder:null,isActive:!1,isVisible:!1,activeTarget:0,isDeviceUpdating:!1,deviceAnimationTimeout:null,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(e){this.draftEditor=e,this._updateIframeProxy=t.proxy(this,"updateIframe"),this.$tempInput=t("<input/>",{type:"hidden",name:"__PREVIEW_FIELDS__",value:"1"}),this.$fieldPlaceholder=t("<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(){if(!this.isActive){if(this.isActive=!0,this.trigger("beforeOpen"),t(document.activeElement).trigger("blur"),!this.$editor){this.$shade=t("<div/>",{class:"modal-shade dark"}).appendTo(Garnish.$bod),this.$previewContainer=t("<div/>",{class:"lp-preview-container"}).appendTo(Garnish.$bod),this.$editorContainer=t("<div/>",{class:"lp-editor-container"}).appendTo(Garnish.$bod);var e=t("<header/>",{class:"flex"}).appendTo(this.$editorContainer);this.$editor=t("<form/>",{class:"lp-editor"}).appendTo(this.$editorContainer),this.$dragHandle=t("<div/>",{class:"lp-draghandle"}).appendTo(this.$editorContainer);var i=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Close Preview")}).appendTo(e);if(t("<div/>",{class:"flex-grow"}).appendTo(e),this.$spinner=t("<div/>",{class:"spinner hidden",title:Craft.t("app","Saving")}).appendTo(e),this.$statusIcon=t("<div/>",{class:"invisible"}).appendTo(e),Craft.Pro){if(this.$previewHeader=t("<header/>",{class:"lp-preview-header"}).appendTo(this.$previewContainer),this.draftEditor.settings.previewTargets.length>1){this.$targetBtn=t("<button/>",{type:"button",class:"btn menubtn",text:this.draftEditor.settings.previewTargets[0].label}).appendTo(this.$previewHeader),this.$targetMenu=t("<div/>",{class:"menu lp-target-menu"}).insertAfter(this.$targetBtn);const e=t("<ul/>",{class:"padded"}).appendTo(this.$targetMenu);let i,s;for(let a=0;a<this.draftEditor.settings.previewTargets.length;a++)i=t("<li/>").appendTo(e),s=t("<a/>",{data:{target:a},text:this.draftEditor.settings.previewTargets[a].label,class:0===a?"sel":null}).appendTo(i);new Garnish.MenuBtn(this.$targetBtn,{onOptionSelect:e=>{this.switchTarget(t(e).data("target"))}}),t('<div class="flex-grow"/>').appendTo(this.$previewHeader)}this.$deviceTypeContainer=t("<div/>",{class:"btngroup lp-device-type",role:"listbox","aria-label":Craft.t("app","Device type"),tabindex:"0"}).appendTo(this.$previewHeader),t("<button/>",{type:"button",role:"option",class:"btn lp-device-type-btn--desktop active",title:Craft.t("app","Desktop"),"aria-label":Craft.t("app","Desktop"),"aria-selected":"true",tabindex:"-1",data:{width:"",height:"",deviceType:"desktop"}}).appendTo(this.$deviceTypeContainer),t("<button/>",{type:"button",role:"option",class:"btn lp-device-type-btn--tablet",title:Craft.t("app","Tablet"),"aria-label":Craft.t("app","Tablet"),"aria-selected":"false",tabindex:"-1",data:{width:768,height:1024,deviceType:"tablet"}}).appendTo(this.$deviceTypeContainer),t("<button/>",{type:"button",role:"option",class:"btn lp-device-type-btn--phone",title:Craft.t("app","Mobile"),"aria-label":Craft.t("app","Mobile"),"aria-selected":"false",tabindex:"-1",data:{width:375,height:667,deviceType:"phone"}}).appendTo(this.$deviceTypeContainer),t('<div class="flex-grow"/>').appendTo(this.$previewHeader),this.$orientationBtn=t("<button/>",{type:"button",class:"btn disabled","data-icon":"refresh",disabled:"","aria-hidden":"",text:Craft.t("app","Rotate")}).appendTo(this.$previewHeader),this.addListener(this.$orientationBtn,"click","switchOrientation"),this.deviceOrientation=Craft.getLocalStorage("LivePreview.orientation"),this.addListener(t(".btn",this.$deviceTypeContainer),"click","switchDeviceType"),this.$deviceMask=t("<div/>",{class:"lp-device-mask"})}this.$iframeContainer=t("<div/>",{class:"lp-iframe-container"}).appendTo(this.$previewContainer),this.$deviceMask&&this.$iframeContainer.append(this.$deviceMask),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",()=>{this.draftEditor.showStatusHud(this.$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 s=t("#content .field").not(t("#content .field .field"));if(s.length){this.$tempInput.insertBefore(s.get(0));for(let e=0;e<s.length;e++){let i=t(s[e]),a=this._getClone(i);this.$fieldPlaceholder.insertAfter(i),i.detach(),this.$fieldPlaceholder.replaceWith(a),i.appendTo(this.$editor),this.fields.push({$field:i,$clone:a})}}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")}},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.trigger("switchTarget",{previewTarget:this.draftEditor.settings.previewTargets[t]})},handleWindowResize:function(){this.editorWidth=this.editorWidth,this.updateWidths()},slideIn:function(){this.isActive&&!this.isVisible&&(t("html").addClass("noscroll"),this.$shade.velocity("fadeIn"),this.$editorContainer.show().velocity("stop").animateLeft(0,"slow",()=>{this.trigger("slideIn"),Garnish.$win.trigger("resize")}),this.$previewContainer.show().velocity("stop").animateRight(0,"slow",()=>{this.addListener(Garnish.$bod,"keyup",(function(t){t.keyCode===Garnish.ESC_KEY&&this.close()}))}),this.isVisible=!0)},close:function(){this.isActive&&this.isVisible&&(this.trigger("beforeClose"),t("html").removeClass("noscroll"),this.removeListener(Garnish.$win,"resize"),this.removeListener(Garnish.$bod,"keyup"),this.$tempInput.detach(),this.moveFieldsBack(),this.$shade.delay(200).velocity("fadeOut"),this.$editorContainer.velocity("stop").animateLeft(-this.editorWidthInPx,"slow",()=>{for(var t=0;t<this.fields.length;t++)this.fields[t].$newClone.remove();this.$editorContainer.hide(),this.trigger("slideOut")}),this.$previewContainer.velocity("stop").animateRight(-this.getIframeWidth(),"slow",()=>{this.$previewContainer.hide(),this.resetDevicePreview()}),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")},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(e){if(!this.isActive)return!1;e=!0===e;var i=this.draftEditor.settings.previewTargets[this.activeTarget],s=!(this.draftId===(this.draftId=this.draftEditor.settings.draftId)&&this.$iframe&&!e&&void 0!==i.refresh&&!i.refresh);this.trigger("beforeUpdateIframe",{previewTarget:i,resetScroll:e,refresh:s}),s?this.draftEditor.getTokenizedPreviewUrl(i.url,"x-craft-live-preview").then(i=>{let s;e?this.scrollTop=null:this.iframeLoaded&&this.$iframe&&(this._useIframeResizer()?(this.iframeHeight=this.$iframe.height(),this.scrollTop=this.$iframeContainer.scrollTop()):(s=Craft.isSameHost(i),s&&this.$iframe[0].contentWindow&&(this.scrollTop=t(this.$iframe[0].contentWindow.document).scrollTop()))),this.iframeLoaded=!1;var a=t("<iframe/>",{class:"lp-preview",frameborder:0,src:i});this.$iframe?this.$iframe.replaceWith(a):a.appendTo(this.$iframeContainer),this._devicePreviewIsActive()&&(this.$devicePreviewContainer||(this.$devicePreviewContainer=t("<div/>",{class:"lp-device-preview-container"}),a.wrap('<div class="lp-device-preview-container"></div>'),this.$devicePreviewContainer=this.$iframeContainer.find(".lp-device-preview-container"))),this._useIframeResizer()?(e||null===this.iframeHeight||(a.height(this.iframeHeight),this.$iframeContainer.scrollTop(this.scrollTop)),iFrameResize(t.extend({checkOrigin:!1,scrolling:!0,onInit:t=>{this.iframeLoaded=!0,this.iframeHeight=null,this.scrollTop=null,t.scrolling="no"}},Craft.previewIframeResizerOptions||{}),a[0])):a.on("load",()=>{this.iframeLoaded=!0,!e&&s&&null!==this.scrollTop&&t(a[0].contentWindow.document).scrollTop(this.scrollTop)}),this.url=i,this.$iframe=a,this._devicePreviewIsActive()&&this.updateDevicePreview(),this.trigger("afterUpdateIframe",{previewTarget:this.draftEditor.settings.previewTargets[this.activeTarget],$iframe:this.$iframe}),this.slideIn()}):this.slideIn()},_devicePreviewIsActive:function(){return"desktop"!==this.currentDeviceType},switchDeviceType:function(e){if(this.isDeviceUpdating)return!1;this.$iframeContainer.removeClass("lp-iframe-container--animating");const i=t(e.target),s=i.data("deviceType");if(s===this.currentDeviceType)return!1;this.currentDeviceType=s,this.deviceWidth=i.data("width"),this.deviceHeight=i.data("height"),this.$deviceTypeContainer.find(".btn").removeClass("active").attr("aria-selected","false"),i.addClass("active").attr("aria-selected","true"),"desktop"===this.currentDeviceType?this.resetDevicePreview():(this.$iframeContainer.addClass("lp-iframe-container--updating"),this.updateIframe(),this.updateDevicePreview())},switchOrientation:function(){if(this.isDeviceUpdating||!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--animating"),this.updateDevicePreview()},updateDevicePreview:function(){if(this.isDeviceUpdating)return!1;this.isDeviceUpdating=!0,this.$orientationBtn.removeClass("disabled").removeAttr("disabled").removeAttr("aria-hidden"),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");let e=1,i=1,s=1,a=this.$previewContainer.height()-50-48,n=this.$previewContainer.width()-48,r=this.deviceMaskDimensions[this.currentDeviceType].height,o=this.deviceMaskDimensions[this.currentDeviceType].width;"landscape"===this.deviceOrientation?(n<r&&(e=n/r),a<o&&(i=a/o)):(a<r&&(e=a/r),n<o&&(i=n/o)),s=e,i<e&&(s=i);const l=-100/s/2,h="landscape"===this.deviceOrientation?"-90deg":"0deg";this.$deviceMask.css({width:this.deviceMaskDimensions[this.currentDeviceType].width+"px",height:this.deviceMaskDimensions[this.currentDeviceType].height+"px",transform:"scale("+s+") translate("+l+"%, "+l+"%) rotate("+h+")"}),this.deviceAnimationTimeout&&clearTimeout(this.deviceAnimationTimeout),this.deviceAnimationTimeout=setTimeout(t.proxy((function(){"landscape"===this.deviceOrientation?this.$devicePreviewContainer.css({width:this.deviceHeight+"px",height:this.deviceWidth+"px",transform:"scale("+s+") translate("+l+"%, "+l+"%)",marginTop:0,marginLeft:"-"+12*s+"px"}):this.$devicePreviewContainer.css({width:this.deviceWidth+"px",height:this.deviceHeight+"px",transform:"scale("+s+") translate("+l+"%, "+l+"%)",marginTop:"-"+12*s+"px",marginLeft:0}),this.$iframeContainer.removeClass("lp-iframe-container--animating"),this.$iframeContainer.removeClass("lp-iframe-container--updating"),this.isDeviceUpdating=!1}),this),300)},resetDevicePreview:function(){this.deviceAnimationTimeout&&clearTimeout(this.deviceAnimationTimeout),this.currentDeviceType="desktop",this.$deviceTypeContainer.find(".btn").removeClass("active").attr("aria-selected","false"),this.$deviceTypeContainer.find(".lp-device-type-btn--desktop").addClass("active").attr("aria-selected","true"),this.$orientationBtn.addClass("disabled").attr("disabled","").attr("aria-hidden",""),this.$iframeContainer.removeClass("lp-iframe-container--animating"),this.$iframeContainer.removeClass("lp-iframe-container--has-device-preview"),this.$iframeContainer.removeClass("lp-iframe-container--tablet"),this.$devicePreviewContainer&&(this._useIframeResizer()&&this.$iframe[0].iFrameResizer.removeListeners(),this.$devicePreviewContainer.detach(),this.$devicePreviewContainer=null,this.$iframe=null,this.updateIframe()),this.isDeviceUpdating=!1},_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}),Craft.PreviewFileModal=Garnish.Modal.extend({assetId:null,$spinner:null,elementSelect:null,type:null,loaded:null,requestId:0,init:function(e,i,s){if((s=t.extend(this.defaultSettings,s)).onHide=this._onHide.bind(this),Craft.PreviewFileModal.openInstance){var a=Craft.PreviewFileModal.openInstance;return a.assetId!==e&&(a.loadAsset(e,s.startingWidth,s.startingHeight),a.elementSelect=i),this.destroy()}Craft.PreviewFileModal.openInstance=this,this.elementSelect=i,this.$container=t('<div class="modal previewmodal loading"/>').appendTo(Garnish.$bod),this.base(this.$container,t.extend({resizable:!0},s)),this.$container&&(this.$container.velocity("stop"),this.$container.show().css("opacity",1),this.$shade.velocity("stop"),this.$shade.show().css("opacity",1)),this.loadAsset(e,s.startingWidth,s.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(e,i,s){this.assetId=e,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,i&&s){var r=i/s;n=Math.min(i,Garnish.$win.width()-2*this.settings.minGutter),(n=(a=Math.min(n/r,Garnish.$win.height()-2*this.settings.minGutter))*r)>Math.min(i,Garnish.$win.width()-2*this.settings.minGutter)&&(a=(n=Math.min(i,Garnish.$win.width()-2*this.settings.minGutter))/r)}this._resizeContainer(n,a),this.$spinner=t('<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:e,requestId:this.requestId},function(e,i){if(this.$container.removeClass("loading"),this.$spinner.remove(),this.loaded=!0,"success"===i)if(e.success){if(e.requestId!=this.requestId)return;if(!e.previewHtml)return this.$container.addClass("zilch"),void this.$container.append(t("<p/>",{text:Craft.t("app","No preview available.")}));this.$container.removeClass("zilch"),this.$container.append(e.previewHtml),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml)}else alert(e.error),this.hide()}.bind(this))},_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}}),Craft.ProgressBar=Garnish.Base.extend({$progressBar:null,$innerProgressBar:null,$progressBarStatus:null,_itemCount:0,_processedItemCount:0,_displaySteps:!1,init:function(e,i){i&&(this._displaySteps=!0),this.$progressBar=t('<div class="progressbar pending hidden"/>').appendTo(e),this.$innerProgressBar=t('<div class="progressbar-inner"/>').appendTo(this.$progressBar),this.$progressBarStatus=t('<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(){this.$progressBar.fadeTo("fast",.01,t.proxy((function(){this.$progressBar.addClass("hidden").fadeTo(1,1,t.noop)}),this))},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+"%"))}}),Craft.PromptHandler=Garnish.Base.extend({modal:null,$modalContainerDiv:null,$prompt:null,$promptApplyToRemainingContainer:null,$promptApplyToRemainingCheckbox:null,$promptApplyToRemainingLabel:null,$pomptChoices:null,_prompts:[],_promptBatchCallback:t.noop,_promptBatchReturnData:[],_promptBatchNum:0,resetPrompts:function(){this._prompts=[],this._promptBatchCallback=t.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 e=this._prompts[this._promptBatchNum].prompt,i=this._prompts.length-(this._promptBatchNum+1);this._showPrompt(e.message,e.choices,t.proxy(this,"_handleBatchPromptSelection"),i)},_handleBatchPromptSelection:function(e,i){var s=this._prompts[this._promptBatchNum],a=this._prompts.length-(this._promptBatchNum+1),n=t.extend(s,{choice:e});this._promptBatchReturnData.push(n),a?(this._promptBatchNum++,i?this._handleBatchPromptSelection(e,!0):this._showNextPromptInBatch()):"function"==typeof this._promptBatchCallback&&this._promptBatchCallback(this._promptBatchReturnData)},_showPrompt:function(e,i,s,a){this._promptCallback=s,null===this.modal&&(this.modal=new Garnish.Modal({closeOtherModals:!1})),null===this.$modalContainerDiv&&(this.$modalContainerDiv=t('<div class="modal fitted prompt-modal"></div>').addClass().appendTo(Garnish.$bod)),this.$prompt=t('<div class="body"></div>').appendTo(this.$modalContainerDiv.empty()),this.$promptMessage=t('<p class="prompt-msg"/>').appendTo(this.$prompt),this.$promptChoices=t('<div class="options"></div>').appendTo(this.$prompt),this.$promptApplyToRemainingContainer=t('<label class="assets-applytoremaining"/>').appendTo(this.$prompt).hide(),this.$promptApplyToRemainingCheckbox=t('<input type="checkbox"/>').appendTo(this.$promptApplyToRemainingContainer),this.$promptApplyToRemainingLabel=t("<span/>").appendTo(this.$promptApplyToRemainingContainer),this.$promptButtons=t('<div class="buttons right"/>').appendTo(this.$prompt),this.modal.setContainer(this.$modalContainerDiv),this.$promptMessage.html(e);let n=t("<button/>",{type:"button",class:"btn",text:Craft.t("app","Cancel")}).appendTo(this.$promptButtons),r=t("<button/>",{type:"submit",class:"btn submit disabled",text:Craft.t("app","OK")}).appendTo(this.$promptButtons);for(var o=0;o<i.length;o++){var l=t('<div><label><input type="radio" name="promptAction" value="'+i[o].value+'"/> '+i[o].title+"</label></div>").appendTo(this.$promptChoices).find("input");this.addListener(l,"click",(function(){r.removeClass("disabled")}))}this.addListener(r,"activate",(function(e){var i=t(e.currentTarget).parents(".modal").find("input[name=promptAction]:checked").val(),s=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice(i,s)})),this.addListener(n,"activate",(function(){var t=this.$promptApplyToRemainingCheckbox.prop("checked");this._selectPromptChoice("cancel",t)})),a&&(this.$promptApplyToRemainingContainer.show(),this.$promptApplyToRemainingLabel.html(" "+Craft.t("app","Apply this to the {number} remaining conflicts?",{number:a}))),this.modal.show(),this.modal.removeListener(Garnish.Modal.$shade,"click"),this.addListener(Garnish.Modal.$shade,"click","_cancelPrompt")},_selectPromptChoice:function(e,i){this.$prompt.fadeOut("fast",t.proxy((function(){this.modal.hide(),this._promptCallback(e,i)}),this))},_cancelPrompt:function(){this._selectPromptChoice("cancel",!0)}}),function(t){Craft.SlidePicker=Garnish.Base.extend({min:null,max:null,totalSteps:null,value:null,$container:null,$buttons:null,init:function(e,i){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",t=>{switch(t.keyCode){case Garnish.UP_KEY:this.setValue(this.value+this.settings.step),t.preventDefault();break;case Garnish.DOWN_KEY:this.setValue(this.value-this.settings.step),t.preventDefault();break;case Garnish.RIGHT_KEY:"ltr"===Craft.orientation?this.setValue(this.value+this.settings.step):this.setValue(this.value-this.settings.step),t.preventDefault();break;case Garnish.LEFT_KEY:"ltr"===Craft.orientation?this.setValue(this.value-this.settings.step):this.setValue(this.value+this.settings.step),t.preventDefault()}})},refresh:function(){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(let e=this.min;e<=this.max;e+=this.settings.step)this.$buttons=this.$buttons.add(t("<a/>",{title:this.settings.valueLabel(e),data:{value:e}}));if(this.$buttons.appendTo(this.$container),null!==this.value){let t=this.value;this.value=null,this.setValue(t,!1)}this.addListener(this.$buttons,"mouseover",e=>{this.$buttons.removeClass("active-hover last-active-hover"),t(e.currentTarget).addClass("active-hover last-active-hover").prevAll().addClass("active-hover")}),this.addListener(this.$buttons,"mouseout",()=>{this.$buttons.removeClass("active-hover")}),this.addListener(this.$buttons,"click",e=>{this.setValue(t.data(e.currentTarget,"value")),e.stopPropagation(),this.$container.focus()})},setValue:function(t,e){if(t=Math.max(Math.min(t,this.max),this.min),this.value===(this.value=t))return;this.$container.attr({"aria-valuenow":this.value,"aria-valuetext":this.settings.valueLabel(this.value)}),this.$buttons.removeClass("last-active active");let 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),Craft.SlideRuleInput=Garnish.Base.extend({$container:null,$options:null,$selectedOption:null,$input:null,value:null,startPositionX:null,init:function(e,i){this.setSettings(i,Craft.SlideRuleInput.defaultSettings),this.value=0,this.graduationsMin=-70,this.graduationsMax=70,this.slideMin=-45,this.slideMax=45,this.$container=t("#"+e),this.$overlay=t('<div class="overlay"></div>').appendTo(this.$container),this.$cursor=t('<div class="cursor"></div>').appendTo(this.$container),this.$graduations=t('<div class="graduations"></div>').appendTo(this.$container),this.$graduationsUl=t("<ul></ul>").appendTo(this.$graduations);for(var s=this.graduationsMin;s<=this.graduationsMax;s++){var a=t('<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",t.proxy(this,"_handleResize")),this.addListener(this.$container,"tapstart",t.proxy(this,"_handleTapStart")),this.addListener(Garnish.$bod,"tapmove",t.proxy(this,"_handleTapMove")),this.addListener(Garnish.$bod,"tapend",t.proxy(this,"_handleTapEnd")),setTimeout(t.proxy((function(){this.graduationsCalculatedWidth=10*(this.$options.length-1),this.$graduationsUl.css("left",-this.graduationsCalculatedWidth/2+this.$container.width()/2)}),this),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(e){var i=this.valueToPosition(e);e<this.slideMin?(e=this.slideMin,i=this.valueToPosition(e)):e>this.slideMax&&(e=this.slideMax,i=this.valueToPosition(e)),this.$graduationsUl.css("left",i),e>=this.slideMin&&e<=this.slideMax&&(this.$options.removeClass("selected"),t.each(this.$options,(function(i,s){t(s).data("graduation")>0&&t(s).data("graduation")<=e&&t(s).addClass("selected"),t(s).data("graduation")<0&&t(s).data("graduation")>=e&&t(s).addClass("selected"),0==t(s).data("graduation")&&t(s).addClass("selected")}))),this.value=e},_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:t.noop,onChange:t.noop,onEnd:t.noop}}),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):""}}),Craft.Structure=Garnish.Base.extend({id:null,$container:null,state:null,structureDrag:null,init:function(e,i,s){this.id=e,this.$container=t(i),this.setSettings(s,Craft.Structure.defaults),this.$container.data("structure")&&(Garnish.log("Double-instantiating a structure on an element"),this.$container.data("structure").destroy()),this.$container.data("structure",this),this.state={},this.settings.storageKey&&t.extend(this.state,Craft.getLocalStorage(this.settings.storageKey,{})),void 0===this.state.collapsedElementIds&&(this.state.collapsedElementIds=[]);for(var a=this.$container.find("ul").prev(".row"),n=0;n<a.length;n++){var r=t(a[n]),o=r.parent(),l=t('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(r);-1!==t.inArray(r.children(".element").data("id"),this.state.collapsedElementIds)&&o.addClass("collapsed"),this.initToggle(l)}this.settings.sortable&&(this.structureDrag=new Craft.StructureDrag(this,this.settings.maxLevels)),this.settings.newChildUrl&&this.initNewChildMenus(this.$container.find(".add"))},initToggle:function(e){e.on("click",t.proxy((function(e){var i=t(e.currentTarget).closest("li"),s=i.children(".row").find(".element:first").data("id"),a=t.inArray(s,this.state.collapsedElementIds);i.hasClass("collapsed")?(i.removeClass("collapsed"),-1!==a&&this.state.collapsedElementIds.splice(a,1)):(i.addClass("collapsed"),-1===a&&this.state.collapsedElementIds.push(s)),this.settings.storageKey&&Craft.setLocalStorage(this.settings.storageKey,this.state)}),this))},initNewChildMenus:function(t){this.addListener(t,"click","onNewChildMenuClick")},onNewChildMenuClick:function(e){var i=t(e.currentTarget);if(!i.data("menubtn")){var s=i.parent().children(".element").data("id"),a=Craft.getUrl(this.settings.newChildUrl,"parentId="+s);t('<div class="menu"><ul><li><a href="'+a+'">'+Craft.t("app","New child")+"</a></li></ul></div>").insertAfter(i),new Garnish.MenuBtn(i).showMenu()}},getIndent:function(t){return Craft.Structure.baseIndent+(t-1)*Craft.Structure.nestedIndent},addElement:function(e){var i=t('<li data-level="1"/>').appendTo(this.$container),s=t('<div class="row" style="margin-'+Craft.left+": -"+Craft.Structure.baseIndent+"px; padding-"+Craft.left+": "+Craft.Structure.baseIndent+'px;">').appendTo(i);if(s.append(e),this.settings.sortable&&(s.append('<a class="move icon" title="'+Craft.t("app","Move")+'"></a>'),this.structureDrag.addItems(i)),this.settings.newChildUrl){var a=t('<a class="add icon" title="'+Craft.t("app","New child")+'"></a>').appendTo(s);this.initNewChildMenus(a)}s.css("margin-bottom",-30),s.velocity({"margin-bottom":0},"fast")},removeElement:function(e){var i,s=e.parent().parent();this.settings.sortable&&this.structureDrag.removeItems(s),s.siblings().length||(i=s.parent()),s.css("visibility","hidden").velocity({marginBottom:-s.height()},"fast",t.proxy((function(){s.remove(),void 0!==i&&this._removeUl(i)}),this))},_removeUl:function(t){t.siblings(".row").children(".toggle").remove(),t.remove()}},{baseIndent:8,nestedIndent:35,defaults:{storageKey:null,sortable:!1,newChildUrl:null,maxLevels:null}}),Craft.StructureDrag=Garnish.Drag.extend({structure:null,maxLevels:null,draggeeLevel:null,$helperLi:null,$targets:null,draggeeHeight:null,init:function(e,i){this.structure=e,this.maxLevels=i,this.$insertion=t('<li class="draginsertion"/>');var s=this.structure.$container.find("li");this.base(s,{handle:".element:first, .move:first",helper:t.proxy(this,"getHelper")})},getHelper:function(e){this.$helperLi=e;var i=t('<ul class="structure draghelper"/>').append(e);return e.css("padding-"+Craft.left,this.$draggee.css("padding-"+Craft.left)),e.find(".move").removeAttr("title"),i},onDragStart:function(){this.$targets=t(),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",t.proxy((function(){this.$draggee.addClass("hidden")}),this)),this.base(),this.addListener(Garnish.$doc,"keydown",(function(t){t.keyCode===Garnish.ESC_KEY&&this.cancelDrag()}))},findTargets:function(e){for(var i=e.children().not(this.$draggee),s=0;s<i.length;s++){var a=t(i[s]);this.$targets=this.$targets.add(a.children(".row")),a.hasClass("collapsed")||this.findTargets(a.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=t(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=t(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=t(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(){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===t.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=t('<div class="toggle" title="'+Craft.t("app","Show/hide children")+'"/>').prependTo(this._.$closestTarget);this.structure.initToggle(n),a=t("<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",t.proxy((function(){this.$draggee.css("height","auto")}),this)),this.returnHelpersToDraggees(),this.base()},setLevel:function(e,i){e.data("level",i);var s=this.structure.getIndent(i),a={};a["margin-"+Craft.left]="-"+s+"px",a["padding-"+Craft.left]=s+"px",this.$draggee.children(".row").css(a);for(var n=e.children("ul").children(),r=0;r<n.length;r++)this.setLevel(t(n[r]),i+1)}}),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,_updateAncestorsProxy:null,_draggeeLevel:null,_draggeeLevelDelta:null,draggingLastElements:null,_loadingDraggeeLevelDelta:!1,_targetLevel:null,_targetLevelBounds:null,_positionChanged:null,init:function(e,i,s){this.tableView=e,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,s=t.extend({},Craft.StructureTableSorter.defaults,s,{handle:".move",collapseDraggees:!0,singleHelper:!0,helperSpacingY:2,magnetStrength:4,helper:t.proxy(this,"getHelper"),helperLagBase:1.5,axis:Garnish.Y_AXIS}),this.base(i,s)},findDraggee:function(){this._draggeeLevel=this._targetLevel=this.$targetItem.data("level"),this._draggeeLevelDelta=0;for(var e=t(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,t.proxy((function(t,e){"success"===e&&(this._loadingDraggeeLevelDelta=!1,this.dragging&&(this._draggeeLevelDelta=t.delta,this.drag(!1)))}),this))}return e},getHelper:function(e){var i=t('<div class="elements datatablesorthelper"/>').appendTo(Garnish.$bod),s=t('<div class="tableview"/>').appendTo(i),a=t('<table class="data"/>').appendTo(s),n=t("<tbody/>").appendTo(a);e.appendTo(n),this._$firstRowCells=this.tableView.$elementContainer.children("tr:first").children();for(var r=e.children(),o=0;o<r.length;o++){var l=t(r[o]);if(l.hasClass("checkbox-cell"))l.remove();else{var h=t(this._$firstRowCells[o]),d=h[0].getBoundingClientRect().width;if(h.css("width",d+"px"),l.css("width",d+"px"),Garnish.hasAttr(h,"data-titlecell")){this._$titleHelperCell=l;parseInt(h.css("padding-"+Craft.left));this._titleHelperCellOuterWidth=d,l.css("padding-"+Craft.left,this._basePadding)}}}return i},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(){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=t(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,t.proxy((function(t,e){if("success"===e){if(!t.success)return Craft.cp.displayError(Craft.t("app","A server error occurred.")),void this.tableView.elementIndex.updateElements();Craft.cp.displayNotice(Craft.t("app","New position saved.")),this.onPositionChange(),d&&d.parent().length&&(d.remove(),this.tableView._expandElement(h,!0)),Craft.cp.runQueue()}}),this))}},onSortChange:function(){this.tableView.elementSelect&&this.tableView.elementSelect.resetItemOrder(),this._positionChanged=!0,this.base()},onPositionChange:function(){Garnish.requestAnimationFrame(t.proxy((function(){this.trigger("positionChange"),this.settings.onPositionChange()}),this))},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._updateAncestorsProxy||(this._updateAncestorsProxy=t.proxy(this,"_updateAncestors")),this._updateAncestorsFrame=Garnish.requestAnimationFrame(this._updateAncestorsProxy)},_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")&&t('<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:t.noop}}),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(),{onSortChange:t.proxy(this,"_onStructureTableSortChange")}):this.structureTableSort=null,"structure"===this.elementIndex.getSelectedSortAttribute()&&this.addListener(this.$elementContainer,"click",(function(e){var i=t(e.target);i.hasClass("toggle")&&!1===this._collapseElement(i)&&this._expandElement(i)}))},initTableHeaders:function(){for(var e=this.elementIndex.getSelectedSortAttribute(),i=this.$table.children("thead").children().children("[data-attribute]"),s=0;s<i.length;s++){var a=i.eq(s),n=a.attr("data-attribute");if(n===e){this.$selectedSortHeader=a;var r=this.elementIndex.getSelectedSortDirection();a.addClass("ordered "+r).on("click",t.proxy(this,"_handleSelectedSortHeaderClick"))}else{this.elementIndex.getSortAttributeOption(n).length&&a.addClass("orderable").on("click",t.proxy(this,"_handleUnselectedSortHeaderClick"))}}},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(e){Craft.createElementEditor(e.data("type"),e,{params:{includeTableAttributesForSource:this.elementIndex.sourceKey},onSaveElement:t.proxy((function(t){t.tableAttributes&&this._updateTableAttributes(e,t.tableAttributes)}),this),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(e,i){if(!i&&e.hasClass("expanded"))return!1;if(e.addClass("expanded"),this.elementIndex.instanceState.collapsedElementIds){var s=e.parent().parent(),a=s.data("id"),n=t.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=t.extend(!0,{},this.settings.params);o.criteria.descendantOf=a,Craft.postActionRequest("element-indexes/get-more-elements",o,t.proxy((function(e,i){if(r.parent().length&&"success"===i){var s=t(e.html),a=this._totalVisible+s.length,n=this.settings.batchSize&&s.length===this.settings.batchSize;if(n){var o=r.nextAll();this.elementSelect&&this.elementSelect.removeItems(o),this.structureTableSort&&this.structureTableSort.removeItems(o),o.remove(),a-=o.length}else n=this._morePending;r.replaceWith(s),this.thumbLoader.load(s),(this.elementIndex.actions||this.settings.selectable)&&(this.elementSelect.addItems(s.filter(":not(.disabled)")),this.elementIndex.updateActionTriggers()),this.structureTableSort&&this.structureTableSort.addItems(s),Craft.appendHeadHtml(e.headHtml),Craft.appendFootHtml(e.footHtml),Craft.cp.updateResponsiveTables(),this.setTotalVisible(a),this.setMorePending(n),this.maybeLoadMore()}}),this))}}},_createSpinnerRowAfter:function(e){return t('<tr data-spinnerrow><td class="centeralign" colspan="'+e.children().length+'"><div class="spinner"/></td></tr>').insertAfter(e)},_isStructureTableDraggingLastElements:function(){return this.structureTableSort&&this.structureTableSort.dragging&&this.structureTableSort.draggingLastElements},_handleSelectedSortHeaderClick:function(e){var i=t(e.currentTarget);if(!i.hasClass("loading")){var s="asc"===this.elementIndex.getSelectedSortDirection()?"desc":"asc";this.elementIndex.setSortDirection(s),this._handleSortHeaderClick(e,i)}},_handleUnselectedSortHeaderClick:function(e){var i=t(e.currentTarget);if(!i.hasClass("loading")){var s=i.attr("data-attribute");this.elementIndex.setSortAttribute(s),this._handleSortHeaderClick(e,i)}},_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])}}),Craft.TagSelectInput=Craft.BaseElementSelectInput.extend({searchTimeout:null,searchMenu:null,$container:null,$elementsContainer:null,$elements:null,$addTagInput:null,$spinner:null,_ignoreBlur:!1,init:function(e){if(!t.isPlainObject(e)){for(var i={},s=["id","name","tagGroupId","sourceElementId"],a=0;a<s.length&&void 0!==arguments[a];a++)i[s[a]]=arguments[a];e=i}this.base(t.extend({},Craft.TagSelectInput.defaults,e)),this.$addTagInput=this.$container.children(".add").children(".text"),this.$spinner=this.$addTagInput.next(),this.addListener(this.$addTagInput,"input",t.proxy((function(){this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout(t.proxy(this,"searchForTags"),500)}),this)),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){let t=this.searchMenu.$options.filter(".hover");if(t.length){let e=t.parent().nextAll().find("a:not(.disabled)").first();e.length&&this.focusOption(e)}else this.focusOption(this.searchMenu.$options.eq(0))}return;case Garnish.UP_KEY:if(t.preventDefault(),this.searchMenu){let t=this.searchMenu.$options.filter(".hover");if(t.length){let e=t.parent().prevAll().find("a:not(.disabled)").last();e.length&&this.focusOption(e)}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(){this._ignoreBlur?this._ignoreBlur=!1:setTimeout(t.proxy((function(){this.searchMenu&&this.searchMenu.hide()}),this),1)}))},focusOption:function(t){this.searchMenu.$options.removeClass("hover"),t.addClass("hover"),this.searchMenu.$menuList.attr("aria-activedescendant",t.attr("id"))},getAddElementsBtn:t.noop,getElementSortAxis:function(){return null},searchForTags:function(){if(this.searchMenu&&this.killSearchMenu(),this.$addTagInput.val()){this.$spinner.removeClass("hidden");for(var e=[],i=0;i<this.$elements.length;i++){var s=t(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,t.proxy((function(e,i){if(this.searchMenu&&this.killSearchMenu(),this.$spinner.addClass("hidden"),"success"===i){for(var s,n=t('<div class="menu tagmenu"/>').appendTo(Garnish.$bod),r=t("<ul/>").appendTo(n),o=0;o<e.tags.length;o++)s=t("<li/>").appendTo(r),t('<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=t("<li/>").appendTo(r),t('<a data-icon="plus"/>').appendTo(s).text(a.search)),r.find("a:not(.disabled):first").addClass("hover"),this.searchMenu=new Garnish.Menu(n,{attachToElement:this.$addTagInput,onOptionSelect:t.proxy(this,"selectTag")}),this.addListener(n,"mousedown",t.proxy((function(){this._ignoreBlur=!0}),this)),this.searchMenu.show()}}),this))}else this.$spinner.addClass("hidden")},selectTag:function(e){var i=t(e);if(!i.hasClass("disabled")){var s=i.data("id"),a=i.text(),n=t("<div/>",{class:"element small removable","data-id":s,"data-site-id":this.settings.targetSiteId,"data-label":a,"data-editable":"1"}).appendTo(this.$elementsContainer),r=t("<input/>",{type:"hidden",name:this.settings.name+"[]",value:s}).appendTo(n);t("<a/>",{class:"delete icon",title:Craft.t("app","Remove")}).appendTo(n);var o=t("<div/>",{class:"label"}).appendTo(n);t("<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,t.proxy((function(t,e){"success"===e&&t.success?(n.attr("data-id",t.id),r.val(t.id),n.removeClass("loading disabled")):(this.removeElement(n),"success"===e&&Craft.cp.displayError(Craft.t("app","A server error occurred.")))}),this))}}},killSearchMenu:function(){this.searchMenu.hide(),this.searchMenu.destroy(),this.searchMenu=null}},{defaults:{tagGroupId:null}}),Craft.ThumbsElementIndexView=Craft.BaseElementIndexView.extend({getElementContainer:function(){return this.$container.children("ul")}}),Craft.ui={createTextInput:function(e){e=t.extend({autocomplete:!1},e);var i=t("<input/>",{attr:{class:"text",type:e.type||"text",inputmode:e.inputmode,id:e.id,size:e.size,name:e.name,value:e.value,maxlength:e.maxlength,autofocus:this.getAutofocusValue(e.autofocus),autocomplete:"boolean"==typeof e.autocomplete?e.autocomplete?"on":"off":e.autocomplete,disabled:this.getDisabledValue(e.disabled),readonly:e.readonly,title:e.title,placeholder:e.placeholder,step:e.step,min:e.min,max:e.max}});return e.class&&i.addClass(e.class),e.placeholder&&i.addClass("nicetext"),"password"===e.type&&i.addClass("password"),e.disabled&&i.addClass("disabled"),e.size||i.addClass("fullwidth"),e.showCharsLeft&&e.maxlength&&i.attr("data-show-chars-left").css("padding-"+("ltr"===Craft.orientation?"right":"left"),7.2*e.maxlength.toString().length+14+"px"),(e.placeholder||e.showCharsLeft)&&new Garnish.NiceText(i),"password"===e.type?t('<div class="passwordwrapper"/>').append(i):i},createTextField:function(t){return t.id||(t.id="text"+Math.floor(1e9*Math.random())),this.createField(this.createTextInput(t),t)},createCopyTextInput:function(e){let i=e.id||"copytext"+Math.floor(1e9*Math.random()),s=e.buttonId||i+"-btn",a=t("<div/>",{class:"copytext"}),n=this.createTextInput(t.extend({},e,{readonly:!0})).appendTo(a);return t("<button/>",{type:"button",id:s,class:"btn","data-icon":"clipboard",title:Craft.t("app","Copy to clipboard"),"aria-label":Craft.t("app","Copy to clipboard")}).appendTo(a).on("click",()=>{n[0].select(),document.execCommand("copy"),Craft.cp.displayNotice(Craft.t("app","Copied to clipboard.")),a.trigger("copy"),n[0].setSelectionRange(0,0)}),a},createCopyTextField:function(t){return t.id||(t.id="copytext"+Math.floor(1e9*Math.random())),this.createField(this.createCopyTextInput(t),t)},createCopyTextPrompt:function(e){let i=t("<div/>",{class:"modal fitted"}),s=t("<div/>",{class:"body"}).appendTo(i);this.createCopyTextField(t.extend({size:Math.max(Math.min(e.value.length,50),25)},e)).appendTo(s);let a=new Garnish.Modal(i,{closeOtherModals:!1});return i.on("copy",()=>{a.hide()}),i},createTextarea:function(e){var i=t("<textarea/>",{class:"text",rows:e.rows||2,cols:e.cols||50,id:e.id,name:e.name,maxlength:e.maxlength,autofocus:e.autofocus&&!Garnish.isMobileBrowser(!0),disabled:!!e.disabled,placeholder:e.placeholder,html:e.value});return e.showCharsLeft&&i.attr("data-show-chars-left",""),e.class&&i.addClass(e.class),e.size||i.addClass("fullwidth"),i},createTextareaField:function(t){return t.id||(t.id="textarea"+Math.floor(1e9*Math.random())),this.createField(this.createTextarea(t),t)},createSelect:function(e){var i=t("<div/>",{class:"select"});e.class&&i.addClass(e.class);var s=t("<select/>",{id:e.id,name:e.name,autofocus:e.autofocus&&Garnish.isMobileBrowser(!0),disabled:e.disabled,"data-target-prefix":e.targetPrefix}).appendTo(i);if(t.isPlainObject(e.options)){let i=[];for(var a in e.options){if(!e.options.hasOwnProperty(a))continue;let s=e.options[a];t.isPlainObject(s)?void 0!==s.optgroup?i.push(s):i.push({label:s.label,value:void 0!==s.value?s.value:a,disabled:void 0!==s.disabled&&s.disabled}):i.push({label:s,value:a})}e.options=i}var n=null;for(let i=0;i<e.options.length;i++){let a=e.options[i];void 0!==a.optgroup?n=t("<optgroup/>",{label:a.label}).appendTo(s):t("<option/>",{value:a.value,selected:a.value==e.value,disabled:void 0!==a.disabled&&a.disabled,html:a.label}).appendTo(n||s)}return e.toggle&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s)),i},createSelectField:function(t){return t.id||(t.id="select"+Math.floor(1e9*Math.random())),this.createField(this.createSelect(t),t)},createCheckbox:function(e){var i=e.id||"checkbox"+Math.floor(1e9*Math.random()),s=t("<input/>",{type:"checkbox",value:void 0!==e.value?e.value:"1",id:i,class:"checkbox",name:e.name,checked:e.checked?"checked":null,autofocus:this.getAutofocusValue(e.autofocus),disabled:this.getDisabledValue(e.disabled),"data-target":e.toggle,"data-reverse-target":e.reverseToggle});e.class&&s.addClass(e.class),(e.toggle||e.reverseToggle)&&(s.addClass("fieldtoggle"),new Craft.FieldToggle(s));var a=t("<label/>",{for:i,html:e.label});return e.name&&(e.name.length<3||"[]"!==e.name.substr(-2))?t([t("<input/>",{type:"hidden",name:e.name,value:""})[0],s[0],a[0]]):t([s[0],a[0]])},createCheckboxField:function(e){e.id||(e.id="checkbox"+Math.floor(1e9*Math.random()));var i=t('<div class="field checkboxfield"/>',{id:e.id+"-field"});return e.first&&i.addClass("first"),e.instructions&&i.addClass("has-instructions"),this.createCheckbox(e).appendTo(i),e.instructions&&t('<div class="instructions"/>').text(e.instructions).appendTo(i),i},createCheckboxSelect:function(e){var i,s,a=t('<fieldset class="checkbox-select"/>');e.class&&a.addClass(e.class),e.showAllOption?(i=e.allValue||"*",s=e.values==i,t("<div/>").appendTo(a).append(this.createCheckbox({id:e.id,class:"all",label:"<b>"+(e.allLabel||Craft.t("app","All"))+"</b>",name:e.name,value:i,checked:s,autofocus:e.autofocus}))):s=!1;for(var n=0;n<e.options.length;n++){var r=e.options[n];r.value!=i&&t("<div/>").appendTo(a).append(this.createCheckbox({label:r.label,name:e.name?e.name+"[]":null,value:r.value,checked:s||(e.values||[]).includes(r.value),disabled:s}))}return new Garnish.CheckboxSelect(a),a},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(e){var i=e.value||"1",s=e.indeterminateValue||"-",a=t("<button/>",{type:"button",class:"lightswitch","data-value":i,"data-indeterminate-value":s,id:e.id,role:"checkbox","aria-checked":e.on?"true":e.indeterminate?"mixed":"false","aria-labelledby":e.labelId,"data-target":e.toggle,"data-reverse-target":e.reverseToggle});return e.on?a.addClass("on"):e.indeterminate&&a.addClass("indeterminate"),e.small&&a.addClass("small"),e.disabled&&a.addClass("disabled"),t('<div class="lightswitch-container"><div class="handle"></div></div>').appendTo(a),e.name&&t("<input/>",{type:"hidden",name:e.name,value:e.on?i:e.indeterminate?s:"",disabled:e.disabled}).appendTo(a),(e.toggle||e.reverseToggle)&&(a.addClass("fieldtoggle"),new Craft.FieldToggle(a)),new Craft.LightSwitch(a,{onChange:e.onChange||t.noop}),a},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(e){var i=e.id||"color"+Math.floor(1e9*Math.random()),s=e.containerId||i+"-container",a=e.name||null,n=e.value||null,r=e.small||!1,o=e.autofocus&&Garnish.isMobileBrowser(!0),l=e.disabled||!1,h=t("<div/>",{id:s,class:"flex color-container"}),d=t("<div/>",{class:"color static"+(r?" small":"")}).appendTo(h);t("<div/>",{class:"color-preview",style:e.value?{backgroundColor:e.value}:null}).appendTo(d),this.createTextInput({id:i,name:a,value:n,size:10,class:"color-input",autofocus:o,disabled:l}).appendTo(h);return new Craft.ColorInput(h),h},createColorField:function(t){return t.id||(t.id="color"+Math.floor(1e9*Math.random())),this.createField(this.createColorInput(t),t)},createDateInput:function(e){var i=(e.id||"date"+Math.floor(1e9*Math.random()))+"-date",s=e.name||null,a=s?s+"[date]":null,n=e.value&&"function"==typeof e.value.getMonth?e.value:null,r=n?Craft.formatDate(n):null,o=e.autofocus&&Garnish.isMobileBrowser(!0),l=e.disabled||!1,h=t("<div/>",{class:"datewrapper"}),d=this.createTextInput({id:i,name:a,value:r,placeholder:" ",autocomplete:!1,autofocus:o,disabled:l}).appendTo(h);return t('<div data-icon="date"></div>').appendTo(h),s&&t("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(h),d.datepicker(t.extend({defaultDate:n||new Date},Craft.datepickerOptions)),h},createDateField:function(t){return t.id||(t.id="date"+Math.floor(1e9*Math.random())),this.createField(this.createDateInput(t),t)},createDateRangePicker:function(e){var i=new Date,s=new Date(i.getFullYear(),i.getMonth(),i.getDate());e=t.extend({class:"",options:["today","thisWeek","thisMonth","thisYear","past7Days","past30Days","past90Days","pastYear"],onChange:t.noop,selected:null,startDate:null,endDate:null},e);var a,n,r=t("<div/>",{class:"menu"}),o=t("<ul/>",{class:"padded"}).appendTo(r),l=t("<a/>").addClass("sel").text(Craft.t("app","All")).data("handle","all");t("<li/>").append(l).appendTo(o);for(var h=0;h<e.options.length;h++){var d=e.options[h];switch(d){case"today":a={label:Craft.t("app","Today"),startDate:s,endDate:s};break;case"thisWeek":var c=i.getDay()-Craft.datepickerOptions.firstDay;c<0&&(c+=7),a={label:Craft.t("app","This week"),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-c),endDate:s};break;case"thisMonth":a={label:Craft.t("app","This month"),startDate:new Date(i.getFullYear(),i.getMonth()),endDate:s};break;case"thisYear":a={label:Craft.t("app","This year"),startDate:new Date(i.getFullYear(),0),endDate:s};break;case"past7Days":a={label:Craft.t("app","Past {num} days",{num:7}),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-7),endDate:s};break;case"past30Days":a={label:Craft.t("app","Past {num} days",{num:30}),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-30),endDate:s};break;case"past90Days":a={label:Craft.t("app","Past {num} days",{num:90}),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-90),endDate:s};break;case"pastYear":a={label:Craft.t("app","Past year"),startDate:new Date(i.getFullYear(),i.getMonth(),i.getDate()-365),endDate:s}}var u=t("<li/>"),p=t("<a/>",{text:a.label}).data("handle",d).data("startDate",a.startDate).data("endDate",a.endDate).data("startTime",a.startDate?a.startDate.getTime():null).data("endTime",a.endDate?a.endDate.getTime():null);e.selected&&d==e.selected&&(n=p[0]),u.append(p),u.appendTo(o)}t("<hr/>").appendTo(r);var g=t("<div/>",{class:"flex flex-nowrap padded"}).appendTo(r),f=this.createDateField({label:Craft.t("app","From")}).appendTo(g).find("input"),m=this.createDateField({label:Craft.t("app","To")}).appendTo(g).find("input"),v=f.add(m);v.on("keyup",(function(e){e.keyCode===Garnish.ESC_KEY&&t(this).data("datepicker").dpDiv.is(":visible")&&e.stopPropagation()})),f.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()})),m.data("datepicker").dpDiv.on("mousedown",(function(t){t.stopPropagation()}));var C=new Garnish.Menu(r,{onOptionSelect:function(i){var s=t(i);_.text(s.text()),C.setPositionRelativeToAnchor(),r.find(".sel").removeClass("sel"),s.addClass("sel"),f.datepicker("setDate",s.data("startDate")),m.datepicker("setDate",s.data("endDate")),e.onChange(s.data("startDate")||null,s.data("endDate")||null,s.data("handle"))}});v.on("change",(function(){let t,i=f.datepicker("getDate"),s=m.datepicker("getDate"),a=i?i.getTime():null,n=s?s.getTime():null,l=o.find("a"),h=!1;for(let i=0;i<l.length;i++)if(t=l.eq(i),a===(t.data("startTime")||null)&&n===(t.data("endTime")||null)){C.selectOption(t[0]),h=!0,e.onChange(null,null,t.data("handle"));break}h||(r.find(".sel").removeClass("sel"),g.addClass("sel"),a||n?a&&n?_.text(f.val()+" - "+m.val()):a?_.text(Craft.t("app","From {date}",{date:f.val()})):_.text(Craft.t("app","To {date}",{date:m.val()})):_.text(Craft.t("app","All")),C.setPositionRelativeToAnchor(),e.onChange(i,s,"custom"))})),C.on("hide",(function(){f.datepicker("hide"),m.datepicker("hide")}));let b="btn menubtn";e.class&&(b=b+" "+e.class);let _=t("<button/>",{type:"button",class:b,"data-icon":"date",text:Craft.t("app","All")});return new Garnish.MenuBtn(_,C),n&&C.selectOption(n),e.startDate&&f.datepicker("setDate",e.startDate),e.endDate&&m.datepicker("setDate",e.endDate),(e.startDate||e.endDate)&&v.trigger("change"),_},createTimeInput:function(e){var i=(e.id||"time"+Math.floor(1e9*Math.random()))+"-time",s=e.name||null,a=s?s+"[time]":null,n=e.value&&"function"==typeof e.value.getMonth?e.value:null,r=e.autofocus&&Garnish.isMobileBrowser(!0),o=e.disabled||!1,l=t("<div/>",{class:"timewrapper"}),h=this.createTextInput({id:i,name:a,placeholder:" ",autocomplete:!1,autofocus:r,disabled:o}).appendTo(l);return t('<div data-icon="time"></div>').appendTo(l),s&&t("<input/>",{type:"hidden",name:s+"[timezone]",val:Craft.timezone}).appendTo(l),h.timepicker(Craft.timepickerOptions),n&&h.timepicker("setTime",3600*n.getHours()+60*n.getMinutes()+n.getSeconds()),l},createTimeField:function(t){return t.id||(t.id="time"+Math.floor(1e9*Math.random())),this.createField(this.createTimeInput(t),t)},createField:function(e,i){var s=i.label&&"__blank__"!==i.label?i.label:null,a=(Craft.isMultiSite&&i.siteId&&i.siteId,t(i.fieldset?"<fieldset/>":"<div/>",{class:"field",id:i.fieldId||(i.id?i.id+"-field":null)}));if(i.first&&a.addClass("first"),s){var n=t('<div class="heading"/>').appendTo(a);t(i.fieldset?"<legend/>":"<label/>",{id:i.labelId||(i.id?`${i.id}-${i.fieldset?"legend":"label"}`:null),class:i.required?"required":null,for:!i.fieldset&&i.id,text:s}).appendTo(n)}return i.instructions&&t('<div class="instructions"/>').text(i.instructions).appendTo(a),t('<div class="input"/>').append(e).appendTo(a),i.warning&&t('<p class="warning"/>').text(i.warning).appendTo(a),i.errors&&this.addErrorsToField(a,i.errors),a},createErrorList:function(e){var i=t('<ul class="errors"/>');return e&&this.addErrorsToList(i,e),i},addErrorsToList:function(e,i){for(var s=0;s<i.length;s++)t("<li/>").text(i[s]).appendTo(e)},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}},Craft.Uploader=Garnish.Base.extend({uploader:null,allowedKinds:null,$element:null,settings:null,_rejectedFiles:{},_extensionList:null,_totalFileCounter:0,_validFileCounter:0,init:function(e,i){this._rejectedFiles={size:[],type:[],limit:[]},this.$element=e,this.allowedKinds=null,this._extensionList=null,this._totalFileCounter=0,this._validFileCounter=0;var s=(i=t.extend({},Craft.Uploader.defaults,i)).events;for(var a in delete i.events,i.allowedKinds&&i.allowedKinds.length&&("string"==typeof i.allowedKinds&&(i.allowedKinds=[i.allowedKinds]),this.allowedKinds=i.allowedKinds,delete i.allowedKinds),i.autoUpload=!1,this.uploader=this.$element.fileupload(i),s)s.hasOwnProperty(a)&&this.uploader.on(a,s[a]);this.settings=i,this.uploader.on("fileuploadadd",t.proxy(this,"onFileAdd"))},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(e,i){e.stopPropagation();var s=!1;return this.allowedKinds&&(this._extensionList||this._createExtensionList(),s=!0),i.process().done(t.proxy((function(){var e=i.files[0],a=!0;if(s){var n=e.name.match(/\.([a-z0-4_]+)$/i)[1];-1===t.inArray(n.toLowerCase(),this._extensionList)&&(a=!1,this._rejectedFiles.type.push("“"+e.name+"”"))}e.size>this.settings.maxFileSize&&(this._rejectedFiles.size.push("“"+e.name+"”"),a=!1),a&&"function"==typeof this.settings.canAddMoreFiles&&!this.settings.canAddMoreFiles(this._validFileCounter)&&(this._rejectedFiles.limit.push("“"+e.name+"”"),a=!1),a&&(this._validFileCounter++,i.submit()),++this._totalFileCounter===i.originalFiles.length&&(this._totalFileCounter=0,this._validFileCounter=0,this.processErrorMessages())}),this)),!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){if(t<1024)return t+" B";var e=-1;do{t/=1024,++e}while(t>=1024);return t.toFixed(1)+" "+["kB","MB","GB","TB","PB","EB","ZB","YB"][e]},_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"}}),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}})}(jQuery);
//# sourceMappingURL=Craft.min.js.map