/*
* 
* Copyright (C) 2024 MODX LLC
* 
* This file is part of MODX Revolution and was compiled using Grunt.
* 
* MODX Revolution is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
* 
* MODX Revolution is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* 
* See the GNU General Public License for more details. You should have received a copy of the GNU
* General Public License along with MODX Revolution. If not, see <http://www.gnu.org/licenses/>.
* 
*/

Ext.onReady((function(){if("en"==MODx.config.cultureKey)return!1;Date.dayNames=[_("sunday"),_("monday"),_("tuesday"),_("wednesday"),_("thursday"),_("friday"),_("saturday")],Date.monthNames=[_("january"),_("february"),_("march"),_("april"),_("may"),_("june"),_("july"),_("august"),_("september"),_("october"),_("november"),_("december")],Ext.apply(Ext.grid.GridView.prototype,{sortAscText:_("ext_sortasc"),sortDescText:_("ext_sortdesc"),lockText:_("ext_column_lock"),unlockText:_("ext_column_unlock"),columnsText:_("ext_columns"),emptyText:_("ext_emptymsg")}),Ext.apply(Ext.DatePicker.prototype,{todayText:_("today"),todayTip:_("ext_today_tip"),minText:_("ext_mindate"),maxText:_("ext_maxdate"),monthNames:Date.monthNames,dayNames:Date.dayNames,nextText:_("ext_nextmonth"),prevText:_("ext_prevmonth"),monthYearText:_("ext_choosemonth")}),Ext.MessageBox.buttonText={yes:_("yes"),no:_("no"),ok:_("ok"),cancel:_("cancel")},Ext.apply(Ext.PagingToolbar.prototype,{afterPageText:_("ext_afterpage"),beforePageText:_("ext_beforepage"),displayMsg:_("ext_displaying"),emptyMsg:_("ext_emptymsg"),firstText:_("ext_first"),prevText:_("ext_prev"),nextText:_("ext_next"),lastText:_("ext_last"),refreshText:_("ext_refresh")}),Ext.apply(Ext.Updater.prototype,{text:_("loading")}),Ext.apply(Ext.LoadMask.prototype,{msg:_("loading")}),Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype,{splitTip:_("ext_splittip")}),Ext.apply(Ext.form.BasicForm.prototype,{waitTitle:_("please_wait")}),Ext.apply(Ext.form.ComboBox.prototype,{loadingText:_("loading")}),Ext.apply(Ext.form.Field.prototype,{invalidText:_("ext_invalidfield")}),Ext.apply(Ext.form.TextField.prototype,{minLengthText:_("ext_minlenfield"),maxLengthText:_("ext_maxlenfield"),invalidText:_("ext_invalidfield"),blankText:_("field_required")}),Ext.apply(Ext.form.NumberField.prototype,{minText:_("ext_minvalfield"),maxText:_("ext_maxvalfield"),nanText:_("ext_nanfield")}),Ext.apply(Ext.form.DateField.prototype,{disabledDaysText:_("disabled"),disabledDatesText:_("disabled"),minText:_("ext_datemin"),maxText:_("ext_datemax"),invalidText:_("ext_dateinv")}),Ext.apply(Ext.form.VTypes,{emailText:_("ext_inv_email"),urlText:_("ext_inv_url"),alphaText:_("ext_inv_alpha"),alphanumText:_("ext_inv_alphanum")}),Ext.apply(Ext.grid.GroupingView.prototype,{emptyGroupText:_("ext_emptygroup"),groupByText:_("ext_groupby"),showGroupsText:_("ext_showgroups")}),Ext.apply(Ext.grid.PropertyColumnModel.prototype,{nameText:_("name"),valueText:_("value")}),Ext.apply(Ext.form.CheckboxGroup.prototype,{blankText:_("ext_checkboxinv")}),Ext.apply(Ext.form.RadioGroup.prototype,{blankText:_("ext_checkboxinv")}),Ext.apply(Ext.form.TimeField.prototype,{minText:_("ext_timemin"),maxText:_("ext_timemax"),invalidText:_("ext_timeinv")})})),Ext.namespace("MODx.util.Progress"),Ext.namespace("MODx.util.Format"),MODx.util.JSONReader=function(config){config=config||{},Ext.applyIf(config,{successProperty:"success",totalProperty:"total",root:"data"}),MODx.util.JSONReader.superclass.constructor.call(this,config,["id","msg"])},Ext.extend(MODx.util.JSONReader,Ext.data.JsonReader),Ext.reg("modx-json-reader",MODx.util.JSONReader),MODx.util.Progress={id:0,time:function(v,id,msg){msg=msg||_("saving"),MODx.util.Progress.id===id&&v<11&&Ext.MessageBox.updateProgress(v/10,msg)},reset:function(){MODx.util.Progress.id=MODx.util.Progress.id+1}},MODx.util.UrlParams={get(){return this.parse(window.location.search)},set(data){const params=decodeURIComponent(new URLSearchParams(data).toString());params.length?window.history.pushState(params,"",document.location.pathname+"?"+params):window.history.pushState("","",document.location.pathname)},add(key,val){const params=this.get();params[key]=val,this.set(params)},remove(key){const params=this.get();delete params[key],this.set(params)},clear(){this.set({})},parse(str){const params=new URLSearchParams(str);return Object.fromEntries(params.entries())}},MODx.LockMask=function(config){config=config||{},Ext.applyIf(config,{msg:_("locked"),msgCls:"modx-lockmask"}),MODx.LockMask.superclass.constructor.call(this,config.el,config)},Ext.extend(MODx.LockMask,Ext.LoadMask,{locked:!1,toggle:function(){this.locked?(this.hide(),this.locked=!1):(this.show(),this.locked=!0)},lock:function(){this.locked=!0,this.show()},unlock:function(){this.locked=!1,this.hide()}}),Ext.reg("modx-lockmask",MODx.LockMask),Ext.override(Ext.form.NumberField,{strictDecimalPrecision:!1,fixPrecision:function(value){var nan=isNaN(value);return this.allowDecimals&&-1!=this.decimalPrecision&&!nan&&value?this.allowDecimals&&this.strictDecimalPrecision?parseFloat(value).toFixed(this.decimalPrecision):parseFloat(parseFloat(value).toFixed(this.decimalPrecision)):nan?"":value}}),Ext.override(Ext.form.BasicForm,{clearDirty:function(nodeToRecurse){(nodeToRecurse=nodeToRecurse||this)?.items?.each?.((function(f){f.getValue&&(f.items?this.clearDirty(f):f.originalValue!=f.getValue()&&(f.originalValue=f.getValue()))}),this)}}),MODx.StaticTextField=Ext.extend(Ext.form.TextField,{fieldClass:"x-static-text-field",onRender:function(){this.readOnly=!0,this.disabled=!this.initialConfig.submitValue,MODx.StaticTextField.superclass.onRender.apply(this,arguments)}}),Ext.reg("statictextfield",MODx.StaticTextField),MODx.StaticBoolean=Ext.extend(Ext.form.TextField,{fieldClass:"x-static-text-field",onRender:function(tf){this.readOnly=!0,this.disabled=!this.initialConfig.submitValue,MODx.StaticBoolean.superclass.onRender.apply(this,arguments),this.on("change",this.onChange,this)},setValue:function(v){1===v?(this.addClass("green"),v=_("yes")):(this.addClass("red"),v=_("no")),MODx.StaticBoolean.superclass.setValue.apply(this,arguments)}}),Ext.reg("staticboolean",MODx.StaticBoolean),MODx.util.safeHtml=function(input,allowedTags,allowedAttributes){var strip=function(input,allowedTags,allowedAttributes){return input.replace(tags,(function($0,$1){return allowedTags.indexOf("<"+$1.toLowerCase()+">")>-1?$0:""})).replace(attributes,(function($0,$1){return allowedAttributes.indexOf($1.toLowerCase()+",")>-1?$0:""}))};allowedTags=(((allowedTags||"<a><br><i><em><b><strong>")+"").toLowerCase().match(/<[a-z][a-z0-9]*>/g)||[]).join(""),allowedAttributes=(((allowedAttributes||"href,class")+"").toLowerCase().match(/[a-z\-,]*/g)||[]).join("").concat(",");var length,tags=/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,attributes=/([a-z][a-z0-9]*)\s*=\s*".*?"/gi;input=input.replace(/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi,"").replace(/href(\s*?=\s*?(["'])javascript:.*?\2|\s*?=\s*?javascript:.*?(?![^> ]))/gi,'href="javascript:void(0)"');do{length=input.length,input=strip(input,allowedTags,allowedAttributes)}while(length!==input.length);return input.replace(/on([a-z][a-z0-9]*\s*=)/gi,"on&#8203;$1")},Ext.override(Ext.form.Checkbox,{setBoxLabel:function(boxLabel){this.boxLabel=boxLabel,this.rendered&&this.wrap.child(".x-form-cb-label").update(boxLabel)}});var FieldSetonRender=Ext.form.FieldSet.prototype.onRender;Ext.override(Ext.form.FieldSet,{onRender:function(ct,position){if(FieldSetonRender.call(this,ct,position),this.checkboxToggle){var trigger=this.el.dom.getElementsByClassName(this.headerTextCls)[0],elem=this;trigger&&trigger.addEventListener("click",(function(e){elem.checkbox.dom.click(e)}),!1)}}}),Array.prototype.in_array=function(p_val){for(var i=0,l=this.length;i<l;i+=1)if(this[i]===p_val)return!0;return!1},Ext.form.setCheckboxValues=function(form,id,mask){for(var f,n=0;null!==(f=form.findField(id+n));)f.setValue(mask&1<<n?"true":"false"),n+=1},Ext.form.getCheckboxMask=function(cbgroup){var mask="";if(void 0!==cbgroup)if("string"==typeof cbgroup)mask=cbgroup+"";else for(var i=0,len=cbgroup.length;i<len;i+=1)mask+=(""!==mask?",":"")+(cbgroup[i]-0);return mask},Ext.form.BasicForm.prototype.append=function(){var layout=new Ext.form.Layout,fields=[];layout.stack.push.apply(layout.stack,arguments);for(var i=0;i<arguments.length;i+=1)arguments[i].isFormField&&fields.push(arguments[i]);if(layout.render(this.el),fields.length>0){this.items.addAll(fields);for(var f=0;f<fields.length;f+=1)fields[f].render("x-form-el-"+fields[f].id)}return this},Ext.form.AMPMField=function(id,v){return new Ext.form.ComboBox({store:new Ext.data.SimpleStore({fields:["ampm"],data:[["am"],["pm"]]}),displayField:"ampm",hiddenName:id,mode:"local",editable:!1,forceSelection:!0,triggerAction:"all",width:60,value:v||"am"})},Ext.form.HourField=function(id,name,v){return new Ext.form.ComboBox({store:new Ext.data.SimpleStore({fields:["hour"],data:[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]]}),displayField:"hour",mode:"local",triggerAction:"all",width:60,forceSelection:!0,rowHeight:!1,editable:!1,value:v||1,transform:id})},Ext.override(Ext.tree.TreeNodeUI,{hasClass:function(className){var el=Ext.fly(this.elNode);return el?className&&-1!==(" "+el.dom.className+" ").indexOf(" "+className+" "):""},renderElements:function(n,a,targetNode,bulkRender){this.indentMarkup=n.parentNode?n.parentNode.ui.getChildIndent():"";var nel,cb=Ext.isBoolean(a.checked),renderer=n.ownerTree&&n.ownerTree.renderItemText?n.ownerTree.renderItemText:this.renderItemText,href=this.getHref(a.page),iconMarkup='<i class="icon'+(a.icon?" x-tree-node-inline-icon":"")+(a.iconCls?" "+a.iconCls:"")+'" unselectable="on"></i>',elbowMarkup=n.attributes.pseudoroot?'<i class="icon-sort-down expanded-icon"></i>':'<i class="x-tree-ec-icon x-tree-elbow"></i>',buf=['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',a.cls,'" unselectable="on">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",elbowMarkup,iconMarkup,cb?'<input class="x-tree-node-cb" type="checkbox" '+(a.checked?'checked="checked" />':"/>"):"",'<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="0" ',a.hrefTarget?' target="'+a.hrefTarget+'"':"",'><span unselectable="on">',renderer(a),"</span></a></div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join("");!0!==bulkRender&&n.nextSibling&&(nel=n.nextSibling.ui.getEl())?this.wrap=Ext.DomHelper.insertHtml("beforeBegin",nel,buf):this.wrap=Ext.DomHelper.insertHtml("beforeEnd",targetNode,buf),this.elNode=this.wrap.childNodes[0],this.ctNode=this.wrap.childNodes[1];var cs=this.elNode.childNodes;this.indentNode=cs[0],this.ecNode=cs[1],this.iconNode=cs[2];var index=3;cb&&(this.checkbox=cs[3],this.checkbox.defaultChecked=this.checkbox.checked,index++),this.anchor=cs[index],this.textNode=cs[index].firstChild},renderItemText:function(item){return Ext.util.Format.htmlEncode(item.text)},getChildIndent:function(){if(!this.childIndent){for(var buf=[],p=this.node;p;)(!p.isRoot||p.isRoot&&p.ownerTree.rootVisible)&&!p.attributes.pseudoroot&&(p.isLast()?buf.unshift('<img alt="" src="'+this.emptyIcon+'" class="x-tree-icon" />'):buf.unshift('<img alt="" src="'+this.emptyIcon+'" class="x-tree-elbow-line" />')),p=p.parentNode;this.childIndent=buf.join("")}return this.childIndent}}),Ext.override(Ext.form.Action.Submit,{handleResponse:function(response){var m=Ext.decode(response.responseText);if(this.form.errorReader){var rs=this.form.errorReader.read(response),errors=[];if(rs.records)for(var i=0,len=rs.records.length;i<len;i+=1){var r=rs.records[i];errors[i]=r.data}return errors.length<1&&(errors=null),{success:rs.success,message:m.message,object:m.object,errors}}return Ext.decode(response.responseText)}}),Ext.form.Field.prototype.afterRender=Ext.form.Field.prototype.afterRender.createSequence((function(){if(this.description&&parseInt(MODx.config.manager_tooltip_enable)){Ext.QuickTips.register({target:this.getEl(),text:this.description,enabled:!0,dismissDelay:MODx.config.manager_tooltip_delay});var label=Ext.form.Field.findLabel(this);label&&Ext.QuickTips.register({target:label,text:this.description,enabled:!0,dismissDelay:MODx.config.manager_tooltip_delay})}})),Ext.applyIf(Ext.form.Field,{findLabel:function(field){var wrapDiv=null,label=null;return(wrapDiv=field.getEl().up("div.x-form-element"))&&(label=wrapDiv.child("label")),label||((wrapDiv=field.getEl().up("div.x-form-item"))&&(label=wrapDiv.child("label")),label||void 0)}}),MODx.util.Format={dateFromTimestamp:function(timestamp,date,time,defaultValue){if(void 0===date&&(date=!0),void 0===time&&(time=!0),void 0===defaultValue&&(defaultValue=""),!((timestamp=parseInt(timestamp))>0))return defaultValue;10===timestamp.toString().length&&(timestamp*=1e3);var format=[];return!0===date&&format.push(MODx.config.manager_date_format),!0===time&&format.push(MODx.config.manager_time_format),0===format.length?defaultValue:(format=format.join(" "),new Date(timestamp).format(format))},trimCharacters:function(string,charList="",direction="both"){if(charList.length){const trimLeft={find:new RegExp(`^([${charList}]+)([^${charList}]?)(.*)`,"g"),replace:"$2$3"},trimRight={find:new RegExp(`(.*)([^${charList}]+)([${charList}]+)$`,"g"),replace:"$1$2"};switch(direction){case"both":return string.replace(trimLeft.find,trimLeft.replace).replace(trimRight.find,trimRight.replace);case"left":return string.replace(trimLeft.find,trimLeft.replace);case"right":return string.replace(trimRight.find,trimRight.replace)}}return string},trimAndCollapseSpace:function(value){return"string"!=typeof value||Ext.isEmpty(value)?value:value.trim().replace(/\s{2,}/," ")},trimCharSeparatedList:function(list,separator=",",padListItems=!0){let formattedList=this.trimCharacters(list,`${separator}\\s`);return formattedList=this.trimAndCollapseSpace(formattedList),formattedList=formattedList.replace(new RegExp(`\\s*${separator}\\s*`,"g"),separator).replace(new RegExp(`[${separator}]{2,}`,"g"),separator),padListItems?formattedList.replaceAll(separator,`${separator} `):formattedList}},MODx.util.getHeaderBreadCrumbs=function(header,trail){return"string"==typeof header&&(header={id:header,xtype:"modx-header"}),void 0===trail&&(trail=[]),Array.isArray(trail)||(trail=[trail]),{xtype:"modx-breadcrumbs-panel",id:"modx-header-breadcrumbs",cls:"modx-header-breadcrumbs",desc:"",bdMarkup:'<ul><tpl for="trail"><li><tpl if="href"><a href="{href}" class="{cls}">{text}</a></tpl><tpl if="!href">{text}</tpl></li></tpl></ul>',init:function(){this.tpl=new Ext.XTemplate(this.bdMarkup,{compiled:!0})},trail,listeners:{afterrender:function(){this.renderTrail()}},renderTrail:function(){this.tpl.overwrite(this.body.dom.lastElementChild,{trail:this.trail})},updateTrail:function(trail,replace){if(void 0===replace&&(replace=!1),!0===replace)return this.trail=Array.isArray(trail)?trail:[trail],this.renderTrail(),!0;if(Array.isArray(trail)){for(var i=0;i<trail.length;i++)this.trail.push(trail[i]);return this.renderTrail(),!0}return this.trail.push(trail),this.renderTrail(),!0},updateHeader:function(text){this.rendered?Ext.getCmp(header.id).getEl().update(text):Ext.getCmp(header.id).html=text},items:[header]}},MODx.util.url={setParams:function(filterData,stateData={}){if(void 0!==window.history.replaceState){const url=new URL(window.location.href),params=url.searchParams;Object.entries(filterData).forEach((([param,value])=>{params.set(param,value)}));const newUrl=url.toString().replace(/%2F/g,"/");window.history.replaceState(stateData,document.title,newUrl)}},clearAllParams:function(stateData={}){if(void 0!==window.history.replaceState){const preserve=["a","id","key","namespace"],preserved=[],urlParts=window.location.href.split("?");urlParts[1].split("&").forEach((param=>{const paramName=param.split("=")[0];preserve.includes(paramName)&&preserved.push(param)}));let newUrl=new URL(`${urlParts[0]}?${preserved.join("&")}`);newUrl=newUrl.toString().replace(/%2F/g,"/"),window.history.replaceState(stateData,document.title,newUrl)}},clearParam:function(reference,referenceIsComponent=!0,stateData={}){if(void 0!==window.history.replaceState){let removeParamName,url=new URL(window.location.href);referenceIsComponent?(removeParamName=this.getParamNameFromCmp(reference),removeParamName="namespace"===removeParamName?"ns":removeParamName):removeParamName=reference.trim(),url.searchParams.delete(removeParamName),url=url.toString().replace(/%2F/g,"/"),window.history.replaceState(stateData,document.title,url)}},getParamNameFromCmp:function(cmp){const param=cmp.itemId.split("-")[1];return"ns"===param?"namespace":param},getParamValue:function(param,setEmptyToString=!1){const key="namespace"===param?"ns":param,emptyValue=setEmptyToString?"":null;return MODx.request[key]?this.decodeParamValue(MODx.request[key]):emptyValue},decodeParamValue:function(value){return value=value.replace(/\+/g," "),decodeURIComponent(value)}},MODx.util.tree={getGroupIdFromNode:function(node){return node.id?node.id.split("_").pop():0}},Ext.util.Format.trimCommas=function(s){var len=(s=s.replace(",,",",")).length;return","==s.substr(len-1,1)&&(s=s.substring(0,len-1)),","==s.substr(0,1)&&(s=s.substring(1)),","==s&&(s=""),s},Ext.ns("Ext.ux.grid"),"function"!=typeof RegExp.escape&&(RegExp.escape=function(s){return"string"!=typeof s?s:s.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g,"\\$1")}),Ext.ux.grid.RowActions=function(a){Ext.apply(this,a),this.addEvents("beforeaction","action","beforegroupaction","groupaction"),Ext.ux.grid.RowActions.superclass.constructor.call(this)},Ext.extend(Ext.ux.grid.RowActions,Ext.util.Observable,{actionEvent:"click",autoWidth:!0,dataIndex:"",editable:!1,header:"",isColumn:!0,keepSelection:!1,menuDisabled:!0,sortable:!1,tplGroup:'<tpl for="actions"><div class="ux-grow-action-item<tpl if="\'right\'===align"> ux-action-right</tpl> {cls}" style="{style}" qtip="{qtip}">{text}</div></tpl>',tplRow:'<div class="ux-row-action"><tpl for="actions"><div class="ux-row-action-item {cls} <tpl if="text">ux-row-action-text</tpl>" style="{hide}{style}" qtip="{qtip}"><tpl if="text"><span qtip="{qtip}">{text}</span></tpl></div></tpl></div>',hideMode:"visibility",widthIntercept:4,widthSlope:21,init:function(g){this.grid=g,this.id=this.id||Ext.id();var h=g.getColumnModel().lookup;delete h[void 0],h[this.id]=this,this.tpl||(this.tpl=this.processActions(this.actions)),this.autoWidth&&(this.width=this.widthSlope*this.actions.length+this.widthIntercept,this.fixed=!0);var i=g.getView(),j={scope:this};j[this.actionEvent]=this.onClick,g.afterRender=g.afterRender.createSequence((function(){i.mainBody.on(j),g.on("destroy",this.purgeListeners,this)}),this),this.renderer||(this.renderer=function(a,b,c,d,e,f){return b.css+=(b.css?" ":"")+"ux-row-action-cell",this.tpl.apply(this.getData(a,b,c,d,e,f))}.createDelegate(this)),i.groupTextTpl&&this.groupActions&&(i.interceptMouse=i.interceptMouse.createInterceptor((function(e){if(e.getTarget(".ux-grow-action-item"))return!1})),i.groupTextTpl='<div class="ux-grow-action-text">'+i.groupTextTpl+"</div>"+this.processActions(this.groupActions,this.tplGroup).apply()),!0===this.keepSelection&&(g.processEvent=g.processEvent.createInterceptor((function(a,e){if("mousedown"===a)return!this.getAction(e)}),this))},getData:function(a,b,c,d,e,f){return c.data||{}},processActions:function(b,c){var d=[];Ext.each(b,(function(a,i){a.iconCls&&"function"==typeof(a.callback||a.cb)&&(this.callbacks=this.callbacks||{},this.callbacks[a.iconCls]=a.callback||a.cb);var o={cls:a.iconIndex?"{"+a.iconIndex+"}":a.iconCls?a.iconCls:"",qtip:a.qtipIndex?"{"+a.qtipIndex+"}":a.tooltip||a.qtip?a.tooltip||a.qtip:"",text:a.textIndex?"{"+a.textIndex+"}":a.text?a.text:"",hide:a.hideIndex?'<tpl if="'+a.hideIndex+'">'+("display"===this.hideMode?"display:none":"visibility:hidden")+";</tpl>":a.hide?"display"===this.hideMode?"display:none":"visibility:hidden;":"",align:a.align||"right",style:a.style?a.style:""};d.push(o)}),this);var e=new Ext.XTemplate(c||this.tplRow);return new Ext.XTemplate(e.apply({actions:d}))},getAction:function(e){var a=!1,t=e.getTarget(".ux-row-action-item");return t&&(a=t.className.replace(/ux-row-action-item /,""))&&(a=(a=a.replace(/ ux-row-action-text/,"")).trim()),a},onClick:function(e,a){var b=this.grid.getView(),c=e.getTarget(".x-grid3-row"),d=b.findCellIndex(a.parentNode.parentNode),f=this.getAction(e);if(!1!==c&&!1!==d&&!1!==f){var g=this.grid.store.getAt(c.rowIndex);if(this.callbacks&&"function"==typeof this.callbacks[f]&&this.callbacks[f](this.grid,g,f,c.rowIndex,d),!0!==this.eventsSuspended&&!1===this.fireEvent("beforeaction",this.grid,g,f,c.rowIndex,d))return;!0!==this.eventsSuspended&&this.fireEvent("action",this.grid,g,f,c.rowIndex,d)}if(t=e.getTarget(".ux-grow-action-item"),t){var j,h=b.findGroup(a),i=h?h.id.replace(/ext-gen[0-9]+-gp-/,""):null;if(i){var k=new RegExp(RegExp.escape(i));j=(j=this.grid.store.queryBy((function(r){return r._groupId.match(k)})))?j.items:[]}if(f=t.className.replace(/ux-grow-action-item (ux-action-right )*/,""),"function"==typeof this.callbacks[f]&&this.callbacks[f](this.grid,j,f,i),!0!==this.eventsSuspended&&!1===this.fireEvent("beforegroupaction",this.grid,j,f,i))return!1;this.fireEvent("groupaction",this.grid,j,f,i)}}}),Ext.reg("rowactions",Ext.ux.grid.RowActions),Ext.SwitchButton=Ext.extend(Ext.Component,{initComponent:function(){Ext.SwitchButton.superclass.initComponent.call(this);var mc=new Ext.util.MixedCollection;mc.addAll(this.items),this.items=mc,this.addEvents("change"),this.handler&&this.on("change",this.handler,this.scope||this)},onRender:function(ct,position){var el=document.createElement("table");el.cellSpacing=0,el.className="x-rbtn",el.id=this.id;var row=document.createElement("tr");el.appendChild(document.createElement("tbody")).appendChild(row);var count=this.items.length,last=count-1;this.activeItem=this.items.get(this.activeItem);for(var i=0;i<count;i++){var item=this.items.itemAt(i),cell=row.appendChild(document.createElement("td"));cell.id=this.id+"-rbi-"+i;var cls=0==i?"x-rbtn-first":i==last?"x-rbtn-last":"x-rbtn-item";item.baseCls=cls,this.activeItem==item&&(cls+="-active"),cell.className=cls;var button=document.createElement("button");button.innerHTML="&#160;",button.className=item.iconCls,button.qtip=item.tooltip,cell.appendChild(button),item.cell=cell}this.el=Ext.get(ct.dom.appendChild(el)),this.el.on("click",this.onClick,this)},getActiveItem:function(){return this.activeItem},setActiveItem:function(item){"object"!=typeof item&&null!==item&&(item=this.items.get(item));var current=this.getActiveItem();return item!=current&&(current&&Ext.fly(current.cell).removeClass(current.baseCls+"-active"),item&&Ext.fly(item.cell).addClass(item.baseCls+"-active"),this.activeItem=item,this.fireEvent("change",this,item)),item},onClick:function(e){var target=e.getTarget("td",2);!this.disabled&&target&&this.setActiveItem(parseInt(target.id.split("-rbi-")[1],10))}}),Ext.reg("switch",Ext.SwitchButton),Ext.onReady((function(){MODx.util.JSONReader=MODx.load({xtype:"modx-json-reader"}),MODx.form.Handler=MODx.load({xtype:"modx-form-handler"}),MODx.msg=MODx.load({xtype:"modx-msg"})})),Ext.form.XCheckbox=Ext.extend(Ext.form.Checkbox,{submitOffValue:0,submitOnValue:1,onRender:function(){this.inputValue=this.submitOnValue,Ext.form.XCheckbox.superclass.onRender.apply(this,arguments),this.hiddenField=this.wrap.insertFirst({tag:"input",type:"hidden"}),this.tooltip&&this.imageEl.set({qtip:this.tooltip}),this.updateHidden()},setValue:function(v){v=this.convertValue(v),this.updateHidden(v),Ext.form.XCheckbox.superclass.setValue.apply(this,arguments)},updateHidden:function(v){v=void 0!==v?v:this.checked,v=this.convertValue(v),this.hiddenField&&(this.hiddenField.dom.value=v?this.submitOnValue:this.submitOffValue,this.hiddenField.dom.name=v?"":this.el.dom.name)},convertValue:function(v){return!0===v||"true"===v||v===this.submitOnValue||"on"===String(v).toLowerCase()}}),Ext.reg("xcheckbox",Ext.form.XCheckbox),Ext.namespace("Ext.ux.dd"),Ext.ux.dd.GridDragDropRowOrder=Ext.extend(Ext.util.Observable,{copy:!1,scrollable:!1,constructor:function(config){config&&Ext.apply(this,config),this.addEvents({beforerowmove:!0,afterrowmove:!0,beforerowcopy:!0,afterrowcopy:!0}),Ext.ux.dd.GridDragDropRowOrder.superclass.constructor.call(this)},init:function(grid){this.grid=grid,grid.enableDragDrop=!0,grid.on({render:{fn:this.onGridRender,scope:this,single:!0}})},onGridRender:function(grid){var self=this;this.target=new Ext.dd.DropTarget(grid.getEl(),{ddGroup:grid.ddGroup||"GridDD",grid,gridDropTarget:this,notifyDrop:function(dd,e,data){this.currentRowEl&&(this.currentRowEl.removeClass("grid-row-insert-below"),this.currentRowEl.removeClass("grid-row-insert-above"));var t=Ext.lib.Event.getTarget(e),rindex=this.grid.getView().findRowIndex(t);if(!1===rindex||rindex==data.rowIndex)return!1;if(!1===this.gridDropTarget.fireEvent(self.copy?"beforerowcopy":"beforerowmove",this.gridDropTarget,data.rowIndex,rindex,data.selections,123))return!1;var ds=this.grid.getStore(),selections=new Array,keys=ds.data.keys;for(var key in keys)for(var i=0;i<data.selections.length;i++)if(keys[key]==data.selections[i].id){if(rindex==key)return!1;selections.push(data.selections[i])}if(rindex>data.rowIndex&&this.rowPosition<0&&rindex--,rindex<data.rowIndex&&this.rowPosition>0&&rindex++,rindex>data.rowIndex&&data.selections.length>1&&(rindex-=data.selections.length-1),rindex==data.rowIndex)return!1;if(!self.copy)for(i=0;i<data.selections.length;i++)ds.remove(ds.getById(data.selections[i].id));for(i=selections.length-1;i>=0;i--){var insertIndex=rindex;ds.insert(insertIndex,selections[i])}var sm=this.grid.getSelectionModel();return sm&&sm.selectRecords(data.selections),this.gridDropTarget.fireEvent(self.copy?"afterrowcopy":"afterrowmove",this.gridDropTarget,data.rowIndex,rindex,data.selections),!0},notifyOver:function(dd,e,data){var t=Ext.lib.Event.getTarget(e),rindex=this.grid.getView().findRowIndex(t),keys=this.grid.getStore().data.keys;for(var key in keys)for(var i=0;i<data.selections.length;i++)if(keys[key]==data.selections[i].id&&rindex==key)return this.currentRowEl&&(this.currentRowEl.removeClass("grid-row-insert-below"),this.currentRowEl.removeClass("grid-row-insert-above")),this.dropNotAllowed;if(rindex<0||!1===rindex)return this.currentRowEl.removeClass("grid-row-insert-above"),this.dropNotAllowed;try{var currentRow=this.grid.getView().getRow(rindex),resolvedRow=new Ext.Element(currentRow).getY()-this.grid.getView().scroller.dom.scrollTop,rowHeight=currentRow.offsetHeight;if(this.rowPosition=e.getPageY()-resolvedRow-rowHeight/2,this.currentRowEl&&(this.currentRowEl.removeClass("grid-row-insert-below"),this.currentRowEl.removeClass("grid-row-insert-above")),this.rowPosition>0)this.currentRowEl=new Ext.Element(currentRow),this.currentRowEl.addClass("grid-row-insert-below");else if(rindex-1>=0){var previousRow=this.grid.getView().getRow(rindex-1);this.currentRowEl=new Ext.Element(previousRow),this.currentRowEl.addClass("grid-row-insert-below")}else this.currentRowEl.addClass("grid-row-insert-above")}catch(err){console.warn(err),rindex=!1}return!1===rindex?this.dropNotAllowed:this.dropAllowed},notifyOut:function(dd,e,data){this.currentRowEl&&(this.currentRowEl.removeClass("grid-row-insert-above"),this.currentRowEl.removeClass("grid-row-insert-below"))}}),this.targetCfg&&Ext.apply(this.target,this.targetCfg),this.scrollable&&(Ext.dd.ScrollManager.register(grid.getView().getEditorParent()),grid.on({beforedestroy:this.onBeforeDestroy,scope:this,single:!0}))},getTarget:function(){return this.target},getGrid:function(){return this.grid},getCopy:function(){return!!this.copy},setCopy:function(b){this.copy=!!b},onBeforeDestroy:function(grid){Ext.dd.ScrollManager.unregister(grid.getView().getEditorParent())}}),Ext.grid.GridView.prototype.templates||(Ext.grid.GridView.prototype.templates={}),Ext.grid.GridView.prototype.templates.cell=new Ext.Template('<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>','<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',"</td>"),MODx.grid||(MODx.grid={}),MODx.grid.ComboColumn=Ext.extend(Ext.grid.Column,{gridId:void 0,constructor:function(cfg){MODx.grid.ComboColumn.superclass.constructor.call(this,cfg),this.renderer=this.editor&&this.editor.triggerAction?MODx.grid.ComboBoxRenderer(this.editor,this.gridId,cfg.renderer):function(value){return value}}}),Ext.grid.Column.types.combocolumn=MODx.grid.ComboColumn,MODx.grid.ComboBoxRenderer=function(combo,gridId,currentRenderer){return function(value,metaData,record,rowIndex,colIndex,store){if(currentRenderer){if("function"==typeof currentRenderer.fn){var scope=!!currentRenderer.scope&&currentRenderer.scope;currentRenderer=currentRenderer.fn.bind(scope)}"function"==typeof currentRenderer&&(value=currentRenderer(value,metaData,record,rowIndex,colIndex,store))}return 0==combo.store.getCount()&&gridId?(combo.store.on("load",(function(){var grid=Ext.getCmp(gridId);grid&&grid.getView().refresh()}),this,{single:!0}),value):function(value){var idx=combo.store.find(combo.valueField,value),rec=combo.store.getAt(idx);return rec?rec.get(combo.displayField):value}(value)}},Ext.Button.buttonTemplate=new Ext.Template('<span id="{4}" class="x-btn {1} {3}" unselectable="on"><em class="{2}"><button type="{0}"></button></em></span>'),Ext.Button.buttonTemplate.compile(),Ext.TabPanel.prototype.itemTpl=new Ext.Template('<li class="{cls}" id="{id}"><a class="x-tab-strip-close"></a>','<span class="x-tab-strip-text {iconCls}">{text}</span></li>'),Ext.TabPanel.prototype.itemTpl.disableFormats=!0,Ext.TabPanel.prototype.itemTpl.compile(),Ext.namespace("Ext.ux.form"),Ext.ux.form.CheckboxGroup=Ext.extend(Ext.form.CheckboxGroup,{aggregateSubmitField:{},initComponent:function(){const me=this,ct=this.ownerCt;"string"==typeof this.name&&this.name.length>0?(this.aggregateSubmitField=new Ext.form.Hidden({name:this.name}),Ext.ux.form.CheckboxGroup.superclass.initComponent.call(this),this.cls="string"==typeof this.cls&&this.cls.length>0?"aggregated-group "+this.cls:"aggregated-group",Ext.each(this.items,(function(item){if("string"==typeof me.value&&me.value.length>0){me.value.split(",").find((function(v){return v==item.inputValue}))==item.inputValue&&(item.checked=!0),me.aggregateSubmitField.setValue(me.value)}item.listeners={check:{fn:me.setHiddenSubmit,scope:me}},item.submitValue=!1})),ct.add(this.aggregateSubmitField)):console.warning("Ext.ux.form.CheckboxGroup: A name must be specified in this component’s config for its values to be saved.",this)},setHiddenSubmit:function(){const groupOpts=this.items.items;let vals=[];Ext.each(groupOpts,(function(item){item.checked&&vals.push(item.inputValue)})),this.aggregateSubmitField.setValue(vals.join(","))}}),Ext.reg("xcheckboxgroup",Ext.ux.form.CheckboxGroup),Ext.define("AddFieldUtilities.plugin.Class",{alias:"plugin.fieldutilities",init:function(cmp){cmp.on("afterrender",this.afterRender,cmp)},afterRender:function(){const me=this;this.label.createChild({tag:"a",title:_("field_reset"),cls:"modx-field-utils modx-field-reset"}).on("click",(function(){me.reset()}),me),this.label.createChild({tag:"a",title:_("field_clear"),cls:"modx-field-utils modx-field-clear"}).on("click",(function(){switch(this.xtype){case"xcheckboxgroup":case"checkboxgroup":Ext.isArray(this.items.items)&&(Ext.each(this.items.items,(function(item){item.setValue(!1)})),this.doLayout());break;case"checkbox":case"radio":me.setValue(!1);break;default:me.setValue("")}}),me)}}),MODx.util.FileDownload=function(fields){if(Ext.isObject(fields)){var me=this;me.clearCookie=function(){Ext.util.Cookies.set(cookieName,null,new Date("January 1, 1970"),"/"),Ext.util.Cookies.clear(cookieName,"/")},me.randomHex=function(len){const hex="0123456789ABCDEF";let output="";for(let i=0;i<len;++i)output+=hex.charAt(Math.floor(Math.random()*hex.length));return output},me.isFinished=function(successCallback,failureCallback){if(Ext.util.Cookies.get(cookieName)&&"true"===Ext.util.Cookies.get(cookieName))return me.clearCookie(),void(successCallback&&successCallback({success:!0,message:_("$file_msg_download_success")}));try{if(frame.dom.contentDocument.body.innerHTML.length>0){var result=Ext.decode(frame.dom.contentDocument.body.innerHTML);return result=result||{success:!1,message:_("file_msg_download_error")},me.clearCookie(),failureCallback&&failureCallback(result),void(frame.dom.contentDocument.body.innerHTML="")}}catch(e){console.log(e)}polling?(debug&&console.log("polling "+polling),window.setTimeout((function(){polling--,me.isFinished(successCallback,failureCallback)}),100)):(me.clearCookie(),failureCallback&&failureCallback({success:!1,message:_("file_err_download_timeout")}))};var cookieName="fileDownload"+me.randomHex(16),polling=10*fields.timeout||300,ident=fields.ident||"filedownload-"+Ext.id(),url=fields.url||MODx.config.connector_url,params=fields.params||{},debug=fields.debug||!1,successCallback=fields.success||null,failureCallback=fields.failure||null,body=Ext.getBody(),frame=body.createChild({tag:"iframe",cls:"x-hidden",id:ident+"-iframe",name:ident+"-iframe"}),form=body.createChild({tag:"form",cls:"x-hidden",id:ident+"-form",action:url,target:ident+"-iframe",method:"post"});params.HTTP_MODAUTH=MODx.siteId,"function"==typeof successCallback&&(params.cookieName=cookieName),Ext.iterate(params,(function(name,value){form.createChild({tag:"input",type:"text",cls:"x-hidden",id:ident+"-"+name,name,value})})),form.dom.submit(),(successCallback||failureCallback)&&me.isFinished(successCallback,failureCallback)}},Ext.override(Ext.form.TimeField,{initDate:"2/1/2008"}),Ext.ns("Ext.ux.form"),Ext.ux.form.DateTime=Ext.extend(Ext.form.Field,{dateValidator:null,defaultAutoCreate:{tag:"input",type:"hidden"},dtSeparator:" ",hiddenFormat:"Y-m-d H:i:s",otherToNow:!0,timePosition:"right",timeValidator:null,timeWidth:100,dateFormat:"m/d/y",timeFormat:"g:i A",maxDateValue:"",minDateValue:"",timeIncrement:15,maxTimeValue:null,minTimeValue:null,disabledDates:null,hideTime:!1,initComponent:function(){Ext.ux.form.DateTime.superclass.initComponent.call(this),this.hasOwnProperty("offset_time")&&!isNaN(this.offset_time)||(this.offset_time=0);var dateConfig=Ext.apply({},{id:this.id+"-date",format:this.dateFormat||Ext.form.DateField.prototype.format,width:this.timeWidth,selectOnFocus:this.selectOnFocus,validator:this.dateValidator,disabledDates:this.disabledDates||null,disabledDays:this.disabledDays||[],showToday:this.showToday||!0,maxValue:this.maxDateValue||"",minValue:this.minDateValue||"",startDay:this.startDay||0,allowBlank:this.allowBlank,msgTarget:this.msgTarget,listeners:{blur:{scope:this,fn:this.onBlur},focus:{scope:this,fn:this.onFocus}}},this.dateConfig);this.df=new Ext.form.DateField(dateConfig),this.df.ownerCt=this,delete this.dateFormat,delete this.disabledDates,delete this.disabledDays,delete this.maxDateValue,delete this.minDateValue,delete this.startDay;var timeConfig=Ext.apply({},{id:this.id+"-time",format:this.timeFormat||Ext.form.TimeField.prototype.format,width:this.timeWidth,selectOnFocus:this.selectOnFocus,validator:this.timeValidator,increment:this.timeIncrement||15,maxValue:this.maxTimeValue||null,minValue:this.minTimeValue||null,hidden:this.hideTime,allowBlank:this.allowBlank,msgTarget:this.msgTarget,listeners:{blur:{scope:this,fn:this.onBlur},focus:{scope:this,fn:this.onFocus}}},this.timeConfig);this.tf=new Ext.form.TimeField(timeConfig),this.tf.ownerCt=this,delete this.timeFormat,delete this.maxTimeValue,delete this.minTimeValue,delete this.timeIncrement,this.relayEvents(this.df,["focus","specialkey","invalid","valid"]),this.relayEvents(this.tf,["focus","specialkey","invalid","valid"]),this.on("specialkey",this.onSpecialKey,this)},onRender:function(ct,position){if(!this.isRendered){var t;switch(Ext.ux.form.DateTime.superclass.onRender.call(this,ct,position),t="below"===this.timePosition||"bellow"===this.timePosition?Ext.DomHelper.append(ct,{tag:"table",style:"border-collapse:collapse",children:[{tag:"tr",children:[{tag:"td",style:"padding-bottom:1px",cls:"ux-datetime-date"}]},{tag:"tr",children:[{tag:"td",cls:"ux-datetime-time"}]}]},!0):Ext.DomHelper.append(ct,{tag:"table",style:"border-collapse:collapse",children:[{tag:"tr",children:[{tag:"td",style:"padding-right:4px",cls:"ux-datetime-date"},{tag:"td",cls:"ux-datetime-time"}]}]},!0),this.tableEl=t,this.wrap=t.wrap({cls:"x-form-field-wrap x-datetime-wrap"}),this.wrap.on("mousedown",this.onMouseDown,this,{delay:10}),this.df.render(t.child("td.ux-datetime-date")),this.tf.render(t.child("td.ux-datetime-time")),this.df.el.swallowEvent(["keydown","keypress"]),this.tf.el.swallowEvent(["keydown","keypress"]),this.msgTarget){case"side":const elp=this.el.findParent(".x-form-element",10,!0);elp&&(this.errorIcon=elp.createChild({cls:"x-form-invalid-icon"}));const o={errorIcon:this.errorIcon,msgTarget:"side",alignErrorIcon:this.alignErrorIcon.createDelegate(this)};Ext.apply(this.df,o),Ext.apply(this.tf,o);break;case"under":const dateMsgElId=`ux-datetime-date-msg-${this.itemId}`,dateMsgWidth=Math.ceil(this.dateWidth-30),dateMsgEl=Ext.DomHelper.append(this.df.container,{tag:"div",cls:"x-form-invalid-msg",style:`display: none; width: ${dateMsgWidth}px;`,id:dateMsgElId}),timeMsgElId=`ux-datetime-time-msg-${this.itemId}`,timeMsgWidth=Math.ceil(this.timeWidth-30),timeMsgEl=Ext.DomHelper.append(this.tf.container,{tag:"div",cls:"x-form-invalid-msg",style:`display: none; width: ${timeMsgWidth}px;`,id:timeMsgElId});this.df.container.appendChild(dateMsgEl),this.tf.container.appendChild(timeMsgEl),this.df.msgTarget=dateMsgElId,this.tf.msgTarget=timeMsgElId}this.el.dom.name=this.hiddenName||this.name||this.id,this.df.el.dom.removeAttribute("name"),this.tf.el.dom.removeAttribute("name"),this.isRendered=!0,this.updateHidden()}},adjustSize:Ext.BoxComponent.prototype.adjustSize,alignErrorIcon:function(){this.errorIcon.alignTo(this.tableEl,"tl-tr",[2,0])},initDateValue:function(){this.dateValue=this.otherToNow?new Date:new Date(1970,0,1,0,0,0)},clearInvalid:function(){this.df.clearInvalid(),this.tf.clearInvalid()},markInvalid:function(msg){this.df.markInvalid(msg),this.tf.markInvalid(msg)},beforeDestroy:function(){this.isRendered&&(this.wrap.removeAllListeners(),this.wrap.remove(),this.tableEl.remove(),this.df.destroy(),this.tf.destroy())},disable:function(){return this.isRendered&&(this.df.disabled=this.disabled,this.df.onDisable(),this.tf.onDisable()),this.disabled=!0,this.df.disabled=!0,this.tf.disabled=!0,this.fireEvent("disable",this),this},enable:function(){return this.rendered&&(this.df.onEnable(),this.tf.onEnable()),this.disabled=!1,this.df.disabled=!1,this.tf.disabled=!1,this.fireEvent("enable",this),this},focus:function(){this.df.focus()},getPositionEl:function(){return this.wrap},getResizeEl:function(){return this.wrap},getValue:function(){return this.dateValue?new Date(this.dateValue):""},isValid:function(){return this.df.isValid()&&this.tf.isValid()},isVisible:function(){return this.df.rendered&&this.df.getActionEl().isVisible()},onBlur:function(f){this.wrapClick&&(f.focus(),this.wrapClick=!1),f===this.df?this.updateDate():this.updateTime(),this.updateHidden(),this.validate(),function(){if(!this.df.hasFocus&&!this.tf.hasFocus){var v=this.getValue();String(v)!==String(this.startValue)&&this.fireEvent("change",this,v,this.startValue),this.hasFocus=!1,this.fireEvent("blur",this)}}.defer(100,this)},onFocus:function(){this.hasFocus||(this.hasFocus=!0,this.startValue=this.getValue(),this.fireEvent("focus",this))},onMouseDown:function(e){this.disabled||(this.wrapClick="td"===e.target.nodeName.toLowerCase())},onSpecialKey:function(t,e){var key=e.getKey();key===e.TAB&&(t!==this.df||e.shiftKey||(this.onBlur(t),e.stopEvent(),this.tf.focus()),t===this.tf&&e.shiftKey&&(this.onBlur(t),e.stopEvent(),this.df.focus()),this.updateValue()),key===e.ENTER&&this.updateValue()},reset:function(){this.df.setValue(this.originalValue),this.tf.setValue(this.originalValue)},setDate:function(date){date&&0!=this.offset_time&&(date=date.add(Date.MINUTE,60*new Number(this.offset_time))),this.df.setValue(date)},setTime:function(date){date&&0!=this.offset_time&&(date=date.add(Date.MINUTE,60*new Number(this.offset_time))),this.tf.setValue(date)},setSize:function(w,h){w&&("below"===this.timePosition?(this.df.setSize(w,h),this.tf.setSize(w,h),Ext.isIE&&(this.df.el.up("td").setWidth(w),this.tf.el.up("td").setWidth(w))):(this.df.setSize(w-this.timeWidth-4,h),this.tf.setSize(this.timeWidth,h),Ext.isIE&&(this.df.el.up("td").setWidth(w-this.timeWidth-4),this.tf.el.up("td").setWidth(this.timeWidth))))},setValue:function(val){if(val||!0!==this.emptyToNow){if(!val)return this.setDate(""),this.setTime(""),void this.updateValue();var da;"number"==typeof val?val=new Date(val):"string"==typeof val&&this.hiddenFormat&&(val=Date.parseDate(val,this.hiddenFormat)),(val=val||new Date(1970,0,1,0,0,0))instanceof Date?(this.setDate(val),this.setTime(val),this.dateValue=new Date(Ext.isIE?val.getTime():val)):(da=val.split(this.dtSeparator),this.setDate(da[0]),da[1]&&(da[2]&&(da[1]+=da[2]),this.setTime(da[1]))),this.updateValue()}else this.setValue(new Date)},setVisible:function(visible){return visible?(this.df.show(),this.tf.show()):(this.df.hide(),this.tf.hide()),this},show:function(){return this.setVisible(!0)},hide:function(){return this.setVisible(!1)},updateDate:function(){var d=this.df.getValue();d?(this.dateValue instanceof Date||(this.initDateValue(),this.tf.getValue()||this.setTime(this.dateValue)),this.dateValue.setMonth(0),this.dateValue.setFullYear(d.getFullYear()),this.dateValue.setMonth(d.getMonth(),d.getDate())):(this.dateValue="",this.setTime(""))},updateTime:function(){let t=this.tf.getValue();!t||t instanceof Date||(t=Date.parseDate(t,this.tf.format)),t&&!this.df.getValue()&&(this.initDateValue(),this.setDate(this.dateValue)),this.dateValue instanceof Date&&(t&&!this.hideTime?(this.dateValue.setHours(t.getHours()),this.dateValue.setMinutes(t.getMinutes()),this.dateValue.setSeconds(t.getSeconds())):(this.dateValue.setHours(0),this.dateValue.setMinutes(0),this.dateValue.setSeconds(0)))},updateHidden:function(){if(this.isRendered){var value="";this.dateValue instanceof Date&&(value=this.dateValue.add(Date.MINUTE,0-60*new Number(this.offset_time)).format(this.hiddenFormat)),this.el.dom.value=value}},updateValue:function(){this.updateDate(),this.updateTime(),this.updateHidden()},validate:function(){return this.df.validate()&&this.tf.validate()},renderer:function(field){var format=field.editor.dateFormat||Ext.ux.form.DateTime.prototype.dateFormat;return format+=" "+(field.editor.timeFormat||Ext.ux.form.DateTime.prototype.timeFormat),function(val){return Ext.util.Format.date(val,format)}}}),Ext.reg("xdatetime",Ext.ux.form.DateTime),Ext.namespace("Ext.ux.Utils"),Ext.ux.Utils.EventQueue=function(handler,scope){if(!handler)throw"Handler is required.";this.handler=handler,this.scope=scope||window,this.queue=[],this.is_processing=!1,this.postEvent=function(event,data){data=data||null,this.queue.push({event,data}),this.is_processing||this.process()},this.flushEventQueue=function(){this.queue=[]},this.process=function(){for(;this.queue.length>0;){this.is_processing=!0;var event_data=this.queue.shift();this.handler.call(this.scope,event_data.event,event_data.data)}this.is_processing=!1}},Ext.ux.Utils.FSA=function(initial_state,trans_table,trans_table_scope){this.current_state=initial_state,this.trans_table=trans_table||{},this.trans_table_scope=trans_table_scope||window,Ext.ux.Utils.FSA.superclass.constructor.call(this,this.processEvent,this)},Ext.extend(Ext.ux.Utils.FSA,Ext.ux.Utils.EventQueue,{current_state:null,trans_table:null,trans_table_scope:null,state:function(){return this.current_state},processEvent:function(event,data){var transitions=this.currentStateEventTransitions(event);if(!transitions)throw"State '"+this.current_state+"' has no transition for event '"+event+"'.";for(var i=0,len=transitions.length;i<len;i++){var transition=transitions[i],predicate=transition.predicate||transition.p||!0,action=transition.action||transition.a||Ext.emptyFn,new_state=transition.state||transition.s||this.current_state,scope=transition.scope||this.trans_table_scope;if(this.computePredicate(predicate,scope,data,event))return this.callAction(action,scope,data,event),void(this.current_state=new_state)}throw"State '"+this.current_state+"' has no transition for event '"+event+"' in current context"},currentStateEventTransitions:function(event){return this.trans_table[this.current_state]&&this.trans_table[this.current_state][event]||!1},computePredicate:function(predicate,scope,data,event){var result=!1;switch(Ext.type(predicate)){case"function":result=predicate.call(scope,data,event,this);break;case"array":result=!0;for(var i=0,len=predicate.length;result&&i<len;i++){if("function"!=Ext.type(predicate[i]))throw["Predicate: ",predicate[i],' is not callable in "',this.current_state,'" state for event "',event].join("");result=predicate[i].call(scope,data,event,this)}break;case"boolean":result=predicate;break;default:throw["Predicate: ",predicate,' is not callable in "',this.current_state,'" state for event "',event].join("")}return result},callAction:function(action,scope,data,event){switch(Ext.type(action)){case"array":for(var i=0,len=action.length;i<len;i++){if("function"!=Ext.type(action[i]))throw["Action: ",action[i],' is not callable in "',this.current_state,'" state for event "',event].join("");action[i].call(scope,data,event,this)}break;case"function":action.call(scope,data,event,this);break;default:throw["Action: ",action,' is not callable in "',this.current_state,'" state for event "',event].join("")}}}),Ext.namespace("Ext.ux.UploadDialog"),Ext.ux.UploadDialog.BrowseButton=Ext.extend(Ext.Button,{input_name:"file",input_file:null,original_handler:null,original_scope:null,initComponent:function(){Ext.ux.UploadDialog.BrowseButton.superclass.initComponent.call(this),this.original_handler=this.handler||null,this.original_scope=this.scope||window,this.handler=null,this.scope=null},onRender:function(ct,position){Ext.ux.UploadDialog.BrowseButton.superclass.onRender.call(this,ct,position),this.createInputFile()},createInputFile:function(){var button_container=this.el;button_container.position("relative"),this.wrap=this.el.wrap({cls:"tbody"}),this.input_file=this.wrap.createChild({tag:"input",type:"file",size:1,name:this.input_name||Ext.id(this.el),style:"position: absolute; display: block; border: none; cursor: pointer"}),this.input_file.setOpacity(0);var button_box=button_container.getBox();this.input_file.setStyle("font-size",.5*button_box.width+"px");var input_box=this.input_file.getBox(),adj={x:3,y:3};Ext.isIE&&(adj={x:0,y:3}),this.input_file.setLeft(button_box.width-input_box.width+adj.x+"px"),this.input_file.setTop(button_box.height-input_box.height+adj.y+"px"),this.input_file.setOpacity(0),this.handleMouseEvents&&(this.input_file.on("mouseover",this.onMouseOver,this),this.input_file.on("mousedown",this.onMouseDown,this)),this.tooltip&&("object"==typeof this.tooltip?Ext.QuickTips.register(Ext.apply({target:this.input_file},this.tooltip)):this.input_file.dom[this.tooltipType]=this.tooltip),this.input_file.on("change",this.onInputFileChange,this),this.input_file.on("click",(function(e){e.stopPropagation()}))},detachInputFile:function(no_create){var result=this.input_file;return no_create=no_create||!1,"object"==typeof this.tooltip?Ext.QuickTips.unregister(this.input_file):this.input_file.dom[this.tooltipType]=null,this.input_file.removeAllListeners(),this.input_file=null,no_create||this.createInputFile(),result},getInputFile:function(){return this.input_file},disable:function(){Ext.ux.UploadDialog.BrowseButton.superclass.disable.call(this),this.input_file.dom.disabled=!0},enable:function(){Ext.ux.UploadDialog.BrowseButton.superclass.enable.call(this),this.input_file.dom.disabled=!1},destroy:function(){var input_file=this.detachInputFile(!0);input_file.remove(),input_file=null,Ext.ux.UploadDialog.BrowseButton.superclass.destroy.call(this)},onInputFileChange:function(){this.original_handler&&this.original_handler.call(this.original_scope,this)}}),Ext.ux.UploadDialog.TBBrowseButton=Ext.extend(Ext.ux.UploadDialog.BrowseButton,{hideParent:!0,onDestroy:function(){Ext.ux.UploadDialog.TBBrowseButton.superclass.onDestroy.call(this),this.container&&this.container.remove()}}),Ext.ux.UploadDialog.FileRecord=Ext.data.Record.create([{name:"filename"},{name:"state",type:"int"},{name:"note"},{name:"input_element"}]),Ext.ux.UploadDialog.FileRecord.STATE_QUEUE=0,Ext.ux.UploadDialog.FileRecord.STATE_FINISHED=1,Ext.ux.UploadDialog.FileRecord.STATE_FAILED=2,Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING=3,Ext.ux.UploadDialog.Dialog=function(config){var default_config={border:!1,width:600,height:350,minHeight:350,plain:!0,constrainHeader:!0,draggable:!0,closable:!0,maximizable:!1,minimizable:!1,resizable:!0,layout:"fit",region:"center",autoDestroy:!0,closeAction:"hide",title:this.i18n.title,cls:"ext-ux-uploaddialog-dialog",url:"",base_params:{},permitted_extensions:[],reset_on_hide:!0,allow_close_on_upload:!1,upload_autostart:!1,Make_Reload:!1,post_var_name:"file"};(config=Ext.applyIf(config||{},default_config)).layout="absolute",Ext.ux.UploadDialog.Dialog.superclass.constructor.call(this,config)},Ext.extend(Ext.ux.UploadDialog.Dialog,Ext.Window,{fsa:null,state_tpl:null,form:null,grid_panel:null,progress_bar:null,is_uploading:!1,initial_queued_count:0,upload_frame:null,initComponent:function(){Ext.ux.UploadDialog.Dialog.superclass.initComponent.call(this);var tt={created:{"window-render":[{action:[this.createForm,this.createProgressBar,this.createGrid],state:"rendering"}],destroy:[{action:this.flushEventQueue,state:"destroyed"}]},rendering:{"grid-render":[{action:[this.fillToolbar,this.updateToolbar],state:"ready"}],destroy:[{action:this.flushEventQueue,state:"destroyed"}]},ready:{"file-selected":[{predicate:[this.fireFileTestEvent,this.isPermittedFile],action:this.addFileToUploadQueue,state:"adding-file"},{}],"grid-selection-change":[{action:this.updateToolbar}],"remove-files":[{action:[this.removeFiles,this.fireFileRemoveEvent]}],"reset-queue":[{action:[this.resetQueue,this.fireResetQueueEvent]}],"start-upload":[{predicate:this.hasUnuploadedFiles,action:[this.setUploadingFlag,this.saveInitialQueuedCount,this.updateToolbar,this.updateProgressBar,this.prepareNextUploadTask,this.fireUploadStartEvent],state:"uploading"},{}],"stop-upload":[{}],hide:[{predicate:[this.isNotEmptyQueue,this.getResetOnHide],action:[this.resetQueue,this.fireResetQueueEvent]},{}],destroy:[{action:this.flushEventQueue,state:"destroyed"}]},"adding-file":{"file-added":[{predicate:this.isUploading,action:[this.incInitialQueuedCount,this.updateProgressBar,this.fireFileAddEvent],state:"uploading"},{predicate:this.getUploadAutostart,action:[this.startUpload,this.fireFileAddEvent],state:"ready"},{action:[this.updateToolbar,this.fireFileAddEvent],state:"ready"}]},uploading:{"file-selected":[{predicate:[this.fireFileTestEvent,this.isPermittedFile],action:this.addFileToUploadQueue,state:"adding-file"},{}],"grid-selection-change":[{}],"start-upload":[{}],"stop-upload":[{predicate:this.hasUnuploadedFiles,action:[this.resetUploadingFlag,this.abortUpload,this.updateToolbar,this.updateProgressBar,this.fireUploadStopEvent],state:"ready"},{action:[this.resetUploadingFlag,this.abortUpload,this.updateToolbar,this.updateProgressBar,this.fireUploadStopEvent,this.fireUploadCompleteEvent],state:"ready"}],"file-upload-start":[{action:[this.uploadFile,this.findUploadFrame,this.fireFileUploadStartEvent]}],"file-upload-success":[{predicate:this.hasUnuploadedFiles,action:[this.resetUploadFrame,this.updateRecordState,this.updateProgressBar,this.prepareNextUploadTask,this.fireUploadSuccessEvent]},{action:[this.resetUploadFrame,this.resetUploadingFlag,this.updateRecordState,this.updateToolbar,this.updateProgressBar,this.fireUploadSuccessEvent,this.fireUploadCompleteEvent],state:"ready"}],"file-upload-error":[{predicate:this.hasUnuploadedFiles,action:[this.resetUploadFrame,this.updateRecordState,this.updateProgressBar,this.prepareNextUploadTask,this.fireUploadErrorEvent]},{action:[this.resetUploadFrame,this.resetUploadingFlag,this.updateRecordState,this.updateToolbar,this.updateProgressBar,this.fireUploadErrorEvent,this.fireUploadCompleteEvent],state:"ready"}],"file-upload-failed":[{predicate:this.hasUnuploadedFiles,action:[this.resetUploadFrame,this.updateRecordState,this.updateProgressBar,this.prepareNextUploadTask,this.fireUploadFailedEvent]},{action:[this.resetUploadFrame,this.resetUploadingFlag,this.updateRecordState,this.updateToolbar,this.updateProgressBar,this.fireUploadFailedEvent,this.fireUploadCompleteEvent],state:"ready"}],hide:[{predicate:this.getResetOnHide,action:[this.stopUpload,this.repostHide]},{}],destroy:[{predicate:this.hasUnuploadedFiles,action:[this.resetUploadingFlag,this.abortUpload,this.fireUploadStopEvent,this.flushEventQueue],state:"destroyed"},{action:[this.resetUploadingFlag,this.abortUpload,this.fireUploadStopEvent,this.fireUploadCompleteEvent,this.flushEventQueue],state:"destroyed"}]},destroyed:{}};this.fsa=new Ext.ux.Utils.FSA("created",tt,this),this.addEvents({filetest:!0,fileadd:!0,fileremove:!0,resetqueue:!0,uploadsuccess:!0,uploaderror:!0,uploadfailed:!0,uploadstart:!0,uploadstop:!0,uploadcomplete:!0,fileuploadstart:!0}),this.on("render",this.onWindowRender,this),this.on("beforehide",this.onWindowBeforeHide,this),this.on("hide",this.onWindowHide,this),this.on("destroy",this.onWindowDestroy,this),this.state_tpl=new Ext.Template("<div class='ext-ux-uploaddialog-state ext-ux-uploaddialog-state-{state}'> </div>").compile()},createForm:function(){this.form=Ext.DomHelper.append(this.body,{tag:"form",method:"post",action:this.url,style:"position: absolute; left: -100px; top: -100px; width: 100px; height: 100px; clear: both;"})},createProgressBar:function(){this.progress_bar=this.add(new Ext.ProgressBar({x:0,y:0,anchor:"0",value:0,text:this.i18n.progress_waiting_text}))},createGrid:function(){var store=new Ext.data.Store({proxy:new Ext.data.MemoryProxy([]),reader:new Ext.data.JsonReader({},Ext.ux.UploadDialog.FileRecord),sortInfo:{field:"state",direction:"DESC"},pruneModifiedRecords:!0}),cm=new Ext.grid.ColumnModel([{header:this.i18n.state_col_title,width:this.i18n.state_col_width,resizable:!1,dataIndex:"state",sortable:!0,renderer:this.renderStateCell.createDelegate(this)},{header:this.i18n.filename_col_title,width:this.i18n.filename_col_width,dataIndex:"filename",sortable:!0,renderer:this.renderFilenameCell.createDelegate(this)},{header:this.i18n.note_col_title,width:this.i18n.note_col_width,dataIndex:"note",sortable:!0,renderer:this.renderNoteCell.createDelegate(this)}]);this.grid_panel=new Ext.grid.GridPanel({ds:store,cm,layout:"fit",height:this.height-100,region:"center",x:0,y:22,border:!0,viewConfig:{autoFill:!0,forceFit:!0},bbar:new Ext.Toolbar}),this.grid_panel.on("render",this.onGridRender,this),this.add(this.grid_panel),this.grid_panel.getSelectionModel().on("selectionchange",this.onGridSelectionChange,this)},fillToolbar:function(){var tb=this.grid_panel.getBottomToolbar();tb.x_buttons={},tb.x_buttons.add=tb.addItem(new Ext.ux.UploadDialog.TBBrowseButton({input_name:this.post_var_name,text:this.i18n.add_btn_text,tooltip:this.i18n.add_btn_tip,iconCls:"ext-ux-uploaddialog-addbtn",handler:this.onAddButtonFileSelected,scope:this})),tb.x_buttons.remove=tb.addButton({text:this.i18n.remove_btn_text,tooltip:this.i18n.remove_btn_tip,iconCls:"ext-ux-uploaddialog-removebtn",handler:this.onRemoveButtonClick,scope:this}),tb.x_buttons.reset=tb.addButton({text:this.i18n.reset_btn_text,tooltip:this.i18n.reset_btn_tip,iconCls:"ext-ux-uploaddialog-resetbtn",handler:this.onResetButtonClick,scope:this}),tb.x_buttons.upload=tb.addButton({text:this.i18n.upload_btn_start_text,tooltip:this.i18n.upload_btn_start_tip,iconCls:"ext-ux-uploaddialog-uploadstartbtn",handler:this.onUploadButtonClick,scope:this}),tb.x_buttons.close=tb.addButton({text:this.i18n.close_btn_text,tooltip:this.i18n.close_btn_tip,handler:this.onCloseButtonClick,scope:this})},renderStateCell:function(data,cell,record,row_index,column_index,store){return this.state_tpl.apply({state:data})},renderFilenameCell:function(data,cell,record,row_index,column_index,store){var view=this.grid_panel.getView();return function(){try{Ext.fly(view.getCell(row_index,column_index)).child(".x-grid3-cell-inner").dom.qtip=data}catch(e){}}.defer(1e3),data},renderNoteCell:function(data,cell,record,row_index,column_index,store){var view=this.grid_panel.getView();return function(){try{Ext.fly(view.getCell(row_index,column_index)).child(".x-grid3-cell-inner").dom.qtip=data}catch(e){}}.defer(1e3),data},getFileExtension:function(filename){var result=null,parts=filename.split(".");return parts.length>1&&(result=parts.pop()),result},isPermittedFileType:function(filename){var result=!0;return this.permitted_extensions.length>0&&(result=-1!=this.permitted_extensions.indexOf(this.getFileExtension(filename))),result},isPermittedFile:function(browse_btn){var result=!1,filename=browse_btn.getInputFile().dom.value;return this.isPermittedFileType(filename)?result=!0:(Ext.Msg.alert(this.i18n.error_msgbox_title,String.format(this.i18n.err_file_type_not_permitted,filename,this.permitted_extensions.join(this.i18n.permitted_extensions_join_str))),result=!1),result},fireFileTestEvent:function(browse_btn){return!1!==this.fireEvent("filetest",this,browse_btn.getInputFile().dom.value)},addFileToUploadQueue:function(browse_btn){var input_file=browse_btn.detachInputFile();input_file.appendTo(this.form),input_file.setStyle("width","100px"),input_file.dom.disabled=!0;var store=this.grid_panel.getStore(),fileApi=input_file.dom.files,filename=void 0!==fileApi?fileApi[0].name:input_file.dom.value.replace("C:\\fakepath\\","");store.add(new Ext.ux.UploadDialog.FileRecord({state:Ext.ux.UploadDialog.FileRecord.STATE_QUEUE,filename,note:this.i18n.note_queued_to_upload,input_element:input_file})),this.fsa.postEvent("file-added",input_file.dom.value)},fireFileAddEvent:function(filename){this.fireEvent("fileadd",this,filename)},updateProgressBar:function(){if(this.is_uploading){var queued=this.getQueuedCount(!0),value=1-queued/this.initial_queued_count;this.progress_bar.updateProgress(value,String.format(this.i18n.progress_uploading_text,this.initial_queued_count-queued,this.initial_queued_count))}else this.progress_bar.updateProgress(0,this.i18n.progress_waiting_text)},updateToolbar:function(){var tb=this.grid_panel.getBottomToolbar();this.is_uploading?(tb.x_buttons.remove.disable(),tb.x_buttons.reset.disable(),tb.x_buttons.upload.enable(),this.getAllowCloseOnUpload()||tb.x_buttons.close.disable(),tb.x_buttons.upload.setIconClass("ext-ux-uploaddialog-uploadstopbtn"),tb.x_buttons.upload.setText(this.i18n.upload_btn_stop_text),tb.x_buttons.upload.getEl().child(tb.x_buttons.upload.buttonSelector).dom[tb.x_buttons.upload.tooltipType]=this.i18n.upload_btn_stop_tip):(tb.x_buttons.remove.enable(),tb.x_buttons.reset.enable(),tb.x_buttons.close.enable(),tb.x_buttons.upload.setIconClass("ext-ux-uploaddialog-uploadstartbtn"),tb.x_buttons.upload.setText(this.i18n.upload_btn_start_text),this.getQueuedCount()>0?tb.x_buttons.upload.enable():tb.x_buttons.upload.disable(),this.grid_panel.getSelectionModel().hasSelection()?tb.x_buttons.remove.enable():tb.x_buttons.remove.disable(),this.grid_panel.getStore().getCount()>0?tb.x_buttons.reset.enable():tb.x_buttons.reset.disable())},saveInitialQueuedCount:function(){this.initial_queued_count=this.getQueuedCount()},incInitialQueuedCount:function(){this.initial_queued_count++},setUploadingFlag:function(){this.is_uploading=!0},resetUploadingFlag:function(){this.is_uploading=!1},prepareNextUploadTask:function(){var store=this.grid_panel.getStore(),record=null;store.each((function(r){record||r.get("state")!=Ext.ux.UploadDialog.FileRecord.STATE_QUEUE?r.get("input_element").dom.disabled=!0:record=r})),record.get("input_element").dom.disabled=!1,record.set("state",Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING),record.set("note",this.i18n.note_processing),record.commit(),this.fsa.postEvent("file-upload-start",record)},fireUploadStartEvent:function(){this.fireEvent("uploadstart",this)},removeFiles:function(file_records){for(var store=this.grid_panel.getStore(),i=0,len=file_records.length;i<len;i++){var r=file_records[i];r.get("input_element").remove(),store.remove(r)}},fireFileRemoveEvent:function(file_records){for(var i=0,len=file_records.length;i<len;i++)this.fireEvent("fileremove",this,file_records[i].get("filename"))},resetQueue:function(){var store=this.grid_panel.getStore();store.each((function(r){r.get("input_element").remove()})),store.removeAll()},fireResetQueueEvent:function(){this.fireEvent("resetqueue",this)},uploadFile:function(record){Ext.Ajax.request({url:this.url,params:this.base_params||this.baseParams||this.params,method:"POST",form:this.form,isUpload:!0,success:this.onAjaxSuccess,failure:this.onAjaxFailure,scope:this,record})},fireFileUploadStartEvent:function(record){this.fireEvent("fileuploadstart",this,record.get("filename"))},updateRecordState:function(data){"success"in data.response&&data.response.success?(data.record.set("state",Ext.ux.UploadDialog.FileRecord.STATE_FINISHED),data.record.set("note",data.response.message||data.response.error||this.i18n.note_upload_success)):(data.record.set("state",Ext.ux.UploadDialog.FileRecord.STATE_FAILED),data.record.set("note",data.response.message||data.response.error||this.i18n.note_upload_error)),data.record.commit()},fireUploadSuccessEvent:function(data){this.fireEvent("uploadsuccess",this,data.record.get("filename"),data.response)},fireUploadErrorEvent:function(data){this.fireEvent("uploaderror",this,data.record.get("filename"),data.response)},fireUploadFailedEvent:function(data){this.fireEvent("uploadfailed",this,data.record.get("filename"))},fireUploadCompleteEvent:function(){this.fireEvent("uploadcomplete",this)},findUploadFrame:function(){this.upload_frame=Ext.getBody().child("iframe.x-hidden:last")},resetUploadFrame:function(){this.upload_frame=null},removeUploadFrame:function(){this.upload_frame&&(this.upload_frame.removeAllListeners(),this.upload_frame.dom.src="about:blank",this.upload_frame.remove()),this.upload_frame=null},abortUpload:function(){this.removeUploadFrame();var store=this.grid_panel.getStore(),record=null;store.each((function(r){if(r.get("state")==Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING)return record=r,!1})),record.set("state",Ext.ux.UploadDialog.FileRecord.STATE_FAILED),record.set("note",this.i18n.note_aborted),record.commit()},fireUploadStopEvent:function(){this.fireEvent("uploadstop",this)},repostHide:function(){this.fsa.postEvent("hide")},flushEventQueue:function(){this.fsa.flushEventQueue()},onWindowRender:function(){this.fsa.postEvent("window-render")},onWindowBeforeHide:function(){return!this.isUploading()||this.getAllowCloseOnUpload()},onWindowHide:function(){this.fsa.postEvent("hide")},onWindowDestroy:function(){this.fsa.postEvent("destroy")},onGridRender:function(){this.fsa.postEvent("grid-render")},onGridSelectionChange:function(){this.fsa.postEvent("grid-selection-change")},onAddButtonFileSelected:function(btn){this.fsa.postEvent("file-selected",btn)},onUploadButtonClick:function(){this.is_uploading?this.fsa.postEvent("stop-upload"):this.fsa.postEvent("start-upload")},onRemoveButtonClick:function(){var selections=this.grid_panel.getSelectionModel().getSelections();this.fsa.postEvent("remove-files",selections)},onResetButtonClick:function(){this.fsa.postEvent("reset-queue")},onCloseButtonClick:function(){this[this.closeAction].call(this),1==this.Make_Reload&&document.location.reload()},onAjaxSuccess:function(response,options){var json_response={success:!1,error:this.i18n.note_upload_error};try{var rt=response.responseText,filter=rt.match(/^<pre>((?:.|\n)*)<\/pre>$/i);filter&&(rt=filter[1]),json_response=Ext.util.JSON.decode(rt)}catch(e){}var data={record:options.record,response:json_response};"success"in json_response&&json_response.success?this.fsa.postEvent("file-upload-success",data):this.fsa.postEvent("file-upload-error",data)},onAjaxFailure:function(response,options){var data={record:options.record,response:{success:!1,error:this.i18n.note_upload_failed}};this.fsa.postEvent("file-upload-failed",data)},startUpload:function(){this.fsa.postEvent("start-upload")},stopUpload:function(){this.fsa.postEvent("stop-upload")},getUrl:function(){return this.url},setUrl:function(url){this.url=url},getBaseParams:function(){return this.base_params},setBaseParams:function(params){this.base_params=params},getUploadAutostart:function(){return this.upload_autostart},setUploadAutostart:function(value){this.upload_autostart=value},getMakeReload:function(){return this.Make_Reload},setMakeReload:function(value){this.Make_Reload=value},getAllowCloseOnUpload:function(){return this.allow_close_on_upload},setAllowCloseOnUpload:function(value){this.allow_close_on_upload},getResetOnHide:function(){return this.reset_on_hide},setResetOnHide:function(value){this.reset_on_hide=value},getPermittedExtensions:function(){return this.permitted_extensions},setPermittedExtensions:function(value){this.permitted_extensions=value},isUploading:function(){return this.is_uploading},isNotEmptyQueue:function(){return this.grid_panel.getStore().getCount()>0},getQueuedCount:function(count_processing){var count=0;return this.grid_panel.getStore().each((function(r){r.get("state")==Ext.ux.UploadDialog.FileRecord.STATE_QUEUE&&count++,count_processing&&r.get("state")==Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING&&count++})),count},hasUnuploadedFiles:function(){return this.getQueuedCount()>0}});var p=Ext.ux.UploadDialog.Dialog.prototype;p.i18n={title:_("upload_files"),state_col_title:_("upf_state"),state_col_width:70,filename_col_title:_("upf_filename"),filename_col_width:230,note_col_title:_("upf_note"),note_col_width:150,add_btn_text:_("upf_add"),add_btn_tip:_("upf_add_desc"),remove_btn_text:_("upf_remove"),remove_btn_tip:_("upf_remove_desc"),reset_btn_text:_("upf_reset"),reset_btn_tip:_("upf_reset_desc"),upload_btn_start_text:_("upf_upload"),upload_btn_start_tip:_("upf_upload_desc"),upload_btn_stop_text:_("upf_abort"),upload_btn_stop_tip:_("upf_abort_desc"),close_btn_text:_("upf_close"),close_btn_tip:_("upf_close_desc"),progress_waiting_text:_("upf_progress_wait"),progress_uploading_text:_("upf_uploading_desc"),error_msgbox_title:_("upf_error"),permitted_extensions_join_str:",",err_file_type_not_permitted:_("upf_err_filetype"),note_queued_to_upload:_("upf_queued"),note_processing:_("upf_uploading"),note_upload_failed:_("upf_err_failed"),note_upload_success:_("upf_success"),note_upload_error:_("upf_upload_err"),note_aborted:_("upf_aborted")},
/*!
 * Ext JS Library 3.4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
Ext.ns("Ext.ux.form"),Ext.ux.form.FileUploadField=Ext.extend(Ext.form.TextField,{buttonText:"Browse...",buttonOnly:!1,buttonOffset:3,readOnly:!0,autoSize:Ext.emptyFn,initComponent:function(){Ext.ux.form.FileUploadField.superclass.initComponent.call(this),this.addEvents("fileselected")},onRender:function(ct,position){Ext.ux.form.FileUploadField.superclass.onRender.call(this,ct,position),this.wrap=this.el.wrap({cls:"x-form-field-wrap x-form-fileupload-wrap"}),this.el.addClass("x-form-file-text"),this.el.dom.removeAttribute("name"),this.createFileInput();var btnCfg=Ext.applyIf(this.buttonCfg||{},{text:this.buttonText});this.button=new Ext.Button(Ext.apply(btnCfg,{renderTo:this.wrap,cls:"x-form-file-btn"+(btnCfg.iconCls?" x-btn-icon":"")})),this.buttonOnly&&(this.el.hide(),this.wrap.setWidth(this.button.getEl().getWidth())),this.bindListeners(),this.resizeEl=this.positionEl=this.wrap},bindListeners:function(){this.fileInput.on({scope:this,mouseenter:function(){this.button.addClass(["x-btn-over","x-btn-focus"])},mouseleave:function(){this.button.removeClass(["x-btn-over","x-btn-focus","x-btn-click"])},mousedown:function(){this.button.addClass("x-btn-click")},mouseup:function(){this.button.removeClass(["x-btn-over","x-btn-focus","x-btn-click"])},change:function(){var v=this.fileInput.dom.value;this.setValue(v),this.fireEvent("fileselected",this,v)}})},createFileInput:function(){this.fileInput=this.wrap.createChild({id:this.getFileInputId(),name:this.name||this.getId(),cls:"x-form-file",tag:"input",type:"file",size:1})},reset:function(){this.rendered&&(this.fileInput.remove(),this.createFileInput(),this.bindListeners()),Ext.ux.form.FileUploadField.superclass.reset.call(this)},getFileInputId:function(){return this.id+"-file"},onResize:function(w,h){if(Ext.ux.form.FileUploadField.superclass.onResize.call(this,w,h),this.wrap.setWidth(w),!this.buttonOnly){w=this.wrap.getWidth()-this.button.getEl().getWidth()-this.buttonOffset;this.el.setWidth(w)}},onDestroy:function(){Ext.ux.form.FileUploadField.superclass.onDestroy.call(this),Ext.destroy(this.fileInput,this.button,this.wrap)},onDisable:function(){Ext.ux.form.FileUploadField.superclass.onDisable.call(this),this.doDisable(!0)},onEnable:function(){Ext.ux.form.FileUploadField.superclass.onEnable.call(this),this.doDisable(!1)},doDisable:function(disabled){this.fileInput.dom.disabled=disabled,this.button.setDisabled(disabled)},preFocus:Ext.emptyFn,alignErrorIcon:function(){this.errorIcon.alignTo(this.wrap,"tl-tr",[2,0])}}),Ext.reg("fileuploadfield",Ext.ux.form.FileUploadField),Ext.form.FileUploadField=Ext.ux.form.FileUploadField,Ext.namespace("Ext.ux.form"),
/**
 * <p>SuperBoxSelect is an extension of the ComboBox component that displays selected items as labelled boxes within the form field. As seen on facebook, hotmail and other sites.</p>
 * 
 * @author <a href="mailto:dan.humphrey@technomedia.co.uk">Dan Humphrey</a>
 * @class Ext.ux.form.SuperBoxSelect
 * @extends Ext.form.ComboBox
 * @constructor
 * @component
 * @version 1.0
 * @license TBA (To be announced)
 * 
 */
Ext.ux.form.SuperBoxSelect=function(config){Ext.ux.form.SuperBoxSelect.superclass.constructor.call(this,config),this.addEvents("beforeadditem","additem","newitem","beforeremoveitem","removeitem","clear")},Ext.ux.form.SuperBoxSelect=Ext.extend(Ext.ux.form.SuperBoxSelect,Ext.form.ComboBox,{addNewDataOnBlur:!1,allowAddNewData:!1,allowQueryAll:!0,backspaceDeletesLastItem:!0,classField:null,clearBtnCls:"",clearLastQueryOnEscape:!1,clearOnEscape:!1,displayFieldTpl:null,extraItemCls:"",extraItemStyle:"",expandBtnCls:"",fixFocusOnTabSelect:!0,forceFormValue:!0,forceSameValueQuery:!1,itemDelimiterKey:Ext.EventObject.ENTER,navigateItemsWithTab:!0,pinList:!0,preventDuplicates:!0,queryFilterRe:"",queryValuesDelimiter:"|",queryValuesIndicator:"valuesqry",removeValuesFromStore:!0,renderFieldBtns:!0,stackItems:!1,styleField:null,supressClearValueRemoveEvents:!1,validationEvent:"blur",valueDelimiter:",",initComponent:function(){Ext.apply(this,{items:new Ext.util.MixedCollection(!1),usedRecords:new Ext.util.MixedCollection(!1),addedRecords:[],remoteLookup:[],hideTrigger:!0,grow:!1,resizable:!1,multiSelectMode:!1,preRenderValue:null,filteredQueryData:""}),this.queryFilterRe&&Ext.isString(this.queryFilterRe)&&(this.queryFilterRe=new RegExp(this.queryFilterRe)),this.transform&&this.doTransform(),this.forceFormValue&&this.items.on({add:this.manageNameAttribute,remove:this.manageNameAttribute,clear:this.manageNameAttribute,scope:this}),Ext.ux.form.SuperBoxSelect.superclass.initComponent.call(this),"remote"===this.mode&&this.store&&this.store.on("load",this.onStoreLoad,this)},onRender:function(ct,position){var h=this.hiddenName;this.hiddenName=null,Ext.ux.form.SuperBoxSelect.superclass.onRender.call(this,ct,position),this.hiddenName=h,this.manageNameAttribute();var extraClass=!0===this.stackItems?"x-superboxselect-stacked":"";this.renderFieldBtns&&(extraClass+=" x-superboxselect-display-btns"),this.el.removeClass("x-form-text").addClass("x-superboxselect-input-field"),this.wrapEl=this.el.wrap({tag:"ul"}),this.outerWrapEl=this.wrapEl.wrap({tag:"div",cls:"x-form-text x-superboxselect "+extraClass}),this.inputEl=this.el.wrap({tag:"li",cls:"x-superboxselect-input"}),this.renderFieldBtns&&this.setupFieldButtons().manageClearBtn(),this.setupFormInterception()},doTransform:function(){var s=Ext.getDom(this.transform),transformValues=[];if(!this.store){this.mode="local";for(var d=[],opts=s.options,i=0,len=opts.length;i<len;i++){var o=opts[i],oe=Ext.get(o),value=oe.getAttributeNS(null,"value")||"",cls=oe.getAttributeNS(null,"className")||"",style=oe.getAttributeNS(null,"style")||"";o.selected&&transformValues.push(value),d.push([value,o.text,cls,"string"==typeof style?style:style.cssText])}this.store=new Ext.data.SimpleStore({id:0,fields:["value","text","cls","style"],data:d}),Ext.apply(this,{valueField:"value",displayField:"text",classField:"cls",styleField:"style"})}transformValues.length&&(this.value=transformValues.join(","))},setupFieldButtons:function(){return this.buttonWrap=this.outerWrapEl.createChild({cls:"x-superboxselect-btns"}),this.buttonClear=this.buttonWrap.createChild({tag:"div",cls:"x-superboxselect-btn-clear "+this.clearBtnCls}),this.allowQueryAll&&(this.buttonExpand=this.buttonWrap.createChild({tag:"div",cls:"x-superboxselect-btn-expand "+this.expandBtnCls})),this.initButtonEvents(),this},initButtonEvents:function(){this.buttonClear.addClassOnOver("x-superboxselect-btn-over").on("click",(function(e){e.stopEvent(),this.disabled||(this.clearValue(),this.el.focus())}),this),this.allowQueryAll&&this.buttonExpand.addClassOnOver("x-superboxselect-btn-over").on("click",(function(e){e.stopEvent(),this.disabled||(this.isExpanded()?this.multiSelectMode=!1:this.pinList&&(this.multiSelectMode=!0),this.onTriggerClick())}),this)},removeButtonEvents:function(){return this.buttonClear.removeAllListeners(),this.allowQueryAll&&this.buttonExpand.removeAllListeners(),this},clearCurrentFocus:function(){return this.currentFocus&&(this.currentFocus.onLnkBlur(),this.currentFocus=null),this},initEvents:function(){var el=this.el;el.on({click:this.onClick,focus:this.clearCurrentFocus,blur:this.onBlur,keydown:this.onKeyDownHandler,keyup:this.onKeyUpBuffered,scope:this}),this.on({collapse:this.onCollapse,expand:this.clearCurrentFocus,scope:this}),this.wrapEl.on("click",this.onWrapClick,this),this.outerWrapEl.on("click",this.onWrapClick,this),this.inputEl.focus=function(){el.focus()},Ext.ux.form.SuperBoxSelect.superclass.initEvents.call(this),Ext.apply(this.keyNav,{tab:function(e){return this.fixFocusOnTabSelect&&this.isExpanded()?(e.stopEvent(),el.blur(),this.onViewClick(!1),this.focus(!1,10),!0):(this.onViewClick(!1),""!==el.dom.value&&this.setRawValue(""),!0)},down:function(e){this.isExpanded()||this.currentFocus?(this.inKeyMode=!0,this.selectNext()):this.allowQueryAll&&this.onTriggerClick()},enter:function(){}})},onClick:function(){this.clearCurrentFocus(),this.collapse(),this.autoSize()},beforeBlur:function(){if(this.allowAddNewData&&this.addNewDataOnBlur){var v=this.el.dom.value;""!==v&&this.fireNewItemEvent(v)}Ext.form.ComboBox.superclass.beforeBlur.call(this)},onFocus:function(){this.outerWrapEl.addClass(this.focusClass),Ext.ux.form.SuperBoxSelect.superclass.onFocus.call(this)},onBlur:function(){this.outerWrapEl.removeClass(this.focusClass),this.clearCurrentFocus(),""!==this.el.dom.value&&(this.applyEmptyText(),this.autoSize()),Ext.ux.form.SuperBoxSelect.superclass.onBlur.call(this)},onCollapse:function(){this.view.clearSelections(),this.multiSelectMode=!1},onWrapClick:function(e){e.stopEvent(),this.collapse(),this.el.focus(),this.clearCurrentFocus()},markInvalid:function(msg){var elp,t;if(this.rendered&&!this.preventMark){switch(this.outerWrapEl.addClass(this.invalidClass),msg=msg||this.invalidText,this.msgTarget){case"qtip":Ext.apply(this.el.dom,{qtip:msg,qclass:"x-form-invalid-tip"}),Ext.apply(this.wrapEl.dom,{qtip:msg,qclass:"x-form-invalid-tip"}),Ext.QuickTips&&Ext.QuickTips.enable();break;case"title":this.el.dom.title=msg,this.wrapEl.dom.title=msg,this.outerWrapEl.dom.title=msg;break;case"under":if(!this.errorEl){if(!(elp=this.getErrorCt())){this.el.dom.title=msg;break}this.errorEl=elp.createChild({cls:"x-form-invalid-msg"}),this.errorEl.setWidth(elp.getWidth(!0)-20)}this.errorEl.update(msg),Ext.form.Field.msgFx[this.msgFx].show(this.errorEl,this);break;case"side":if(!this.errorIcon){if(!(elp=this.getErrorCt())){this.el.dom.title=msg;break}this.errorIcon=elp.createChild({cls:"x-form-invalid-icon"})}this.alignErrorIcon(),Ext.apply(this.errorIcon.dom,{qtip:msg,qclass:"x-form-invalid-tip"}),this.errorIcon.show(),this.on("resize",this.alignErrorIcon,this);break;default:(t=Ext.getDom(this.msgTarget)).innerHTML=msg,t.style.display=this.msgDisplay}this.fireEvent("invalid",this,msg)}},clearInvalid:function(){if(this.rendered&&!this.preventMark){switch(this.outerWrapEl.removeClass(this.invalidClass),this.msgTarget){case"qtip":this.el.dom.qtip="",this.wrapEl.dom.qtip="";break;case"title":this.el.dom.title="",this.wrapEl.dom.title="",this.outerWrapEl.dom.title="";break;case"under":this.errorEl&&Ext.form.Field.msgFx[this.msgFx].hide(this.errorEl,this);break;case"side":this.errorIcon&&(this.errorIcon.dom.qtip="",this.errorIcon.hide(),this.un("resize",this.alignErrorIcon,this));break;default:var t=Ext.getDom(this.msgTarget);t.innerHTML="",t.style.display="none"}this.fireEvent("valid",this)}},alignErrorIcon:function(){this.wrap&&this.errorIcon.alignTo(this.wrap,"tl-tr",[Ext.isIE?5:2,3])},expand:function(){!this.isExpanded()&&this.hasFocus&&(this.bufferSize&&(this.doResize(this.bufferSize),delete this.bufferSize),this.list.alignTo(this.outerWrapEl,this.listAlign).show(),this.innerList.setOverflow("auto"),this.mon(Ext.getDoc(),{scope:this,mousewheel:this.collapseIf,mousedown:this.collapseIf}),this.fireEvent("expand",this))},restrictHeight:function(){var inner=this.innerList.dom,st=inner.scrollTop,list=this.list;inner.style.height="";var pad=list.getFrameWidth("tb")+(this.resizable?this.handleHeight:0)+this.assetHeight,h=Math.max(inner.clientHeight,inner.offsetHeight,inner.scrollHeight),ha=this.getPosition()[1]-Ext.getBody().getScroll().top,hb=Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,space=Math.max(ha,hb,this.minHeight||0)-list.shadowOffset-pad-5;h=Math.min(h,space,this.maxHeight),this.innerList.setHeight(h),list.beginUpdate(),list.setHeight(h+pad),list.alignTo(this.outerWrapEl,this.listAlign),list.endUpdate(),this.multiSelectMode&&(inner.scrollTop=st)},validateValue:function(val){return 0===this.items.getCount()?this.allowBlank?(this.clearInvalid(),!0):(this.markInvalid(this.blankText),!1):(this.clearInvalid(),!0)},manageNameAttribute:function(){0===this.items.getCount()&&this.forceFormValue?this.el.dom.setAttribute("name",this.hiddenName||this.name):this.el.dom.removeAttribute("name")},setupFormInterception:function(){var form;if(this.findParentBy((function(p){p.getForm&&(form=p.getForm())})),form){var formGet=form.getValues;form.getValues=function(asString){this.el.dom.disabled=!0;var oldVal=this.el.dom.value;this.setRawValue("");var vals=formGet.call(form);return this.el.dom.disabled=!1,this.setRawValue(oldVal),this.forceFormValue&&0===this.items.getCount()&&(vals[this.name]=""),asString?Ext.urlEncode(vals):vals}.createDelegate(this)}},onResize:function(w,h,rw,rh){var reduce=Ext.isIE6?4:Ext.isIE7||Ext.isIE8?1:0;this.wrapEl&&(this._width=w,this.outerWrapEl.setWidth(w-reduce),this.renderFieldBtns&&(reduce+=this.buttonWrap.getWidth()+20,this.wrapEl.setWidth(w-reduce))),Ext.ux.form.SuperBoxSelect.superclass.onResize.call(this,w,h,rw,rh),this.autoSize()},onEnable:function(){Ext.ux.form.SuperBoxSelect.superclass.onEnable.call(this),this.items.each((function(item){item.enable()})),this.renderFieldBtns&&this.initButtonEvents()},onDisable:function(){Ext.ux.form.SuperBoxSelect.superclass.onDisable.call(this),this.items.each((function(item){item.disable()})),this.renderFieldBtns&&this.removeButtonEvents()},clearValue:function(supressRemoveEvent){return Ext.ux.form.SuperBoxSelect.superclass.clearValue.call(this),this.preventMultipleRemoveEvents=supressRemoveEvent||this.supressClearValueRemoveEvents||!1,this.removeAllItems(),this.preventMultipleRemoveEvents=!1,this.fireEvent("clear",this),this},fireNewItemEvent:function(val){this.view.clearSelections(),this.collapse(),this.setRawValue(""),this.queryFilterRe&&!(val=val.replace(this.queryFilterRe,""))||this.fireEvent("newitem",this,val,this.filteredQueryData)},onKeyUp:function(e){!1===this.editable||e.isSpecialKey()&&e.getKey()!==e.BACKSPACE||this.itemDelimiterKey.indexOf===e.getKey()||e.hasModifier()&&!e.shiftKey||(this.lastKey=e.getKey(),this.dqTask.delay(this.queryDelay))},onKeyDownHandler:function(e,t){var toDestroy,nextFocus,idx;if(e.getKey()===e.ESC&&(this.isExpanded()||""!=this.el.dom.value&&(this.clearOnEscape||this.clearLastQueryOnEscape)&&(this.clearOnEscape&&(this.el.dom.value=""),this.clearLastQueryOnEscape&&(this.lastQuery=""),e.stopEvent())),(e.getKey()===e.DELETE||e.getKey()===e.SPACE)&&this.currentFocus)return e.stopEvent(),toDestroy=this.currentFocus,this.on("expand",(function(){this.collapse()}),this,{single:!0}),idx=this.items.indexOfKey(this.currentFocus.key),this.clearCurrentFocus(),idx<this.items.getCount()-1&&(nextFocus=this.items.itemAt(idx+1)),toDestroy.preDestroy(!0),nextFocus&&function(){nextFocus.onLnkFocus(),this.currentFocus=nextFocus}.defer(200,this),!0;var it,val=this.el.dom.value,ctrl=e.ctrlKey;if(this.itemDelimiterKey===e.getKey()){if(e.stopEvent(),""!==val)ctrl||!this.isExpanded()?this.fireNewItemEvent(val):(this.onViewClick(),this.unsetDelayCheck&&(this.delayedCheck=!0,this.unsetDelayCheck.defer(10,this)));else{if(!this.isExpanded())return;this.onViewClick(),this.unsetDelayCheck&&(this.delayedCheck=!0,this.unsetDelayCheck.defer(10,this))}return!0}if(""===val)return e.getKey()===e.HOME?(e.stopEvent(),this.items.getCount()>0&&(this.collapse(),(it=this.items.get(0)).el.focus()),!0):e.getKey()===e.BACKSPACE?(e.stopEvent(),this.currentFocus?(toDestroy=this.currentFocus,this.on("expand",(function(){this.collapse()}),this,{single:!0}),idx=this.items.indexOfKey(toDestroy.key),this.clearCurrentFocus(),idx<this.items.getCount()-1&&(nextFocus=this.items.itemAt(idx+1)),toDestroy.preDestroy(!0),void(nextFocus&&function(){nextFocus.onLnkFocus(),this.currentFocus=nextFocus}.defer(200,this))):((it=this.items.get(this.items.getCount()-1))&&(this.backspaceDeletesLastItem?(this.on("expand",(function(){this.collapse()}),this,{single:!0}),it.preDestroy(!0)):this.navigateItemsWithTab?it.onElClick():this.on("expand",(function(){this.collapse(),this.currentFocus=it,this.currentFocus.onLnkFocus.defer(20,this.currentFocus)}),this,{single:!0})),!0)):e.isNavKeyPress()?e.getKey()===e.LEFT||e.getKey()===e.UP&&!this.isExpanded()?(e.stopEvent(),this.collapse(),it=this.items.get(this.items.getCount()-1),this.navigateItemsWithTab?it&&it.focus():this.currentFocus?(idx=this.items.indexOfKey(this.currentFocus.key),this.clearCurrentFocus(),0!==idx&&(this.currentFocus=this.items.itemAt(idx-1),this.currentFocus.onLnkFocus())):(this.currentFocus=it,it&&it.onLnkFocus()),!0):e.getKey()===e.DOWN&&this.currentFocus?(this.collapse(),e.stopEvent(),(idx=this.items.indexOfKey(this.currentFocus.key))==this.items.getCount()-1?this.clearCurrentFocus.defer(10,this):(this.clearCurrentFocus(),this.currentFocus=this.items.itemAt(idx+1),this.currentFocus&&this.currentFocus.onLnkFocus()),!0):void(e.getKey()===e.RIGHT&&(this.collapse(),it=this.items.itemAt(0),this.navigateItemsWithTab?it&&it.focus():this.currentFocus?(idx=this.items.indexOfKey(this.currentFocus.key),this.clearCurrentFocus(),idx<this.items.getCount()-1&&(this.currentFocus=this.items.itemAt(idx+1),this.currentFocus&&this.currentFocus.onLnkFocus())):(this.currentFocus=it,it&&it.onLnkFocus()))):(this.multiSelectMode=!1,void this.clearCurrentFocus());this.autoSize()},onKeyUpBuffered:function(e){e.isNavKeyPress()||this.autoSize()},reset:function(){this.killItems(),Ext.ux.form.SuperBoxSelect.superclass.reset.call(this),this.addedRecords=[],this.autoSize().setRawValue("")},applyEmptyText:function(){return this.setRawValue(""),this.items.getCount()>0?(this.el.removeClass(this.emptyClass),this.setRawValue(""),this):(this.rendered&&this.emptyText&&this.getRawValue().length<1&&(this.setRawValue(this.emptyText),this.el.addClass(this.emptyClass)),this)},removeAllItems:function(){return this.items.each((function(item){item.preDestroy(!0)}),this),this.manageClearBtn(),this},killItems:function(){return this.items.each((function(item){item.kill()}),this),this.resetStore(),this.items.clear(),this.manageClearBtn(),this},resetStore:function(){return this.store.clearFilter(),this.removeValuesFromStore?(this.usedRecords.each((function(rec){this.store.add(rec)}),this),this.usedRecords.clear(),this.store.remoteSort||this.store.sort(this.displayField,"ASC"),this):this},sortStore:function(){var ss=this.store.getSortState();return ss&&ss.field&&this.store.sort(ss.field,ss.direction),this},getCaption:function(dataObject){"string"==typeof this.displayFieldTpl&&(this.displayFieldTpl=new Ext.XTemplate(this.displayFieldTpl));var caption,recordData=dataObject instanceof Ext.data.Record?dataObject.data:dataObject;return this.displayFieldTpl?caption=this.displayFieldTpl.apply(recordData):this.displayField&&(caption=recordData[this.displayField]),caption},addRecord:function(record){var display=record.data[this.displayField],caption=this.getCaption(record),val=record.data[this.valueField],cls=this.classField?record.data[this.classField]:"",style=this.styleField?record.data[this.styleField]:"";this.removeValuesFromStore&&(this.usedRecords.add(val,record),this.store.remove(record)),this.addItemBox(val,display,caption,cls,style),this.fireEvent("additem",this,val,record)},createRecord:function(recordData){if(!this.recordConstructor){var recordFields=[{name:this.valueField},{name:this.displayField}];this.classField&&recordFields.push({name:this.classField}),this.styleField&&recordFields.push({name:this.styleField}),this.recordConstructor=Ext.data.Record.create(recordFields)}return new this.recordConstructor(recordData)},addItems:function(newItemObjects){Ext.isArray(newItemObjects)?Ext.each(newItemObjects,(function(item){this.addItem(item)}),this):this.addItem(newItemObjects)},addNewItem:function(newItemObject){this.addItem(newItemObject,!0)},addItem:function(newItemObject,forcedAdd){var val=newItemObject[this.valueField];if(this.disabled)return!1;if(!this.preventDuplicates||!this.hasValue(val)){var record=this.findRecord(this.valueField,val);if(record)this.addRecord(record);else if(this.allowAddNewData){if("remote"===this.mode)return this.remoteLookup.push(newItemObject),void this.doQuery(val,!1,!1,forcedAdd);var rec=this.createRecord(newItemObject);return this.store.add(rec),this.addRecord(rec),!0}}},addItemBox:function(itemVal,itemDisplay,itemCaption,itemClass,itemStyle){var hConfig,itemKey=Ext.id(null,"sbx-item"),box=new Ext.ux.form.SuperBoxSelectItem({owner:this,disabled:this.disabled,renderTo:this.wrapEl,cls:this.extraItemCls+" "+itemClass,style:function(s){var ret="";switch(typeof s){case"function":ret=s.call();break;case"object":for(var p in s)ret+=p+":"+s[p]+";";break;case"string":ret=s+";"}return ret}(this.extraItemStyle)+" "+itemStyle,caption:itemCaption,display:itemDisplay,value:itemVal,key:itemKey,listeners:{remove:function(item){if(!1===this.fireEvent("beforeremoveitem",this,item.value))return!1;this.items.removeKey(item.key),this.removeValuesFromStore&&this.usedRecords.containsKey(item.value)&&(this.store.add(this.usedRecords.get(item.value)),this.usedRecords.removeKey(item.value),this.sortStore(),this.view&&this.view.render()),this.preventMultipleRemoveEvents||this.fireEvent.defer(250,this,["removeitem",this,item.value,this.findInStore(item.value)])},destroy:function(){this.collapse(),this.autoSize().manageClearBtn().validateValue()},scope:this}});box.render(),hConfig={tag:"input",type:"hidden",value:itemVal,name:this.hiddenName||this.name},this.disabled&&Ext.apply(hConfig,{disabled:"disabled"}),box.hidden=this.el.insertSibling(hConfig,"before"),this.items.add(itemKey,box),this.applyEmptyText().autoSize().manageClearBtn().validateValue()},manageClearBtn:function(){if(!this.renderFieldBtns||!this.rendered)return this;var cls="x-superboxselect-btn-hide";return 0===this.items.getCount()?this.buttonClear.addClass(cls):this.buttonClear.removeClass(cls),this},findInStore:function(val){var index=this.store.find(this.valueField,val);return index>-1&&this.store.getAt(index)},getSelectedRecords:function(){var ret=[];if(this.removeValuesFromStore)ret=this.usedRecords.getRange();else{var vals=[];this.items.each((function(item){vals.push(item.value)})),Ext.each(vals,(function(val){ret.push(this.findInStore(val))}),this)}return ret},findSelectedItem:function(el){var ret;return this.items.each((function(item){if(item.el.dom===el)return ret=item,!1})),ret},findSelectedRecord:function(el){var ret,item=this.findSelectedItem(el);return item&&(ret=this.findSelectedRecordByValue(item.value)),ret},findSelectedRecordByValue:function(val){var ret;return this.removeValuesFromStore?this.usedRecords.each((function(rec){if(rec.get(this.valueField)==val)return ret=rec,!1}),this):ret=this.findInStore(val),ret},getValue:function(){var ret=[];return this.items.each((function(item){ret.push(item.value)})),ret.join(this.valueDelimiter)},getCount:function(){return this.items.getCount()},getValueEx:function(){var ret=[];return this.items.each((function(item){var newItem={};newItem[this.valueField]=item.value,newItem[this.displayField]=item.display,this.classField&&(newItem[this.classField]=item.cls||""),this.styleField&&(newItem[this.styleField]=item.style||""),ret.push(newItem)}),this),ret},initValue:function(){Ext.isObject(this.value)||Ext.isArray(this.value)?(this.setValueEx(this.value),this.originalValue=this.getValue()):Ext.ux.form.SuperBoxSelect.superclass.initValue.call(this),"remote"===this.mode&&(this.setOriginal=!0)},addValue:function(value){if(!Ext.isEmpty(value)){var values=value;if(Ext.isArray(value)||(values=(value=""+value).split(this.valueDelimiter)),Ext.each(values,(function(val){var record=this.findRecord(this.valueField,val);record?this.addRecord(record):"remote"===this.mode&&this.remoteLookup.push(val)}),this),"remote"===this.mode){var q=this.remoteLookup.join(this.queryValuesDelimiter);this.doQuery(q,!1,!0)}}},setValue:function(value){this.rendered?(this.removeAllItems().resetStore(),this.remoteLookup=[],this.addValue(value)):this.value=value},setValueEx:function(data){this.rendered?(this.removeAllItems().resetStore(),Ext.isArray(data)||(data=[data]),this.remoteLookup=[],this.allowAddNewData&&"remote"===this.mode?Ext.each(data,(function(d){var r=this.findRecord(this.valueField,d[this.valueField])||this.createRecord(d);this.addRecord(r)}),this):Ext.each(data,(function(item){this.addItem(item)}),this)):this.value=data},hasValue:function(val){var has=!1;return this.items.each((function(item){if(item.value==val)return has=!0,!1}),this),has},onSelect:function(record,index){if(!1!==this.fireEvent("beforeselect",this,record,index)){var val=record.data[this.valueField];if(this.preventDuplicates&&this.hasValue(val))return;this.setRawValue(""),this.lastSelectionText="",!1!==this.fireEvent("beforeadditem",this,val,record,this.filteredQueryData)&&this.addRecord(record),0!==this.store.getCount()&&this.multiSelectMode?this.restrictHeight():this.collapse()}},onDestroy:function(){this.items.purgeListeners(),this.killItems(),this.allowQueryAll&&Ext.destroy(this.buttonExpand),this.renderFieldBtns&&Ext.destroy(this.buttonClear,this.buttonWrap),Ext.destroy(this.inputEl,this.wrapEl,this.outerWrapEl),Ext.ux.form.SuperBoxSelect.superclass.onDestroy.call(this)},autoSize:function(){if(!this.rendered)return this;this.metrics||(this.metrics=Ext.util.TextMetrics.createInstance(this.el));var v=this.el.dom.value,d=document.createElement("div");""===v&&this.emptyText&&this.items.getCount()<1&&(v=this.emptyText),d.appendChild(document.createTextNode(v)),v=d.innerHTML,d=null,v+="&#160;";var w=Math.max(this.metrics.getWidth(v)+24,24);return void 0!==this._width&&(w=Math.min(this._width,w)),this.el.setWidth(w),Ext.isIE&&(this.el.dom.style.top="0"),this.fireEvent("autosize",this,w),this},shouldQuery:function(q){if(this.lastQuery){var m=q.match("^"+this.lastQuery);return!(m&&!this.store.getCount())||m[0]!==this.lastQuery}return!0},doQuery:function(q,forceAll,valuesQuery,forcedAdd){if(q=Ext.isEmpty(q)?"":q,this.queryFilterRe){this.filteredQueryData="";var m=q.match(this.queryFilterRe);if(m&&m.length&&(this.filteredQueryData=m[0]),!(q=q.replace(this.queryFilterRe,""))&&m)return}var qe={query:q,forceAll,combo:this,cancel:!1};if(!1===this.fireEvent("beforequery",qe)||qe.cancel)return!1;q=qe.query,(!0===(forceAll=qe.forceAll)||q.length>=this.minChars||valuesQuery&&!Ext.isEmpty(q))&&(forcedAdd||this.forceSameValueQuery||this.shouldQuery(q)?(this.lastQuery=q,"local"==this.mode?(this.selectedIndex=-1,forceAll?this.store.clearFilter():this.store.filter(this.displayField,q),this.onLoad()):(this.store.baseParams[this.queryParam]=q,this.store.baseParams[this.queryValuesIndicator]=valuesQuery,this.store.load({params:this.getParams(q)}),forcedAdd||this.expand())):(this.selectedIndex=-1,this.onLoad()))},onStoreLoad:function(store,records,options){var q=options.params[this.queryParam]||store.baseParams[this.queryParam]||"",isValuesQuery=options.params[this.queryValuesIndicator]||store.baseParams[this.queryValuesIndicator];if(this.removeValuesFromStore&&this.store.each((function(record){this.usedRecords.containsKey(record.get(this.valueField))&&this.store.remove(record)}),this),isValuesQuery){var params=q.split(this.queryValuesDelimiter);Ext.each(params,(function(p){this.remoteLookup.remove(p);var rec=this.findRecord(this.valueField,p);rec&&this.addRecord(rec)}),this),this.setOriginal&&(this.setOriginal=!1,this.originalValue=this.getValue())}""!==q&&this.allowAddNewData&&Ext.each(this.remoteLookup,(function(r){if("object"==typeof r&&r[this.valueField]===q){if(this.remoteLookup.remove(r),records.length&&records[0].get(this.valueField)===q)return void this.addRecord(records[0]);var rec=this.createRecord(r);return this.store.add(rec),this.addRecord(rec),this.addedRecords.push(rec),void function(){this.isExpanded()&&this.collapse()}.defer(10,this)}}),this);var toAdd=[];if(""===q)Ext.each(this.addedRecords,(function(rec){this.preventDuplicates&&this.usedRecords.containsKey(rec.get(this.valueField))||toAdd.push(rec)}),this);else{var re=new RegExp(Ext.escapeRe(q)+".*","i");Ext.each(this.addedRecords,(function(rec){this.preventDuplicates&&this.usedRecords.containsKey(rec.get(this.valueField))||re.test(rec.get(this.displayField))&&toAdd.push(rec)}),this)}this.store.add(toAdd),this.sortStore(),0===this.store.getCount()&&this.isExpanded()&&this.collapse()}}),Ext.reg("superboxselect",Ext.ux.form.SuperBoxSelect),Ext.ux.form.SuperBoxSelectItem=function(config){Ext.apply(this,config),Ext.ux.form.SuperBoxSelectItem.superclass.constructor.call(this)},Ext.ux.form.SuperBoxSelectItem=Ext.extend(Ext.ux.form.SuperBoxSelectItem,Ext.Component,{initComponent:function(){Ext.ux.form.SuperBoxSelectItem.superclass.initComponent.call(this)},onElClick:function(e){var o=this.owner;if(o.clearCurrentFocus().collapse(),o.navigateItemsWithTab)this.focus();else{o.el.dom.focus();(function(){this.onLnkFocus(),o.currentFocus=this}).defer(10,this)}},onLnkClick:function(e){e&&e.stopEvent(),this.preDestroy(),this.owner.navigateItemsWithTab||this.owner.el.focus()},onLnkFocus:function(){this.el.addClass("x-superboxselect-item-focus"),this.owner.outerWrapEl.addClass("x-form-focus")},onLnkBlur:function(){this.el.removeClass("x-superboxselect-item-focus"),this.owner.outerWrapEl.removeClass("x-form-focus")},enableElListeners:function(){this.el.on("click",this.onElClick,this,{stopEvent:!0}),this.el.addClassOnOver("x-superboxselect-item x-superboxselect-item-hover")},enableLnkListeners:function(){this.lnk.on({click:this.onLnkClick,focus:this.onLnkFocus,blur:this.onLnkBlur,scope:this})},enableAllListeners:function(){this.enableElListeners(),this.enableLnkListeners()},disableAllListeners:function(){this.el.removeAllListeners(),this.lnk.un("click",this.onLnkClick,this),this.lnk.un("focus",this.onLnkFocus,this),this.lnk.un("blur",this.onLnkBlur,this)},onRender:function(ct,position){Ext.ux.form.SuperBoxSelectItem.superclass.onRender.call(this,ct,position);var el=this.el;el&&el.remove(),this.el=el=ct.createChild({tag:"li"},ct.last()),el.addClass("x-superboxselect-item");var btnEl=this.owner.navigateItemsWithTab?"a":"span";this.key;Ext.apply(el,{focus:function(){var c=this.down(btnEl+".x-superboxselect-item-close");c&&c.focus()},preDestroy:function(){this.preDestroy()}.createDelegate(this)}),this.enableElListeners(),el.update(this.caption);var cfg={tag:btnEl,class:"x-superboxselect-item-close",tabIndex:this.owner.navigateItemsWithTab?"0":"-1"};"a"===btnEl&&(cfg.href="#"),this.lnk=el.createChild(cfg),this.disabled?this.disableAllListeners():this.enableLnkListeners(),this.on({disable:this.disableAllListeners,enable:this.enableAllListeners,scope:this}),this.setupKeyMap()},setupKeyMap:function(){this.keyMap=new Ext.KeyMap(this.lnk,[{key:[Ext.EventObject.BACKSPACE,Ext.EventObject.DELETE,Ext.EventObject.SPACE],fn:this.preDestroy,scope:this},{key:[Ext.EventObject.RIGHT,Ext.EventObject.DOWN],fn:function(){this.moveFocus("right")},scope:this},{key:[Ext.EventObject.LEFT,Ext.EventObject.UP],fn:function(){this.moveFocus("left")},scope:this},{key:[Ext.EventObject.HOME],fn:function(){var l=this.owner.items.get(0).el.focus();l&&l.el.focus()},scope:this},{key:[Ext.EventObject.END],fn:function(){this.owner.el.focus()},scope:this},{key:Ext.EventObject.ENTER,fn:function(){}}]),this.keyMap.stopEvent=!0},moveFocus:function(dir){var el=this.el["left"==dir?"prev":"next"]()||this.owner.el;el.focus.defer(100,el)},preDestroy:function(supressEffect){if(!1!==this.fireEvent("remove",this)){var actionDestroy=function(){this.owner.navigateItemsWithTab&&this.moveFocus("right"),this.hidden.remove(),this.hidden=null,this.destroy()};return supressEffect?actionDestroy.call(this):this.el.hide({duration:.2,callback:actionDestroy,scope:this}),this}},kill:function(){this.hidden.remove(),this.hidden=null,this.purgeListeners(),this.destroy()},onDisable:function(){this.hidden&&this.hidden.dom.setAttribute("disabled","disabled"),this.keyMap.disable(),Ext.ux.form.SuperBoxSelectItem.superclass.onDisable.call(this)},onEnable:function(){this.hidden&&this.hidden.dom.removeAttribute("disabled"),this.keyMap.enable(),Ext.ux.form.SuperBoxSelectItem.superclass.onEnable.call(this)},onDestroy:function(){Ext.destroy(this.lnk,this.el),Ext.ux.form.SuperBoxSelectItem.superclass.onDestroy.call(this)}}),MODx.Component=function(config){config=config||{},MODx.Component.superclass.constructor.call(this,config),this.config=config,this._loadForm(),this.config.tabs&&this._loadTabs(),this._loadComponents(),this._loadActionButtons(),MODx.activePage=this},Ext.extend(MODx.Component,Ext.Component,{fields:{},form:null,action:!1,_loadForm:function(){if(!this.config.form)return!1;if(this.form=new Ext.form.BasicForm(Ext.get(this.config.form),{errorReader:MODx.util.JSONReader}),this.config.fields)for(var i in this.config.fields)if(this.config.fields.hasOwnProperty(i)){var f=this.config.fields[i];f.xtype&&(f=Ext.ComponentMgr.create(f)),this.fields[i]=f,this.form.add(f)}return this.form.render()},_loadActionButtons:function(){return!!this.config.buttons&&(this.ab=MODx.load({xtype:"modx-actionbuttons",form:this.form||null,formpanel:this.config.formpanel||null,actions:this.config.actions||null,items:this.config.buttons||[]}),this.ab)},_loadTabs:function(){if(!this.config.tabs)return!1;var o=this.config.tabOptions||{};return Ext.applyIf(o,{xtype:"modx-tabs",renderTo:this.config.tabs_div||"tabs_div",items:this.config.tabs}),MODx.load(o)},_loadComponents:function(){if(!this.config.components)return!1;for(var l=this.config.components.length,cp=Ext.getCmp("modx-content"),i=0;i<l;i+=1){var a=MODx.load(this.config.components[i]);cp&&cp.add(a)}return cp&&cp.doLayout(),!0},submitForm:function(listeners,options,otherParams){if(listeners=listeners||{},otherParams=otherParams||{},!this.config.formpanel||!this.config.action)return!1;if(f=Ext.getCmp(this.config.formpanel),!f)return!1;for(var i in listeners)"function"==typeof listeners[i]?f.on(i,listeners[i],this):listeners[i]&&"object"==typeof listeners[i]&&listeners[i].fn&&f.on(i,listeners[i].fn,listeners[i].scope||this);return Ext.apply(f.baseParams,{action:this.config.action}),Ext.apply(f.baseParams,otherParams),(options=options||{}).headers={"Powered-By":"MODx",modAuth:MODx.siteId},f.submit(options),!0}}),Ext.reg("modx-component",MODx.Component),MODx.toolbar.ActionButtons=function(config){config=config||{},Ext.applyIf(config,{actions:{close:"welcome"},formpanel:!1,id:"modx-action-buttons",params:{},items:[],renderTo:Ext.get("modx-action-buttons-container")?"modx-action-buttons-container":"modx-container"}),config.formpanel&&this.setupDirtyButtons(config.formpanel),this.checkDirtyBtns=[],MODx.toolbar.ActionButtons.superclass.constructor.call(this,config),this.config=config},Ext.extend(MODx.toolbar.ActionButtons,Ext.Toolbar,{id:"",buttons:[],options:{a_close:"welcome"},add:function(){for(var a=arguments,l=a.length,i=0;i<l;i++){var el=a[i],ex=["-","->","<-",""," "];if(-1!=ex.indexOf(el)||el.xtype&&"switch"==el.xtype)MODx.toolbar.ActionButtons.superclass.add.call(this,el);else{var id=el.id||Ext.id();if(Ext.applyIf(el,{xtype:"button",cls:el.icon?"x-btn-icon bmenu":"x-btn-text bmenu",scope:this,disabled:!!el.checkDirty,listeners:{},id}),el.button&&MODx.toolbar.ActionButtons.superclass.add.call(this,el),null===el.handler&&null===el.menu?el.handler=this.checkConfirm:el.confirm&&el.handler?el.handler=function(){Ext.Msg.confirm(_("warning"),el.confirm,(function(e){"yes"===e&&Ext.callback(el.handler,this)}),el.scope||this)}:el.handler||(el.handler=this.handleClick),el.javascript&&(el.listeners.click={fn:this.evalJS,scope:this}),"button"==el.xtype&&(el.listeners.render={fn:function(btn){el.checkDirty&&btn&&this.checkDirtyBtns.push(btn)},scope:this}),el.keys){el.keyMap=new Ext.KeyMap(Ext.get(document));for(var j=0;j<el.keys.length;j++){var key=el.keys[j];Ext.applyIf(key,{scope:this,stopEvent:!0,fn:function(e){var b=Ext.getCmp(id);b&&this.checkConfirm(b,e)}}),el.keyMap.addBinding(key)}el.listeners.destroy={fn:function(btn){btn.keyMap.disable()},scope:this}}MODx.toolbar.ActionButtons.superclass.add.call(this,el)}}},evalJS:function(itm,e){eval(itm.javascript)||(e.stopEvent(),e.preventDefault())},checkConfirm:function(itm,e){return null!==itm.confirm&&void 0!==itm.confirm?this.confirm(itm,(function(){this.handleClick(itm,e)}),this):this.handleClick(itm,e),!1},confirm:function(itm,callback,scope){return null===itm.confirm||Ext.Msg.confirm("",itm.confirm,(function(e){if("yes"===e){if(null===callback)return!0;"function"==typeof callback?Ext.callback(callback,scope||this,[itm]):location.href=callback}return!0}),this),!0},reloadPage:function(){location.href=location.href},handleClick:function(itm,e){var o=this.config;if(!1===o.formpanel||void 0===o.formpanel||null===o.formpanel)return!1;if("remote"===itm.method){if(MODx.util.Progress.reset(),o.form=Ext.getCmp(o.formpanel),!o.form)return!1;var f=o.form.getForm?o.form.getForm():o.form,isv=!0;f.items&&f.items.items&&f.items.items.forEach((item=>{item&&item.validate&&!item.validate()&&(isv=!1)})),isv?(Ext.applyIf(o.params,{action:itm.process}),Ext.apply(f.baseParams,o.params),o.form.on("success",(function(r){if(o.form.clearDirty&&o.form.clearDirty(),MODx.msg.status({title:_("success"),message:r.result.message||_("save_successful"),dontHide:""!=r.result.message}),0!=itm.redirect){var redirect=this.redirect;"function"==typeof itm.redirect&&(redirect=itm.redirect),Ext.callback(redirect,this,[o,itm,r.result],1e3)}this.resetDirtyButtons(r.result)}),this),o.form.submit({headers:{"Powered-By":"MODx",modAuth:MODx.siteId}})):(o.form.fireEvent("failureSubmit"),Ext.Msg.alert(_("error"),_("correct_errors")))}else{var params=itm.params||{};Ext.applyIf(params,o.baseParams||{}),MODx.loadPage("?"+Ext.urlEncode(params))}return!1},resetDirtyButtons:function(r){for(var i=0;i<this.checkDirtyBtns.length;i+=1){this.checkDirtyBtns[i].setDisabled(!0)}},redirect:function(o,itm,res){var url;o=this.config,itm.params=itm.params||{},Ext.applyIf(itm.params,o.baseParams);var action,process=itm.process.substr(itm.process.lastIndexOf("/")+1).toLowerCase();("create"===process||"duplicate"===process||itm.reload)&&res.object.id?(itm.params.id=res.object.id,MODx.request.parent&&(itm.params.parent=MODx.request.parent),MODx.request.context_key&&(itm.params.context_key=MODx.request.context_key),url=Ext.urlEncode(itm.params),action=o.actions&&o.actions.edit?o.actions.edit:itm.process.replace("create","update").replace("Create","Update"),MODx.loadPage(action,url)):"delete"===process&&(itm.params.a=o.actions.cancel,url=Ext.urlEncode(itm.params),MODx.loadPage("?"+url))},refreshTreeNode:function(tree,node,self){return parent.Ext.getCmp(tree).refreshNode(node,self||!1),!1},setupDirtyButtons:function(f){var fp=Ext.getCmp(f);fp&&fp.on("fieldChange",(function(o){for(var i=0;i<this.checkDirtyBtns.length;i+=1){this.checkDirtyBtns[i].setDisabled(!1)}}),this)}}),Ext.reg("modx-actionbuttons",MODx.toolbar.ActionButtons),MODx.DataView=function(config){config=config||{},this._loadStore(config),Ext.applyIf(config.listeners||{},{loadexception:{fn:this.onLoadException,scope:this},beforeselect:{fn:function(view){return view.store.getRange().length>0}},contextmenu:{fn:this._showContextMenu,scope:this}}),Ext.applyIf(config,{store:this.store,singleSelect:!0,overClass:"x-view-over",emptyText:'<div style="padding:10px;">'+_("file_err_filter")+"</div>",closeAction:"hide"}),MODx.DataView.superclass.constructor.call(this,config),this.config=config,this.cm=new Ext.menu.Menu},Ext.extend(MODx.DataView,Ext.DataView,{lookup:{},onLoadException:function(){this.getEl().update('<div style="padding:10px;">'+_("data_err_load")+"</div>")},_addContextMenuItem:function(items){for(var a=items,l=a.length,i=0;i<l;i+=1){var options=a[i];if("-"!==options){var h=Ext.emptyFn;h=options.handler?eval(options.handler):function(itm,e){var o=itm.options,id=this.cm.activeNode.id.split("_");id=id[1];var w=Ext.get("modx_content");if(o.confirm)Ext.Msg.confirm("",o.confirm,(function(e){if("yes"===e){var a=Ext.urlEncode(o.params||{action:o.action}),s="?id="+id+"&"+a;null===w?location.href=s:w.dom.src=s}}),this);else{var a=Ext.urlEncode(o.params),s="?id="+id+"&"+a;null===w?location.href=s:w.dom.src=s}},this.cm.add({id:options.id,text:options.text,scope:this,options,handler:h})}else this.cm.add("-")}},_loadStore:function(config){this.store=new Ext.data.JsonStore({url:config.url,baseParams:config.baseParams||{action:"Browser/Directory/GetList",wctx:config.wctx||MODx.ctx,dir:config.openTo||"",source:config.source||0},root:config.root||"results",fields:config.fields,totalProperty:"total",listeners:{load:{fn:function(){this.select(0)},scope:this,single:!0}}}),this.store.load()},_showContextMenu:function(v,i,n,e){e.preventDefault();var data=this.lookup[n.id],m=this.cm;m.removeAll(),data.menu&&(this._addContextMenuItem(data.menu),m.showAt(e.xy)),m.activeNode=n}}),Ext.reg("modx-dataview",MODx.DataView),MODx.Button=function(config){(config=config||{}).iconCls&&(config.ctCls=config.cls+" "+config.ctCls,config.cls=config.iconCls,config.iconCls=""),Ext.applyIf(config,{template:new Ext.XTemplate('<a href="javascrpt:;" id="{4}" class="x-btn icon {1} {3}">   <i class="{2}">   </i></a>').compile()}),MODx.Button.superclass.constructor.call(this,config)},Ext.extend(MODx.Button,Ext.Button,{onRender:function(ct,position){this.template||(Ext.Button.buttonTemplate||(Ext.Button.buttonTemplate=new Ext.Template('<span id="{4}" class="x-btn icon {1} {3}" unselectable="on">   <i class="{iconCls}"></i></span>'),Ext.Button.buttonTemplate.compile()),this.template=Ext.Button.buttonTemplate);var btn,targs=this.getTemplateArgs();targs.iconCls=this.iconCls,btn=position?this.template.insertBefore(position,targs,!0):this.template.append(ct,targs,!0),this.btnEl=btn.child("i"),this.mon(this.btnEl,{scope:this,focus:this.onFocus,blur:this.onBlur}),this.initButtonEl(btn,this.btnEl),Ext.ButtonToggleMgr.register(this)}}),Ext.reg("modx-button",MODx.Button),MODx.SearchBar=function(config){config=config||{},Ext.applyIf(config,{renderTo:"modx-manager-search",listClass:"modx-manager-search-results",emptyText:_("search"),id:"modx-uberbar",maxHeight:this.getViewPortSize(),typeAhead:!0,listAlign:["tl-bl?",[-12,12]],triggerConfig:{tag:"button",id:"modx-uberbar-trigger",type:"submit","aria-label":"Go",cls:"x-form-trigger icon icon-large icon-search"},defaultAutoCreate:{tag:"input",type:"text",size:"24",tabindex:"0",hasfocus:!0,"aria-label":_("search")},hasfocus:!0,minChars:1,displayField:"name",valueField:"_action",width:380,itemSelector:".x-combo-list-item",tpl:new Ext.XTemplate('<tpl for=".">','<div class="section">','<tpl if="this.type != values.type">','<tpl exec="this.type = values.type; values.label = this.getLabel(values)"></tpl>',"<h3>{label:htmlEncode}</h3>","</tpl>",'<p class="x-combo-list-item"><a href="?a={_action}"><tpl exec="values.icon = this.getClass(values)"><i class="icon icon-{icon:htmlEncode}"></i></tpl>{name:htmlEncode}<tpl if="description"><em> – {description:htmlEncode}</em></tpl></a></p>',"</div >","</tpl>",{getClass:function(values){if(values.icon)return values.icon;if(values.class)switch(values.class){case"MODX\\Revolution\\modDocument":return"file";case"MODX\\Revolution\\modSymLink":return"files-o";case"MODX\\Revolution\\modWebLink":return"link";case"MODX\\Revolution\\modStaticResource":return"file-text-o"}switch(values.type){case"resources":return"file";case"chunks":return"th-large";case"templates":return"columns";case"snippets":return"code";case"tvs":return"list-alt";case"plugins":return"cogs";case"users":return"user";case"actions":return"mail-forward"}},getLabel:function(values){return values.label?values.label:_("search_resulttype_"+values.type)}}),store:new Ext.data.JsonStore({url:MODx.config.connector_url,baseParams:{action:"Search/Search"},root:"results",totalProperty:"total",fields:["name","_action","description","type","icon","label","class"],listeners:{beforeload:function(store,options){if(options.params._action)return!1}}}),listeners:{beforequery:{fn:function(){this.tpl.type=null}},focus:this.focusBar,blur:this.blurBar,afterrender:function(){document.getElementById("modx-manager-search").onclick=function(e){e.stopPropagation()}},scope:this}}),MODx.SearchBar.superclass.constructor.call(this,config),this.blur(),this.setKeyMap()},Ext.extend(MODx.SearchBar,Ext.form.ComboBox,{setKeyMap:function(){new Ext.KeyMap(document,{key:27,handler:function(){this.hideBar()},scope:this,stopEvent:!1})},initList:function(){if(!this.list){var cls="x-combo-list",listParent=Ext.getDom(this.getListParent()||Ext.getBody());this.list=new Ext.Layer({parentEl:listParent,shadow:this.shadow,cls:[cls,this.listClass].join(" "),constrain:!1,zindex:this.getZIndex(listParent)}),this.list.on("click",(function(e){e.stopPropagation()}));var lw=this.listWidth||Math.max(this.wrap.getWidth(),this.minListWidth);this.list.setSize(lw,0),this.list.swallowEvent("mousewheel"),this.assetHeight=0,!1!==this.syncFont&&this.list.setStyle("font-size",this.el.getStyle("font-size")),this.title&&(this.header=this.list.createChild({cls:cls+"-hd",html:this.title}),this.assetHeight+=this.header.getHeight()),this.innerList=this.list.createChild({cls:cls+"-inner"}),this.mon(this.innerList,"mouseover",this.onViewOver,this),this.mon(this.innerList,"mousemove",this.onViewMove,this),this.innerList.setWidth(lw-this.list.getFrameWidth("lr")),this.pageSize&&(this.footer=this.list.createChild({cls:cls+"-ft"}),this.pageTb=new Ext.PagingToolbar({store:this.store,pageSize:this.pageSize,renderTo:this.footer}),this.assetHeight+=this.footer.getHeight()),this.tpl||(this.tpl='<tpl for="."><div class="'+cls+'-item">{'+this.displayField+"}</div></tpl>"),this.view=new Ext.DataView({applyTo:this.innerList,tpl:this.tpl,singleSelect:!0,selectedClass:this.selectedClass,itemSelector:this.itemSelector||"."+cls+"-item",emptyText:this.listEmptyText,deferEmptyText:!1}),this.view.on("click",(function(view,index,node,vent){view.select(node),window.event||(window.event=vent),this.onViewClick()}),this),this.bindStore(this.store,!0),this.resizable&&(this.resizer=new Ext.Resizable(this.list,{pinned:!0,handles:"se"}),this.mon(this.resizer,"resize",(function(r,w,h){this.maxHeight=h-this.handleHeight-this.list.getFrameWidth("tb")-this.assetHeight,this.listWidth=w,this.innerList.setWidth(w-this.list.getFrameWidth("lr")),this.restrictHeight()}),this),this[this.pageSize?"footer":"innerList"].setStyle("margin-bottom",this.handleHeight+"px"))}},onTypeAhead:function(){},onSelect:function(record,index){var e=Ext.EventObject;e.stopPropagation(),e.preventDefault();var target="?a="+record.data._action;if(e.ctrlKey||e.metaKey||e.shiftKey)return window.open(target);MODx.loadPage(target)},hideBar:function(){},focusBar:function(){this.selectText()},blurBar:function(){},getViewPortSize:function(){var height=300;return void 0!==window.innerHeight&&(height=window.innerHeight),height-70}}),Ext.reg("modx-searchbar",MODx.SearchBar),Ext.namespace("MODx.panel"),MODx.Panel=function(config){config=config||{},Ext.applyIf(config,{cls:"modx-panel",title:""}),MODx.Panel.superclass.constructor.call(this,config),this.config=config},Ext.extend(MODx.Panel,Ext.Panel),Ext.reg("modx-panel",MODx.Panel),MODx.FormPanel=function(config){config=config||{},Ext.applyIf(config,{autoHeight:!0,collapsible:!0,bodyStyle:"",layout:"anchor",border:!1,header:!1,method:"POST",cls:"modx-form",allowDrop:!0,errorReader:MODx.util.JSONReader,checkDirty:!0,useLoadingMask:!1,defaults:{collapsible:!1,autoHeight:!0,border:!1}}),config.items&&this.addChangeEvent(config.items),MODx.FormPanel.superclass.constructor.call(this,config),this.config=config,this.addEvents({setup:!0,fieldChange:!0,ready:!0,beforeSubmit:!0,success:!0,failure:!0,save:!0,actionNew:!0,actionContinue:!0,actionClose:!0,postReady:!0}),this.getForm().addEvents({success:!0,failure:!0}),this.dropTargets=[],this.on("ready",this.onReady),this.config.useLoadingMask&&this.on("render",(function(){this.mask=new Ext.LoadMask(this.getEl()),this.mask.show()})),this.fireEvent("setup",config)&&this.clearDirty(),this.focusFirstField()},Ext.extend(MODx.FormPanel,Ext.FormPanel,{isReady:!1,defaultValues:[],initialized:!1,isStatic:!1,errorHandlingTabs:[],errorHandlingIgnoreTabs:[],submit:function(o){var fm=this.getForm();return!(!fm.isValid()&&!o.bypassValidCheck)&&((o=o||{}).headers={"Powered-By":"MODx",modAuth:MODx.siteId},this.fireEvent("beforeSubmit",{form:fm,options:o,config:this.config})&&fm.submit({waitMsg:this.config.saveMsg||_("saving"),scope:this,headers:o.headers,clientValidation:!o.bypassValidCheck,failure:function(f,a){this.fireEvent("failure",{form:f,result:a.result,options:o,config:this.config})&&MODx.form.Handler.errorExt(a.result,f)},success:function(f,a){this.config.success&&Ext.callback(this.config.success,this.config.scope||this,[f,a]),this.fireEvent("success",{form:f,result:a.result,options:o,config:this.config}),this.clearDirty(),this.fireEvent("setup",this.config);var lastActiveEle=Ext.state.Manager.get("curFocus");if(lastActiveEle&&""!=lastActiveEle){Ext.state.Manager.clear("curFocus");var initFocus=document.getElementById(lastActiveEle);initFocus&&initFocus.focus()}}}),!0)},failure:function(o){if(this.warnUnsavedChanges=!0,-1!==this.getForm().baseParams.action.search(/\/create/i)){const btn=Ext.getCmp("modx-abtn-save");btn&&btn.enable()}this.fireEvent("failureSubmit")},focusFirstField:function(){if(this.getForm().items.getCount()>0){var fld=this.findFirstTextField();fld&&fld.focus(!1,200)}},findFirstTextField:function(i){i=i||0;var fld=this.getForm().items.itemAt(i);return!!fld&&((fld.isXType("combo")||fld.isXType("checkbox")||fld.isXType("radio")||fld.isXType("displayfield")||fld.isXType("statictextfield")||fld.isXType("hidden"))&&(i+=1,fld=this.findFirstTextField(i)),fld)},addChangeEvent:function(items){if(!items)return!1;"object"==typeof items&&items.items&&(items=items.items);for(var f=0;f<items.length;f++){var cmp=items[f];if(cmp.items)this.addChangeEvent(cmp.items);else if(cmp.xtype){cmp.listeners||(cmp.listeners={});var ctypes=["change"];switch(cmp.enableKeyEvents=!0,cmp.xtype){case"numberfield":case"textfield":case"textarea":ctypes=["keydown","change"];break;case"checkbox":case"xcheckbox":case"radio":ctypes=["check"]}cmp.xtype&&0==cmp.xtype.indexOf("modx-combo")&&(ctypes=["select"]);var that=this;Ext.iterate(ctypes,(function(ctype){cmp.listeners[ctype]&&cmp.listeners[ctype].fn?cmp.listeners[ctype]={fn:that.fieldChangeEvent.createSequence(cmp.listeners[ctype].fn,cmp.listeners[ctype].scope),scope:that}:cmp.listeners[ctype]={fn:that.fieldChangeEvent,scope:that}}))}}},fieldChangeEvent:function(fld,nv,ov,f){if(!this.isReady)return!1;f=this.config.onDirtyForm?Ext.getCmp(this.config.onDirtyForm):this.getForm();this.fireEvent("fieldChange",{field:fld,nv,ov,form:f})},markDirty:function(){this.fireEvent("fieldChange")},isDirty:function(){return(this.config.onDirtyForm?Ext.getCmp(this.config.onDirtyForm):this.getForm()).isDirty()},clearDirty:function(){return(this.config.onDirtyForm?Ext.getCmp(this.config.onDirtyForm):this.getForm()).clearDirty()},onReady:function(r){this.isReady=!0,this.config.allowDrop&&this.loadDropZones(),this.config.useLoadingMask&&this.mask&&this.mask.hide(),this.fireEvent("postReady")},loadDropZones:function(){var dropTargets=this.dropTargets;this.getForm().items.each((function(fld){if(fld.isFormField&&(fld.isXType("textfield")||fld.isXType("textarea"))&&!fld.isXType("combo")){var el=fld.getEl();if(el){var target=new MODx.load({xtype:"modx-treedrop",target:fld,targetEl:el.dom});dropTargets.push(target)}}}))},getField:function(f){var fld=!1;return"string"==typeof f&&((fld=this.getForm().findField(f))||(fld=Ext.getCmp(f))),fld},hideField:function(fieldId){const field=this.getField(fieldId);if(!field)return;field.hide();const label=field.getEl().up(".x-form-item");label&&label.setDisplayed(!1)},showField:function(flds){var f;Ext.isArray(flds)||(flds=flds[flds]);for(var i=0;i<flds.length;i++){if(!(f=this.getField(flds[i])))return;f.enable(),f.show();var d=f.getEl().up(".x-form-item");d&&d.setDisplayed(!0)}},setLabel:function(fieldId,newLabel){const field=this.getField(fieldId);if(field)switch(field.xtype){case"checkbox":case"xcheckbox":case"radio":field.setBoxLabel(newLabel);break;default:field.label&&field.label.update(newLabel)}},setMediaSources:function(formId,fieldKeys="static",sharedSourceKey=""){Array.isArray(fieldKeys)||(fieldKeys=fieldKeys.split(",")),fieldKeys.forEach((fieldKey=>{fieldKey=fieldKey.trim();const fieldCmpId=`modx-${formId}-${fieldKey}-file`,sourceKey=Ext.isEmpty(sharedSourceKey)?fieldKey:sharedSourceKey,sourceCmpId=`modx-${formId}-${sourceKey}-source`,fieldCmp=Ext.getCmp(fieldCmpId),sourceCmp=Ext.getCmp(sourceCmpId);fieldCmp&&sourceCmp&&(fieldCmp.config.source=sourceCmp.getValue())}))},destroy:function(){for(var i=0;i<this.dropTargets.length;i++)this.dropTargets[i].destroy();MODx.FormPanel.superclass.destroy.call(this)},getTabIdsFromKeys:function(map,keys){const tabIds=[];return"object"==typeof map&&Array.isArray(keys)&&keys.length>0&&keys.forEach((function(key){map.hasOwnProperty(key)&&"string"==typeof map[key].id?tabIds.push(map[key].id):"modx-panel-resource-tv"==key&&1==MODx.config.tvs_below_content&&tabIds.push(key)})),tabIds},showErroredTab:function(targetForms,tabsId){const mainTabs=Ext.getCmp(tabsId),searchTabs=this.getTabIdsFromKeys(mainTabs.items.map,targetForms);let component,mainTabName=null,mainTabIndex=null,erroredNode=null;mainTabs.items.length>mainTabs.initialConfig.items.length&&mainTabs.items.keys.forEach((function(key){mainTabs.items.map[key].hasOwnProperty("id")&&(this.errorHandlingIgnoreTabs.includes(mainTabs.items.map[key].id)||searchTabs.includes(mainTabs.items.map[key].id)||searchTabs.push(mainTabs.items.map[key].id))}),this);for(let i=0;i<searchTabs.length;i++)if(component=Ext.getCmp(searchTabs[i]),component&&component.el&&component.el.dom&&(erroredNode=this.detectErrors(component.el.dom),!1!==erroredNode)){mainTabName=component.itemId?component.itemId:searchTabs[i];break}if(null!==mainTabName){const errFld=document.getElementById(erroredNode);if(mainTabs&&mainTabs.items&&mainTabs.items.keys&&(mainTabIndex=mainTabs.items.keys.indexOf(mainTabName),("modx-panel-resource-tv"==component.id&&0==MODx.config.tvs_below_content||"modx-panel-resource-tv"!=component.id)&&mainTabs.items.items[mainTabIndex].hidden&&mainTabs.activate(mainTabName)),"modx-panel-resource-tv"==component.id){const errFldPanelId=errFld.closest(".x-panel").id,tvTabs=Ext.getCmp("modx-resource-vtabs");if(tvTabs&&tvTabs.items&&tvTabs.items.keys){const tvTabIndex=tvTabs.items.keys.indexOf(errFldPanelId);tvTabs.items.items[tvTabIndex]&&tvTabs.items.items[tvTabIndex].hidden&&tvTabs.activate(errFldPanelId)}}errFld.focus()}},detectErrors:function(node){const erroredFlds=document.getElementById(node.id).querySelectorAll(".x-form-invalid");return erroredFlds.length>0&&erroredFlds[0].id},insertTagCopyUtility:function(cmp,elType){const helpTag=cmp.getEl().child(".example-replace-name"),elTag=cmp.getEl().child(".copy-this");let tagText,nameVal=cmp.previousSibling().getValue();helpTag&&(nameVal.length>0&&(helpTag.update(nameVal),tagText=elTag.dom.innerText),helpTag.on({click:function(){if(nameVal=cmp.previousSibling().getValue(),nameVal.length>0){tagText=elTag.dom.innerText;const tmp=document.createElement("textarea");if(tmp.value=tagText,document.body.appendChild(tmp),tmp.select(),document.execCommand("copy")){const feedback=document.createElement("span");feedback.className="element-panel feedback item-copied",feedback.textContent=_(elType+"_tag_copied"),elTag.insertSibling(feedback,"after"),setTimeout((function(){feedback.style.opacity=0,setTimeout((function(){feedback.remove()}),1200)}),10)}tmp.remove()}}}))},onChangeStaticSource:function(cmp,elType){const isStatic=Ext.getCmp(`modx-${elType}-static`).getValue(),staticFileField=Ext.getCmp(`modx-${elType}-static-file`),staticFile=staticFileField.getValue(),staticDir=staticFile.slice(0,staticFile.lastIndexOf("/")+1),staticFileFieldId=staticFileField.id,staticFileFieldContainer=Ext.getCmp(staticFileField.ownerCt.id),itemKey=staticFileFieldContainer.items.keys.indexOf(staticFileFieldId),previousSource=this.previousFileSource||0,currentSource=cmp.getValue(),currentRecord={static:isStatic,static_file:staticFile,source:currentSource,openTo:staticDir};let newStaticFile,changeFieldType=!1,updateFieldSource=!1;if("template"===elType)var newPreviewFileField,staticPreviewFileField=Ext.getCmp(`modx-${elType}-preview-file`),staticPreviewFile=staticPreviewFileField.getValue(),staticPreviewDir=staticPreviewFile.slice(0,staticPreviewFile.lastIndexOf("/")+1),staticPreviewFileFieldId=staticPreviewFileField.id,staticPreviewFileFieldContainer=Ext.getCmp(staticPreviewFileField.ownerCt.id),previewItemKey=staticPreviewFileFieldContainer.items.keys.indexOf(staticPreviewFileFieldId),currentPreviewRecord={static:isStatic,preview_file:staticPreviewFile,source:currentSource,openTo:staticPreviewDir};this.previousFileSource=currentSource,previousSource>0&&0==currentSource?(newStaticFile=this.getStaticFileField(elType,currentRecord,!1),"template"===elType&&(newPreviewFileField=this.getTemplatePreviewImageField(currentPreviewRecord,!1)),changeFieldType=!0):0==previousSource&&currentSource>0?(newStaticFile=this.getStaticFileField(elType,currentRecord),"template"===elType&&(newPreviewFileField=this.getTemplatePreviewImageField(currentPreviewRecord)),changeFieldType=!0,updateFieldSource=!0):updateFieldSource=!0,updateFieldSource&&(changeFieldType?(newStaticFile.source=currentSource,"template"===elType&&(newPreviewFileField.source=currentSource)):(staticFileField.config.source=currentSource,"template"===elType&&(staticPreviewFileField.config.source=currentSource))),changeFieldType&&(staticFileField.clearInvalid(),staticFileField.destroy(),staticFileFieldContainer.insert(itemKey,newStaticFile),"template"===elType&&(staticPreviewFileField.clearInvalid(),staticPreviewFileField.destroy(),staticPreviewFileFieldContainer.insert(previewItemKey,newPreviewFileField)),this.doLayout())},getStaticFileField:function(elType,record,loadBrowserField=!0){const sharedConfig={fieldLabel:_("static_file"),description:MODx.expandHelp?"":_("static_file_desc"),name:"static_file",id:`modx-${elType}-static-file`,maxLength:255,anchor:"100%",value:record.static_file||""};let finalConfig;return(0===record.source||!record.hasOwnProperty("source")&&Ext.isEmpty(MODx.config.default_media_source))&&(loadBrowserField=!1),finalConfig=loadBrowserField?Object.assign(sharedConfig,{xtype:"modx-combo-browser",browserEl:"modx-browser",triggerClass:"x-form-code-trigger",source:null!=record.source?record.source:MODx.config.default_media_source,openTo:record.openTo||""}):Object.assign(sharedConfig,{xtype:"textfield"}),record.static||(finalConfig.hidden=!0),finalConfig},getTemplatePreviewImageField:function(record,loadBrowserField=!0){const sharedConfig={fieldLabel:_("template_preview"),description:MODx.expandHelp?"":_("template_preview_description"),name:"preview_file",id:"modx-template-preview-file",allowedFileTypes:"jpg,jpeg,png,gif,bmp",maxLength:255,anchor:"100%",value:record.preview_file||""};let finalConfig;return(0===record.source||!record.hasOwnProperty("source")&&Ext.isEmpty(MODx.config.default_media_source))&&(loadBrowserField=!1),finalConfig=loadBrowserField?Object.assign(sharedConfig,{xtype:"modx-combo-browser",browserEl:"modx-browser",triggerClass:"x-form-image-trigger",source:null!=record.source?record.source:MODx.config.default_media_source,openTo:record.openTo||""}):Object.assign(sharedConfig,{xtype:"textfield"}),finalConfig},toggleFieldVisibility:function(ctrlId,containerId,fieldIds,ctrlValToShow,addSibling){const ctrlCmp=Ext.getCmp(ctrlId),containerCmp=Ext.getCmp(containerId);if(!ctrlCmp||void 0===ctrlCmp)return console.error(`toggleFieldVisibility: Could not get the control component with the id '${ctrlId}'`),!1;if(containerId&&(!containerCmp||void 0===containerCmp))return console.error(`toggleFieldVisibility: Could not get the container component with the id '${containerId}'`),!1;addSibling=!1!==addSibling,ctrlValToShow=!1!==ctrlValToShow;const showVal="combo-boolean"===ctrlCmp.xtype?ctrlCmp.getValue():ctrlCmp.checked,show=!1===ctrlValToShow?!showVal:showVal;show?(containerCmp.show(),containerCmp.doLayout()):containerCmp.hide(),fieldIds.forEach((field=>{const fieldCmp=Ext.getCmp(field),sibling=fieldCmp.nextSibling(),siblingIsHelp=sibling&&"label"===sibling.xtype;fieldCmp&&(show?(fieldCmp.show(),addSibling&&siblingIsHelp&&sibling.show()):(fieldCmp.hide(),addSibling&&siblingIsHelp&&sibling.hide()))}))},formatMainPanelTitle:function(formId,record,realtimeValue=null,returnBaseTitle=!1){let title="",baseTitle="";const modeCreate=!(record.hasOwnProperty("id")&&record.id>0),prefixSeparator=modeCreate&&!realtimeValue?"":": ",prefix=(modeCreate?_("create")+" ":_("edit")+" ")+_("resource"===formId?"document":formId)+prefixSeparator;if(!Ext.isEmpty(record)){const postfix=MODx.perm.tree_show_resource_ids&&!Ext.isEmpty(record.id)?` <small>(${record.id})</small>`:"";if("resource"===formId){const headerCmp=Ext.getCmp("modx-header-breadcrumbs");title=realtimeValue||record.pagetitle,baseTitle=this.encodeTitle(title,!1),title=void 0===title?prefix:this.encodeTitle(title)+postfix,headerCmp?headerCmp.updateHeader(title):Ext.getCmp("modx-resource-header").el.dom.innerText=title}else{const headerCmpId=`modx-${formId}-header`;realtimeValue?baseTitle=this.encodeTitle(realtimeValue):(title="template"===formId?record.templatename:record.name,baseTitle=this.encodeTitle(title)),title=void 0===title?prefix:prefix+baseTitle+postfix,Ext.getCmp(headerCmpId).getEl().update(title)}}if(returnBaseTitle)return baseTitle},encodeTitle:function(title,htmlEncode=!0){return title&&(title=htmlEncode?Ext.util.Format.htmlEncode(Ext.util.Format.stripTags(title)):Ext.util.Format.stripTags(title)),title},getElementProperties:function(properties){if(!Ext.isEmpty(properties)){const gridCmp=Ext.getCmp("modx-grid-element-properties");gridCmp&&(gridCmp.defaultProperties=properties,gridCmp.getStore().loadData(properties))}}}),Ext.reg("modx-formpanel",MODx.FormPanel),MODx.panel.Wizard=function(config){config=config||{},Ext.applyIf(config,{layout:"card",activeItem:0,resizable:!0,collapsible:!0,maximizable:!0,autoHeight:!0,width:750,firstPanel:"",lastPanel:"",defaults:{border:!1},modal:!0,txtFinish:_("finish"),txtNext:_("next"),txtBack:_("back"),bbar:[{id:"pi-btn-bck",itemId:"btn-back",text:config.txtBack||_("back"),handler:this.navHandler.createDelegate(this,[-1]),scope:this,disabled:!0},{id:"pi-btn-fwd",itemId:"btn-fwd",text:config.txtNext||_("next"),handler:this.navHandler.createDelegate(this,[1]),scope:this}]}),MODx.panel.Wizard.superclass.constructor.call(this,config),this.config=config,this.lastActiveItem=this.config.firstPanel,this._go()},Ext.extend(MODx.panel.Wizard,Ext.Panel,{windows:{},_go:function(){this.getBottomToolbar().items.item(1).setText(this.config.txtNext),this.proceed(this.config.firstPanel)},navHandler:function(dir){this.doLayout();var a=this.getLayout().activeItem;-1==dir?this.proceed(a.config.back||a.config.id):a.submit({scope:this,proceed:this.proceed})},proceed:function(id){this.doLayout(),this.getLayout().setActiveItem(id),id==this.config.firstPanel?(this.getBottomToolbar().items.item(0).setDisabled(!0),this.getBottomToolbar().items.item(1).setText(this.config.txtNext)):id==this.config.lastPanel?this.getBottomToolbar().items.item(1).setText(this.config.txtFinish):(this.getBottomToolbar().items.item(0).setDisabled(!1),this.getBottomToolbar().items.item(1).setText(this.config.txtNext))}}),Ext.reg("modx-panel-wizard",MODx.panel.Wizard),MODx.panel.WizardPanel=function(config){config=config||{},Ext.applyIf(config,{wizard:null,checkDirty:!1,bodyStyle:"padding: 3em 3em",hideMode:"offsets"}),MODx.panel.WizardPanel.superclass.constructor.call(this,config)},Ext.extend(MODx.panel.WizardPanel,MODx.FormPanel),Ext.reg("modx-wizard-panel",MODx.panel.WizardPanel),MODx.PanelSpacer={html:"<br />",border:!1},MODx.TemplatePanel=function(config){config=config||{},Ext.applyIf(config,{frame:!1,startingMarkup:'<tpl for="."><div class="empty-text-wrapper"><p>{text}</p></div></tpl>',startingText:"Loading...",markup:null,plain:!0,border:!1}),MODx.TemplatePanel.superclass.constructor.call(this,config),this.on("render",this.init,this)},Ext.extend(MODx.TemplatePanel,Ext.Panel,{init:function(){this.defaultMarkup=new Ext.XTemplate(this.startingMarkup,{compiled:!0}),this.reset(),this.tpl=new Ext.XTemplate(this.markup,{compiled:!0})},reset:function(){this.body.hide(),this.defaultMarkup.overwrite(this.body,{text:this.startingText}),this.body.slideIn("r",{stopFx:!0,duration:.2}),setTimeout((function(){Ext.getCmp("modx-content").doLayout()}),500)},updateDetail:function(data){this.body.hide(),this.tpl.overwrite(this.body,data),this.body.slideIn("r",{stopFx:!0,duration:.2}),setTimeout((function(){Ext.getCmp("modx-content").doLayout()}),500)}}),Ext.reg("modx-template-panel",MODx.TemplatePanel),MODx.BreadcrumbsPanel=function(config){config=config||{},Ext.applyIf(config,{frame:!1,plain:!0,border:!1,desc:"This the description part of this panel",bdMarkup:"<tpl if=\"typeof(trail) != &quot;undefined&quot;\"><div class=\"crumb_wrapper\"><ul class=\"crumbs\"><tpl for=\"trail\"><li{[values.className != undefined ? ' class=\"'+values.className+'\"' : '' ]}><tpl if=\"typeof pnl != 'undefined'\"><button type=\"button\" class=\"controlBtn {pnl}{[values.root ? ' root' : '' ]}\">{text}</button></tpl><tpl if=\"typeof install != 'undefined'\"><button type=\"button\" class=\"controlBtn install{[values.root ? ' root' : '' ]}\">{text}</button></tpl><tpl if=\"typeof pnl == 'undefined' && typeof install == 'undefined'\"><span class=\"text{[values.root ? ' root' : '' ]}\">{text}</span></tpl></li></tpl></ul></div></tpl><tpl if=\"typeof(text) != &quot;undefined&quot;\"><div class=\"panel-desc{[values.className != undefined ? ' '+values.className+'\"' : '' ]}\"><p>{text}</p></div></tpl>",root:{text:"Home",className:"first",root:!0,pnl:""},bodyCssClass:"breadcrumbs"}),MODx.BreadcrumbsPanel.superclass.constructor.call(this,config),this.on("render",this.init,this)},Ext.extend(MODx.BreadcrumbsPanel,Ext.Panel,{data:{trail:[]},init:function(){this.tpl=new Ext.XTemplate(this.bdMarkup,{compiled:!0}),this.reset(this.desc),this.body.on("click",this.onClick,this)},getResetText:function(srcInstance){if("object"!=typeof srcInstance||null==srcInstance)return srcInstance;var newInstance=srcInstance.constructor();for(var i in srcInstance)newInstance[i]=this.getResetText(srcInstance[i]);return newInstance.hasOwnProperty("pnl")&&delete newInstance.pnl,newInstance},updateDetail:function(data){(this.data=data,data.hasOwnProperty("trail"))&&data.trail.unshift(this.root);this._updatePanel(data)},getData:function(){return this.data},reset:function(msg){void 0===this.resetText&&(this.resetText=this.getResetText(this.root)),this.data={text:msg,trail:[this.resetText]},this._updatePanel(this.data)},onClick:function(e){for(var target=e.getTarget(),index=1,parent=target.parentElement;null!=(parent=parent.previousSibling);)index+=1;for(var remove=this.data.trail.length-index;remove>0;)this.data.trail.pop(),remove-=1;if(elm=target.className.split(" ")[0],""!=elm&&"controlBtn"==elm){var panel=target.className.split(" ")[1];if("install"==panel){var last=this.data.trail[this.data.trail.length-1];if(null!=last&&null!=last.rec)return this.data.trail.pop(),void Ext.getCmp("modx-package-grid").install(last.rec)}else Ext.getCmp(panel).activate()}},_updatePanel:function(data){this.body.hide(),this.tpl.overwrite(this.body,data),this.body.slideIn("r",{stopFx:!0,duration:.2}),setTimeout((function(){Ext.getCmp("modx-content").doLayout()}),500)}}),Ext.reg("modx-breadcrumbs-panel",MODx.BreadcrumbsPanel),Ext.override(Ext.TabPanel,{onStripMouseDown:function(e){if(0!==e.button)return;e.preventDefault();const t=this.findTargets(e);t.close?!1!==t.item.fireEvent("beforeclose",t.item)&&(t.item.fireEvent("close",t.item),this.remove(t.item)):t.item&&t.item!==this.activeTab&&(this.tabClicked=!0,this.setActiveTab(t.item))}}),MODx.Tabs=function(config={}){Ext.applyIf(config,{enableTabScroll:!0,layoutOnTabChange:!0,plain:!0,deferredRender:!0,hideMode:"offsets",defaults:{autoHeight:!0,hideMode:"offsets",border:!0,autoWidth:!0,bodyCssClass:"tab-panel-wrapper"},activeTab:0,tabClicked:!1,border:!1,autoScroll:!0,autoHeight:!0,cls:"modx-tabs",itemTpl:new Ext.XTemplate('<li class="{cls}" id="{id}">','<a class="x-tab-strip-close"></a>','<a href="#">','<span class="x-tab-strip-text">{text}</span>',"</a>","</li>")}),MODx.Tabs.superclass.constructor.call(this,config),this.config=config,this.on({afterrender:function(tabPanel){if(MODx.request&&Object.prototype.hasOwnProperty.call(MODx.request,"tab")){const tabId=parseInt(MODx.request.tab,10);"modx-leftbar-tabpanel"!==this.id&&this.setActiveTab(tabId)}tabPanel.on({beforetabchange:function(tabPanelCmp,newTab,currentTab){if(this.tabClicked&&newTab&&currentTab&&newTab.id!==currentTab.id){const resetVerticalTabPanelFilters="modx-vtabs"===currentTab.items?.items[0]?.xtype||"modx-vtabs"===currentTab.ownerCt?.xtype,changedBetweenVtabs="modx-vtabs"===newTab.ownerCt?.xtype&&"modx-vtabs"===currentTab.ownerCt?.xtype;if("modx-usergroup-permissions-panel"===newTab.itemId&&!this.stateful){const vTabPanel=newTab.items?.items[0];vTabPanel&&"modx-vtabs"===vTabPanel.xtype&&vTabPanel.setActiveTab(0)}this.clearFiltersBeforeChange(currentTab,resetVerticalTabPanelFilters,changedBetweenVtabs)}}})}})},Ext.extend(MODx.Tabs,Ext.TabPanel,{findGridObject:function(itemsSource){const grid=itemsSource.find((obj=>Object.entries(obj).find((([key,value])=>"xtype"===key&&value.includes("-grid-")))));if(grid)return grid;const nextItemsSource=itemsSource?.items;nextItemsSource&&this.findGridObject(nextItemsSource)},clearFiltersBeforeChange:function(tabObj,resetVtabFilters,changedVtabs){let itemsSource,gridObj=null;if(itemsSource=resetVtabFilters?changedVtabs?tabObj.items:tabObj.items.items[0].activeTab.items:tabObj.items,itemsSource.length>0&&(gridObj=this.findGridObject(itemsSource),!gridObj)){let customItemsSource=null;itemsSource?.map["modx-tree-panel-usergroup"]?customItemsSource=itemsSource.map["modx-tree-panel-usergroup"].items:itemsSource?.map["packages-breadcrumbs"]&&(customItemsSource=itemsSource.map["card-container"].items.map["modx-panel-packages"].items),customItemsSource&&(gridObj=this.findGridObject(customItemsSource))}if(gridObj){const toolbar=gridObj.getTopToolbar(),filterIds=[];toolbar&&toolbar.items.items.length>0&&toolbar.items.items.forEach((cmp=>{cmp.xtype&&(cmp.xtype.includes("combo")||"textfield"===cmp.xtype)&&cmp.itemId&&filterIds.push(cmp.itemId)})),filterIds.length>0&&gridObj.clearGridFilters(filterIds)}}}),Ext.reg("modx-tabs",MODx.Tabs),MODx.VerticalTabs=function(config={}){Ext.applyIf(config,{cls:"vertical-tabs-panel",headerCfg:{tag:"div",cls:"x-tab-panel-header vertical-tabs-header"},bwrapCfg:{tag:"div",cls:"x-tab-panel-bwrap vertical-tabs-bwrap"},defaults:{bodyCssClass:"vertical-tabs-body",autoScroll:!0,autoHeight:!0,autoWidth:!0,layout:"form"}}),MODx.VerticalTabs.superclass.constructor.call(this,config),this.config=config,this.on({afterrender:function(){if(MODx.request&&Object.prototype.hasOwnProperty.call(MODx.request,"vtab")){const tabId=parseInt(MODx.request.vtab,10);this.setActiveTab(tabId)}}})},Ext.extend(MODx.VerticalTabs,MODx.Tabs),Ext.reg("modx-vtabs",MODx.VerticalTabs),Ext.Window.prototype.floating={shadow:!1},Ext.override(Ext.Window,{animShow:function(){this.afterShow();var win=this;setTimeout((function(){win.el.hasClass("anim-ready")||(win.el.addClass("anim-ready"),setTimeout((function(){void 0!==win.mask&&(win.mask instanceof Ext.Element?win.mask.addClass("fade-in"):win.mask.el.addClass("fade-in")),win.el.addClass("zoom-in")}),250))}),300)},animHide:function(){this.afterHide()},onShow:function(){if(this.el.hasClass("x-window-dlg"))this.mask.addClass("fade-in"),this.el.applyStyles({opacity:1});else{this.addClass("anim-ready");var win=this;setTimeout((function(){void 0!==win.mask&&(win.mask instanceof Ext.Element?win.mask.addClass("fade-in"):win.mask.el.addClass("fade-in")),win.el.addClass("zoom-in")}),250)}},onHide:function(){if(this.el.hasClass("zoom-in")){this.el.removeClass("zoom-in"),void 0!==this.mask&&(this.mask instanceof Ext.Element?this.mask.removeClass("fade-in"):this.mask.el.removeClass("fade-in")),this.addClass("zoom-out");var win=this;setTimeout((function(){win.isDestroyed||(win.el.hide(),win.el.removeClass("zoom-out"),win.el.removeClass("anim-ready"))}),250)}else this.el.hasClass("x-window-dlg")&&(this.el.applyStyles({opacity:0}),void 0!==this.mask&&(this.mask instanceof Ext.Element?this.mask.removeClass("fade-in"):this.mask.el.removeClass("fade-in")))}}),MODx.Window=function(config){config=config||{},Ext.applyIf(config,{modal:!1,layout:"auto",closeAction:"hide",shadow:!0,resizable:!0,collapsible:!0,maximizable:!0,autoHeight:!1,autoScroll:!0,allowDrop:!0,width:400,constrain:!0,constrainHeader:!0,cls:"modx-window",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){"close"!==config.closeAction?this.hide():this.close()}},{text:config.saveBtnText||_("save"),cls:"primary-button",scope:this,handler:this.submit}],record:{},keys:[{key:Ext.EventObject.ENTER,fn:function(keyCode,event){var elem=event.getTarget(),component=Ext.getCmp(elem.id);if(component instanceof Ext.form.TextArea)return component.append("\n");this.submit()},scope:this}]}),MODx.Window.superclass.constructor.call(this,config),this.options=config,this.config=config,this.addEvents({success:!0,failure:!0,beforeSubmit:!0,updateWindow:!1}),this._loadForm(),this.on("show",(function(){this.config.blankValues&&this.fp.getForm().reset(),this.config.allowDrop&&this.loadDropZones(),this.syncSize(),this.focusFirstField()}),this),this.on("afterrender",(function(){this.originalHeight=this.el.getHeight(),this.toolsHeight=this.originalHeight-this.body.getHeight()+50,this.resizeWindow()})),Ext.EventManager.onWindowResize(this.resizeWindow,this)},Ext.extend(MODx.Window,Ext.Window,{_loadForm:function(){if(this.checkIfLoaded(this.config.record||null))return!1;var r=this.config.record;if(this.config.fields)for(var l=this.config.fields.length,i=0;i<l;i++){var f=this.config.fields[i];r[f.name]&&("checkbox"==f.xtype||"radio"==f.xtype?f.checked=r[f.name]:f.value=r[f.name])}this.fp=this.createForm({url:this.config.url,baseParams:this.config.baseParams||{action:this.config.action||""},items:this.config.fields||[]});var w=this;this.fp.getForm().items.each((function(f){f.on("invalid",(function(){w.doLayout()}))})),this.renderForm()},focusFirstField:function(){if(this.fp&&this.fp.getForm()&&this.fp.getForm().items.getCount()>0){var fld=this.findFirstTextField();fld&&fld.focus(!1,200)}},findFirstTextField:function(i){i=i||0;var fld=this.fp.getForm().items.itemAt(i);return!!fld&&((fld.isXType("combo")||fld.isXType("checkbox")||fld.isXType("radio")||fld.isXType("displayfield")||fld.isXType("statictextfield")||fld.isXType("hidden"))&&(i+=1,fld=this.findFirstTextField(i)),fld)},submit:function(close){close=!1!==close;var f=this.fp.getForm();f.isValid()&&this.fireEvent("beforeSubmit",f.getValues())&&f.submit({waitMsg:this.config.waitMsg||_("saving"),submitEmptyText:!1!==this.config.submitEmptyText,scope:this,failure:function(frm,a){this.fireEvent("failure",{f:frm,a})&&MODx.form.Handler.errorExt(a.result,frm),this.doLayout()},success:function(frm,a){this.config.success&&Ext.callback(this.config.success,this.config.scope||this,[frm,a]),this.fireEvent("success",{f:frm,a}),close&&("close"!==this.config.closeAction?this.hide():this.close()),this.doLayout()}})},createForm:function(config){return Ext.applyIf(this.config,{formFrame:!0,border:!1,bodyBorder:!1,autoHeight:!0}),config=config||{},Ext.applyIf(config,{labelAlign:this.config.labelAlign||"top",labelWidth:this.config.labelWidth||100,labelSeparator:this.config.labelSeparator||"",frame:this.config.formFrame,border:this.config.border,bodyBorder:this.config.bodyBorder,autoHeight:this.config.autoHeight,anchor:"100% 100%",errorReader:MODx.util.JSONReader,defaults:this.config.formDefaults||{msgTarget:this.config.msgTarget||"under"},url:this.config.url,baseParams:this.config.baseParams||{},fileUpload:this.config.fileUpload||!1}),new Ext.FormPanel(config)},renderForm:function(){this.fp.on("destroy",(function(){Ext.EventManager.removeResizeListener(this.resizeWindow,this)}),this),this.add(this.fp)},checkIfLoaded:function(r){return r=r||{},!(!this.fp||!this.fp.getForm())&&(this.fp.getForm().reset(),this.fp.getForm().setValues(r),!0)},setValues:function(r){if(null===r)return!1;this.fp.getForm().setValues(r)},reset:function(){this.fp.getForm().reset()},hideField:function(f){f.disable(),f.hide();var d=f.getEl().up(".x-form-item");d&&d.setDisplayed(!1)},showField:function(f){f.enable(),f.show();var d=f.getEl().up(".x-form-item");d&&d.setDisplayed(!0)},loadDropZones:function(){if(this._dzLoaded)return!1;this.fp.getForm().items.each((function(fld){fld.isFormField&&(fld.isXType("textfield")||fld.isXType("textarea"))&&!fld.isXType("combo")&&new MODx.load({xtype:"modx-treedrop",target:fld,targetEl:fld.getEl().dom})})),this._dzLoaded=!0},resizeWindow:function(){var viewHeight=Ext.getBody().getViewSize().height,el=this.fp.getForm().el;viewHeight<this.originalHeight?(el.setStyle("overflow-y","scroll"),el.setHeight(viewHeight-this.toolsHeight)):(el.setStyle("overflow-y","auto"),el.setHeight("auto"))}}),Ext.reg("modx-window",MODx.Window),Ext.namespace("MODx.combo"),Ext.form.ComboBox.prototype.shadow=!1,Ext.override(Ext.form.TriggerField,{onRender:function(ct,position){this.doc=Ext.isIE?Ext.getBody():Ext.getDoc(),Ext.form.TriggerField.superclass.onRender.call(this,ct,position),this.wrap=this.el.wrap({cls:"x-form-field-wrap x-form-field-trigger-wrap"}),this.trigger=this.wrap.createChild(this.triggerConfig||{tag:"div",cls:"x-form-trigger "+(this.triggerClass||"")}),this.initTrigger(),this.width||this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()),this.resizeEl=this.positionEl=this.wrap}});var originalComboBoxOnLoad=Ext.form.ComboBox.prototype.onLoad;Ext.override(Ext.form.ComboBox,{loaded:!1,setValue:Ext.form.ComboBox.prototype.setValue.createSequence((function(v){var a=this.store.find(this.valueField,v);if(null!=v&&"remote"==this.mode&&-1==a&&!this.loaded){var p={};p[this.valueField]=v,this.loaded=!0,this.store.load({scope:this,params:p,callback:function(){this.setValue(v),this.collapse()}})}})),onLoad:function(){var ret=originalComboBoxOnLoad.apply(this,arguments),maxwidth=Math.max(this.minListWidth||0,this.wrap.getWidth(!0));return this.list.setWidth(maxwidth),ret}}),MODx.combo.ComboBox=function(config,getStore){return config=config||{},Ext.applyIf(config,{displayField:"name",valueField:"id",triggerAction:"all",fields:["id","name"],baseParams:{action:"GetList"},width:150,editable:!1,resizable:!0,typeAhead:!1,forceSelection:!0,minChars:3,cls:"modx-combo",tries:0}),Ext.applyIf(config,{store:new Ext.data.JsonStore({url:config.connector||config.url,root:"results",totalProperty:"total",fields:config.fields,errorReader:MODx.util.JSONReader,baseParams:config.baseParams||{},remoteSort:config.remoteSort||!1,autoDestroy:!0,listeners:{loadexception:{fn:function(o,trans,resp){var status=_("code")+": "+resp.status+" "+resp.statusText,response=Ext.decode(resp.responseText||"[]");MODx.msg.alert(_("error"),response.message||status)}}}})}),!0===getStore?(config.store.load(),config.store):(MODx.combo.ComboBox.superclass.constructor.call(this,config),this.config=config,this.addEvents({loaded:!0}),this.on("collapse",(function(){this.wrap.removeClass("x-trigger-wrap-open")})),this.store.on("load",(function(){this.fireEvent("loaded",this),this.loaded=!0,this.isExpanded()&&this.pageSize<this.store.getTotalCount()&&void 0!==this.pageTb&&!0===this.pageTb.hidden&&(this.collapse(),this.expand())}),this,{single:!0}),this)},Ext.extend(MODx.combo.ComboBox,Ext.form.ComboBox,{expand:function(){if(!this.isExpanded()&&this.hasFocus){if(this.wrap.addClass("x-trigger-wrap-open"),"remote"===this.mode&&!this.loaded&&this.tries<4)return this.tries+=1,Ext.defer(this.expand,250,this),!1;this.tries=0,(this.title||this.pageSize)&&(this.assetHeight=0,this.title&&(this.assetHeight+=this.header.getHeight()),this.pageSize<this.store.getTotalCount()?(this.assetHeight+=this.footer.getHeight(),this.pageTb.show()):(this.list.setHeight(this.list.getHeight()-this.footer.getHeight()),this.pageTb.hide())),this.bufferSize&&(this.doResize(this.bufferSize),delete this.bufferSize),this.list.alignTo.apply(this.list,[this.el].concat(this.listAlign)),this.list.setZIndex(this.getZIndex()),this.list.show(),Ext.isGecko2&&this.innerList.setOverflow("auto"),this.mon(Ext.getDoc(),{scope:this,mousewheel:this.collapseIf,mousedown:this.collapseIf}),this.fireEvent("expand",this)}}}),Ext.reg("modx-combo",MODx.combo.ComboBox),Ext.util.Format.comboRenderer=function(combo,val){return function(v,md,rec,ri,ci,s){if(!s)return v;if(!combo.findRecord)return v;var record=combo.findRecord(combo.valueField,v);return val=record?record.get(combo.displayField):val,Ext.util.Format.htmlEncode(val)}},MODx.combo.Renderer=function(combo){var loaded=!1;return function(v){var idx,rec;if(!combo.store)return v;loaded||(void 0!==combo.store.proxy&&null!==combo.store.proxy&&combo.store.load(),loaded=!0);var v2=combo.getValue();return idx=combo.store.find(combo.valueField,v2||v),null==(rec=combo.store.getAt(idx))?v2||v:rec.get(combo.displayField)}},MODx.combo.Boolean=function(config){config=config||{},Ext.applyIf(config,{store:new Ext.data.SimpleStore({fields:["d","v"],data:[[_("yes"),!0],[_("no"),!1]]}),displayField:"d",valueField:"v",mode:"local",triggerAction:"all",editable:!1,selectOnFocus:!1,preventRender:!0,forceSelection:!0,enableKeyEvents:!0}),MODx.combo.Boolean.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Boolean,MODx.combo.ComboBox),Ext.reg("combo-boolean",MODx.combo.Boolean),Ext.reg("modx-combo-boolean",MODx.combo.Boolean),MODx.util.PasswordField=function(config){delete(config=config||{}).xtype,Ext.applyIf(config,{xtype:"textfield",inputType:"password"}),MODx.util.PasswordField.superclass.constructor.call(this,config)},Ext.extend(MODx.util.PasswordField,Ext.form.TextField),Ext.reg("text-password",MODx.util.PasswordField),Ext.reg("modx-text-password",MODx.util.PasswordField),MODx.combo.User=function(config){config=config||{},Ext.applyIf(config,{name:"user",hiddenName:"user",displayField:"username",valueField:"id",fields:["username","id"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/User/GetList"},typeAhead:!0,editable:!0}),MODx.combo.User.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.User,MODx.combo.ComboBox),Ext.reg("modx-combo-user",MODx.combo.User),MODx.combo.UserGroup=function(config){config=config||{},Ext.applyIf(config,{name:"group",hiddenName:"group",displayField:"name",valueField:"id",fields:["name","id","description"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/Group/GetList"},tpl:new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item"><span style="font-weight: bold">{name:htmlEncode}</span>',"<br />{description:htmlEncode}</div></tpl>")}),MODx.combo.UserGroup.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.UserGroup,MODx.combo.ComboBox),Ext.reg("modx-combo-usergroup",MODx.combo.UserGroup),MODx.combo.UserGroupRole=function(config){config=config||{},Ext.applyIf(config,{name:"role",hiddenName:"role",displayField:"name",valueField:"id",fields:["name","id"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/Role/GetList"}}),MODx.combo.UserGroupRole.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.UserGroupRole,MODx.combo.ComboBox),Ext.reg("modx-combo-usergrouprole",MODx.combo.UserGroupRole),MODx.combo.EventGroup=function(config){config=config||{},Ext.applyIf(config,{name:"group",hiddenName:"group",displayField:"name",valueField:"name",fields:["name"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"System/Event/GroupList"},tpl:new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item"><span style="font-weight: bold">{name:htmlEncode}</span>',"</div></tpl>")}),MODx.combo.EventGroup.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.EventGroup,MODx.combo.ComboBox),Ext.reg("modx-combo-eventgroup",MODx.combo.EventGroup),MODx.combo.ResourceGroup=function(config){config=config||{},Ext.applyIf(config,{name:"resourcegroup",hiddenName:"resourcegroup",displayField:"name",valueField:"id",fields:["name","id"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/ResourceGroup/GetList"}}),MODx.combo.ResourceGroup.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.ResourceGroup,MODx.combo.ComboBox),Ext.reg("modx-combo-resourcegroup",MODx.combo.ResourceGroup),MODx.combo.Context=function(config){config=config||{},Ext.applyIf(config,{name:"context",hiddenName:"context",displayField:"key",valueField:"key",fields:["key","name"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Context/GetList",exclude:config.exclude||""},tpl:new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item"><span style="font-weight: bold">{name:htmlEncode}</span> <span style="font-style: italic; font-size: small;">({key:htmlEncode})</span></div></tpl>')}),MODx.combo.Context.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Context,MODx.combo.ComboBox),Ext.reg("modx-combo-context",MODx.combo.Context),MODx.combo.Policy=function(config){config=config||{},Ext.applyIf(config,{name:"policy",hiddenName:"policy",displayField:"name",valueField:"id",fields:["id","name","permissions"],allowBlank:!1,editable:!1,pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/Access/Policy/GetList"}}),MODx.combo.Policy.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Policy,MODx.combo.ComboBox),Ext.reg("modx-combo-policy",MODx.combo.Policy),MODx.combo.Template=function(config){config=config||{},Ext.applyIf(config,{url:MODx.config.connector_url,baseParams:{action:"Element/Template/GetList",combo:!0},fields:["id","templatename","description","category_name","preview","time"],name:"template",hiddenName:"template",displayField:"templatename",valueField:"id",pageSize:20,allowBlank:!0,editable:!0,typeAhead:!0,tpl:new Ext.XTemplate('<tpl for="."><tpl if="!Ext.isEmpty(this.getGroup(values.category_name, values.time))"><div class="x-combo-list-group">{this.label:htmlEncode}</div></tpl><div class="x-combo-list-item x-combo-list-item-grouped"><div class="x-combo-list-title">{templatename:htmlEncode}</div>{description:htmlEncode()}</div></tpl>',{group:null,label:null,getGroup:function(label,time){var group=time+"_"+label;return group===this.group||Ext.isEmpty(group)?null:(this.group=group,this.label=label)}})}),MODx.combo.Template.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Template,MODx.combo.ComboBox),Ext.reg("modx-combo-template",MODx.combo.Template),MODx.combo.Category=function(config){config=config||{},Ext.applyIf(config,{name:"category",hiddenName:"category",displayField:"name",valueField:"id",fields:["id","category","parent","name"],forceSelection:!0,typeAhead:!1,allowBlank:!0,editable:!1,enableKeyEvents:!0,pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Element/Category/GetList",showNone:!0,limit:0}}),MODx.combo.Category.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Category,MODx.combo.ComboBox,{_onblur:function(t,e){var v=this.getRawValue();this.setRawValue(v),this.setValue(v,!0)}}),Ext.reg("modx-combo-category",MODx.combo.Category),MODx.combo.Language=function(config){config=config||{},Ext.applyIf(config,{name:"language",hiddenName:"language",displayField:"name",valueField:"name",fields:["name"],typeAhead:!0,minChars:1,editable:!0,allowBlank:!0,url:MODx.config.connector_url,baseParams:{action:"System/Language/GetList"}}),MODx.combo.Language.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Language,MODx.combo.ComboBox),Ext.reg("modx-combo-language",MODx.combo.Language),MODx.combo.Charset=function(config){config=config||{},Ext.applyIf(config,{name:"charset",hiddenName:"charset",displayField:"text",valueField:"value",fields:["value","text"],forceSelection:!0,typeAhead:!1,editable:!1,allowBlank:!1,url:MODx.config.connector_url,baseParams:{action:"System/Charset/GetList"}}),MODx.combo.Charset.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Charset,MODx.combo.ComboBox),Ext.reg("modx-combo-charset",MODx.combo.Charset),MODx.combo.RTE=function(config){config=config||{},Ext.applyIf(config,{name:"rte",hiddenName:"rte",displayField:"value",valueField:"value",fields:["value"],forceSelection:!0,typeAhead:!1,editable:!1,allowBlank:!1,url:MODx.config.connector_url,baseParams:{action:"System/Rte/GetList"}}),MODx.combo.RTE.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.RTE,MODx.combo.ComboBox),Ext.reg("modx-combo-rte",MODx.combo.RTE),MODx.combo.Role=function(config){config=config||{},Ext.applyIf(config,{name:"role",hiddenName:"role",forceSelection:!0,typeAhead:!1,editable:!1,allowBlank:!1,pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/Role/GetList",addNone:!0}}),MODx.combo.Role.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Role,MODx.combo.ComboBox),Ext.reg("modx-combo-role",MODx.combo.Role),MODx.combo.ContentType=function(config){config=config||{},Ext.applyIf(config,{name:"content_type",hiddenName:"content_type",forceSelection:!0,typeAhead:!1,editable:!1,allowBlank:!1,pageSize:20,url:MODx.config.connector_url,baseParams:{action:"System/ContentType/GetList"}}),MODx.combo.ContentType.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.ContentType,MODx.combo.ComboBox),Ext.reg("modx-combo-content-type",MODx.combo.ContentType),MODx.combo.ContentDisposition=function(config){config=config||{},Ext.applyIf(config,{store:new Ext.data.SimpleStore({fields:["d","v"],data:[[_("inline"),0],[_("attachment"),1]]}),name:"content_dispo",hiddenName:"content_dispo",displayField:"d",valueField:"v",mode:"local",triggerAction:"all",editable:!1,pageSize:20,selectOnFocus:!1,preventRender:!0}),MODx.combo.ContentDisposition.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.ContentDisposition,MODx.combo.ComboBox),Ext.reg("modx-combo-content-disposition",MODx.combo.ContentDisposition),MODx.combo.ClassDerivatives=function(config){config=config||{},Ext.applyIf(config,{name:"class",hiddenName:"class",url:MODx.config.connector_url,baseParams:{action:"System/Derivatives/GetList",class:"MODX\\Revolution\\modResource"},displayField:"name",valueField:"id",fields:["id","name"],forceSelection:!0,typeAhead:!1,editable:!1,allowBlank:!1,pageSize:20}),MODx.combo.ClassDerivatives.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.ClassDerivatives,MODx.combo.ComboBox),Ext.reg("modx-combo-class-derivatives",MODx.combo.ClassDerivatives),MODx.combo.Namespace=function(config){config=config||{},Ext.applyIf(config,{name:"namespace",hiddenName:"namespace",typeAhead:!0,minChars:1,queryParam:"query",editable:!0,allowBlank:!0,preselectValue:!1,pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Workspace/PackageNamespace/GetList"},fields:["name"],displayField:"name",valueField:"name"}),MODx.combo.Namespace.superclass.constructor.call(this,config),!1!==config.preselectValue&&(this.store.on("load",this.preselectFirstValue,this,{single:!0}),this.store.load())},Ext.extend(MODx.combo.Namespace,MODx.combo.ComboBox,{preselectFirstValue:function(r){var item;if(""==this.config.preselectValue)item=r.getAt(0);else{var found=r.find("name",this.config.preselectValue);item=-1!=found?r.getAt(found):r.getAt(0)}item&&(this.setValue(item.data.name),this.fireEvent("select",this,item))}}),Ext.reg("modx-combo-namespace",MODx.combo.Namespace),MODx.combo.Browser=function(config){config=config||{},Ext.applyIf(config,{width:400,triggerAction:"all",triggerClass:"x-form-file-trigger",source:config.source||MODx.config.default_media_source}),MODx.combo.Browser.superclass.constructor.call(this,config),this.config=config},Ext.extend(MODx.combo.Browser,Ext.form.TriggerField,{browser:null,onTriggerClick:function(btn){return!this.disabled&&(this.browser=MODx.load({xtype:"modx-browser",closeAction:"close",id:Ext.id(),multiple:!0,source:this.config.source||MODx.config.default_media_source,hideFiles:this.config.hideFiles||!1,rootVisible:this.config.rootVisible||!1,allowedFileTypes:this.config.allowedFileTypes||"",wctx:this.config.wctx||"web",openTo:this.config.openTo||"",rootId:this.config.rootId||"/",hideSourceCombo:this.config.hideSourceCombo||!1,listeners:{select:{fn:function(data){this.setValue(data.relativeUrl),this.fireEvent("select",data)},scope:this}}}),this.browser.show(btn),!0)},onDestroy:function(){MODx.combo.Browser.superclass.onDestroy.call(this)}}),Ext.reg("modx-combo-browser",MODx.combo.Browser),MODx.combo.Country=function(config){config=config||{},Ext.applyIf(config,{name:"country",hiddenName:"country",url:MODx.config.connector_url,baseParams:{action:"System/Country/GetList",combo:!0},displayField:"country",valueField:"iso",fields:["iso","country","value"],editable:!0,typeAhead:!0}),MODx.combo.Country.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Country,MODx.combo.ComboBox),Ext.reg("modx-combo-country",MODx.combo.Country),MODx.combo.Gender=function(config){config=config||{},Ext.applyIf(config,{store:new Ext.data.SimpleStore({fields:["d","v"],data:[["",0],[_("user_male"),1],[_("user_female"),2],[_("user_other"),3]]}),displayField:"d",valueField:"v",mode:"local",triggerAction:"all",editable:!1,selectOnFocus:!1}),MODx.combo.Gender.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Gender,Ext.form.ComboBox),Ext.reg("modx-combo-gender",MODx.combo.Gender),MODx.combo.PropertySet=function(config){config=config||{},Ext.applyIf(config,{name:"propertyset",hiddenName:"propertyset",url:MODx.config.connector_url,baseParams:{action:"Element/PropertySet/GetList"},displayField:"name",valueField:"id",fields:["id","name"],editable:!1,pageSize:20,width:300}),MODx.combo.PropertySet.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.PropertySet,MODx.combo.ComboBox),Ext.reg("modx-combo-property-set",MODx.combo.PropertySet),MODx.ChangeParentField=function(config){config=config||{},Ext.applyIf(config,{triggerAction:"all",editable:!1,readOnly:!1,formpanel:"modx-panel-resource",parentcmp:"modx-resource-parent-hidden",contextcmp:"modx-resource-context-key",currentid:MODx.request.id}),MODx.ChangeParentField.superclass.constructor.call(this,config),this.config=config,this.on("click",this.onTriggerClick,this),this.addEvents({end:!0}),this.on("end",this.end,this)},Ext.extend(MODx.ChangeParentField,Ext.form.TriggerField,{oldValue:!1,oldDisplayValue:!1,end:function(p){var t=Ext.getCmp("modx-resource-tree");t&&(p.d=p.d||p.v,t.removeListener("click",this.handleChangeParent,this),t.on("click",t._handleClick,t),t.disableHref=!1,MODx.debug("Setting parent to: "+p.v),Ext.getCmp(this.config.parentcmp).setValue(p.v),this.setValue(p.d),this.oldValue=!1,"modx-template-picker-parent-id"!==this.config.parentcmp&&Ext.getCmp(this.config.formpanel).fireEvent("fieldChange"))},onTriggerClick:function(){if(this.disabled)return!1;if(this.oldValue)return this.fireEvent("end",{v:this.oldValue,d:this.oldDisplayValue}),!1;if(MODx.debug("onTriggerClick"),!Ext.getCmp("modx-resource-tree")){MODx.debug("no tree found, trying to activate");var tp=Ext.getCmp("modx-leftbar-tabpanel");return tp?(tp.on("tabchange",(function(tbp,tab){"modx-resource-tree-ct"==tab.id&&this.disableTreeClick()}),this),tp.activate("modx-resource-tree-ct")):MODx.debug("no tabpanel"),!1}this.disableTreeClick()},disableTreeClick:function(){return MODx.debug("Disabling tree click"),t=Ext.getCmp("modx-resource-tree"),t?(this.oldDisplayValue=this.getValue(),this.oldValue=Ext.getCmp(this.config.parentcmp).getValue(),this.setValue(_("resource_parent_select_node")),t.expand(),t.removeListener("click",t._handleClick),t.on("click",this.handleChangeParent,this),t.disableHref=!0,!0):(MODx.debug("No tree found in disableTreeClick!"),!1)},handleChangeParent:function(node,e){var t=Ext.getCmp("modx-resource-tree");if(!t)return!1;t.disableHref=!0;var id=node.id.split("_");if((id=id[1])==this.config.currentid)return MODx.msg.alert("",_("resource_err_own_parent")),!1;var ctxf=Ext.getCmp(this.config.contextcmp);if(ctxf){var ctxv=ctxf.getValue();node.attributes&&node.attributes.ctx!=ctxv&&ctxf.setValue(node.attributes.ctx)}return this.fireEvent("end",{v:"modContext"!=node.attributes.type?id:node.attributes.pk,d:Ext.util.Format.stripTags(node.text)}),e.preventDefault(),e.stopEvent(),!0}}),Ext.reg("modx-field-parent-change",MODx.ChangeParentField),MODx.combo.TVWidget=function(config){config=config||{},Ext.applyIf(config,{name:"widget",hiddenName:"widget",displayField:"name",valueField:"value",fields:["value","name"],editable:!1,url:MODx.config.connector_url,baseParams:{action:"Element/TemplateVar/Renders/GetOutputs"},value:"default"}),MODx.combo.TVWidget.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.TVWidget,MODx.combo.ComboBox),Ext.reg("modx-combo-tv-widget",MODx.combo.TVWidget),MODx.combo.TVInputType=function(config){config=config||{},Ext.applyIf(config,{name:"type",hiddenName:"type",displayField:"name",valueField:"value",editable:!1,fields:["value","name"],url:MODx.config.connector_url,baseParams:{action:"Element/TemplateVar/Renders/GetInputs"},value:"text"}),MODx.combo.TVInputType.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.TVInputType,MODx.combo.ComboBox),Ext.reg("modx-combo-tv-input-type",MODx.combo.TVInputType),MODx.combo.Dashboard=function(config){config=config||{},Ext.applyIf(config,{name:"dashboard",hiddenName:"dashboard",displayField:"name",valueField:"id",fields:["id","name","description"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"System/Dashboard/GetList"},tpl:new Ext.XTemplate('<tpl for=".">','<div class="x-combo-list-item">','<h4 class="modx-combo-title">{name:htmlEncode}</h4>','<p class="modx-combo-desc">{description:htmlEncode}</p>',"</div></tpl>")}),MODx.combo.Dashboard.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Dashboard,MODx.combo.ComboBox),Ext.reg("modx-combo-dashboard",MODx.combo.Dashboard),MODx.combo.MediaSource=function(config){config=config||{},Ext.applyIf(config,{name:"source",hiddenName:"source",displayField:"name",valueField:"id",fields:["id","name","description"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Source/GetList"},tpl:new Ext.XTemplate('<tpl for=".">','<div class="x-combo-list-item">','<h4 class="modx-combo-title">{name:htmlEncode}</h4>','<p class="modx-combo-desc">{description:htmlEncode}</p>',"</div></tpl>")}),MODx.combo.MediaSource.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.MediaSource,MODx.combo.ComboBox),Ext.reg("modx-combo-source",MODx.combo.MediaSource),MODx.combo.MediaSourceType=function(config){config=config||{},Ext.applyIf(config,{name:"class_key",hiddenName:"class_key",displayField:"name",valueField:"class",fields:["id","class","name","description"],pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Source/Type/GetList"},tpl:new Ext.XTemplate('<tpl for=".">','<div class="x-combo-list-item">','<h4 class="modx-combo-title">{name:htmlEncode}</h4>','<p class="modx-combo-desc">{description:htmlEncode}</p>',"</div></tpl>")}),MODx.combo.MediaSourceType.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.MediaSourceType,MODx.combo.ComboBox),Ext.reg("modx-combo-source-type",MODx.combo.MediaSourceType),MODx.combo.Authority=function(config){config=config||{},Ext.applyIf(config,{name:"authority",hiddenName:"authority",forceSelection:!0,typeAhead:!1,editable:!1,allowBlank:!1,pageSize:20,url:MODx.config.connector_url,baseParams:{action:"Security/Role/GetAuthorityList",addNone:!0}}),MODx.combo.Authority.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Authority,MODx.combo.ComboBox),Ext.reg("modx-combo-authority",MODx.combo.Authority),MODx.combo.ManagerTheme=function(config){config=config||{},Ext.applyIf(config,{name:"theme",hiddenName:"theme",displayField:"theme",valueField:"theme",fields:["theme"],url:MODx.config.connector_url,baseParams:{action:"Workspace/Theme/GetList"},typeAhead:!1,editable:!1}),MODx.combo.ManagerTheme.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.ManagerTheme,MODx.combo.ComboBox),Ext.reg("modx-combo-manager-theme",MODx.combo.ManagerTheme),MODx.combo.SettingKey=function(config){config=config||{},Ext.applyIf(config,{name:"key",hiddenName:"key",displayField:"key",valueField:"key",fields:["key"],url:MODx.config.connector_url,baseParams:{action:"System/Settings/GetList"},triggerAction:"all",editable:!0,forceSelection:!1,pageSize:20}),MODx.combo.SettingKey.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.SettingKey,MODx.combo.ComboBox),Ext.reg("modx-combo-setting-key",MODx.combo.SettingKey),MODx.combo.Visibility=function(config){config=config||{},Ext.applyIf(config,{name:"visibility",hiddenName:"visibility",store:new Ext.data.SimpleStore({fields:["d","v"],data:[[_("file_folder_visibility_public"),"public"],[_("file_folder_visibility_private"),"private"]]}),displayField:"d",valueField:"v",mode:"local",triggerAction:"all",editable:!1,selectOnFocus:!1,preventRender:!0,forceSelection:!0,enableKeyEvents:!0}),MODx.combo.Visibility.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Visibility,MODx.combo.ComboBox),Ext.reg("modx-combo-visibility",MODx.combo.Visibility),MODx.combo.Permission=function(config){config=config||{},Ext.applyIf(config,{name:"permission",hiddenName:"permission",displayField:"name",valueField:"name",fields:["name","description"],editable:!0,typeAhead:!1,forceSelection:!1,enableKeyEvents:!0,autoSelect:!1,pageSize:20,tpl:new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item"><span style="font-weight: bold">{name:htmlEncode}</span>','<p style="margin: 0; font-size: 11px; color: gray;">{description:htmlEncode}</p></div></tpl>'),url:MODx.config.connector_url,baseParams:{action:"Security/Access/Permission/GetList"}}),MODx.combo.Permission.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.Permission,MODx.combo.ComboBox),Ext.reg("modx-combo-permission",MODx.combo.Permission),Ext.namespace("MODx.grid"),MODx.grid.Grid=function(config={}){if(this.config=config,this._loadStore(),this._loadColumnModel(),Ext.applyIf(config,{store:this.store,cm:this.cm,sm:new Ext.grid.RowSelectionModel({singleSelect:!0}),paging:!!config.bbar,loadMask:!0,autoHeight:!0,collapsible:!0,stripeRows:!0,header:!1,cls:"modx-grid",preventRender:!0,preventSaveRefresh:!0,showPerPage:!0,stateful:!1,showActionsColumn:!0,disableContextMenuAction:!1,menuConfig:{defaultAlign:"tl-b?",enableScrolling:!1},viewConfig:{forceFit:!0,enableRowBody:!0,autoFill:!0,showPreview:!0,scrollOffset:0,emptyText:config.emptyText||_("ext_emptymsg")},groupingConfig:{enableGroupingMenu:!0}}),config.paging){var pgItms=config.showPerPage?[_("per_page")+":",{xtype:"textfield",cls:"x-tbar-page-size",value:config.pageSize||parseInt(MODx.config.default_per_page)||20,listeners:{change:{fn:this.onChangePerPage,scope:this},render:{fn:function(cmp){new Ext.KeyMap(cmp.getEl(),{key:Ext.EventObject.ENTER,fn:this.blur,scope:cmp})},scope:this}}}]:[];if(config.pagingItems)for(var i=0;i<config.pagingItems.length;i++)pgItms.push(config.pagingItems[i]);Ext.applyIf(config,{bbar:new Ext.PagingToolbar({pageSize:config.pageSize||parseInt(MODx.config.default_per_page)||20,store:this.getStore(),displayInfo:!0,items:pgItms})})}if(config.grouping){var groupingConfig={forceFit:!0,scrollOffset:0,groupTextTpl:'{text} ({[values.rs.length]} {[values.rs.length > 1 ? "'+(config.pluralText||_("records"))+'" : "'+(config.singleText||_("record"))+'"]})'};Ext.applyIf(config.groupingConfig,groupingConfig),Ext.applyIf(config,{view:new Ext.grid.GroupingView(config.groupingConfig)})}if(config.tbar)for(var ix=0;ix<config.tbar.length;ix++){var itm=config.tbar[ix];itm.handler&&"object"==typeof itm.handler&&itm.handler.xtype&&(itm.handler=this.loadWindow.createDelegate(this,[itm.handler],!0)),itm.scope||(itm.scope=this)}if(config.showActionsColumn){var defaultActionsColumnWidth=50,isPercentage=function(columns){for(var i=0;i<columns.length;i++)if(columns[i].width&&columns[i].width>1)return!1;return!0};config.columns&&Array.isArray(config.columns)&&(void 0===config.actionsColumnWidth&&isPercentage(config.columns)&&(defaultActionsColumnWidth=.1),config.columns.push({id:"modx-actions",width:config.actionsColumnWidth||defaultActionsColumnWidth,menuDisabled:!0,renderer:this.actionsColumnRenderer.bind(this)})),config.cm&&config.cm.columns&&Array.isArray(config.cm.columns)&&(void 0===config.actionsColumnWidth&&isPercentage(config.cm.columns)&&(defaultActionsColumnWidth=.1),config.cm.columns.push({id:"modx-actions",width:config.actionsColumnWidth||defaultActionsColumnWidth,menuDisabled:!0,renderer:this.actionsColumnRenderer.bind(this)}))}MODx.grid.Grid.superclass.constructor.call(this,config),this._loadMenu(config),this.addEvents("beforeRemoveRow","afterRemoveRow","afterAutoSave"),this.autosave&&this.on("afterAutoSave",this.onAfterAutoSave,this),config.preventRender||this.render(),this.on({render:{fn:function(){const topToolbar=this.getTopToolbar();topToolbar&&topToolbar.initialConfig.cls&&"has-nested-filters"==topToolbar.initialConfig.cls&&(this.hasNestedFilters=!0)},scope:this},rowcontextmenu:{fn:this._showMenu,scope:this}}),config.autosave&&this.on("afteredit",this.saveRecord,this),config.paging&&config.grouping&&this.getBottomToolbar().bind(this.store),config.paging||config.hasOwnProperty("pageSize")||(config.pageSize=0),this.getStore().load({params:{start:config.pageStart||0,limit:config.hasOwnProperty("pageSize")?config.pageSize:parseInt(MODx.config.default_per_page)||20}}),this.getStore().on("exception",this.onStoreException,this),this.config=config,this.on("click",this.onClickHandler,this)},Ext.extend(MODx.grid.Grid,Ext.grid.EditorGridPanel,{windows:{},onStoreException:function(dataProxy,type,action,options,response){const responseStatusCode=response.status||"Unknown",responseStatusText=Ext.isEmpty(response.statusText)?"":`(${response.statusText})`;let output="",msg="";if(Ext.isEmpty(response.responseText))output=200!==responseStatusCode?`<div class="error-status-info">${responseStatusCode} ${responseStatusText}</div>`:"";else try{const responseText=Ext.decode(response.responseText);responseText&&responseText.message&&(output=responseText.message)}catch(e){output=response.responseText}output?MODx.config.debug>0?(output=MODx.util.safeHtml(output,"<table><tbody><tr><th><td><div><i><em><b><strong>","class,colspan,rowspan"),msg=_("error_grid_get_content_toscreen",{message:`<pre><code>${output}</code></pre>`})):(msg=_("error_grid_get_content_tolog"),output=Ext.util.Format.stripTags(output).replaceAll("&gt;",">").replaceAll("&lt;","<"),console.error(output)):msg=_("error_grid_get_content_no_msg"),this.getView().emptyText=`<div class="error-with-icon">${msg}</div>`,this.getView().refresh(!1)},saveRecord:function(e){e.record.data.menu=null;var p=this.config.saveParams||{};Ext.apply(e.record.data,p);var d=Ext.util.JSON.encode(e.record.data),url=this.config.saveUrl||this.config.url||this.config.connector;MODx.Ajax.request({url,params:{action:this.config.save_action||"updateFromGrid",data:d},listeners:{success:{fn:function(r){if(this.config.save_callback&&Ext.callback(this.config.save_callback,this.config.scope||this,[r]),e.record.commit(),!this.config.preventSaveRefresh){new Ext.util.DelayedTask((()=>this.refresh())).delay(200)}this.fireEvent("afterAutoSave",r)},scope:this},failure:{fn:function(r){e.record.reject(),this.fireEvent("afterAutoSave",r)},scope:this}}})},onAfterAutoSave:function(response){if(!response.success&&""===response.message){var msg="";response.data.length&&Ext.each(response.data,(function(data,index,list){msg+=(""!=msg?"<br/>":"")+data.msg}),this),Ext.isEmpty(msg)&&(msg=this.autosaveErrorMsg||_("error")),MODx.msg.alert(_("error"),msg)}},onChangePerPage:function(tf,nv){if(Ext.isEmpty(nv))return!1;nv=parseInt(nv),this.getBottomToolbar().pageSize=nv,this.store.load({params:{start:0,limit:nv}})},loadWindow:function(btn,e,win,or){var r=this.menu.record;this.windows[win.xtype]&&!win.force||(Ext.applyIf(win,{record:win.blankValues?{}:r,grid:this,listeners:{success:{fn:win.success||this.refresh,scope:win.scope||this}}}),or&&Ext.apply(win,or),this.windows[win.xtype]=Ext.ComponentMgr.create(win)),this.windows[win.xtype].setValues&&!0!==win.blankValues&&null!=r&&this.windows[win.xtype].setValues(r),this.windows[win.xtype].show(e.target)},confirm:function(type,text){var p={action:type},k=this.config.primaryKey||"id";p[k]=this.menu.record[k],MODx.msg.confirm({title:_(type),text:_(text)||_("confirm_remove"),url:this.config.url,params:p,listeners:{success:{fn:this.refresh,scope:this}}})},remove:function(text,action){if(this.destroying)return MODx.grid.Grid.superclass.remove.apply(this,arguments);var r=this.menu.record;text=text||"confirm_remove";var p=this.config.saveParams||{};Ext.apply(p,{action:action||"remove"});var k=this.config.primaryKey||"id";p[k]=r[k],this.fireEvent("beforeRemoveRow",r)&&MODx.msg.confirm({title:_("warning"),text:_(text,r),url:this.config.url,params:p,listeners:{success:{fn:function(){this.removeActiveRow(r)},scope:this}}})},removeActiveRow:function(r){if(this.fireEvent("afterRemoveRow",r)){var rx=this.getSelectionModel().getSelected();this.getStore().remove(rx)}},_loadMenu:function(){this.menu=new Ext.menu.Menu(this.config.menuConfig)},_showMenu:function(g,ri,e){if(e.stopEvent(),e.preventDefault(),this.menu.record=this.getStore().getAt(ri).data,this.getSelectionModel().isSelected(ri)||this.getSelectionModel().selectRow(ri),this.menu.removeAll(),this.getMenu){var m=this.getMenu(g,ri,e);m&&m.length&&m.length>0&&this.addContextMenuItem(m)}(!m||m.length<=0)&&this.menu.record.menu&&this.addContextMenuItem(this.menu.record.menu),this.menu.items.length>0&&this.menu.showAt(e.xy)},_loadStore:function(){this.config.grouping?this.store=new Ext.data.GroupingStore({url:this.config.url,baseParams:this.config.baseParams||{action:this.config.action||"getList"},reader:new Ext.data.JsonReader({totalProperty:"total",root:"results",fields:this.config.fields}),sortInfo:{field:this.config.sortBy||"id",direction:this.config.sortDir||"ASC"},remoteSort:this.config.remoteSort||!1,remoteGroup:this.config.remoteGroup||!1,groupField:this.config.groupBy||"name",groupDir:this.config.groupDir||"ASC",storeId:this.config.storeId||Ext.id(),autoDestroy:!0,listeners:{beforeload:function(store,options){store.groupField===store.sortInfo.field&&store.groupDir!==store.sortInfo.direction&&(store.groupDir=store.sortInfo.direction,store.baseParams.groupDir=store.sortInfo.direction)},load:function(store,records,options){const cmp=Ext.getCmp("modx-content");cmp&&cmp.doLayout()},groupchange:{fn:function(store,groupField){store.groupDir=this.config.groupDir||"ASC",store.baseParams.groupDir=store.groupDir,store.sortInfo.direction=this.config.sortDir||"ASC",store.load()},scope:this}}}):this.store=new Ext.data.JsonStore({url:this.config.url,baseParams:this.config.baseParams||{action:this.config.action||"getList"},fields:this.config.fields,root:"results",totalProperty:"total",remoteSort:this.config.remoteSort||!1,storeId:this.config.storeId||Ext.id(),autoDestroy:!0,listeners:{load:function(){const cmp=Ext.getCmp("modx-content");cmp&&cmp.doLayout()}}})},_loadColumnModel:function(){if(this.config.columns){for(var c=this.config.columns,i=0;i<c.length;i++){if("string"==typeof c[i].editor&&(c[i].editor=eval(c[i].editor)),"string"==typeof c[i].renderer&&(c[i].renderer=eval(c[i].renderer)),"object"==typeof c[i].editor&&c[i].editor.xtype){var r=c[i].editor.renderer;Ext.isEmpty(c[i].editor.id)&&(c[i].editor.id=Ext.id()),c[i].editor=Ext.ComponentMgr.create(c[i].editor),!0===r?(c[i].editor&&c[i].editor.store&&!c[i].editor.store.isLoaded&&"local"!=c[i].editor.config.mode&&(c[i].editor.store.load(),c[i].editor.store.isLoaded=!0),c[i].renderer=Ext.util.Format.comboRenderer(c[i].editor)):"datefield"===c[i].editor.initialConfig.xtype?c[i].renderer=Ext.util.Format.dateRenderer(c[i].editor.initialConfig.format||"Y-m-d"):"boolean"===r?c[i].renderer=this.rendYesNo:"password"===r?c[i].renderer=this.rendPassword:"local"===r&&"string"==typeof c[i].renderer&&(c[i].renderer=eval(c[i].renderer))}Ext.isEmpty(c[i].renderer)&&(c[i].renderer=Ext.util.Format.htmlEncode),c[i].editor&&(c[i].renderer=this.renderEditableColumn(c[i].renderer))}this.cm=new Ext.grid.ColumnModel(c)}},addContextMenuItem:function(items){for(var l=items.length,i=0;i<l;i++){var options=items[i];if("-"!=options){var h=Ext.emptyFn;options.handler?(h=eval(options.handler),h&&"object"==typeof h&&h.xtype&&(h=this.loadWindow.createDelegate(this,[h],!0))):h=function(itm){var o=itm.options,id=this.menu.record.id;if(o.confirm)Ext.Msg.confirm("",o.confirm,(function(e){if("yes"==e){var act=Ext.urlEncode(o.params||{action:o.action});location.href="?id="+id+"&"+act}}),this);else{var act=Ext.urlEncode(o.params||{action:o.action});location.href="?id="+id+"&"+act}},this.menu.add({id:options.id||Ext.id(),text:options.text,scope:options.scope||this,options,handler:h})}else this.menu.add("-")}},refresh:function(){this.getStore().reload()},rendPassword:function(v){for(var z="",i=0;i<v.length;i++)z+="*";return z},renderEditableColumn:function(renderer){return function(value,metaData,record,rowIndex,colIndex,store){if(renderer){if("function"==typeof renderer.fn){var scope=!!renderer.scope&&renderer.scope;renderer=renderer.fn.bind(scope)}"function"==typeof renderer&&(value=renderer(value,metaData,record,rowIndex,colIndex,store))}return metaData.css=["x-editable-column",metaData.css||""].join(" "),value}},rendYesNo:function(v,md){switch(1!==v&&"1"!=v||(v=!0),0!==v&&"0"!=v||(v=!1),v){case!0:case"true":case 1:return md.css="green",_("yes");case!1:case"false":case"":case 0:return md.css="red",_("no")}},getSelectedAsList:function(){var sels=this.getSelectionModel().getSelections();if(sels.length<=0)return!1;for(var cs="",i=0;i<sels.length;i++)cs+=","+sels[i].data[this.config.primaryKey||"id"];return","==cs[0]&&(cs=cs.substr(1)),cs},editorYesNo:function(r){return r=r||{},Ext.applyIf(r,{store:new Ext.data.SimpleStore({fields:["d","v"],data:[[_("yes"),!0],[_("no"),!1]]}),displayField:"d",valueField:"v",mode:"local",triggerAction:"all",editable:!1,selectOnFocus:!1}),new Ext.form.ComboBox(r)},encodeModified:function(){for(var p=this.getStore().getModifiedRecords(),rs={},i=0;i<p.length;i++)rs[p[i].data[this.config.primaryKey||"id"]]=p[i].data;return Ext.encode(rs)},encode:function(){for(var p=this.getStore().getRange(),rs={},i=0;i<p.length;i++)rs[p[i].data[this.config.primaryKey||"id"]]=p[i].data;return Ext.encode(rs)},expandAll:function(){var expander=this.findExpanderPlugin(this.config.plugins);if(!expander)return!1;for(var rows=this.getView().getRows(),i=0;i<rows.length;i++)expander.expandRow(rows[i]);return void 0!==this.tools.plus&&this.tools.plus.hide(),void 0!==this.tools.minus&&this.tools.minus.show(),!0},collapseAll:function(){var expander=this.findExpanderPlugin(this.config.plugins);if(!expander)return!1;for(var rows=this.getView().getRows(),i=0;i<rows.length;i++)expander.collapseRow(rows[i]);return void 0!==this.tools.minus&&this.tools.minus.hide(),void 0!==this.tools.plus&&this.tools.plus.show(),!0},findExpanderPlugin:function(plugins){return Ext.isObject(plugins)&&(plugins=[plugins]),plugins[Ext.each(plugins,(function(item){if(void 0!==item.id&&"expander"===item.id)return!1}))]},_getActionsColumnTpl:function(){return new Ext.XTemplate('<tpl for="."><tpl if="actions !== null"><ul class="x-grid-buttons"><tpl for="actions"><li><i class="x-grid-action icon icon-{icon:htmlEncode}" title="{text:htmlEncode}" data-action="{action:htmlEncode}"></i></li></tpl></ul></tpl></tpl>',{compiled:!0})},actionsColumnRenderer:function(value,metaData,record,rowIndex,colIndex,store){var actions=this.getActions.apply(this,[record,rowIndex,colIndex,store]);return!0!==this.config.disableContextMenuAction&&actions.push({text:_("context_menu"),action:"contextMenu",icon:"gear"}),this._getActionsColumnTpl().apply({actions})},renderLink:function(v,attr){var el=new Ext.Element(document.createElement("a"));for(var i in el.addClass("x-grid-link"),el.dom.title=_("edit"),attr)el.dom[i]=attr[i];return el.dom.innerHTML=Ext.util.Format.htmlEncode(v),el.dom.outerHTML},checkEditable:function(e){this.checkCellIsEditable(e)},checkCellIsEditable:function(e){if(-1===(e.record.data.perm||"").indexOf("edit"))return!1;switch(e.grid.xtype){case"modx-grid-role":{const isAuthorityField="authority"===e.field;if(e.record.json.isAssigned&&isAuthorityField)return!1;break}}return!0},setEditableCellClasses:function(record,lockConditions=[],lockedClasses="locked",conditionsRequireAll=!0){const permissions=record.data.perm.trim(),hasEditPermission=permissions.split(" ").includes("edit");let classes="",shouldLock=!1;return lockConditions.length>0&&(shouldLock=conditionsRequireAll?lockConditions.every((condition=>!0===Boolean(condition))):lockConditions.some((condition=>!0===Boolean(condition)))),Ext.isEmpty(permissions)?classes="editor-disabled":hasEditPermission&&shouldLock&&(classes=lockedClasses),classes},getLinkTemplate:function(controllerPath,displayValueIndex,options={}){Ext.applyIf(options,{linkParams:[],linkClass:"x-grid-link",linkTitle:_("edit"),linkTarget:"_blank"});let params="";return controllerPath=0===controllerPath.indexOf("?a=")?controllerPath:`?a=${controllerPath}`,options.linkParams.length>0&&(params=[],options.linkParams.forEach((param=>{params.push(`${param.key}={${param.valueIndex}}`)})),params=`&${params.join("&")}`),new Ext.Template(`<tpl><a href="${controllerPath}${params}" class="${options.linkClass}" title="${options.linkTitle}" target="${options.linkTarget}">{${displayValueIndex}:htmlEncode}</a></tpl>`,{compiled:!0})},getActions:function(record,rowIndex,colIndex,store){return[]},onClickHandler:function(e){var target=e.getTarget();if(target.classList.contains("x-grid-action")&&target.dataset.action){var actionHandler="action"+target.dataset.action.charAt(0).toUpperCase()+target.dataset.action.slice(1);if(this[actionHandler]&&"function"==typeof this[actionHandler]||this[actionHandler=target.dataset.action]&&"function"==typeof this[actionHandler]){var record=this.getSelectionModel().getSelected(),recordIndex=this.store.indexOf(record);this.menu.record=record.data,this[actionHandler](record,recordIndex,e)}}},actionContextMenu:function(record,recordIndex,e){this._showMenu(this,recordIndex,e)},makeUrl:function(){if(Array.isArray(this.config.urlFilters)&&this.config.urlFilters.length>0){var s=this.getStore(),p={a:MODx.request.a};MODx.request.id&&(p.id=MODx.request.id),MODx.request.key&&(p.key=MODx.request.key);for(var i=0;i<this.config.urlFilters.length;++i)s.baseParams.hasOwnProperty(this.config.urlFilters[i])&&s.baseParams[this.config.urlFilters[i]]&&("namespace"===this.config.urlFilters[i]?p.ns=s.baseParams[this.config.urlFilters[i]]:p[this.config.urlFilters[i]]=s.baseParams[this.config.urlFilters[i]]);return Ext.urlAppend(MODx.config.manager_url,Ext.urlEncode(p).replace(/%2F/g,"/"))}},replaceState:function(){void 0!==window.history.replaceState&&Array.isArray(this.config.urlFilters)&&this.config.urlFilters.length>0&&window.history.replaceState(this.getStore().baseParams,document.title,this.makeUrl())},findTabPanel:function(referenceCmp){if(!referenceCmp.hasOwnProperty("ownerCt"))return console.error("MODx.grid.Grid::findTabPanel: This component must have an ownerCt to find its tab panel."),!1;const container=referenceCmp.ownerCt;return container.hasOwnProperty("xtype")&&container.xtype.includes("tabs")?container:this.findTabPanel(container)},hasNestedFilters:!1,currentLanguage:MODx.config.cultureKey||"en",applyRequestFilter:function(tabPanelIndex,requestKey="policy",tabPanelType="vtab",setEmptyToString=!1){const emptyVal=setEmptyToString?"":null;return Object.prototype.hasOwnProperty.call(MODx.request,tabPanelType)&&parseInt(MODx.request[tabPanelType],10)===tabPanelIndex&&Object.prototype.hasOwnProperty.call(MODx.request,requestKey)?MODx.util.url.getParamValue(requestKey):emptyVal},applyGridFilter:function(cmp,param="query"){const filterValue=cmp.getValue(),store=this.getStore(),urlParams={},tabPanel=this.findTabPanel(this),bottomToolbar=this.getBottomToolbar();let parentTabItems,activeParentTabIdx,hasParentTabPanel=!1;if(Ext.isEmpty(filterValue)?MODx.request[param]?urlParams[param]=MODx.request[param]:MODx.util.url.clearParam(cmp):urlParams[param]=filterValue,"ns"==param?store.baseParams.namespace=filterValue:store.baseParams[param]=filterValue,tabPanel){if("modx-vtabs"==tabPanel.xtype){const parentTabPanel=this.findTabPanel(tabPanel);if(parentTabPanel){const activeParentTab=parentTabPanel.getActiveTab();hasParentTabPanel=!0,parentTabItems=parentTabPanel.items,activeParentTabIdx=parentTabItems.indexOf(activeParentTab)}}const activeTab=tabPanel.getActiveTab(),tabItems=tabPanel.items,activeTabIdx=tabItems.indexOf(activeTab);hasParentTabPanel?(tabItems.length>1&&(urlParams.vtab=activeTabIdx),parentTabItems.length>1&&(urlParams.tab=activeParentTabIdx)):tabItems.length>1&&(urlParams.tab=activeTabIdx)}store.load(),MODx.util.url.setParams(urlParams),bottomToolbar&&bottomToolbar.changePage(1)},clearGridFilters:function(items){const store=this.getStore(),bottomToolbar=this.getBottomToolbar();(Array.isArray(items)?items:items.split(",")).forEach((item=>{const itemData=item.replace(/\s+/g,"").split(":"),itemId=itemData[0],itemDefaultVal=2==itemData.length?itemData[1]:null,cmp=this.getFilterComponent(itemId),param=MODx.util.url.getParamNameFromCmp(cmp),isCombo=cmp?.xtype?.includes("combo");if(isCombo?""===itemDefaultVal?cmp.setValue(null):cmp.setValue(itemDefaultVal):cmp.setValue(""),!Ext.isEmpty(itemDefaultVal)){Object.keys(cmp.baseParams).forEach((param=>{switch(param){case"namespace":cmp.baseParams[param]="core";break;case"topic":cmp.baseParams[param]="default"}}))}isCombo&&"local"!==cmp.mode&&cmp.getStore().load(),store.baseParams[param]=itemDefaultVal})),store.load(),MODx.util.url.clearAllParams(),bottomToolbar&&bottomToolbar.changePage(1)},hasNestedFilters:!1,getFilterComponent:function(filterId){const topToolbar=this.getTopToolbar(),cmp=this.hasNestedFilters&&"filter-query"!==filterId?topToolbar.find("itemId",`${filterId}-container`)[0].getComponent(filterId):topToolbar.getComponent(filterId);if(void 0!==cmp)return cmp;console.error(`getFilterComponent: The filter component with itemId '${filterId}' could not be retrieved.`)},refreshFilterOptions:function(filterData=[],clearDependentParams=!0){filterData.length>0&&(filterData.forEach((data=>{const filter=this.getFilterComponent(data.filterId);if(filter){const store=filter.getStore();if(filter.setValue(""),store){if(data.hasOwnProperty("dependentParams")){(Array.isArray(data.dependentParams)?data.dependentParams:data.dependentParams.split(",")).forEach((param=>{clearDependentParams&&store.baseParams.hasOwnProperty(param)&&(store.baseParams[param]="")}))}store.load()}}})),this.refresh())},updateDependentFilter:function(filterId,paramKey,paramValue,clearValue=!1){const filter=this.getFilterComponent(filterId),filterStore=filter?filter.getStore():null;filterStore&&"string"==typeof paramKey&&(clearValue&&filter.setValue(""),filterStore.baseParams[paramKey]=paramValue,filterStore.load())},getQueryFilterField:function(filterSpec="filter-query",implementation="default"){let queryValue="";const filterSpecs=filterSpec.split(":"),filterId=filterSpecs[0].trim();return queryValue=2===filterSpecs.length?filterSpecs[1]:MODx.request.query?MODx.util.url.decodeParamValue(MODx.request.query):"",{xtype:"textfield",itemId:filterId,emptyText:_("search"),value:queryValue,cls:"filter-query",listeners:{change:{fn:function(cmp,newValue,oldValue){this.applyGridFilter(cmp);const usergroupTree=Ext.getCmp("modx-tree-usergroup");if("user-group-users"===implementation&&usergroupTree){const selectedNode=usergroupTree.getSelectionModel().getSelectedNode(),groupId=MODx.util.tree.getGroupIdFromNode(selectedNode);MODx.util.url.setParams({group:groupId})}},scope:this},afterrender:{fn:function(cmp){MODx.request.query&&this.applyGridFilter(cmp)},scope:this},render:{fn:function(cmp){new Ext.KeyMap(cmp.getEl(),{key:Ext.EventObject.ENTER,fn:this.blur,scope:cmp})},scope:this}}}},getClearFiltersButton:function(filters="filter-query",dependentFilterResets=null){if(Ext.isEmpty(filters))return console.error("MODx.grid.Grid::getClearFiltersButton: There was a problem creating the Clear Filter button because the supplied filters list is invalid."),{};const config={text:_("filter_clear"),itemId:"filter-clear",listeners:{click:{fn:function(cmp){if(cmp.dependentResets){cmp.dependentResets.split(",").forEach((reset=>{const[filterId,filterDataIndex]=reset.split(":").map((item=>item.trim()));this.updateDependentFilter(filterId,filterDataIndex,"",!0)}))}this.clearGridFilters(filters)},scope:this},mouseout:{fn:function(evt){this.removeClass("x-btn-focus")}}}};return dependentFilterResets&&(config.dependentResets=dependentFilterResets),config}}),MODx.grid.LocalGrid=function(config){if((config=config||{}).grouping&&Ext.applyIf(config,{view:new Ext.grid.GroupingView({forceFit:!0,scrollOffset:0,hideGroupedColumn:!!config.hideGroupedColumn,groupTextTpl:config.groupTextTpl||'{text} ({[values.rs.length]} {[values.rs.length > 1 ? "'+(config.pluralText||_("records"))+'" : "'+(config.singleText||_("record"))+'"]})'})}),config.tbar)for(var i=0;i<config.tbar.length;i++){var itm=config.tbar[i];itm.handler&&"object"==typeof itm.handler&&itm.handler.xtype&&(itm.handler=this.loadWindow.createDelegate(this,[itm.handler],!0)),itm.scope||(itm.scope=this)}Ext.applyIf(config,{title:"",store:this._loadStore(config),sm:new Ext.grid.RowSelectionModel({singleSelect:!1}),loadMask:!0,collapsible:!0,stripeRows:!0,enableColumnMove:!0,header:!1,cls:"modx-grid",showActionsColumn:!0,actionsColumnWidth:50,disableContextMenuAction:!1,viewConfig:{forceFit:!0,enableRowBody:!0,autoFill:!0,showPreview:!0,scrollOffset:0,emptyText:config.emptyText||_("ext_emptymsg")},menuConfig:{defaultAlign:"tl-b?",enableScrolling:!1}}),this.menu=new Ext.menu.Menu(config.menuConfig),this.config=config,this._loadColumnModel(),config.showActionsColumn&&config.columns&&Array.isArray(config.columns)&&config.columns.push({width:config.actionsColumnWidth||50,menuDisabled:!0,renderer:{fn:this.actionsColumnRenderer,scope:this}}),MODx.grid.LocalGrid.superclass.constructor.call(this,config),this.addEvents({beforeRemoveRow:!0,afterRemoveRow:!0}),this.on("rowcontextmenu",this._showMenu,this)},Ext.extend(MODx.grid.LocalGrid,Ext.grid.EditorGridPanel,{windows:{},_loadStore:function(config){return config.grouping?this.store=new Ext.data.GroupingStore({data:config.data||[],reader:new Ext.data.ArrayReader({},config.fields||[]),sortInfo:config.sortInfo||{field:config.sortBy||"name",direction:config.sortDir||"ASC"},groupField:config.groupBy||"name"}):this.store=new Ext.data.SimpleStore({fields:config.fields,data:config.data||[]}),this.store},loadWindow:function(btn,e,win,or){var r=this.menu.record;this.windows[win.xtype]||(Ext.applyIf(win,{scope:this,success:this.refresh,record:win.blankValues?{}:r}),or&&Ext.apply(win,or),this.windows[win.xtype]=Ext.ComponentMgr.create(win)),this.windows[win.xtype].setValues&&!0!==win.blankValues&&null!=r&&this.windows[win.xtype].setValues(r),this.windows[win.xtype].show(e.target)},_loadColumnModel:function(){if(this.config.columns){for(var c=this.config.columns,i=0;i<c.length;i++){if("string"==typeof c[i].editor&&(c[i].editor=eval(c[i].editor)),"string"==typeof c[i].renderer&&(c[i].renderer=eval(c[i].renderer)),"object"==typeof c[i].editor&&c[i].editor.xtype){var r=c[i].editor.renderer;c[i].editor=Ext.ComponentMgr.create(c[i].editor),!0===r?(c[i].editor&&c[i].editor.store&&!c[i].editor.store.isLoaded&&"local"!=c[i].editor.config.mode&&(c[i].editor.store.load(),c[i].editor.store.isLoaded=!0),c[i].renderer=Ext.util.Format.comboRenderer(c[i].editor)):"datefield"===c[i].editor.initialConfig.xtype?c[i].renderer=Ext.util.Format.dateRenderer(c[i].editor.initialConfig.format||"Y-m-d"):"boolean"===r?c[i].renderer=this.rendYesNo:"password"===r?c[i].renderer=this.rendPassword:"local"===r&&"string"==typeof c[i].renderer&&(c[i].renderer=eval(c[i].renderer))}Ext.isEmpty(c[i].renderer)&&(c[i].renderer=Ext.util.Format.htmlEncode),c[i].editor&&(c[i].renderer=this.renderEditableColumn(c[i].renderer))}this.cm=new Ext.grid.ColumnModel(c)}},renderEditableColumn:function(renderer){return function(value,metaData,record,rowIndex,colIndex,store){if(renderer){if("function"==typeof renderer.fn){var scope=!!renderer.scope&&renderer.scope;renderer=renderer.fn.bind(scope)}"function"==typeof renderer&&(value=renderer(value,metaData,record,rowIndex,colIndex,store))}return metaData.css=["x-editable-column",metaData.css||""].join(" "),value}},_showMenu:function(g,ri,e){e.stopEvent(),e.preventDefault(),this.menu.recordIndex=ri,this.menu.record=this.getStore().getAt(ri).data,this.getSelectionModel().isSelected(ri)||this.getSelectionModel().selectRow(ri),this.menu.removeAll();var m=this.getMenu(g,ri);m&&(this.addContextMenuItem(m),this.menu.showAt(e.xy))},getMenu:function(){return this.menu.record.menu},addContextMenuItem:function(items){for(var l=items.length,i=0;i<l;i++){var options=items[i];if("-"!=options){var h=Ext.emptyFn;options.handler?(h=eval(options.handler),h&&"object"==typeof h&&h.xtype&&(h=this.loadWindow.createDelegate(this,[h],!0))):h=function(itm){var o=itm.options,id=this.menu.record.id,w=Ext.get("modx_content");if(o.confirm)Ext.Msg.confirm("",o.confirm,(function(e){if("yes"==e){var a=Ext.urlEncode(o.params||{action:o.action}),s="?id="+id+"&"+a;null===w?location.href=s:w.dom.src=s}}),this);else{var a=Ext.urlEncode(o.params||{action:o.action}),s="?id="+id+"&"+a;null===w?location.href=s:w.dom.src=s}},this.menu.add({id:options.id||Ext.id(),text:options.text,scope:this,options,handler:h})}else this.menu.add("-")}},remove:function(config){if(this.destroying)return MODx.grid.LocalGrid.superclass.remove.apply(this,arguments);var r=this.getSelectionModel().getSelected();this.fireEvent("beforeRemoveRow",r)&&Ext.Msg.confirm(config.title||"",config.text||"",(function(e){"yes"==e&&(this.getStore().remove(r),this.fireEvent("afterRemoveRow",r))}),this)},encode:function(){for(var r,s=this.getStore(),ct=s.getCount(),rs=this.config.encodeByPk?{}:[],j=0;j<ct;j++)(r=s.getAt(j).data).menu=null,this.config.encodeAssoc?rs[r[this.config.encodeByPk||"id"]]=r:rs.push(r);return Ext.encode(rs)},expandAll:function(){var expander=this.findExpanderPlugin(this.config.plugins);if(!expander)return!1;for(var rows=this.getView().getRows(),i=0;i<rows.length;i++)expander.expandRow(rows[i]);return void 0!==this.tools.plus&&this.tools.plus.hide(),void 0!==this.tools.minus&&this.tools.minus.show(),!0},collapseAll:function(){var expander=this.findExpanderPlugin(this.config.plugins);if(!expander)return!1;for(var rows=this.getView().getRows(),i=0;i<rows.length;i++)expander.collapseRow(rows[i]);return void 0!==this.tools.minus&&this.tools.minus.hide(),void 0!==this.tools.plus&&this.tools.plus.show(),!0},findExpanderPlugin:function(plugins){return Ext.isObject(plugins)&&(plugins=[plugins]),plugins[Ext.each(plugins,(function(item){if(void 0!==item.id&&"expander"===item.id)return!1}))]},rendYesNo:function(d,c){switch(d){case"":return"-";case!1:return c.css="red",_("no");case!0:return c.css="green",_("yes")}},rendPassword:function(v){for(var z="",i=0;i<v.length;i++)z+="*";return z},_getActionsColumnTpl:function(){return new Ext.XTemplate('<tpl for="."><tpl if="actions !== null"><ul class="x-grid-buttons"><tpl for="actions"><li><i class="x-grid-action icon icon-{icon:htmlEncode}" title="{text:htmlEncode}" data-action="{action:htmlEncode}"></i></li></tpl></ul></tpl></tpl>',{compiled:!0})},actionsColumnRenderer:function(value,metaData,record,rowIndex,colIndex,store){var actions=this.getActions.apply(this,arguments);return!0!==this.config.disableContextMenuAction&&actions.push({text:_("context_menu"),action:"contextMenu",icon:"gear"}),this._getActionsColumnTpl().apply({actions})},renderLink:function(v,attr){var el=new Ext.Element(document.createElement("a"));for(var i in el.addClass("x-grid-link"),el.dom.title=_("edit"),attr)el.dom[i]=attr[i];return el.dom.innerHTML=Ext.util.Format.htmlEncode(v),el.dom.outerHTML},getActions:function(value,metaData,record,rowIndex,colIndex,store){return[]},onClick:function(e){var target=e.getTarget();if(target.classList.contains("x-grid-action")&&target.dataset.action){var actionHandler="action"+target.dataset.action.charAt(0).toUpperCase()+target.dataset.action.slice(1);if(this[actionHandler]&&"function"==typeof this[actionHandler]||this[actionHandler=target.dataset.action]&&"function"==typeof this[actionHandler]){var record=this.getSelectionModel().getSelected(),recordIndex=this.store.indexOf(record);this.menu.record=record.data,this[actionHandler](record,recordIndex,e)}}},actionContextMenu:function(record,recordIndex,e){this._showMenu(this,recordIndex,e)}}),Ext.reg("grid-local",MODx.grid.LocalGrid),Ext.reg("modx-grid-local",MODx.grid.LocalGrid),
/*!
 * Ext JS Library 3.4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
Ext.ns("Ext.ux.grid"),Ext.ux.grid.RowExpander=Ext.extend(Ext.util.Observable,{expandOnEnter:!0,expandOnDblClick:!0,header:"",width:20,sortable:!1,fixed:!0,hideable:!1,menuDisabled:!0,dataIndex:"",id:"expander",lazyRender:!0,enableCaching:!0,constructor:function(config){Ext.apply(this,config),this.addEvents({beforeexpand:!0,expand:!0,beforecollapse:!0,collapse:!0}),Ext.ux.grid.RowExpander.superclass.constructor.call(this),this.tpl&&("string"==typeof this.tpl&&(this.tpl=new Ext.Template(this.tpl)),this.tpl.compile()),this.state={},this.bodyContent={}},getRowClass:function(record,rowIndex,p,ds){p.cols=p.cols-1;var content=this.bodyContent[record.id];return content||this.lazyRender||(content=this.getBodyContent(record,rowIndex)),content&&(p.body=content),this.state[record.id]?"x-grid3-row-expanded":"x-grid3-row-collapsed"},init:function(grid){this.grid=grid;var view=grid.getView();view.getRowClass=this.getRowClass.createDelegate(this),view.enableRowBody=!0,grid.on("render",this.onRender,this),grid.on("destroy",this.onDestroy,this)},onRender:function(){var grid=this.grid;grid.getView().mainBody.on("mousedown",this.onMouseDown,this,{delegate:".x-grid3-row-expander"}),this.expandOnEnter&&(this.keyNav=new Ext.KeyNav(this.grid.getGridEl(),{enter:this.onEnter,scope:this})),this.expandOnDblClick&&grid.on("rowdblclick",this.onRowDblClick,this)},onDestroy:function(){this.keyNav&&(this.keyNav.disable(),delete this.keyNav);var mainBody=this.grid.getView().mainBody;mainBody&&mainBody.un("mousedown",this.onMouseDown,this)},onRowDblClick:function(grid,rowIdx,e){this.toggleRow(rowIdx)},onEnter:function(e){for(var g=this.grid,sels=g.getSelectionModel().getSelections(),i=0,len=sels.length;i<len;i++){var rowIdx=g.getStore().indexOf(sels[i]);this.toggleRow(rowIdx)}},getBodyContent:function(record,index){if(!this.enableCaching)return this.tpl.apply(record.data);var content=this.bodyContent[record.id];return content||(content=this.tpl.apply(record.data),this.bodyContent[record.id]=content),content},onMouseDown:function(e,t){e.stopEvent();var row=e.getTarget(".x-grid3-row");this.toggleRow(row)},renderer:function(v,p,record){return p.cellAttr='rowspan="2"','<div class="x-grid3-row-expander">&#160;</div>'},beforeExpand:function(record,body,rowIndex){return!1!==this.fireEvent("beforeexpand",this,record,body,rowIndex)&&(this.tpl&&this.lazyRender&&(body.innerHTML=this.getBodyContent(record,rowIndex)),!0)},toggleRow:function(row){"number"==typeof row&&(row=this.grid.view.getRow(row)),this[Ext.fly(row).hasClass("x-grid3-row-collapsed")?"expandRow":"collapseRow"](row)},expandRow:function(row){"number"==typeof row&&(row=this.grid.view.getRow(row));var record=this.grid.store.getAt(row.rowIndex),body=Ext.DomQuery.selectNode("tr:nth(2) div.x-grid3-row-body",row);this.beforeExpand(record,body,row.rowIndex)&&(this.state[record.id]=!0,Ext.fly(row).replaceClass("x-grid3-row-collapsed","x-grid3-row-expanded"),this.fireEvent("expand",this,record,body,row.rowIndex))},collapseRow:function(row){"number"==typeof row&&(row=this.grid.view.getRow(row));var record=this.grid.store.getAt(row.rowIndex),body=Ext.fly(row).child("tr:nth(1) div.x-grid3-row-body",!0);!1!==this.fireEvent("beforecollapse",this,record,body,row.rowIndex)&&(this.state[record.id]=!1,Ext.fly(row).replaceClass("x-grid3-row-expanded","x-grid3-row-collapsed"),this.fireEvent("collapse",this,record,body,row.rowIndex))}}),Ext.preg("rowexpander",Ext.ux.grid.RowExpander),Ext.grid.RowExpander=Ext.ux.grid.RowExpander,Ext.ns("Ext.ux.grid"),Ext.ux.grid.CheckColumn=function(a){Ext.apply(this,a),this.id||(this.id=Ext.id()),this.renderer=this.renderer.createDelegate(this)},Ext.ux.grid.CheckColumn.prototype={init:function(b){this.grid=b,this.grid.on("render",(function(){this.grid.getView().mainBody.on("mousedown",this.onMouseDown,this)}),this),this.grid.on("destroy",this.onDestroy,this)},onMouseDown:function(e,t){if(this.grid.fireEvent("rowclick"),t.className&&-1!=t.className.indexOf("x-grid3-cc-"+this.id)){e.stopEvent();var a=this.grid.getView().findRowIndex(t),b=this.grid.store.getAt(a),sv=b.data[this.dataIndex];b.set(this.dataIndex,!sv),this.grid.fireEvent("afteredit",{grid:this.grid,record:b,field:this.dataIndex,originalValue:sv,value:b.data[this.dataIndex],cancel:!1})}},renderer:function(v,p,a){return p.css+=" x-grid3-check-col-td",'<div class="x-grid3-check-col'+(v?"-on":"")+" x-grid3-cc-"+this.id+'">&#160;</div>'},onDestroy:function(){var mainBody=this.grid.getView().mainBody;mainBody&&mainBody.un("mousedown",this.onMouseDown,this)}},Ext.preg("checkcolumn",Ext.ux.grid.CheckColumn),Ext.grid.CheckColumn=Ext.ux.grid.CheckColumn,Ext.grid.PropertyColumnModel=function(a,b){var g=Ext.grid,f=Ext.form;this.grid=a,g.PropertyColumnModel.superclass.constructor.call(this,[{header:this.nameText,width:50,sortable:!0,dataIndex:"name",id:"name",menuDisabled:!0},{header:this.valueText,width:50,resizable:!1,dataIndex:"value",id:"value",menuDisabled:!0}]),this.store=b;var c=new f.Field({autoCreate:{tag:"select",children:[{tag:"option",value:"true",html:"true"},{tag:"option",value:"false",html:"false"}]},getValue:function(){return"true"==this.el.dom.value}});this.editors={date:new g.GridEditor(new f.DateField({selectOnFocus:!0})),string:new g.GridEditor(new f.TextField({selectOnFocus:!0})),number:new g.GridEditor(new f.NumberField({selectOnFocus:!0,style:"text-align:left;"})),boolean:new g.GridEditor(c)},this.renderCellDelegate=this.renderCell.createDelegate(this),this.renderPropDelegate=this.renderProp.createDelegate(this)},Ext.extend(Ext.grid.PropertyColumnModel,Ext.grid.ColumnModel,{nameText:"Name",valueText:"Value",dateFormat:"m/j/Y",renderDate:function(a){return a.dateFormat(this.dateFormat)},renderBool:function(a){return a?"true":"false"},isCellEditable:function(a,b){return 1==a},getRenderer:function(a){return 1==a?this.renderCellDelegate:this.renderPropDelegate},renderProp:function(v){return this.getPropertyName(v)},renderCell:function(a){var b=a;return Ext.isDate(a)?b=this.renderDate(a):"boolean"==typeof a&&(b=this.renderBool(a)),Ext.util.Format.htmlEncode(b)},getPropertyName:function(a){var b=this.grid.propertyNames;return b&&b[a]?b[a]:a},getCellEditor:function(a,b){var p=this.store.getProperty(b),n=p.data.name,val=p.data.value;return this.grid.customEditors[n]?this.grid.customEditors[n]:Ext.isDate(val)?this.editors.date:"number"==typeof val?this.editors.number:"boolean"==typeof val?this.editors.boolean:this.editors.string},destroy:function(){for(var a in Ext.grid.PropertyColumnModel.superclass.destroy.call(this),this.editors)Ext.destroy(a)}}),MODx.grid.JsonGrid=function(config){config=config||{},this.ident=config.ident||"jsongrid-mecitem"+Ext.id(),this.hiddenField=new Ext.form.TextArea({name:config.hiddenName||config.name,hidden:!0}),this.fieldConfig=config.fieldConfig||[{name:"key"},{name:"value"}],this.fieldConfig.push({name:"id",hidden:!0}),this.fieldColumns=[],this.fieldNames=[],Ext.each(this.fieldConfig,(function(el){this.fieldNames.push(el.name),this.fieldColumns.push({header:el.header||_(el.name),dataIndex:el.name,editable:!0,menuDisabled:!0,hidden:el.hidden||!1,editor:{xtype:el.xtype||"textfield",allowBlank:el.allowBlank||!0,enableKeyEvents:!0,fieldname:el.name,listeners:{change:{fn:this.saveValue,scope:this},keyup:{fn:function(sb){var record=this.getSelectionModel().getSelected();record&&(record.set(sb.fieldname,sb.el.dom.value),this.saveValue())},scope:this}}},renderer:function(value,metadata){return metadata.css+="x-editable-column ",value},width:el.width||100})}),this),Ext.applyIf(config,{id:this.ident+"-json-grid",fields:this.fieldNames,autoHeight:!0,store:new Ext.data.JsonStore({fields:this.fieldNames,data:this.loadValue(config.value)}),enableDragDrop:!0,ddGroup:this.ident+"-json-grid-dd",labelStyle:"position: absolute",columns:this.fieldColumns,disableContextMenuAction:!0,tbar:["->",{text:'<i class="icon icon-plus"></i> '+_("add"),cls:"primary-button",handler:this.addElement,scope:this}],listeners:{render:{fn:this.renderListener,scope:this}}}),MODx.grid.JsonGrid.superclass.constructor.call(this,config)},Ext.extend(MODx.grid.JsonGrid,MODx.grid.LocalGrid,{getMenu:function(){var m=[];return m.push({text:_("remove"),handler:this.removeElement}),m},getActions:function(){return[{action:"removeElement",icon:"trash-o",text:_("remove")}]},addElement:function(){var ds=this.getStore(),row={};Ext.each(this.fieldNames,(function(fieldname){row[fieldname]=""})),row.id=this.getStore().getCount(),this.getStore().insert(this.getStore().getCount(),new ds.recordType(row)),this.getView().refresh(),this.getSelectionModel().selectRow(0)},removeElement:function(){Ext.Msg.confirm(_("remove")||"",_("confirm_remove")||"",(function(e){if("yes"===e){var ds=this.getStore(),rows=this.getSelectionModel().getSelections();if(!rows.length)return!1;for(var i=0;i<rows.length;i++){var id=rows[i].id,index=ds.findBy((function(record){if(record.id===id)return!0}));ds.removeAt(index)}this.getView().refresh(),this.saveValue()}}),this)},renderListener:function(grid){new Ext.dd.DropTarget(grid.container,{copy:!1,ddGroup:this.ident+"-json-grid-dd",notifyDrop:function(dd,e,data){var ds=grid.store,sm=grid.getSelectionModel(),rows=sm.getSelections(),dragData=dd.getDragData(e);if(dragData){var cindex=dragData.rowIndex;if(void 0!==cindex){for(var i=0;i<rows.length;i++)ds.remove(ds.getById(rows[i].id));ds.insert(cindex,data.selections),sm.clearSelections()}}grid.getView().refresh(),grid.saveValue()}}),this.add(this.hiddenField),this.saveValue()},loadValue:function(value){return(value=Ext.util.JSON.decode(value))&&Array.isArray(value)?Ext.each(value,(function(record,idx){value[idx].id=idx})):value=[],value},saveValue:function(){var value=[];Ext.each(this.getStore().getRange(),(function(record){var row={};Ext.each(this.fieldNames,(function(fieldname){"id"!==fieldname&&(row[fieldname]=record.data[fieldname])})),value.push(row)}),this),this.hiddenField.setValue(Ext.util.JSON.encode(value))},_getActionsColumnTpl:function(){return new Ext.XTemplate('<tpl for="."><tpl if="actions !== null"><ul class="x-grid-buttons"><tpl for="actions"><li><i class="x-grid-action icon icon-{icon:htmlEncode}" title="{text:htmlEncode}" data-action="{action:htmlEncode}"></i></li></tpl></ul></tpl></tpl>',{compiled:!0})},actionsColumnRenderer:function(value,metaData,record,rowIndex,colIndex,store){return this._getActionsColumnTpl().apply({actions:this.getActions()})},onClick:function(e){var target=e.getTarget();if(target.classList.contains("x-grid-action")&&target.dataset.action){var actionHandler="action"+target.dataset.action.charAt(0).toUpperCase()+target.dataset.action.slice(1);if(this[actionHandler]&&"function"==typeof this[actionHandler]||this[actionHandler=target.dataset.action]&&"function"==typeof this[actionHandler]){var record=this.getSelectionModel().getSelected(),recordIndex=this.store.indexOf(record);this.menu.record=record.data,this[actionHandler](record,recordIndex,e)}}}}),Ext.reg("grid-json",MODx.grid.JsonGrid),Ext.reg("modx-grid-json",MODx.grid.JsonGrid),MODx.Console=function(config){config=config||{},Ext.Updater.defaults.showLoadIndicator=!1,Ext.applyIf(config,{title:_("console"),modal:!Ext.isIE,closeAction:"hide",resizable:!1,collapsible:!1,closable:!0,maximizable:!0,autoScroll:!0,height:400,width:600,refreshRate:2,cls:"modx-window modx-console",items:[{itemId:"header",cls:"modx-console-text",html:_("console_running"),border:!1},{xtype:"panel",itemId:"body",cls:"x-panel-bwrap modx-console-text"}],buttons:[{text:_("console_download_output"),handler:this.download,scope:this},{text:_("ok"),cls:"primary-button",itemId:"okBtn",disabled:!0,scope:this,handler:this.hideConsole}],keys:[{key:Ext.EventObject.S,ctrl:!0,fn:this.download,scope:this},{key:Ext.EventObject.ENTER,fn:this.hideConsole,scope:this}]}),MODx.Console.superclass.constructor.call(this,config),this.config=config,this.addEvents({shutdown:!0,complete:!0}),this.on("show",this.init,this),this.on("hide",(function(){if(this.provider&&this.provider.disconnect)try{this.provider.disconnect()}catch(e){}this.fireEvent("shutdown"),this.destroy()})),this.on("complete",this.onComplete,this)},Ext.extend(MODx.Console,Ext.Window,{mgr:null,running:!1,init:function(){Ext.Msg.hide(),this.fbar.setDisabled(!0),this.keyMap.setDisabled(!0),this.getComponent("body").el.dom.innerHTML="",this.provider=new Ext.direct.PollingProvider({type:"polling",url:MODx.config.connector_url,interval:1e3,baseParams:{action:"System/Console",register:this.config.register||"",topic:this.config.topic||"",clear:!1,show_filename:this.config.show_filename||0,format:this.config.format||"html_log"}}),Ext.Direct.addProvider(this.provider),Ext.Direct.on("message",this.onMessage,this)},onMessage:function(e,p){var out=this.getComponent("body");out&&(out.el.insertHtml("beforeEnd",e.data),e.data="",out.el.scroll("b",out.el.getHeight(),!0)),e.complete&&this.fireEvent("complete"),delete e},onComplete:function(){if(this.provider&&this.provider.disconnect)try{this.provider.disconnect()}catch(e){}this.fbar.setDisabled(!1),this.keyMap.setDisabled(!1)},download:function(){var c=this.getComponent("body").getEl().dom.innerHTML||"&nbsp;";MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"System/DownloadOutput",data:c},listeners:{success:{fn:function(r){location.href=MODx.config.connector_url+"?action=System/DownloadOutput&HTTP_MODAUTH="+MODx.siteId+"&download="+r.message},scope:this}}})},setRegister:function(register,topic){this.config.register=register,this.config.topic=topic},hideConsole:function(){this.hide()}}),Ext.reg("modx-console",MODx.Console),Ext.namespace("MODx.portal"),Ext.ux.Portal=Ext.extend(Ext.Panel,{layout:"column",cls:"x-portal",defaultType:"portalcolumn",initComponent:function(){Ext.ux.Portal.superclass.initComponent.call(this),this.addEvents({validatedrop:!0,beforedragover:!0,dragover:!0,beforedrop:!0,drop:!0})},initEvents:function(){Ext.ux.Portal.superclass.initEvents.call(this),this.dd=new Ext.ux.Portal.DropZone(this,this.dropConfig)},beforeDestroy:function(){this.dd&&this.dd.unreg(),Ext.ux.Portal.superclass.beforeDestroy.call(this)}}),Ext.reg("portal",Ext.ux.Portal),Ext.ux.Portal.DropZone=function(a,b){this.portal=a,Ext.dd.ScrollManager.register(a.body),Ext.ux.Portal.DropZone.superclass.constructor.call(this,a.bwrap.dom,b),a.body.ddScrollConfig=this.ddScrollConfig},Ext.extend(Ext.ux.Portal.DropZone,Ext.dd.DropTarget,{ddScrollConfig:{vthresh:50,hthresh:-1,animate:!0,increment:200},createEvent:function(a,e,b,d,c,f){return{portal:this.portal,panel:b.panel,columnIndex:d,column:c,position:f,data:b,source:a,rawEvent:e,status:this.dropAllowed}},notifyOver:function(a,e,b){var d=e.getXY(),portal=this.portal,px=a.proxy;this.grid||(this.grid=this.getGrid());var f=portal.body.dom.clientWidth;this.lastCW?this.lastCW!=f&&(this.lastCW=f,portal.doLayout(),this.grid=this.getGrid()):this.lastCW=f;for(var g=0,xs=this.grid.columnX,cmatch=!1,i=xs.length;g<i;g++)if(d[0]<xs[g].x+xs[g].w){cmatch=!0;break}cmatch||g--;var p,match=!1,pos=0,c=portal.items.itemAt(g),items=c.items.items,overSelf=!1;for(i=items.length;pos<i;pos++){var h=(p=items[pos]).el.getHeight();if(0===h)overSelf=!0;else if(p.el.getY()+h/2>d[1]){match=!0;break}}pos=(match&&p?pos:c.items.getCount())+(overSelf?-1:0);var j=this.createEvent(a,e,b,g,c,pos);return!1!==portal.fireEvent("validatedrop",j)&&!1!==portal.fireEvent("beforedragover",j)?(px.getProxy().setWidth("auto"),p?px.moveProxy(p.el.dom.parentNode,match?p.el.dom:null):px.moveProxy(c.el.dom,null),this.lastPos={c,col:g,p:!!(overSelf||match&&p)&&pos},this.scrollPos=portal.body.getScroll(),portal.fireEvent("dragover",j),j.status):j.status},notifyOut:function(){delete this.grid},notifyDrop:function(a,e,b){if(delete this.grid,this.lastPos){var c=this.lastPos.c,col=this.lastPos.col,pos=this.lastPos.p,f=this.createEvent(a,e,b,col,c,!1!==pos?pos:c.items.getCount());if(!1!==this.portal.fireEvent("validatedrop",f)&&!1!==this.portal.fireEvent("beforedrop",f)){a.proxy.getProxy().remove(),a.panel.el.dom.parentNode.removeChild(a.panel.el.dom),!1!==pos?(c==a.panel.ownerCt&&c.items.items.indexOf(a.panel)<=pos&&pos++,c.insert(pos,a.panel)):c.add(a.panel),c.doLayout(),this.portal.fireEvent("drop",f);var g=this.scrollPos.top;if(g){var d=this.portal.body.dom;setTimeout((function(){d.scrollTop=g}),10)}}delete this.lastPos}},getGrid:function(){var a=this.portal.bwrap.getBox();return a.columnX=[],this.portal.items.each((function(c){a.columnX.push({x:c.el.getX(),w:c.el.getWidth()})})),a},unreg:function(){Ext.ux.Portal.DropZone.superclass.unreg.call(this)}}),MODx.portal.Column=Ext.extend(Ext.Container,{layout:"anchor",defaultType:"portlet",cls:"x-portal-column",style:"padding:10px;",columnWidth:1,defaults:{collapsible:!0,autoHeight:!0,titleCollapse:!0,draggable:!0,style:"padding: 5px 0;",bodyStyle:"padding: 15px;"}}),Ext.reg("portalcolumn",MODx.portal.Column),MODx.portal.Portlet=Ext.extend(Ext.Panel,{anchor:Ext.isSafari?"98%":"100%",frame:!0,collapsible:!0,draggable:!0,cls:"x-portlet",stateful:!1,layout:"form"}),Ext.reg("portlet",MODx.portal.Portlet),MODx.window.DuplicateResource=function(config){config=config||{},this.ident=config.ident||"dupres"+Ext.id(),Ext.applyIf(config,{title:config.pagetitle?_("duplicate")+" "+config.pagetitle:_("duplication_options"),id:this.ident}),MODx.window.DuplicateResource.superclass.constructor.call(this,config)},Ext.extend(MODx.window.DuplicateResource,MODx.Window,{_loadForm:function(){if(this.checkIfLoaded(this.config.record))return this.fp.getForm().baseParams={action:"Resource/Updateduplicate",prefixDuplicate:!0,id:this.config.resource},!1;var items=[];items.push({xtype:"textfield",id:"modx-"+this.ident+"-name",fieldLabel:_("resource_name_new"),name:"name",anchor:"100%",value:""}),this.config.hasChildren&&items.push({xtype:"xcheckbox",boxLabel:_("duplicate_children")+"  ("+this.config.childCount+")",hideLabel:!0,name:"duplicate_children",id:"modx-"+this.ident+"-duplicate-children",checked:!0}),items.push({xtype:"xcheckbox",boxLabel:_("duplicate_redirect"),hideLabel:!0,name:"redirect",id:"modx-"+this.ident+"-duplicate-redirect",checked:this.config.redirect});var pov=MODx.config.default_duplicate_publish_option||"preserve";items.push({xtype:"fieldset",title:_("publishing_options"),items:[{xtype:"radiogroup",hideLabel:!0,columns:1,value:pov,items:[{boxLabel:_("po_make_all_unpub"),hideLabel:!0,name:"published_mode",inputValue:"unpublish"},{boxLabel:_("po_make_all_pub"),hideLabel:!0,name:"published_mode",inputValue:"publish"},{boxLabel:_("po_preserve"),hideLabel:!0,name:"published_mode",inputValue:"preserve"}]}]}),this.fp=this.createForm({url:this.config.url||MODx.config.connector_url,baseParams:this.config.baseParams||{action:"Resource/Duplicate",id:this.config.resource,prefixDuplicate:!0},labelWidth:125,defaultType:"textfield",autoHeight:!0,items}),this.renderForm()}}),Ext.reg("modx-window-resource-duplicate",MODx.window.DuplicateResource),MODx.window.DuplicateElement=function(config){config=config||{},this.ident=config.ident||"dupeel-"+Ext.id();var flds=[{xtype:"hidden",name:"id",id:"modx-"+this.ident+"-id"},{xtype:"hidden",name:"source",id:"modx-"+this.ident+"-source"},{xtype:"textfield",fieldLabel:_("element_name_new"),name:"template"==config.record.type?"templatename":"name",id:"modx-"+this.ident+"-name",anchor:"100%",enableKeyEvents:!0,listeners:{afterRender:{scope:this,fn:function(f,e){this.setStaticElementsPath(f)}},keyup:{scope:this,fn:function(f,e){this.setStaticElementsPath(f)}}}}];"tv"==config.record.type&&(flds.push({xtype:"textfield",fieldLabel:_("element_caption_new"),name:"caption",id:"modx-"+this.ident+"-caption",anchor:"100%"}),flds.push({xtype:"xcheckbox",hideLabel:!0,boxLabel:_("element_duplicate_values"),labelSeparator:"",name:"duplicateValues",id:"modx-"+this.ident+"-duplicate-values",anchor:"100%",inputValue:1,checked:!1})),!0===config.record.static&&flds.push({xtype:"textfield",fieldLabel:_("static_file"),name:"static_file",id:"modx-"+this.ident+"-static_file",anchor:"100%"}),flds.push({xtype:"xcheckbox",boxLabel:_("duplicate_redirect"),hideLabel:!0,name:"redirect",id:"modx-"+this.ident+"-duplicate-redirect",checked:config.redirect}),Ext.applyIf(config,{title:_("duplicate_"+config.record.type),url:MODx.config.connector_url,action:"element/"+config.record.type+"/duplicate",width:600,fields:flds,labelWidth:150}),MODx.window.DuplicateElement.superclass.constructor.call(this,config)},Ext.extend(MODx.window.DuplicateElement,MODx.Window,{setStaticElementsPath:function(f){if(!0===this.config.record.static){var category=this.config.record.category;if("number"!=typeof category){Ext.getCmp("modx-"+this.config.record.type+"-category").getValue()>0&&(category=Ext.getCmp("modx-"+this.config.record.type+"-category").lastSelectionText);var path=MODx.getStaticElementsPath(f.getValue(),category,this.config.record.type+"s");Ext.getCmp("modx-"+this.ident+"-static_file").setValue(path)}else"number"==typeof category&&category>0&&MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Element/Category/GetList",id:category},listeners:{success:{fn:function(response){for(var i=0;i<response.results.length;i++)response.results[i].id===category&&(category=response.results[i].name);var path=MODx.getStaticElementsPath(f.getValue(),category,this.config.record.type+"s");Ext.getCmp("modx-"+this.ident+"-static_file").setValue(path)},scope:this}}})}}}),Ext.reg("modx-window-element-duplicate",MODx.window.DuplicateElement),MODx.window.CreateCategory=function(config){config=config||{},this.ident=config.ident||"ccat"+Ext.id(),Ext.applyIf(config,{title:_("category_create"),id:this.ident,url:MODx.config.connector_url,action:"Element/Category/Create",fields:[{xtype:"modx-description",html:_("category_create_desc")},{fieldLabel:_("name"),name:"category",id:"modx-"+this.ident+"-category",xtype:"textfield",anchor:"100%"},{fieldLabel:_("parent"),name:"parent",hiddenName:"parent",id:"modx-"+this.ident+"-parent",xtype:"modx-combo-category",anchor:"100%"},{fieldLabel:_("rank"),name:"rank",id:"modx-"+this.ident+"-rank",xtype:"numberfield",anchor:"100%"}]}),MODx.window.CreateCategory.superclass.constructor.call(this,config)},Ext.extend(MODx.window.CreateCategory,MODx.Window),Ext.reg("modx-window-category-create",MODx.window.CreateCategory),MODx.window.RenameCategory=function(config){config=config||{},this.ident=config.ident||"rencat-"+Ext.id(),Ext.applyIf(config,{title:_("category_rename"),url:MODx.config.connector_url,action:"Element/Category/Update",fields:[{xtype:"hidden",name:"id",id:"modx-"+this.ident+"-id",value:config.record.id},{xtype:"textfield",fieldLabel:_("name"),name:"category",id:"modx-"+this.ident+"-category",width:150,value:config.record.category,anchor:"100%"},{fieldLabel:_("rank"),name:"rank",id:"modx-"+this.ident+"-rank",xtype:"numberfield",anchor:"100%"}]}),MODx.window.RenameCategory.superclass.constructor.call(this,config)},Ext.extend(MODx.window.RenameCategory,MODx.Window),Ext.reg("modx-window-category-rename",MODx.window.RenameCategory),MODx.window.CreateNamespace=function(config){(config=config||{}).record;this.ident=config.ident||"cns"+Ext.id(),Ext.applyIf(config,{title:_("create"),id:this.ident,width:600,url:MODx.config.connector_url,action:"Workspace/PackageNamespace/Create",fields:[{xtype:"textfield",fieldLabel:_("name"),description:MODx.expandHelp?"":_("namespace_name_desc"),name:"name",id:"modx-"+this.ident+"-name",anchor:"100%",maxLength:100,readOnly:config.isUpdate||!1},{xtype:MODx.expandHelp?"label":"hidden",forId:"modx-"+this.ident+"-name",html:_("namespace_name_desc"),cls:"desc-under"},{xtype:"textfield",fieldLabel:_("namespace_path"),description:MODx.expandHelp?"":_("namespace_path_desc"),name:"path",id:"modx-"+this.ident+"-path",anchor:"100%"},{xtype:MODx.expandHelp?"label":"hidden",forId:"modx-"+this.ident+"-path",html:_("namespace_path_desc"),cls:"desc-under"},{xtype:"textfield",fieldLabel:_("namespace_assets_path"),description:MODx.expandHelp?"":_("namespace_assets_path_desc"),name:"assets_path",id:"modx-"+this.ident+"-assets-path",anchor:"100%"},{xtype:MODx.expandHelp?"label":"hidden",forId:"modx-"+this.ident+"-assets-path",html:_("namespace_assets_path_desc"),cls:"desc-under"}]}),MODx.window.CreateNamespace.superclass.constructor.call(this,config)},Ext.extend(MODx.window.CreateNamespace,MODx.Window),Ext.reg("modx-window-namespace-create",MODx.window.CreateNamespace),MODx.window.UpdateNamespace=function(config){config=config||{},Ext.applyIf(config,{title:_("edit"),action:"Workspace/PackageNamespace/Update",isUpdate:!0}),MODx.window.UpdateNamespace.superclass.constructor.call(this,config)},Ext.extend(MODx.window.UpdateNamespace,MODx.window.CreateNamespace,{}),Ext.reg("modx-window-namespace-update",MODx.window.UpdateNamespace),MODx.window.QuickCreateChunk=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_create_chunk"),width:600,layout:"anchor",url:MODx.config.connector_url,action:"Element/Chunk/Create",fields:[{xtype:"hidden",name:"id"},{xtype:"textfield",name:"name",fieldLabel:_("name"),anchor:"100%"},{xtype:"modx-combo-category",name:"category",fieldLabel:_("category"),anchor:"100%"},{xtype:"textarea",name:"description",fieldLabel:_("description"),anchor:"100%"},{xtype:"textarea",name:"snippet",fieldLabel:_("code"),anchor:"100%",grow:!0,growMax:216},{xtype:"xcheckbox",name:"clearCache",hideLabel:!0,boxLabel:_("clear_cache_on_save"),description:_("clear_cache_on_save_msg"),inputValue:1,checked:!0}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreateChunk.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreateChunk,MODx.Window),Ext.reg("modx-window-quick-create-chunk",MODx.window.QuickCreateChunk),MODx.window.QuickUpdateChunk=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_update_chunk"),action:"Element/Chunk/Update",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdateChunk.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdateChunk,MODx.window.QuickCreateChunk),Ext.reg("modx-window-quick-update-chunk",MODx.window.QuickUpdateChunk),MODx.window.QuickCreateTemplate=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_create_template"),width:600,layout:"anchor",url:MODx.config.connector_url,action:"Element/Template/Create",fields:[{xtype:"hidden",name:"id"},{xtype:"textfield",name:"templatename",fieldLabel:_("name"),anchor:"100%"},{xtype:"modx-combo-category",name:"category",fieldLabel:_("category"),anchor:"100%"},{xtype:"textarea",name:"description",fieldLabel:_("description"),anchor:"100%"},{xtype:"textarea",name:"content",fieldLabel:_("code"),anchor:"100%",grow:!0,growMax:216},{xtype:"xcheckbox",name:"clearCache",hideLabel:!0,boxLabel:_("clear_cache_on_save"),description:_("clear_cache_on_save_msg"),inputValue:1,checked:!0}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreateTemplate.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreateTemplate,MODx.Window),Ext.reg("modx-window-quick-create-template",MODx.window.QuickCreateTemplate),MODx.window.QuickUpdateTemplate=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_update_template"),action:"Element/Template/Update",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdateTemplate.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdateTemplate,MODx.window.QuickCreateTemplate),Ext.reg("modx-window-quick-update-template",MODx.window.QuickUpdateTemplate),MODx.window.QuickCreateSnippet=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_create_snippet"),width:600,layout:"anchor",url:MODx.config.connector_url,action:"Element/Snippet/Create",fields:[{xtype:"hidden",name:"id"},{xtype:"textfield",name:"name",fieldLabel:_("name"),anchor:"100%"},{xtype:"modx-combo-category",name:"category",fieldLabel:_("category"),anchor:"100%"},{xtype:"textarea",name:"description",fieldLabel:_("description"),anchor:"100%"},{xtype:"textarea",name:"snippet",fieldLabel:_("code"),anchor:"100%",grow:!0,growMax:216},{xtype:"xcheckbox",name:"clearCache",hideLabel:!0,boxLabel:_("clear_cache_on_save"),description:_("clear_cache_on_save_msg"),inputValue:1,checked:!0}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreateSnippet.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreateSnippet,MODx.Window),Ext.reg("modx-window-quick-create-snippet",MODx.window.QuickCreateSnippet),MODx.window.QuickUpdateSnippet=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_update_snippet"),action:"Element/Snippet/Update",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdateSnippet.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdateSnippet,MODx.window.QuickCreateSnippet),Ext.reg("modx-window-quick-update-snippet",MODx.window.QuickUpdateSnippet),MODx.window.QuickCreatePlugin=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_create_plugin"),width:600,layout:"anchor",url:MODx.config.connector_url,action:"Element/Plugin/Create",fields:[{xtype:"hidden",name:"id"},{xtype:"textfield",name:"name",fieldLabel:_("name"),anchor:"100%"},{xtype:"modx-combo-category",name:"category",fieldLabel:_("category"),anchor:"100%"},{xtype:"textarea",name:"description",fieldLabel:_("description"),anchor:"100%",rows:2},{xtype:"textarea",name:"plugincode",fieldLabel:_("code"),anchor:"100%",grow:!0,growMax:216},{xtype:"xcheckbox",name:"disabled",boxLabel:_("disabled"),hideLabel:!0,inputValue:1,checked:!1},{xtype:"xcheckbox",name:"clearCache",boxLabel:_("clear_cache_on_save"),hideLabel:!0,description:_("clear_cache_on_save_msg"),inputValue:1,checked:!0}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreatePlugin.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreatePlugin,MODx.Window),Ext.reg("modx-window-quick-create-plugin",MODx.window.QuickCreatePlugin),MODx.window.QuickUpdatePlugin=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_update_plugin"),action:"Element/Plugin/Update",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdatePlugin.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdatePlugin,MODx.window.QuickCreatePlugin),Ext.reg("modx-window-quick-update-plugin",MODx.window.QuickUpdatePlugin),MODx.window.QuickCreateTV=function(config){config=config||{},this.ident=config.ident||"qtv"+Ext.id(),Ext.applyIf(config,{title:_("quick_create_tv"),width:700,url:MODx.config.connector_url,action:"Element/TemplateVar/Create",fields:[{xtype:"hidden",name:"id"},{layout:"column",border:!1,items:[{columnWidth:.6,layout:"form",items:[{xtype:"textfield",name:"name",fieldLabel:_("name"),anchor:"100%"},{xtype:"textfield",name:"caption",id:"modx-"+this.ident+"-caption",fieldLabel:_("caption"),anchor:"100%"},{xtype:"label",forId:"modx-"+this.ident+"-caption",html:_("caption_desc"),cls:"desc-under"},{xtype:"modx-combo-category",name:"category",fieldLabel:_("category"),anchor:"100%"},{xtype:"textarea",name:"description",fieldLabel:_("description"),anchor:"100%"}]},{columnWidth:.4,border:!1,layout:"form",items:[{xtype:"modx-combo-tv-input-type",fieldLabel:_("tv_type"),name:"type",anchor:"100%"},{xtype:"textfield",fieldLabel:_("tv_elements"),name:"els",id:"modx-"+this.ident+"-elements",anchor:"100%"},{xtype:"label",forId:"modx-"+this.ident+"-elements",html:_("tv_elements_short_desc"),cls:"desc-under"},{xtype:"textarea",fieldLabel:_("tv_default"),name:"default_text",id:"modx-"+this.ident+"-default-text",anchor:"100%",grow:!0,growMax:Ext.getBody().getViewSize().height<=768?300:380},{xtype:"label",forId:"modx-"+this.ident+"-default-text",html:_("tv_default_desc"),cls:"desc-under"}]}]},{xtype:"xcheckbox",name:"clearCache",hideLabel:!0,boxLabel:_("clear_cache_on_save"),description:_("clear_cache_on_save_msg"),inputValue:1,checked:!0}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreateTV.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreateTV,MODx.Window),Ext.reg("modx-window-quick-create-tv",MODx.window.QuickCreateTV),MODx.window.QuickUpdateTV=function(config){config=config||{},Ext.applyIf(config,{title:_("quick_update_tv"),action:"Element/TemplateVar/Update",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdateTV.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdateTV,MODx.window.QuickCreateTV),Ext.reg("modx-window-quick-update-tv",MODx.window.QuickUpdateTV),MODx.window.DuplicateContext=function(config){config=config||{},this.ident=config.ident||"dupctx"+Ext.id(),Ext.Ajax.timeout=0,Ext.applyIf(config,{title:_("duplicate"),id:this.ident,url:MODx.config.connector_url,action:"Context/Duplicate",fields:[{xtype:"statictextfield",id:"modx-"+this.ident+"-key",fieldLabel:_("old_key"),name:"key",anchor:"100%",submitValue:!0},{xtype:"textfield",id:"modx-"+this.ident+"-newkey",fieldLabel:_("new_key"),name:"newkey",anchor:"100%",value:""},{xtype:"checkbox",id:"modx-"+this.ident+"-preserveresources",hideLabel:!0,boxLabel:_("preserve_resources"),name:"preserve_resources",anchor:"100%",checked:!0,listeners:{check:{fn:function(cb,checked){checked?(this.fp.getForm().findField("modx-"+this.ident+"-preservealias").setValue(!0).enable(),this.fp.getForm().findField("modx-"+this.ident+"-preservemenuindex").setValue(!0).enable()):(this.fp.getForm().findField("modx-"+this.ident+"-preservealias").setValue(!1).disable(),this.fp.getForm().findField("modx-"+this.ident+"-preservemenuindex").setValue(!1).disable())},scope:this}}},{xtype:"checkbox",id:"modx-"+this.ident+"-preservealias",hideLabel:!0,boxLabel:_("preserve_alias"),name:"preserve_alias",anchor:"100%",checked:!0},{xtype:"checkbox",id:"modx-"+this.ident+"-preservemenuindex",hideLabel:!0,boxLabel:_("preserve_menuindex"),name:"preserve_menuindex",anchor:"100%",checked:!0}]}),MODx.window.DuplicateContext.superclass.constructor.call(this,config)},Ext.extend(MODx.window.DuplicateContext,MODx.Window),Ext.reg("modx-window-context-duplicate",MODx.window.DuplicateContext),MODx.window.Login=function(config){config=config||{},this.ident=config.ident||"dupctx"+Ext.id(),Ext.Ajax.timeout=0,Ext.applyIf(config,{title:_("login"),id:this.ident,url:MODx.config.connectors_url,action:"Security/Login",fields:[{html:"<p>"+_("session_logging_out")+"</p>",xtype:"modx-description"},{xtype:"textfield",id:"modx-"+this.ident+"-username",fieldLabel:_("username"),name:"username",anchor:"100%"},{xtype:"textfield",inputType:"password",id:"modx-"+this.ident+"-password",fieldLabel:_("password"),name:"password",anchor:"100%"},{xtype:"hidden",name:"rememberme",value:1}],buttons:[{text:_("logout"),scope:this,handler:function(){location.href="?logout=1"}},{text:_("login"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.Login.superclass.constructor.call(this,config),this.on("success",this.onLogin,this)},Ext.extend(MODx.window.Login,MODx.Window,{onLogin:function(o){var r=o.a.result;r.object&&r.object.token&&(Ext.Ajax.defaultHeaders={modAuth:r.object.token},Ext.Ajax.extraParams={HTTP_MODAUTH:r.object.token},MODx.siteId=r.object.token,MODx.msg.status({message:_("session_extended")}))}}),Ext.reg("modx-window-login",MODx.window.Login),
/*! FileAPI 2.0.25 - BSD | git://github.com/mailru/FileAPI.git
 * FileAPI — a set of  javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.
 */
function(window){"use strict";var CanvasPrototype=window.HTMLCanvasElement&&window.HTMLCanvasElement.prototype,hasBlobConstructor=window.Blob&&function(){try{return Boolean(new Blob)}catch(e){return!1}}(),hasArrayBufferViewSupport=hasBlobConstructor&&window.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(e){return!1}}(),BlobBuilder=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,dataURLtoBlob=(hasBlobConstructor||BlobBuilder)&&window.atob&&window.ArrayBuffer&&window.Uint8Array&&function(dataURI){var byteString,arrayBuffer,intArray,i,mimeString,bb;for(byteString=dataURI.split(",")[0].indexOf("base64")>=0?atob(dataURI.split(",")[1]):decodeURIComponent(dataURI.split(",")[1]),arrayBuffer=new ArrayBuffer(byteString.length),intArray=new Uint8Array(arrayBuffer),i=0;i<byteString.length;i+=1)intArray[i]=byteString.charCodeAt(i);return mimeString=dataURI.split(",")[0].split(":")[1].split(";")[0],hasBlobConstructor?new Blob([hasArrayBufferViewSupport?intArray:arrayBuffer],{type:mimeString}):((bb=new BlobBuilder).append(arrayBuffer),bb.getBlob(mimeString))};window.HTMLCanvasElement&&!CanvasPrototype.toBlob&&(CanvasPrototype.mozGetAsFile?CanvasPrototype.toBlob=function(callback,type,quality){quality&&CanvasPrototype.toDataURL&&dataURLtoBlob?callback(dataURLtoBlob(this.toDataURL(type,quality))):callback(this.mozGetAsFile("blob",type))}:CanvasPrototype.toDataURL&&dataURLtoBlob&&(CanvasPrototype.toBlob=function(callback,type,quality){callback(dataURLtoBlob(this.toDataURL(type,quality)))})),window.dataURLtoBlob=dataURLtoBlob}(window),function(window,undef){"use strict";var _supportConsoleLog,_supportConsoleLogApply,gid=1,noop=function(){},document=window.document,doctype=document.doctype||{},userAgent=window.navigator.userAgent,safari=/safari\//i.test(userAgent)&&!/chrome\//i.test(userAgent),iemobile=/iemobile\//i.test(userAgent),insecureChrome=!safari&&/chrome\//i.test(userAgent)&&"http:"===window.location.protocol,apiURL=window.createObjectURL&&window||window.URL&&URL.revokeObjectURL&&URL||window.webkitURL&&webkitURL,Blob=window.Blob,File=window.File,FileReader=window.FileReader,FormData=window.FormData,XMLHttpRequest=window.XMLHttpRequest,jQuery=window.jQuery,html5=!(!(File&&FileReader&&(window.Uint8Array||FormData||XMLHttpRequest.prototype.sendAsBinary))||safari&&/windows/i.test(userAgent)&&!iemobile),cors=html5&&"withCredentials"in new XMLHttpRequest,chunked=html5&&!!Blob&&!!(Blob.prototype.webkitSlice||Blob.prototype.mozSlice||Blob.prototype.slice),normalize=(""+"".normalize).indexOf("[native code]")>0,dataURLtoBlob=window.dataURLtoBlob,_rimg=/img/i,_rcanvas=/canvas/i,_rimgcanvas=/img|canvas/i,_rinput=/input/i,_rdata=/^data:[^,]+,/,_toString={}.toString,Math=window.Math,_SIZE_CONST=function(pow){return(pow=new window.Number(Math.pow(1024,pow))).from=function(sz){return Math.round(sz*this)},pow},_elEvents={},_infoReader=[],_readerEvents="abort progress error load loadend",_xhrPropsExport="status statusText readyState response responseXML responseText responseBody".split(" "),_isArray=function(ar){return ar&&"length"in ar},_each=function(obj,fn,ctx){if(obj)if(_isArray(obj))for(var i=0,n=obj.length;i<n;i++)i in obj&&fn.call(ctx,obj[i],i,obj);else for(var key in obj)obj.hasOwnProperty(key)&&fn.call(ctx,obj[key],key,obj)},_extend=function(dst){for(var args=arguments,i=1,_ext=function(val,key){dst[key]=val};i<args.length;i++)_each(args[i],_ext);return dst},_on=function(el,type,fn){if(el){var uid=api.uid(el);_elEvents[uid]||(_elEvents[uid]={});var isFileReader=FileReader&&el&&el instanceof FileReader;_each(type.split(/\s+/),(function(type){jQuery&&!isFileReader?jQuery.event.add(el,type,fn):(_elEvents[uid][type]||(_elEvents[uid][type]=[]),_elEvents[uid][type].push(fn),el.addEventListener?el.addEventListener(type,fn,!1):el.attachEvent?el.attachEvent("on"+type,fn):el["on"+type]=fn)}))}},_off=function(el,type,fn){if(el){var uid=api.uid(el),events=_elEvents[uid]||{},isFileReader=FileReader&&el&&el instanceof FileReader;_each(type.split(/\s+/),(function(type){if(jQuery&&!isFileReader)jQuery.event.remove(el,type,fn);else{for(var fns=events[type]||[],i=fns.length;i--;)if(fns[i]===fn){fns.splice(i,1);break}el.addEventListener?el.removeEventListener(type,fn,!1):el.detachEvent?el.detachEvent("on"+type,fn):el["on"+type]=null}}))}},_one=function(el,type,fn){_on(el,type,(function _(evt){_off(el,type,_),fn(evt)}))},_fixEvent=function(evt){return evt.target||(evt.target=window.event&&window.event.srcElement||document),3===evt.target.nodeType&&(evt.target=evt.target.parentNode),evt},_supportInputAttr=function(attr){var input=document.createElement("input");return input.setAttribute("type","file"),attr in input},api={version:"2.0.25",cors:!1,html5:!0,media:!1,formData:!0,multiPassResize:!0,insecureChrome,debug:!1,pingUrl:!1,multiFlash:!1,flashAbortTimeout:0,withCredentials:!0,staticPath:"./dist/",flashUrl:0,flashImageUrl:0,postNameConcat:function(name,idx){return name+(null!=idx?"["+idx+"]":"")},ext2mime:{jpg:"image/jpeg",tif:"image/tiff",txt:"text/plain"},accept:{"image/*":"art bm bmp dwg dxf cbr cbz fif fpx gif ico iefs jfif jpe jpeg jpg jps jut mcf nap nif pbm pcx pgm pict pm png pnm qif qtif ras rast rf rp svf tga tif tiff xbm xbm xpm xwd","audio/*":"m4a flac aac rm mpa wav wma ogg mp3 mp2 m3u mod amf dmf dsm far gdm imf it m15 med okt s3m stm sfx ult uni xm sid ac3 dts cue aif aiff wpl ape mac mpc mpp shn wv nsf spc gym adplug adx dsp adp ymf ast afc hps xs","video/*":"m4v 3gp nsv ts ty strm rm rmvb m3u ifo mov qt divx xvid bivx vob nrg img iso pva wmv asf asx ogm m2v avi bin dat dvr-ms mpg mpeg mp4 mkv avc vp3 svq3 nuv viv dv fli flv wpl"},uploadRetry:0,networkDownRetryTimeout:5e3,chunkSize:0,chunkUploadRetry:0,chunkNetworkDownRetryTimeout:2e3,KB:_SIZE_CONST(1),MB:_SIZE_CONST(2),GB:_SIZE_CONST(3),TB:_SIZE_CONST(4),EMPTY_PNG:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=",expando:"fileapi"+(new Date).getTime(),uid:function(obj){return obj?obj[api.expando]=obj[api.expando]||api.uid():(++gid,api.expando+gid)},log:function(){api.debug&&_supportConsoleLog&&(_supportConsoleLogApply?console.log.apply(console,arguments):console.log([].join.call(arguments," ")))},newImage:function(src,fn){var img=document.createElement("img");return fn&&api.event.one(img,"error load",(function(evt){fn("error"==evt.type,img),img=null})),img.src=src,img},getXHR:function(){var xhr;if(XMLHttpRequest)xhr=new XMLHttpRequest;else if(window.ActiveXObject)try{xhr=new ActiveXObject("MSXML2.XMLHttp.3.0")}catch(e){xhr=new ActiveXObject("Microsoft.XMLHTTP")}return xhr},isArray:_isArray,support:{dnd:cors&&"ondrop"in document.createElement("div"),cors,html5,chunked,dataURI:!0,accept:_supportInputAttr("accept"),multiple:_supportInputAttr("multiple")},event:{on:_on,off:_off,one:_one,fix:_fixEvent},throttle:function(fn,delay){var id,args;return function(){args=arguments,id||(fn.apply(window,args),id=setTimeout((function(){id=0,fn.apply(window,args)}),delay))}},F:function(){},parseJSON:function(str){return window.JSON&&JSON.parse?JSON.parse(str):new Function("return ("+str.replace(/([\r\n])/g,"\\$1")+");")()},trim:function(str){return(str=String(str)).trim?str.trim():str.replace(/^\s+|\s+$/g,"")},defer:function(){var result,error,list=[],defer={resolve:function(err,res){for(defer.resolve=noop,error=err||!1,result=res;res=list.shift();)res(error,result)},then:function(fn){undefined!==error?fn(error,result):list.push(fn)}};return defer},queue:function(fn){var _idx=0,_length=0,_fail=!1,_end=!1,queue={inc:function(){_length++},next:function(){_idx++,setTimeout(queue.check,0)},check:function(){_idx>=_length&&!_fail&&queue.end()},isFail:function(){return _fail},fail:function(){!_fail&&fn(_fail=!0)},end:function(){_end||(_end=!0,fn())}};return queue},each:_each,afor:function(array,callback){var i=0,n=array.length;_isArray(array)&&n--?function _next(){callback(n!=i&&_next,array[i],i++)}():callback(!1)},extend:_extend,isFile:function(file){return"[object File]"===_toString.call(file)},isBlob:function(blob){return this.isFile(blob)||"[object Blob]"===_toString.call(blob)},isCanvas:function(el){return el&&_rcanvas.test(el.nodeName)},getFilesFilter:function(filter){return(filter="string"==typeof filter?filter:filter.getAttribute&&filter.getAttribute("accept")||"")?new RegExp("("+filter.replace(/\./g,"\\.").replace(/,/g,"|")+")$","i"):/./},readAsDataURL:function(file,fn){api.isCanvas(file)?_emit(file,fn,"load",api.toDataURL(file)):_readAs(file,fn,"DataURL")},readAsBinaryString:function(file,fn){_hasSupportReadAs("BinaryString")?_readAs(file,fn,"BinaryString"):_readAs(file,(function(evt){if("load"==evt.type)try{evt.result=api.toBinaryString(evt.result)}catch(e){evt.type="error",evt.message=e.toString()}fn(evt)}),"DataURL")},readAsArrayBuffer:function(file,fn){_readAs(file,fn,"ArrayBuffer")},readAsText:function(file,encoding,fn){fn||(fn=encoding,encoding="utf-8"),_readAs(file,fn,"Text",encoding)},toDataURL:function(el,type){return"string"==typeof el?el:el.toDataURL?el.toDataURL(type||"image/png"):void 0},toBinaryString:function(val){return window.atob(api.toDataURL(val).replace(_rdata,""))},readAsImage:function(file,fn,progress){if(api.isBlob(file))if(apiURL){var data=apiURL.createObjectURL(file);undefined===data?_emit(file,fn,"error"):api.readAsImage(data,fn,progress)}else api.readAsDataURL(file,(function(evt){"load"==evt.type?api.readAsImage(evt.result,fn,progress):(progress||"error"==evt.type)&&_emit(file,fn,evt,null,{loaded:evt.loaded,total:evt.total})}));else if(api.isCanvas(file))_emit(file,fn,"load",file);else if(_rimg.test(file.nodeName))if(file.complete)_emit(file,fn,"load",file);else{_one(file,"error abort load",(function _fn(evt){"load"==evt.type&&apiURL&&apiURL.revokeObjectURL(file.src),_off(file,"error abort load",_fn),_emit(file,fn,evt,file)}))}else if(file.iframe)_emit(file,fn,{type:"error"});else{var img=api.newImage(file.dataURL||file);api.readAsImage(img,fn,progress)}},checkFileObj:function(name){var file={},accept=api.accept;return"object"==typeof name?file=name:file.name=(name+"").split(/\\|\//g).pop(),null==file.type&&(file.type=file.name.split(".").pop()),_each(accept,(function(ext,type){((ext=new RegExp(ext.replace(/\s/g,"|"),"i")).test(file.type)||api.ext2mime[file.type])&&(file.type=api.ext2mime[file.type]||type.split("/")[0]+"/"+file.type)})),file},getDropFiles:function(evt,callback){var items,files=[],all=[],dataTransfer=_getDataTransfer(evt),transFiles=dataTransfer.files,transItems=dataTransfer.items,entrySupport=_isArray(transItems)&&transItems[0]&&_getAsEntry(transItems[0]),queue=api.queue((function(){callback(files,all)}));if(entrySupport)if(normalize&&transFiles){var file,entry,i=transFiles.length;for(items=new Array(i);i--;){file=transFiles[i];try{entry=_getAsEntry(transItems[i])}catch(err){api.log("[err] getDropFiles: ",err),entry=null}_isEntry(entry)&&(entry.isDirectory||entry.isFile&&file.name==file.name.normalize("NFC"))?items[i]=entry:items[i]=file}}else items=transItems;else items=transFiles;_each(items||[],(function(item){queue.inc();try{entrySupport&&_isEntry(item)?_readEntryAsFiles(item,(function(err,entryFiles,allEntries){err?api.log("[err] getDropFiles:",err):files.push.apply(files,entryFiles),all.push.apply(all,allEntries),queue.next()})):function(file,callback){if(!file.type&&(safari||file.size%4096==0&&file.size<=102400))if(FileReader)try{var reader=new FileReader;_one(reader,_readerEvents,(function(evt){var isFile="error"!=evt.type;isFile?(null!=reader.readyState&&reader.readyState!==reader.LOADING||reader.abort(),callback(isFile)):callback(!1,reader.error)})),reader.readAsDataURL(file)}catch(err){callback(!1,err)}else callback(null,new Error("FileReader is not supported"));else callback(!0)}(item,(function(yes,err){yes?files.push(item):item.error=err,all.push(item),queue.next()}))}catch(err){queue.next(),api.log("[err] getDropFiles: ",err)}})),queue.check()},getFiles:function(input,filter,callback){var files=[];return callback?(api.filterFiles(api.getFiles(input),filter,callback),null):(input.jquery&&(input.each((function(){files=files.concat(api.getFiles(this))})),input=files,files=[]),"string"==typeof filter&&(filter=api.getFilesFilter(filter)),input.originalEvent?input=_fixEvent(input.originalEvent):input.srcElement&&(input=_fixEvent(input)),input.dataTransfer?input=input.dataTransfer:input.target&&(input=input.target),input.files?(files=input.files,html5||(files[0].blob=input,files[0].iframe=!0)):!html5&&isInputFile(input)?api.trim(input.value)&&((files=[api.checkFileObj(input.value)])[0].blob=input,files[0].iframe=!0):_isArray(input)&&(files=input),api.filter(files,(function(file){return!filter||filter.test(file.name)})))},getTotalSize:function(files){for(var size=0,i=files&&files.length;i--;)size+=files[i].size;return size},getInfo:function(file,fn){var info={},readers=_infoReader.concat();api.isBlob(file)?function _next(){var reader=readers.shift();reader?reader.test(file.type)?reader(file,(function(err,res){err?fn(err):(_extend(info,res),_next())})):_next():fn(!1,info)}():fn("not_support_info",info)},addInfoReader:function(mime,fn){fn.test=function(type){return mime.test(type)},_infoReader.push(fn)},filter:function(input,fn){for(var val,result=[],i=0,n=input.length;i<n;i++)i in input&&(val=input[i],fn.call(val,val,i,input)&&result.push(val));return result},filterFiles:function(files,eachFn,resultFn){if(files.length){var file,queue=files.concat(),result=[],deleted=[];!function _next(){queue.length?(file=queue.shift(),api.getInfo(file,(function(err,info){(eachFn(file,!err&&info)?result:deleted).push(file),_next()}))):resultFn(result,deleted)}()}else resultFn([],files)},upload:function(options){(options=_extend({jsonp:"callback",prepare:api.F,beforeupload:api.F,upload:api.F,fileupload:api.F,fileprogress:api.F,filecomplete:api.F,progress:api.F,complete:api.F,pause:api.F,imageOriginal:!0,chunkSize:api.chunkSize,chunkUploadRetry:api.chunkUploadRetry,uploadRetry:api.uploadRetry},options)).imageAutoOrientation&&!options.imageTransform&&(options.imageTransform={rotate:"auto"});var _nextFile,proxyXHR=new api.XHR(options),dataArray=this._getFilesDataArray(options.files),_this=this,_total=0,_loaded=0,_complete=!1;return _each(dataArray,(function(data){_total+=data.size})),proxyXHR.files=[],_each(dataArray,(function(data){proxyXHR.files.push(data.file)})),proxyXHR.total=_total,proxyXHR.loaded=0,proxyXHR.filesLeft=dataArray.length,options.beforeupload(proxyXHR,options),_nextFile=function(){var copy,data=dataArray.shift(),_file=data&&data.file,_fileLoaded=!1,_fileOptions=(copy={},_each(options,(function(val,key){val&&"object"==typeof val&&void 0===val.nodeType&&(val=_extend({},val)),copy[key]=val})),copy);if(proxyXHR.filesLeft=dataArray.length,_file&&_file.name===api.expando&&(_file=null,api.log("[warn] FileAPI.upload() — called without files")),("abort"!=proxyXHR.statusText||proxyXHR.current)&&data){if(_complete=!1,proxyXHR.currentFile=_file,_file&&!1===options.prepare(_file,_fileOptions))return void _nextFile.call(_this);_fileOptions.file=_file,_this._getFormData(_fileOptions,data,(function(form){_loaded||options.upload(proxyXHR,options);var xhr=new api.XHR(_extend({},_fileOptions,{upload:_file?function(){options.fileupload(_file,xhr,_fileOptions)}:noop,progress:_file?function(evt){_fileLoaded||(_fileLoaded=evt.loaded===evt.total,options.fileprogress({type:"progress",total:data.total=evt.total,loaded:data.loaded=evt.loaded},_file,xhr,_fileOptions),options.progress({type:"progress",total:_total,loaded:proxyXHR.loaded=_loaded+data.size*(evt.loaded/evt.total)||0},_file,xhr,_fileOptions))}:noop,complete:function(err){_each(_xhrPropsExport,(function(name){proxyXHR[name]=xhr[name]})),_file&&(data.total=data.total||data.size,data.loaded=data.total,err||(this.progress(data),_fileLoaded=!0,_loaded+=data.size,proxyXHR.loaded=_loaded),options.filecomplete(err,xhr,_file,_fileOptions)),setTimeout((function(){_nextFile.call(_this)}),0)}}));proxyXHR.abort=function(current){current||(dataArray.length=0),this.current=current,xhr.abort()},xhr.send(form)}))}else{var successful=200==proxyXHR.status||201==proxyXHR.status||204==proxyXHR.status;options.complete(!successful&&(proxyXHR.statusText||"error"),proxyXHR,options),_complete=!0}},setTimeout(_nextFile,0),proxyXHR.append=function(files,first){files=api._getFilesDataArray([].concat(files)),_each(files,(function(data){_total+=data.size,proxyXHR.files.push(data.file),first?dataArray.unshift(data):dataArray.push(data)})),proxyXHR.statusText="",_complete&&_nextFile.call(_this)},proxyXHR.remove=function(file){for(var _file,i=dataArray.length;i--;)dataArray[i].file==file&&(_file=dataArray.splice(i,1),_total-=_file.size);return _file},proxyXHR},_getFilesDataArray:function(data){var files=[],oFiles={};if(isInputFile(data)){var tmp=api.getFiles(data);oFiles[data.name||"file"]=null!==data.getAttribute("multiple")?tmp:tmp[0]}else _isArray(data)&&isInputFile(data[0])?_each(data,(function(input){oFiles[input.name||"file"]=api.getFiles(input)})):oFiles=data;return _each(oFiles,(function add(file,name){_isArray(file)?_each(file,(function(file){add(file,name)})):file&&(file.name||file.image)&&files.push({name,file,size:file.size,total:file.size,loaded:0})})),files.length||files.push({file:{name:api.expando}}),files},_getFormData:function(options,data,fn){var file=data.file,name=data.name,filename=file.name,filetype=file.type,trans=api.support.transform&&options.imageTransform,Form=new api.Form,queue=api.queue((function(){fn(Form)})),isOrignTrans=trans&&function(trans){var key;for(key in trans)if(trans.hasOwnProperty(key)&&!(trans[key]instanceof Object||"overlay"===key||"filter"===key))return!0;return!1}(trans),postNameConcat=api.postNameConcat;_each(options.data,(function add(val,name){"object"==typeof val?_each(val,(function(v,i){add(v,postNameConcat(name,i))})):Form.append(name,val)})),function _addFile(file){file.image?(queue.inc(),file.toData((function(err,image){file.file&&(image.type=file.file.type,image.quality=file.matrix.quality,filename=file.file&&file.file.name),filename=filename||(new Date).getTime()+".png",_addFile(image),queue.next()}))):api.Image&&trans&&(/^image/.test(file.type)||_rimgcanvas.test(file.nodeName))?(queue.inc(),isOrignTrans&&(trans=[trans]),api.Image.transform(file,trans,options.imageAutoOrientation,(function(err,images){if(isOrignTrans&&!err)dataURLtoBlob||api.flashEngine||(Form.multipart=!0),Form.append(name,images[0],filename,trans[0].type||filetype);else{var addOrigin=0;err||_each(images,(function(image,idx){dataURLtoBlob||api.flashEngine||(Form.multipart=!0),trans[idx].postName||(addOrigin=1),Form.append(trans[idx].postName||postNameConcat(name,idx),image,filename,trans[idx].type||filetype)})),(err||options.imageOriginal)&&Form.append(postNameConcat(name,addOrigin?"original":null),file,filename,filetype)}queue.next()}))):filename!==api.expando&&Form.append(name,file,filename)}(file),queue.check()},reset:function(inp,notRemove){var parent,clone;return jQuery?(clone=jQuery(inp).clone(!0).insertBefore(inp).val("")[0],notRemove||jQuery(inp).remove()):(parent=inp.parentNode,(clone=parent.insertBefore(inp.cloneNode(!0),inp)).value="",notRemove||parent.removeChild(inp),_each(_elEvents[api.uid(inp)],(function(fns,type){_each(fns,(function(fn){_off(inp,type,fn),_on(clone,type,fn)}))}))),clone},load:function(url,fn){var xhr=api.getXHR();return xhr?(xhr.open("GET",url,!0),xhr.overrideMimeType&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),_on(xhr,"progress",(function(evt){evt.lengthComputable&&fn({type:evt.type,loaded:evt.loaded,total:evt.total},xhr)})),xhr.onreadystatechange=function(){if(4==xhr.readyState)if(xhr.onreadystatechange=null,200==xhr.status){var file={name:(url=url.split("/"))[url.length-1],size:xhr.getResponseHeader("Content-Length"),type:xhr.getResponseHeader("Content-Type")};file.dataURL="data:"+file.type+";base64,"+api.encode64(xhr.responseBody||xhr.responseText),fn({type:"load",result:file},xhr)}else fn({type:"error"},xhr)},xhr.send(null)):fn({type:"error"}),xhr},encode64:function(str){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",outStr="",i=0;for("string"!=typeof str&&(str=String(str));i<str.length;){var enc3,enc4,byte1=255&str.charCodeAt(i++),byte2=255&str.charCodeAt(i++),byte3=255&str.charCodeAt(i++),enc1=byte1>>2,enc2=(3&byte1)<<4|byte2>>4;isNaN(byte2)?enc3=enc4=64:(enc3=(15&byte2)<<2|byte3>>6,enc4=isNaN(byte3)?64:63&byte3),outStr+=b64.charAt(enc1)+b64.charAt(enc2)+b64.charAt(enc3)+b64.charAt(enc4)}return outStr}};function _emit(target,fn,name,res,ext){var evt={type:name.type||name,target,result:res};_extend(evt,ext),fn(evt)}function _hasSupportReadAs(method){return FileReader&&!!FileReader.prototype["readAs"+method]}function _readAs(file,fn,method,encoding){if(api.isBlob(file)&&_hasSupportReadAs(method)){var Reader=new FileReader;_on(Reader,_readerEvents,(function _fn(evt){var type=evt.type;"progress"==type?_emit(file,fn,evt,evt.target.result,{loaded:evt.loaded,total:evt.total}):"loadend"==type?(_off(Reader,_readerEvents,_fn),Reader=null):_emit(file,fn,evt,evt.target.result)}));try{encoding?Reader["readAs"+method](file,encoding):Reader["readAs"+method](file)}catch(err){_emit(file,fn,"error",undefined,{error:err.toString()})}}else _emit(file,fn,"error",undefined,{error:"filreader_not_support_"+method})}function _isEntry(item){return item&&(item.isFile||item.isDirectory)}function _getAsEntry(item){var entry;return item.getAsEntry?entry=item.getAsEntry():item.webkitGetAsEntry&&(entry=item.webkitGetAsEntry()),entry}function _readEntryAsFiles(entry,callback){if(entry)if(entry.isFile)entry.file((function(file){file.fullPath=entry.fullPath,callback(!1,[file],[file])}),(function(err){entry.error=err,callback("FileError.code: "+err.code,[],[entry])}));else if(entry.isDirectory){var reader=entry.createReader(),firstAttempt=!0,files=[],all=[entry],onerror=function(err){entry.error=err,callback("DirectoryError.code: "+err.code,files,all)};reader.readEntries((function ondone(entries){firstAttempt&&(firstAttempt=!1,entries.length||(entry.error=new Error("directory is empty"))),entries.length?api.afor(entries,(function(next,entry){_readEntryAsFiles(entry,(function(err,entryFiles,allEntries){err||(files=files.concat(entryFiles)),all=all.concat(allEntries),next?next():reader.readEntries(ondone,onerror)}))})):callback(!1,files,all)}),onerror)}else _readEntryAsFiles(_getAsEntry(entry),callback);else{var err=new Error("invalid entry");(entry=new Object(entry)).error=err,callback(err.message,[],[entry])}}function isInputFile(el){return _rinput.test(el&&el.tagName)}function _getDataTransfer(evt){return(evt.originalEvent||evt||"").dataTransfer||{}}api.addInfoReader(/^image/,(function(file,callback){if(!file.__dimensions){var defer=file.__dimensions=api.defer();api.readAsImage(file,(function(evt){var img=evt.target;defer.resolve("load"!=evt.type&&"error",{width:img.width,height:img.height}),img.src=api.EMPTY_PNG,img=null}))}file.__dimensions.then(callback)})),api.event.dnd=function(el,onHover,onDrop){var _id,_type;onDrop||(onDrop=onHover,onHover=api.F),FileReader?(_on(el,"dragenter dragleave dragover",onHover.ff=onHover.ff||function(evt){for(var types=_getDataTransfer(evt).types,i=types&&types.length,debounceTrigger=!1;i--;)if(~types[i].indexOf("File")){evt.preventDefault(),_type!==evt.type&&("dragleave"!=(_type=evt.type)&&onHover.call(evt.currentTarget,!0,evt),debounceTrigger=!0);break}debounceTrigger&&(clearTimeout(_id),_id=setTimeout((function(){onHover.call(evt.currentTarget,"dragleave"!=_type,evt)}),50))}),_on(el,"drop",onDrop.ff=onDrop.ff||function(evt){evt.preventDefault(),_type=0,api.getDropFiles(evt,(function(files,all){onDrop.call(evt.currentTarget,files,all,evt)})),onHover.call(evt.currentTarget,!1,evt)})):api.log("Drag'n'Drop -- not supported")},api.event.dnd.off=function(el,onHover,onDrop){_off(el,"dragenter dragleave dragover",onHover.ff),_off(el,"drop",onDrop.ff)},jQuery&&!jQuery.fn.dnd&&(jQuery.fn.dnd=function(onHover,onDrop){return this.each((function(){api.event.dnd(this,onHover,onDrop)}))},jQuery.fn.offdnd=function(onHover,onDrop){return this.each((function(){api.event.dnd.off(this,onHover,onDrop)}))}),window.FileAPI=_extend(api,window.FileAPI),api.log("FileAPI: "+api.version),api.log("protocol: "+window.location.protocol),api.log("doctype: ["+doctype.name+"] "+doctype.publicId+" "+doctype.systemId),_each(document.getElementsByTagName("meta"),(function(meta){/x-ua-compatible/i.test(meta.getAttribute("http-equiv"))&&api.log("meta.http-equiv: "+meta.getAttribute("content"))}));try{_supportConsoleLog=!!console.log,_supportConsoleLogApply=!!console.log.apply}catch(err){}api.flashUrl||(api.flashUrl=api.staticPath+"FileAPI.flash.swf"),api.flashImageUrl||(api.flashImageUrl=api.staticPath+"FileAPI.flash.image.swf"),api.flashWebcamUrl||(api.flashWebcamUrl=api.staticPath+"FileAPI.flash.camera.swf")}(window),function(api,document,undef){"use strict";var min=Math.min,round=Math.round,getCanvas=function(){return document.createElement("canvas")},support=!1,exifOrientation={8:270,3:180,6:90,7:270,4:180,5:90};try{support=getCanvas().toDataURL("image/png").indexOf("data:image/png")>-1}catch(e){}function Image(file){if(file instanceof Image){var img=new Image(file.file);return api.extend(img.matrix,file.matrix),img}if(!(this instanceof Image))return new Image(file);this.file=file,this.size=file.size||100,this.matrix={sx:0,sy:0,sw:0,sh:0,dx:0,dy:0,dw:0,dh:0,resize:0,deg:0,quality:1,filter:0}}Image.prototype={image:!0,constructor:Image,set:function(attrs){return api.extend(this.matrix,attrs),this},crop:function(x,y,w,h){return undefined===w&&(w=x,h=y,x=y=0),this.set({sx:x,sy:y,sw:w,sh:h||w})},resize:function(w,h,strategy){return/min|max|height|width/.test(h)&&(strategy=h,h=w),this.set({dw:w,dh:h||w,resize:strategy})},preview:function(w,h){return this.resize(w,h||w,"preview")},rotate:function(deg){return this.set({deg})},filter:function(filter){return this.set({filter})},overlay:function(images){return this.set({overlay:images})},clone:function(){return new Image(this)},_load:function(image,fn){var self=this;/img|video/i.test(image.nodeName)?fn.call(self,null,image):api.readAsImage(image,(function(evt){fn.call(self,"load"!=evt.type,evt.result)}))},_apply:function(image,fn){var copy,canvas=getCanvas(),m=this.getMatrix(image),ctx=canvas.getContext("2d"),width=image.videoWidth||image.width,height=image.videoHeight||image.height,deg=m.deg,dw=m.dw,dh=m.dh,w=width,h=height,filter=m.filter,buffer=image,overlay=m.overlay,queue=api.queue((function(){image.src=api.EMPTY_PNG,fn(!1,canvas)})),renderImageToCanvas=api.renderImageToCanvas;for(deg-=360*Math.floor(deg/360),image._type=this.file.type;m.multipass&&min(w/dw,h/dh)>2;)w=w/2+.5|0,h=h/2+.5|0,(copy=getCanvas()).width=w,copy.height=h,buffer!==image?(renderImageToCanvas(copy,buffer,0,0,buffer.width,buffer.height,0,0,w,h),buffer=copy):(renderImageToCanvas(buffer=copy,image,m.sx,m.sy,m.sw,m.sh,0,0,w,h),m.sx=m.sy=m.sw=m.sh=0);canvas.width=deg%180?dh:dw,canvas.height=deg%180?dw:dh,canvas.type=m.type,canvas.quality=m.quality,ctx.rotate(deg*Math.PI/180),renderImageToCanvas(ctx.canvas,buffer,m.sx,m.sy,m.sw||buffer.width,m.sh||buffer.height,180==deg||270==deg?-dw:0,90==deg||180==deg?-dh:0,dw,dh),dw=canvas.width,dh=canvas.height,overlay&&api.each([].concat(overlay),(function(over){queue.inc();var img=new window.Image,fn=function(){var x=0|over.x,y=0|over.y,w=over.w||img.width,h=over.h||img.height,rel=over.rel;x=1==rel||4==rel||7==rel?(dw-w+x)/2:2==rel||5==rel||8==rel?dw-(w+x):x,y=3==rel||4==rel||5==rel?(dh-h+y)/2:rel>=6?dh-(h+y):y,api.event.off(img,"error load abort",fn);try{ctx.globalAlpha=over.opacity||1,ctx.drawImage(img,x,y,w,h)}catch(er){}queue.next()};api.event.on(img,"error load abort",fn),img.src=over.src,img.complete&&fn()})),filter&&(queue.inc(),Image.applyFilter(canvas,filter,queue.next)),queue.check()},getMatrix:function(image){var w,h,m=api.extend({},this.matrix),sw=m.sw=m.sw||image.videoWidth||image.naturalWidth||image.width,sh=m.sh=m.sh||image.videoHeight||image.naturalHeight||image.height,dw=m.dw=m.dw||sw,dh=m.dh=m.dh||sh,sf=sw/sh,df=dw/dh,strategy=m.resize;"preview"==strategy?dw==sw&&dh==sh||(df>=sf?h=(w=sw)/df:w=(h=sh)*df,w==sw&&h==sh||(m.sx=~~((sw-w)/2),m.sy=~~((sh-h)/2),sw=w,sh=h)):"height"==strategy?dw=dh*sf:"width"==strategy?dh=dw/sf:strategy&&(sw>dw||sh>dh?"min"==strategy?(dw=round(sf<df?min(sw,dw):dh*sf),dh=round(sf<df?dw/sf:min(sh,dh))):(dw=round(sf>=df?min(sw,dw):dh*sf),dh=round(sf>=df?dw/sf:min(sh,dh))):(dw=sw,dh=sh));return m.sw=sw,m.sh=sh,m.dw=dw,m.dh=dh,m.multipass=api.multiPassResize,m},_trans:function(fn){this._load(this.file,(function(err,image){if(err)fn(err);else try{this._apply(image,fn)}catch(err){api.log("[err] FileAPI.Image.fn._apply:",err),fn(err)}}))},get:function(fn){if(api.support.transform){var _this=this,matrix=_this.matrix;"auto"==matrix.deg?api.getInfo(_this.file,(function(err,info){matrix.deg=exifOrientation[info&&info.exif&&info.exif.Orientation]||0,_this._trans(fn)})):_this._trans(fn)}else fn("not_support_transform");return this},toData:function(fn){return this.get(fn)}},Image.exifOrientation=exifOrientation,Image.transform=function(file,transform,autoOrientation,fn){function _transform(err,img){var images={},queue=api.queue((function(err){fn(err,images)}));err?queue.fail():api.each(transform,(function(params,name){if(!queue.isFail()){var ImgTrans=new Image(img.nodeType?img:file),isFn="function"==typeof params;if(isFn?params(img,ImgTrans):params.width?ImgTrans[params.preview?"preview":"resize"](params.width,params.height,params.strategy):params.maxWidth&&(img.width>params.maxWidth||img.height>params.maxHeight)&&ImgTrans.resize(params.maxWidth,params.maxHeight,"max"),params.crop){var crop=params.crop;ImgTrans.crop(0|crop.x,0|crop.y,crop.w||crop.width,crop.h||crop.height)}undefined===params.rotate&&autoOrientation&&(params.rotate="auto"),ImgTrans.set({type:ImgTrans.matrix.type||params.type||file.type||"image/png"}),isFn||ImgTrans.set({deg:params.rotate,overlay:params.overlay,filter:params.filter,quality:params.quality||1}),queue.inc(),ImgTrans.toData((function(err,image){err?queue.fail():(images[name]=image,queue.next())}))}}))}file.width?_transform(!1,file):api.getInfo(file,_transform)},api.each(["TOP","CENTER","BOTTOM"],(function(x,i){api.each(["LEFT","CENTER","RIGHT"],(function(y,j){Image[x+"_"+y]=3*i+j,Image[y+"_"+x]=3*i+j}))})),Image.toCanvas=function(el){var canvas=document.createElement("canvas");return canvas.width=el.videoWidth||el.width,canvas.height=el.videoHeight||el.height,canvas.getContext("2d").drawImage(el,0,0),canvas},Image.fromDataURL=function(dataURL,size,callback){var img=api.newImage(dataURL);api.extend(img,size),callback(img)},Image.applyFilter=function(canvas,filter,doneFn){"function"==typeof filter?filter(canvas,doneFn):window.Caman&&window.Caman("IMG"==canvas.tagName?Image.toCanvas(canvas):canvas,(function(){"string"==typeof filter?this[filter]():api.each(filter,(function(val,method){this[method](val)}),this),this.render(doneFn)}))},api.renderImageToCanvas=function(canvas,img,sx,sy,sw,sh,dx,dy,dw,dh){try{return canvas.getContext("2d").drawImage(img,sx,sy,sw,sh,dx,dy,dw,dh)}catch(ex){throw api.log("renderImageToCanvas failed"),ex}},api.support.canvas=api.support.transform=support,api.Image=Image}(FileAPI,document),function(factory){"use strict";!function(loadImage){if(!window.navigator||!window.navigator.platform||!/iP(hone|od|ad)/.test(window.navigator.platform))return;var originalRenderMethod=loadImage.renderImageToCanvas;loadImage.detectSubsampling=function(img){var canvas,context;return img.width*img.height>1048576&&((canvas=document.createElement("canvas")).width=canvas.height=1,(context=canvas.getContext("2d")).drawImage(img,1-img.width,0),0===context.getImageData(0,0,1,1).data[3])},loadImage.detectVerticalSquash=function(img,subsampled){var data,sy,ey,py,naturalHeight=img.naturalHeight||img.height,canvas=document.createElement("canvas"),context=canvas.getContext("2d");for(subsampled&&(naturalHeight/=2),canvas.width=1,canvas.height=naturalHeight,context.drawImage(img,0,0),data=context.getImageData(0,0,1,naturalHeight).data,sy=0,ey=naturalHeight,py=naturalHeight;py>sy;)0===data[4*(py-1)+3]?ey=py:sy=py,py=ey+sy>>1;return py/naturalHeight||1},loadImage.renderImageToCanvas=function(canvas,img,sourceX,sourceY,sourceWidth,sourceHeight,destX,destY,destWidth,destHeight){if("image/jpeg"===img._type){var subsampled,vertSquashRatio,tileX,tileY,context=canvas.getContext("2d"),tmpCanvas=document.createElement("canvas"),tileSize=1024,tmpContext=tmpCanvas.getContext("2d");if(tmpCanvas.width=tileSize,tmpCanvas.height=tileSize,context.save(),(subsampled=loadImage.detectSubsampling(img))&&(sourceX/=2,sourceY/=2,sourceWidth/=2,sourceHeight/=2),vertSquashRatio=loadImage.detectVerticalSquash(img,subsampled),subsampled||1!==vertSquashRatio){for(sourceY*=vertSquashRatio,destWidth=Math.ceil(tileSize*destWidth/sourceWidth),destHeight=Math.ceil(tileSize*destHeight/sourceHeight/vertSquashRatio),destY=0,tileY=0;tileY<sourceHeight;){for(destX=0,tileX=0;tileX<sourceWidth;)tmpContext.clearRect(0,0,tileSize,tileSize),tmpContext.drawImage(img,sourceX,sourceY,sourceWidth,sourceHeight,-tileX,-tileY,sourceWidth,sourceHeight),context.drawImage(tmpCanvas,0,0,tileSize,tileSize,destX,destY,destWidth,destHeight),tileX+=tileSize,destX+=destWidth;tileY+=tileSize,destY+=destHeight}return context.restore(),canvas}}return originalRenderMethod(canvas,img,sourceX,sourceY,sourceWidth,sourceHeight,destX,destY,destWidth,destHeight)}}(FileAPI)}(),function(api,window){"use strict";var document=window.document,FormData=window.FormData,Form=function(){this.items=[]},encodeURIComponent=window.encodeURIComponent;function _convertFile(file,fn,useBinaryString){var blob=file.blob,filename=file.file;if(filename){if(!blob.toDataURL)return void api.readAsBinaryString(blob,(function(evt){"load"==evt.type&&fn(file,evt.result)}));var mime={"image/jpeg":".jpe?g","image/png":".png"},type=mime[file.type]?file.type:"image/png",ext=mime[type]||".png",quality=blob.quality||1;filename.match(new RegExp(ext+"$","i"))||(filename+=ext.replace("?","")),file.file=filename,file.type=type,!useBinaryString&&blob.toBlob?blob.toBlob((function(blob){fn(file,blob)}),type,quality):fn(file,api.toBinaryString(blob.toDataURL(type,quality)))}else fn(file,blob)}Form.prototype={append:function(name,blob,file,type){this.items.push({name,blob:blob&&blob.blob||(null==blob?"":blob),file:blob&&(file||blob.name),type:blob&&(type||blob.type)})},each:function(fn){for(var i=0,n=this.items.length;i<n;i++)fn.call(this,this.items[i])},toData:function(fn,options){options._chunked=api.support.chunked&&options.chunkSize>0&&1==api.filter(this.items,(function(item){return item.file})).length,api.support.html5?api.formData&&!this.multipart&&FormData?options._chunked?(api.log("FileAPI.Form.toPlainData"),this.toPlainData(fn)):(api.log("FileAPI.Form.toFormData"),this.toFormData(fn)):(api.log("FileAPI.Form.toMultipartData"),this.toMultipartData(fn)):(api.log("FileAPI.Form.toHtmlData"),this.toHtmlData(fn))},_to:function(data,complete,next,arg){var queue=api.queue((function(){complete(data)}));this.each((function(file){try{next(file,data,queue,arg)}catch(err){api.log("FileAPI.Form._to: "+err.message),complete(err)}})),queue.check()},toHtmlData:function(fn){this._to(document.createDocumentFragment(),fn,(function(file,data){var hidden,blob=file.blob;file.file?(api.reset(blob,!0),blob.name=file.name,blob.disabled=!1,data.appendChild(blob)):((hidden=document.createElement("input")).name=file.name,hidden.type="hidden",hidden.value=blob,data.appendChild(hidden))}))},toPlainData:function(fn){this._to({},fn,(function(file,data,queue){file.file&&(data.type=file.file),file.blob.toBlob?(queue.inc(),_convertFile(file,(function(file,blob){data.name=file.name,data.file=blob,data.size=blob.length,data.type=file.type,queue.next()}))):file.file?(data.name=file.blob.name,data.file=file.blob,data.size=file.blob.size,data.type=file.type):(data.params||(data.params=[]),data.params.push(encodeURIComponent(file.name)+"="+encodeURIComponent(file.blob))),data.start=-1,data.end=data.file&&data.file.FileAPIReadPosition||-1,data.retry=0}))},toFormData:function(fn){this._to(new FormData,fn,(function(file,data,queue){file.blob&&file.blob.toBlob?(queue.inc(),_convertFile(file,(function(file,blob){data.append(file.name,blob,file.file),queue.next()}))):file.file?data.append(file.name,file.blob,file.file):data.append(file.name,file.blob),file.file&&data.append("_"+file.name,file.file)}))},toMultipartData:function(fn){this._to([],fn,(function(file,data,queue,boundary){queue.inc(),_convertFile(file,(function(file,blob){data.push("--_"+boundary+'\r\nContent-Disposition: form-data; name="'+file.name+'"'+(file.file?'; filename="'+encodeURIComponent(file.file)+'"':"")+(file.file?"\r\nContent-Type: "+(file.type||"application/octet-stream"):"")+"\r\n\r\n"+(file.file?blob:encodeURIComponent(blob))+"\r\n"),queue.next()}),!0)}),api.expando)}},api.Form=Form}(FileAPI,window),function(window,api){"use strict";var noop=function(){},document=window.document,XHR=function(options){this.uid=api.uid(),this.xhr={abort:noop,getResponseHeader:noop,getAllResponseHeaders:noop},this.options=options},_xhrResponsePostfix={"":1,XML:1,Text:1,Body:1};XHR.prototype={status:0,statusText:"",constructor:XHR,getResponseHeader:function(name){return this.xhr.getResponseHeader(name)},getAllResponseHeaders:function(){return this.xhr.getAllResponseHeaders()||{}},end:function(status,statusText){var _this=this,options=_this.options;_this.end=_this.abort=noop,_this.status=status,statusText&&(_this.statusText=statusText),api.log("xhr.end:",status,statusText),options.complete(200!=status&&201!=status&&(_this.statusText||"unknown"),_this),_this.xhr&&_this.xhr.node&&setTimeout((function(){var node=_this.xhr.node;try{node.parentNode.removeChild(node)}catch(e){}try{delete window[_this.uid]}catch(e){}window[_this.uid]=_this.xhr.node=null}),9)},abort:function(){this.end(0,"abort"),this.xhr&&(this.xhr.aborted=!0,this.xhr.abort())},send:function(FormData){var _this=this,options=this.options;FormData.toData((function(data){data instanceof Error?_this.end(0,data.message):(options.upload(options,_this),_this._send.call(_this,options,data))}),options)},_send:function(options,data){var xhr,_this=this,uid=_this.uid,onLoadFnName=_this.uid+"Load",url=options.url;if(api.log("XHR._send:",data),options.cache||(url+=(~url.indexOf("?")?"&":"?")+api.uid()),data.nodeName){var jsonp=options.jsonp;url=url.replace(/([a-z]+)=(\?)/i,"$1="+uid),options.upload(options,_this);var onPostMessage=function(evt){if(~url.indexOf(evt.origin))try{var result=api.parseJSON(evt.data);result.id==uid&&complete(result.status,result.statusText,result.response)}catch(err){complete(0,err.message)}},complete=window[uid]=function(status,statusText,response){_this.readyState=4,_this.responseText=response,_this.end(status,statusText),api.event.off(window,"message",onPostMessage),window[uid]=xhr=transport=window[onLoadFnName]=null};_this.xhr.abort=function(){try{transport.stop?transport.stop():transport.contentWindow.stop?transport.contentWindow.stop():transport.contentWindow.document.execCommand("Stop")}catch(er){}complete(0,"abort")},api.event.on(window,"message",onPostMessage),window[onLoadFnName]=function(){try{var win=transport.contentWindow,doc=win.document,result=win.result||api.parseJSON(doc.body.innerHTML);complete(result.status,result.statusText,result.response)}catch(e){api.log("[transport.onload]",e)}},(xhr=document.createElement("div")).innerHTML='<form target="'+uid+'" action="'+url+'" method="POST" enctype="multipart/form-data" style="position: absolute; top: -1000px; overflow: hidden; width: 1px; height: 1px;"><iframe name="'+uid+'" src="javascript:false;" onload="window.'+onLoadFnName+" && "+onLoadFnName+'();"></iframe>'+(jsonp&&options.url.indexOf("=?")<0?'<input value="'+uid+'" name="'+jsonp+'" type="hidden"/>':"")+"</form>";var form=xhr.getElementsByTagName("form")[0],transport=xhr.getElementsByTagName("iframe")[0];form.appendChild(data),api.log(form.parentNode.innerHTML),document.body.appendChild(xhr),_this.xhr.node=xhr,_this.readyState=2;try{form.submit()}catch(err){api.log("iframe.error: "+err)}form=null}else{if(url=url.replace(/([a-z]+)=(\?)&?/i,""),this.xhr&&this.xhr.aborted)return void api.log("Error: already aborted");if(xhr=_this.xhr=api.getXHR(),data.params&&(url+=(url.indexOf("?")<0?"?":"&")+data.params.join("&")),xhr.open("POST",url,!0),api.withCredentials&&(xhr.withCredentials="true"),options.headers&&options.headers["X-Requested-With"]||xhr.setRequestHeader("X-Requested-With","XMLHttpRequest"),api.each(options.headers,(function(val,key){xhr.setRequestHeader(key,val)})),options._chunked){xhr.upload&&xhr.upload.addEventListener("progress",api.throttle((function(evt){data.retry||options.progress({type:evt.type,total:data.size,loaded:data.start+evt.loaded,totalSize:data.size},_this,options)}),100),!1),xhr.onreadystatechange=function(){var lkb=parseInt(xhr.getResponseHeader("X-Last-Known-Byte"),10);if(_this.status=xhr.status,_this.statusText=xhr.statusText,_this.readyState=xhr.readyState,4==xhr.readyState){for(var k in _xhrResponsePostfix)_this["response"+k]=xhr["response"+k];if(xhr.onreadystatechange=null,!xhr.status||xhr.status-201>0)if(api.log("Error: "+xhr.status),(!xhr.status&&!xhr.aborted||500==xhr.status||416==xhr.status)&&++data.retry<=options.chunkUploadRetry){var delay=xhr.status?0:api.chunkNetworkDownRetryTimeout;options.pause(data.file,options),api.log("X-Last-Known-Byte: "+lkb),lkb?data.end=lkb:(data.end=data.start-1,416==xhr.status&&(data.end=data.end-options.chunkSize)),setTimeout((function(){_this._send(options,data)}),delay)}else _this.end(xhr.status);else data.retry=0,data.end==data.size-1?_this.end(xhr.status):(api.log("X-Last-Known-Byte: "+lkb),lkb&&(data.end=lkb),data.file.FileAPIReadPosition=data.end,setTimeout((function(){_this._send(options,data)}),0));xhr=null}},data.start=data.end+1,data.end=Math.max(Math.min(data.start+options.chunkSize,data.size)-1,data.start);var file=data.file,slice=(file.slice||file.mozSlice||file.webkitSlice).call(file,data.start,data.end+1);data.size&&!slice.size?setTimeout((function(){_this.end(-1)})):(xhr.setRequestHeader("Content-Range","bytes "+data.start+"-"+data.end+"/"+data.size),xhr.setRequestHeader("Content-Disposition","attachment; filename="+encodeURIComponent(data.name)),xhr.setRequestHeader("Content-Type",data.type||"application/octet-stream"),xhr.send(slice)),file=slice=null}else if(xhr.upload&&xhr.upload.addEventListener("progress",api.throttle((function(evt){options.progress(evt,_this,options)}),100),!1),xhr.onreadystatechange=function(){if(_this.status=xhr.status,_this.statusText=xhr.statusText,_this.readyState=xhr.readyState,4==xhr.readyState){for(var k in _xhrResponsePostfix)_this["response"+k]=xhr["response"+k];if(xhr.onreadystatechange=null,!xhr.status||xhr.status>201)if(api.log("Error: "+xhr.status),(!xhr.status&&!xhr.aborted||500==xhr.status)&&(options.retry||0)<options.uploadRetry){options.retry=(options.retry||0)+1;var delay=api.networkDownRetryTimeout;options.pause(options.file,options),setTimeout((function(){_this._send(options,data)}),delay)}else _this.end(xhr.status);else _this.end(xhr.status);xhr=null}},api.isArray(data)){xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=_"+api.expando);var rawData=data.join("")+"--_"+api.expando+"--";if(xhr.sendAsBinary)xhr.sendAsBinary(rawData);else{var bytes=Array.prototype.map.call(rawData,(function(c){return 255&c.charCodeAt(0)}));xhr.send(new Uint8Array(bytes).buffer)}}else xhr.send(data)}}},api.XHR=XHR}(window,FileAPI),function(window,api){"use strict";var URL=window.URL||window.webkitURL,document=window.document,navigator=window.navigator,getMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,html5=!!getMedia;api.support.media=html5;var enumerateDevices,mediaDevices,MediaStreamTrack,navigatorEnumerateDevices,Camera=function(video){this.video=video};Camera.prototype={isActive:function(){return!!this._active},start:function(callback){var _successId,_failId,_this=this,video=_this.video,_complete=function(err){_this._active=!err,clearTimeout(_failId),clearTimeout(_successId),callback&&callback(err,_this)};getMedia.call(navigator,{video:!0},(function(stream){_this.stream=stream,video.src=URL.createObjectURL(stream),_successId=setInterval((function(){(function(video){var ctx,canvas=document.createElement("canvas"),res=!1;try{(ctx=canvas.getContext("2d")).drawImage(video,0,0,1,1),res=255!=ctx.getImageData(0,0,1,1).data[4]}catch(err){api.log("[FileAPI.Camera] detectVideoSignal:",err)}return res})(video)&&_complete(null)}),1e3),_failId=setTimeout((function(){_complete("timeout")}),5e3),video.play()}),_complete)},stop:function(){try{this._active=!1,this.video.pause();try{this.stream.stop()}catch(err){api.each(this.stream.getTracks(),(function(track){track.stop()}))}this.stream=null}catch(err){api.log("[FileAPI.Camera] stop:",err)}},shot:function(){return new Shot(this.video)}},Camera.get=function(el){return new Camera(el.firstChild)},Camera.publish=function(el,options,callback){"function"==typeof options&&(callback=options,options={}),options=api.extend({},{width:"100%",height:"100%",start:!0},options),el.jquery&&(el=el[0]);var doneFn=function(err){if(err)callback(err);else{var cam=Camera.get(el);options.start?cam.start(callback):callback(null,cam)}};if(el.style.width=_px(options.width),el.style.height=_px(options.height),api.html5&&html5&&!api.insecureChrome){var video=document.createElement("video");video.style.width=_px(options.width),video.style.height=_px(options.height),window.jQuery?jQuery(el).empty():el.innerHTML="",el.appendChild(video),doneFn()}else Camera.fallback(el,options,doneFn)},Camera.fallback=function(el,options,callback){callback("not_support_camera")},Camera.checkAlreadyCaptured=(mediaDevices=navigator.mediaDevices,MediaStreamTrack=window.MediaStreamTrack,navigatorEnumerateDevices=navigator.enumerateDevices,enumerateDevices=mediaDevices&&mediaDevices.enumerateDevices?function(callback){mediaDevices.enumerateDevices().then(callback)}:MediaStreamTrack&&MediaStreamTrack.getSources?MediaStreamTrack.getSources.bind(MediaStreamTrack):navigatorEnumerateDevices?navigatorEnumerateDevices.bind(navigator):function(fn){fn([])},function(callback){enumerateDevices((function(devices){var deviceExists=devices.some((function(device){return("videoinput"===device.kind||"video"===device.kind)&&device.label}));callback(deviceExists)}))});var Shot=function(video){var canvas=video.nodeName?api.Image.toCanvas(video):video,shot=api.Image(canvas);return shot.type="image/png",shot.width=canvas.width,shot.height=canvas.height,shot.size=canvas.width*canvas.height*4,shot};function _px(val){return val>=0?val+"px":val}Camera.Shot=Shot,api.Camera=Camera}(window,FileAPI),function(window,jQuery,api){"use strict";var document=window.document,location=window.location,navigator=window.navigator,_each=api.each;api.support.flash=!1,api.support.flash&&(!api.html5||!api.support.html5||api.cors&&!api.support.cors||api.media&&!api.support.media||api.insecureChrome)&&function(){var _attr=api.uid(),_retry=0,_files={},_rhttp=/^https?:/i,flash={_fn:{},init:function(){var child=document.body&&document.body.firstChild;if(child)do{if(1==child.nodeType){api.log("FlashAPI.state: awaiting");var dummy=document.createElement("div");return dummy.id="_"+_attr,_css(dummy,{top:1,right:1,width:5,height:5,position:"absolute",zIndex:"2147483647"}),child.parentNode.insertBefore(dummy,child),void flash.publish(dummy,_attr)}}while(child=child.nextSibling);_retry<10&&setTimeout(flash.init,50*++_retry)},publish:function(el,id,opts){opts=opts||{},el.innerHTML=_makeFlashHTML({id,src:_getUrl(api.flashUrl,"r="+api.version),wmode:opts.camera?"":"transparent",flashvars:"callback="+(opts.onEvent||"FileAPI.Flash.onEvent")+"&flashId="+id+"&storeKey="+navigator.userAgent.match(/\d/gi).join("")+"_"+api.version+(flash.isReady||(api.pingUrl?"&ping="+api.pingUrl:""))+"&timeout="+api.flashAbortTimeout+(opts.camera?"&useCamera="+_getUrl(api.flashWebcamUrl):"")+"&debug="+(api.debug?"1":"")})},ready:function(){api.log("FlashAPI.state: ready"),flash.ready=api.F,flash.isReady=!0,flash.patch(),flash.patchCamera&&flash.patchCamera(),api.event.on(document,"mouseover",flash.mouseover),api.event.on(document,"click",(function(evt){flash.mouseover(evt)&&(evt.preventDefault?evt.preventDefault():evt.returnValue=!0)}))},getEl:function(){return document.getElementById("_"+_attr)},getWrapper:function(node){do{if(/js-fileapi-wrapper/.test(node.className))return node}while((node=node.parentNode)&&node!==document.body)},mouseover:function(evt){var target=api.event.fix(evt).target;if(/input/i.test(target.nodeName)&&"file"==target.type&&!target.disabled){var state=target.getAttribute(_attr),wrapper=flash.getWrapper(target);if(api.multiFlash){if("i"==state||"r"==state)return!1;if("p"!=state){target.setAttribute(_attr,"i");var dummy=document.createElement("div");if(!wrapper)return void api.log("[err] FlashAPI.mouseover: js-fileapi-wrapper not found");_css(dummy,{top:0,left:0,width:target.offsetWidth,height:target.offsetHeight,zIndex:"2147483647",position:"absolute"}),wrapper.appendChild(dummy),flash.publish(dummy,api.uid()),target.setAttribute(_attr,"p")}return!0}if(wrapper){var box=function(el){var box=el.getBoundingClientRect(),body=document.body,docEl=(el&&el.ownerDocument).documentElement;return{top:box.top+(window.pageYOffset||docEl.scrollTop)-(docEl.clientTop||body.clientTop||0),left:box.left+(window.pageXOffset||docEl.scrollLeft)-(docEl.clientLeft||body.clientLeft||0),width:box.right-box.left,height:box.bottom-box.top}}(wrapper);_css(flash.getEl(),box),flash.curInp=target}}else/object|embed/i.test(target.nodeName)||_css(flash.getEl(),{top:1,left:1,width:5,height:5})},onEvent:function(evt){var type=evt.type;if("ready"==type){try{flash.getInput(evt.flashId).setAttribute(_attr,"r")}catch(e){}return flash.ready(),setTimeout((function(){flash.mouseenter(evt)}),50),!0}"ping"===type?api.log("(flash -> js).ping:",[evt.status,evt.savedStatus],evt.error):"log"===type?api.log("(flash -> js).log:",evt.target):type in flash&&setTimeout((function(){api.log("FlashAPI.event."+evt.type+":",evt),flash[type](evt)}),1)},mouseenter:function(evt){var node=flash.getInput(evt.flashId);if(node){flash.cmd(evt,"multiple",null!=node.getAttribute("multiple"));var accept=[],exts={};_each((node.getAttribute("accept")||"").split(/,\s*/),(function(mime){api.accept[mime]&&_each(api.accept[mime].split(" "),(function(ext){exts[ext]=1}))})),_each(exts,(function(i,ext){accept.push(ext)})),flash.cmd(evt,"accept",accept.length?accept.join(",")+","+accept.join(",").toUpperCase():"*")}},get:function(id){return document[id]||window[id]||document.embeds[id]},getInput:function(id){if(!api.multiFlash)return flash.curInp;try{var node=flash.getWrapper(flash.get(id));if(node)return node.getElementsByTagName("input")[0]}catch(e){api.log('[err] Can not find "input" by flashId:',id,e)}},select:function(evt){var event,inp=flash.getInput(evt.flashId),uid=api.uid(inp),files=evt.target.files;_each(files,(function(file){api.checkFileObj(file)})),_files[uid]=files,document.createEvent?((event=document.createEvent("Event")).files=files,event.initEvent("change",!0,!0),inp.dispatchEvent(event)):jQuery?jQuery(inp).trigger({type:"change",files}):((event=document.createEventObject()).files=files,inp.fireEvent("onchange",event))},cmd:function(id,name,data,last){try{return api.log("(js -> flash)."+name+":",data),flash.get(id.flashId||id).cmd(name,data)}catch(err){api.log("(js -> flash).onError:",err.toString()),last||setTimeout((function(){flash.cmd(id,name,data,!0)}),50)}},patch:function(){api.flashEngine=!0,_inherit(api,{getFiles:function(input,filter,callback){if(callback)return api.filterFiles(api.getFiles(input),filter,callback),null;var files=api.isArray(input)?input:_files[api.uid(input.target||input.srcElement||input)];return files?(filter&&(filter=api.getFilesFilter(filter),files=api.filter(files,(function(file){return filter.test(file.name)}))),files):this.parent.apply(this,arguments)},getInfo:function(file,fn){if(_isHtmlFile(file))this.parent.apply(this,arguments);else if(file.isShot)fn(null,file.info={width:file.width,height:file.height});else{if(!file.__info){var defer=file.__info=api.defer();flash.cmd(file,"getFileInfo",{id:file.id,callback:_wrap((function _(err,info){_unwrap(_),defer.resolve(err,file.info=info)}))})}file.__info.then(fn)}}}),api.support.transform=!0,api.Image&&_inherit(api.Image.prototype,{get:function(fn,scaleMode){return this.set({scaleMode:scaleMode||"noScale"}),this.parent(fn)},_load:function(file,fn){if(api.log("FlashAPI.Image._load:",file),_isHtmlFile(file))this.parent.apply(this,arguments);else{var _this=this;api.getInfo(file,(function(err){fn.call(_this,err,file)}))}},_apply:function(file,fn){if(api.log("FlashAPI.Image._apply:",file),_isHtmlFile(file))this.parent.apply(this,arguments);else{var m=this.getMatrix(file.info),doneFn=fn;flash.cmd(file,"imageTransform",{id:file.id,matrix:m,callback:_wrap((function _(err,base64){api.log("FlashAPI.Image._apply.callback:",err),_unwrap(_),err?doneFn(err):api.support.html5||api.support.dataURI&&!(base64.length>3e4)?(m.filter&&(doneFn=function(err,img){err?fn(err):api.Image.applyFilter(img,m.filter,(function(){fn(err,this.canvas)}))}),api.newImage("data:"+file.type+";base64,"+base64,doneFn)):_makeFlashImage({width:m.deg%180?m.dh:m.dw,height:m.deg%180?m.dw:m.dh,scale:m.scaleMode},base64,doneFn)}))})}},toData:function(fn){var file=this.file,info=file.info,matrix=this.getMatrix(info);api.log("FlashAPI.Image.toData"),_isHtmlFile(file)?this.parent.apply(this,arguments):("auto"==matrix.deg&&(matrix.deg=api.Image.exifOrientation[info&&info.exif&&info.exif.Orientation]||0),fn.call(this,!file.info,{id:file.id,flashId:file.flashId,name:file.name,type:file.type,matrix}))}}),api.Image&&_inherit(api.Image,{fromDataURL:function(dataURL,size,callback){!api.support.dataURI||dataURL.length>3e4?_makeFlashImage(api.extend({scale:"exactFit"},size),dataURL.replace(/^data:[^,]+,/,""),(function(err,el){callback(el)})):this.parent(dataURL,size,callback)}}),_inherit(api.Form.prototype,{toData:function(fn){for(var items=this.items,i=items.length;i--;)if(items[i].file&&_isHtmlFile(items[i].blob))return this.parent.apply(this,arguments);api.log("FlashAPI.Form.toData"),fn(items)}}),_inherit(api.XHR.prototype,{_send:function(options,formData){if(formData.nodeName||formData.append&&api.support.html5||api.isArray(formData)&&"string"==typeof formData[0])return this.parent.apply(this,arguments);var flashId,fileId,data={},files={},_this=this;if(_each(formData,(function(item){item.file?(files[item.name]=item=_getFileDescr(item.blob),fileId=item.id,flashId=item.flashId):data[item.name]=item.blob})),fileId||(flashId=_attr),!flashId)return api.log("[err] FlashAPI._send: flashId -- undefined"),this.parent.apply(this,arguments);api.log("FlashAPI.XHR._send: "+flashId+" -> "+fileId),_this.xhr={headers:{},abort:function(){flash.cmd(flashId,"abort",{id:fileId})},getResponseHeader:function(name){return this.headers[name]},getAllResponseHeaders:function(){return this.headers}};var queue=api.queue((function(){flash.cmd(flashId,"upload",{url:_getUrl(options.url.replace(/([a-z]+)=(\?)&?/i,"")),data,files:fileId?files:null,headers:options.headers||{},callback:_wrap((function upload(evt){var type=evt.type,result=evt.result;api.log("FlashAPI.upload."+type),"progress"==type?(evt.loaded=Math.min(evt.loaded,evt.total),evt.lengthComputable=!0,options.progress(evt)):"complete"==type?(_unwrap(upload),"string"==typeof result&&(_this.responseText=result.replace(/%22/g,'"').replace(/%5c/g,"\\").replace(/%26/g,"&").replace(/%25/g,"%")),_this.end(evt.status||200)):"abort"!=type&&"error"!=type||(_this.end(evt.status||0,evt.message),_unwrap(upload))}))})}));_each(files,(function(file){queue.inc(),api.getInfo(file,queue.next)})),queue.check()}})}};function _makeFlashHTML(opts){return('<object id="#id#" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+(opts.width||"100%")+'" height="'+(opts.height||"100%")+'"><param name="movie" value="#src#" /><param name="flashvars" value="#flashvars#" /><param name="swliveconnect" value="true" /><param name="allowscriptaccess" value="always" /><param name="allownetworking" value="all" /><param name="menu" value="false" /><param name="wmode" value="#wmode#" /><embed flashvars="#flashvars#" swliveconnect="true" allownetworking="all" allowscriptaccess="always" name="#id#" src="#src#" width="'+(opts.width||"100%")+'" height="'+(opts.height||"100%")+'" menu="false" wmode="transparent" type="application/x-shockwave-flash"></embed></object>').replace(/#(\w+)#/gi,(function(a,name){return opts[name]}))}function _css(el,css){var key,val;if(el&&el.style)for(key in css){"number"==typeof(val=css[key])&&(val+="px");try{el.style[key]=val}catch(e){}}}function _inherit(obj,methods){_each(methods,(function(fn,name){var prev=obj[name];obj[name]=function(){return this.parent=prev,fn.apply(this,arguments)}}))}function _isHtmlFile(file){return file&&!file.flashId}function _wrap(fn){var id=fn.wid=api.uid();return flash._fn[id]=fn,"FileAPI.Flash._fn."+id}function _unwrap(fn){try{flash._fn[fn.wid]=null,delete flash._fn[fn.wid]}catch(e){}}function _getUrl(url,params){if(!_rhttp.test(url)){if(/^\.\//.test(url)||"/"!=url.charAt(0)){var path=location.pathname;url=((path=path.substr(0,path.lastIndexOf("/")))+"/"+url).replace("/./","/")}"//"!=url.substr(0,2)&&(url="//"+location.host+url),_rhttp.test(url)||(url=location.protocol+url)}return params&&(url+=(/\?/.test(url)?"&":"?")+params),url}function _makeFlashImage(opts,base64,fn){var key,flashId=api.uid(),el=document.createElement("div"),attempts=10;for(key in opts)el.setAttribute(key,opts[key]),el[key]=opts[key];_css(el,opts),opts.width="100%",opts.height="100%",el.innerHTML=_makeFlashHTML(api.extend({id:flashId,src:_getUrl(api.flashImageUrl,"r="+api.uid()),wmode:"opaque",flashvars:"scale="+opts.scale+"&callback="+_wrap((function _(){return _unwrap(_),--attempts>0&&function(){try{flash.get(flashId).setImage(base64)}catch(e){api.log('[err] FlashAPI.Preview.setImage -- can not set "base64":',e)}}(),!0}))},opts)),fn(!1,el),el=null}function _getFileDescr(file){return{id:file.id,name:file.name,matrix:file.matrix,flashId:file.flashId}}api.Flash=flash,api.newImage("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",(function(err,img){api.support.dataURI=!(1!=img.width||1!=img.height),flash.init()}))}()}(window,window.jQuery,FileAPI),function(window,jQuery,api){"use strict";var _each=api.each,_cameraQueue=[];!api.support.flash||!api.media||api.support.media&&api.html5&&!api.insecureChrome||function(){function _wrap(fn){var id=fn.wid=api.uid();return api.Flash._fn[id]=fn,"FileAPI.Flash._fn."+id}function _unwrap(fn){try{api.Flash._fn[fn.wid]=null,delete api.Flash._fn[fn.wid]}catch(e){}}var flash=api.Flash;api.extend(api.Flash,{patchCamera:function(){api.Camera.fallback=function(el,options,callback){var camId=api.uid();api.log("FlashAPI.Camera.publish: "+camId),flash.publish(el,camId,api.extend(options,{camera:!0,onEvent:_wrap((function _(evt){"camera"===evt.type&&(_unwrap(_),evt.error?(api.log("FlashAPI.Camera.publish.error: "+evt.error),callback(evt.error)):(api.log("FlashAPI.Camera.publish.success: "+camId),callback(null)))}))}))},_each(_cameraQueue,(function(args){api.Camera.fallback.apply(api.Camera,args)})),_cameraQueue=[],api.extend(api.Camera.prototype,{_id:function(){return this.video.id},start:function(callback){var _this=this;flash.cmd(this._id(),"camera.on",{callback:_wrap((function _(evt){_unwrap(_),evt.error?(api.log("FlashAPI.camera.on.error: "+evt.error),callback(evt.error,_this)):(api.log("FlashAPI.camera.on.success: "+_this._id()),_this._active=!0,callback(null,_this))}))})},stop:function(){this._active=!1,flash.cmd(this._id(),"camera.off")},shot:function(){api.log("FlashAPI.Camera.shot:",this._id());var shot=api.Flash.cmd(this._id(),"shot",{});return shot.type="image/png",shot.flashId=this._id(),shot.isShot=!0,new api.Camera.Shot(shot)}})}}),api.Camera.fallback=function(){_cameraQueue.push(arguments)}}()}(window,window.jQuery,FileAPI),"function"==typeof define&&define.amd&&define("FileAPI",[],(function(){return FileAPI})),function(){Ext.namespace("MODx.util.MultiUploadDialog");var maxFileSize=parseInt(MODx.config.upload_maxsize,10),permittedFileTypes=MODx.config.upload_files.toLowerCase().split(",");FileAPI.debug=!1,FileAPI.support.flash=!1,FileAPI.staticPath=MODx.config.manager_url+"assets/fileapi/";var api={humanFileSize:function(bytes,si){var thresh=si?1e3:1024;if(bytes<thresh)return bytes+" B";var units=si?["kB","MB","GB","TB","PB","EB","ZB","YB"]:["KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"],u=-1;do{bytes/=thresh,++u}while(bytes>=thresh);return bytes.toFixed(1)+" "+units[u]},getFileExtension:function(filename){var result="",parts=filename.split(".");return parts.length>1&&(result=parts.pop()),result},isFileSizePermitted:function(size){return size<=maxFileSize},formatBytes:function(size,unit){return unit=unit||FileAPI.MB,Math.round(100*(size/unit+1e-5))/100},isFileTypePermitted:function(filename,extensions){var ext=this.getFileExtension(filename);return extensions.indexOf(ext.toLowerCase())>-1}};MODx.util.MultiUploadDialog.Upload=function(config){Ext.applyIf(config,{url:MODx.config.connector_url,permitted_extensions:permittedFileTypes,base_params:{action:"Browser/File/Upload",wctx:MODx.ctx||"",source:1}}),MODx.util.MultiUploadDialog.Upload.superclass.constructor.call(this,config)},Ext.extend(MODx.util.MultiUploadDialog.Upload,Ext.Component,{errors:{},initComponent:function(){this.input_file=document.createElement("input"),this.input_file.type="file",this.input_file.name=this.input_name||Ext.id(this.el),this.input_file.hidden=!0,this.input_file.multiple=!0,this.input_file.accept="."+this.permitted_extensions.join(",."),this.input_file.addEventListener("change",this.onInputFileChange.bind(this)),this.input_file.addEventListener("click",(function(e){e.stopPropagation()})),document.getElementsByTagName("body")[0].appendChild(this.input_file)},addDropZone:function(dnd,browser){var el=dnd.getEl().dom,upload=this;el.className+=" drag-n-drop",FileAPI.event.dnd(el,(function(over){over?el.className.match(/drag-over/)||(el.className+=" drag-over"):el.className=el.className.replace(" drag-over","")}),(function(files){upload.startUpload(files,browser)}))},setBaseParams:function(params){this.base_params=Ext.apply(this.base_params,params)},show:function(){this.fireEvent("show"),this.input_file.click()},onInputFileChange:function(e){var files=FileAPI.getFiles(e);this.input_file.value="",this.startUpload(files,this.browser)},startUpload:function(files,browser){var upload=this,approved=[];if(this.fireEvent("beforeupload",files),FileAPI.each(files,(function(file){api.isFileSizePermitted(file.size)?api.isFileTypePermitted(file.name,upload.permitted_extensions)?approved.push(file):upload.addError(file.name,_("upload.notpermitted.extension",{ext:api.getFileExtension(file.name)})):upload.addError(file.name,_("upload.notpermitted.filesize",{size:api.humanFileSize(file.size),max:api.humanFileSize(maxFileSize)}))})),!approved.length)return this.showErrors(),!1;this.progress=Ext.MessageBox.progress(_("please_wait")),FileAPI.upload({url:this.url,data:Ext.apply(this.base_params,{HTTP_MODAUTH:MODx.siteId}),files:{file:approved},fileprogress:function(e,file){upload.progress&&(upload.progress.updateText(file.name),upload.progress.updateProgress(e.loaded/e.total))},filecomplete:function(err,xhr,file){if(err)401!==xhr.status&&(upload.fireEvent("uploadfailed",err,xhr,file),MODx.msg.alert(_("upload.msg.title.error"),err));else{var r=Ext.util.JSON.decode(xhr.response);r.success||upload.addError(file.name,r.message)}},complete:function(err,xhr){err?upload.fireEvent("uploadfailed",xhr):(upload.fireEvent("uploadsuccess"),upload.progress&&upload.progress.hide(),void 0!==browser&&void 0!==browser.run&&browser.run()),upload.showErrors()}})},addError:function(key,message){this.errors[key]=message},showErrors:function(){var errors="";for(var i in this.errors)this.errors.hasOwnProperty(i)&&(errors+=this.errors[i]+"<br>");""!=errors&&MODx.msg.alert(_("error"),errors),this.errors={}}}),MODx.util.MultiUploadDialog.BrowseButton=Ext.extend(Ext.Button,{input_name:"file",input_file:null,original_handler:null,original_scope:null,initComponent:function(){MODx.util.MultiUploadDialog.BrowseButton.superclass.initComponent.call(this),this.original_handler=this.handler||null,this.original_scope=this.scope||window,this.handler=null,this.scope=null},onRender:function(ct,position){MODx.util.MultiUploadDialog.BrowseButton.superclass.onRender.call(this,ct,position),this.createInputFile()},createInputFile:function(){var button_container=this.el.child("button").wrap();this.input_file=button_container.createChild({tag:"input",type:"file",size:1,name:this.input_name||Ext.id(this.el),style:"cursor: pointer; display: inline-block; opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%;",multiple:!0}),this.handleMouseEvents&&(this.input_file.on("mouseover",this.onMouseOver,this),this.input_file.on("mousedown",this.onMouseDown,this)),this.tooltip&&("object"==typeof this.tooltip?Ext.QuickTips.register(Ext.apply({target:this.input_file},this.tooltip)):this.input_file.dom[this.tooltipType]=this.tooltip),this.input_file.on("change",this.onInputFileChange,this),this.input_file.on("click",(function(e){e.stopPropagation()}))},detachInputFile:function(no_create){var result=this.input_file;return"object"==typeof this.tooltip?Ext.QuickTips.unregister(this.input_file):this.input_file.dom[this.tooltipType]=null,this.input_file.removeAllListeners(),this.input_file=null,result},getInputFile:function(){return this.input_file},disable:function(){MODx.util.MultiUploadDialog.BrowseButton.superclass.disable.call(this),this.input_file.dom.disabled=!0},enable:function(){MODx.util.MultiUploadDialog.BrowseButton.superclass.enable.call(this),this.input_file.dom.disabled=!1},destroy:function(){var input_file=this.detachInputFile(!0);input_file.remove(),input_file=null,MODx.util.MultiUploadDialog.BrowseButton.superclass.destroy.call(this)},reset:function(){var form=new Ext.Element(document.createElement("form")),buttonParent=this.input_file.parent();form.appendChild(this.input_file),form.dom.reset(),buttonParent.appendChild(this.input_file)},onInputFileChange:function(ev){this.original_handler&&this.original_handler.call(this.original_scope,this,ev),this.fireEvent("click",this,ev)}}),Ext.reg("multiupload-browse-btn",MODx.util.MultiUploadDialog.BrowseButton),MODx.util.MultiUploadDialog.FilesGrid=function(config){config=config||{},Ext.applyIf(config,{height:300,autoScroll:!0,border:!1,fields:["name","size","file","permitted","message","uploaded"],paging:!1,remoteSort:!1,viewConfig:{forceFit:!0,getRowClass:function(record,index,rowParams){return record.get("permitted")?record.get("uploaded")?"upload-success":void 0:"upload-error"}},sortInfo:{field:"name",direction:"ASC"},deferRowRender:!0,anchor:"100%",autoExpandColumn:"state",columns:[{header:_("upload.columns.file"),dataIndex:"name",sortable:!0,width:200,renderer:function(value,meta,record){var id=Ext.id();return FileAPI.Image(record.get("file")).resize(100,50,"max").get((function(err,img){err||(img=new Ext.Element(img).addClass("upload-thumb"),Ext.get(id).insertFirst(img))})),'<div id="'+id+'"><p>'+value+"</p></div>"}},{header:_("upload.columns.state"),id:"state",width:100,renderer:function(value,meta,record){if(!record.get("permitted")||record.get("uploaded"))return'<p class="upload-status-text">'+record.get("message")+"</p>";var id=Ext.id();return function(){record.progressbar=new Ext.ProgressBar({renderTo:id,value:0,text:"0 / "+record.get("size")})}.defer(25),'<div id="'+id+'"></div>'}}],getMenu:function(){return[{text:_("upload.contextmenu.remove_entry"),handler:this.removeFile}]}}),MODx.util.MultiUploadDialog.FilesGrid.superclass.constructor.call(this,config)},Ext.extend(MODx.util.MultiUploadDialog.FilesGrid,MODx.grid.LocalGrid,{removeFile:function(){var selected=this.getSelectionModel().getSelections();this.getStore().remove(selected)}}),Ext.reg("multiupload-grid-files",MODx.util.MultiUploadDialog.FilesGrid),MODx.util.MultiUploadDialog.Dialog=function(config){this.filesGridId=Ext.id(),config=config||{},Ext.applyIf(config,{permitted_extensions:permittedFileTypes,autoHeight:!0,width:600,closeAction:"hide",layout:"anchor",listeners:{show:{fn:this.onShow},hide:{fn:this.onHide}},items:[{xtype:"multiupload-grid-files",id:this.filesGridId,anchor:"100%"}],buttons:[{xtype:"multiupload-browse-btn",text:_("upload.buttons.choose"),cls:"primary-button",listeners:{click:{scope:this,fn:function(btn,ev){var files=FileAPI.getFiles(ev);this.addFiles(files),btn.reset()}}}},{xtype:"splitbutton",text:_("upload.buttons.clear"),listeners:{click:{scope:this,fn:this.clearStore}},menu:new Ext.menu.Menu({items:[{text:_("upload.clear_list.all"),listeners:{click:{scope:this,fn:this.clearStore}}},{text:_("upload.clear_list.notpermitted"),listeners:{click:{scope:this,fn:this.clearNotPermittedItems}}}]})},{xtype:"button",text:_("upload.buttons.upload"),cls:"primary-button",listeners:{click:{scope:this,fn:this.startUpload}}},{xtype:"button",text:_("upload.buttons.close"),listeners:{click:{scope:this,fn:this.hideDialog}}}]}),MODx.util.MultiUploadDialog.Dialog.superclass.constructor.call(this,config)};var originalWindowOnShow=Ext.Window.prototype.onShow,originalWindowOnHide=Ext.Window.prototype.onHide;Ext.extend(MODx.util.MultiUploadDialog.Dialog,Ext.Window,{addFiles:function(files){var store=Ext.getCmp(this.filesGridId).getStore(),dialog=this;FileAPI.each(files,(function(file){var permitted=!0,message="";api.isFileSizePermitted(file.size)||(message=_("upload.notpermitted.filesize",{size:api.humanFileSize(file.size),max:api.humanFileSize(maxFileSize)}),permitted=!1),api.isFileTypePermitted(file.name,dialog.permitted_extensions)||(message=_("upload.notpermitted.extension",{ext:api.getFileExtension(file.name)}),permitted=!1);var data={name:file.name,size:api.humanFileSize(file.size),file,permitted,message,uploaded:!1},p=new store.recordType(data);store.insert(0,p)}))},startUpload:function(){var dialog=this,files=[],params=Ext.apply(this.base_params,{HTTP_MODAUTH:MODx.siteId});Ext.getCmp(this.filesGridId).getStore().each((function(){var file=this.get("file");this.get("permitted")&&!this.get("uploaded")&&(file.record=this,files.push(file))}));FileAPI.upload({url:this.url,data:params,files:{file:files},fileprogress:function(evt,file){file.record.progressbar.updateProgress(evt.loaded/evt.total,_("upload.upload_progress",{loaded:api.humanFileSize(evt.loaded),total:file.record.get("size")}),!0)},filecomplete:function(err,xhr,file,options){if(err)401!==xhr.status&&MODx.msg.alert(_("upload.msg.title.error"),err);else{var resp=Ext.util.JSON.decode(xhr.response);resp.success?(file.record.set("uploaded",!0),file.record.set("message",_("upload.upload.success"))):(file.record.set("permitted",!1),file.record.set("message",resp.message))}},complete:function(err,xhr){dialog.fireEvent("uploadsuccess")}})},removeEntry:function(record){Ext.getCmp(this.filesGridId).getStore().remove(record)},clearStore:function(){Ext.getCmp(this.filesGridId).getStore().removeAll()},clearNotPermittedItems:function(){var store=Ext.getCmp(this.filesGridId).getStore(),notPermitted=store.query("permitted",!1);store.remove(notPermitted.getRange())},hideDialog:function(){this.hide()},onDDrag:function(ev){ev&&ev.preventDefault()},onDDrop:function(ev){ev&&ev.preventDefault();var dialog=this;FileAPI.getDropFiles(ev.browserEvent,(function(files){files.length&&dialog.addFiles(files)}))},onShow:function(){var ret=originalWindowOnShow.apply(this,arguments),store=Ext.getCmp(this.filesGridId).getStore();return store.removeAll(),this.isDDSet||(this.el.on("dragenter",this.onDDrag,this),this.el.on("dragover",this.onDDrag,this),this.el.on("dragleave",this.onDDrag,this),this.el.on("drop",this.onDDrop,this),this.isDDSet=!0),ret},onHide:function(){var ret=originalWindowOnHide.apply(this,arguments);return this.el.un("dragenter",this.onDDrag,this),this.el.un("dragover",this.onDDrag,this),this.el.un("dragleave",this.onDDrag,this),this.el.un("drop",this.onDDrop,this),this.isDDSet=!1,ret},setBaseParams:function(params){this.base_params=params,this.setTitle(_("upload.title.destination_path",{path:this.base_params.path}))}}),Ext.reg("multiupload-window-dialog",MODx.util.MultiUploadDialog.Dialog)}(),Ext.namespace("MODx.tree"),MODx.tree.Tree=function(config){var tl,root;if(config=config||{},Ext.applyIf(config,{baseParams:{},action:"getNodes",loaderConfig:{}}),config.action&&(config.baseParams.action=config.action),config.loaderConfig.dataUrl=config.url,config.loaderConfig.baseParams=config.baseParams,Ext.applyIf(config.loaderConfig,{preloadChildren:!0,clearOnLoad:!0}),this.config=config,this.config.url?((tl=new MODx.tree.TreeLoader(config.loaderConfig)).on("beforeload",(function(l,node){tl.dataUrl=this.config.url+"?action="+this.config.action+"&id="+node.attributes.id,node.attributes.type&&(tl.dataUrl+="&type="+node.attributes.type)}),this),tl.on("load",this.onLoad,this),root={nodeType:"async",text:config.root_name||config.rootName||"",qtip:config.root_qtip||config.rootQtip||"",draggable:!1,id:config.root_id||config.rootId||"root",pseudoroot:!0,attributes:{pseudoroot:!0},cls:"tree-pseudoroot-node",iconCls:config.root_iconCls||config.rootIconCls||""}):(tl=new Ext.tree.TreeLoader({preloadChildren:!0,baseAttrs:{uiProvider:MODx.tree.CheckboxNodeUI}}),root=new Ext.tree.TreeNode({text:this.config.rootName||"",draggable:!1,id:this.config.rootId||"root",children:this.config.data||[],pseudoroot:!0})),Ext.applyIf(config,{useArrows:!0,autoScroll:!0,animate:!0,enableDD:!0,enableDrop:!0,ddAppendOnly:!1,containerScroll:!0,collapsible:!0,border:!1,autoHeight:!0,rootVisible:!0,loader:tl,header:!1,hideBorders:!0,bodyBorder:!1,cls:"modx-tree",root,preventRender:!1,stateful:!0,menuConfig:{defaultAlign:"tl-b?",enableScrolling:!1,listeners:{show:function(){var node=this.activeNode;node&&node.ui.addClass("x-tree-selected")},hide:function(){var node=this.activeNode;node&&(node.isSelected()||node.ui&&node.ui.removeClass("x-tree-selected"))}}}}),!0!==config.remoteToolbar||void 0!==config.tbar&&null!==config.tbar){var tb=this.getToolbar();if(config.tbar&&config.useDefaultToolbar)for(var i=0;i<config.tbar.length;i++)tb.push(config.tbar[i]);else config.tbar&&(tb=config.tbar);Ext.apply(config,{tbar:tb})}else Ext.Ajax.request({url:config.remoteToolbarUrl||config.url,params:{action:config.remoteToolbarAction||"getToolbar"},success:function(r){r=Ext.decode(r.responseText);var itms=this._formatToolbar(r.object),tb=this.getTopToolbar();if(tb){for(var i=0;i<itms.length;i++)tb.add(itms[i]);tb.doLayout()}},scope:this}),config.tbar={bodyStyle:"padding: 0"};this.setup(config),this.config=config,this.on("append",this._onAppend,this)},Ext.extend(MODx.tree.Tree,Ext.tree.TreePanel,{menu:null,options:{},disableHref:!1,onLoad:function(ldr,node,resp){this.prepareNodes(node);var r=Ext.decode(resp.responseText);if(r.message){var el=this.getTreeEl();el.addClass("modx-tree-load-msg"),el.update(r.message);var w=270;this.config.width>150&&(w=this.config.width),el.setWidth(w),this.doLayout()}},setup:function(config){config.listeners=config.listeners||{},config.listeners.render={fn:function(){!1===config.autoExpandRoot&&config.hasOwnProperty("autoExpandRoot")||this.root.expand();var tl=this.getLoader();Ext.apply(tl,{fullMask:new Ext.LoadMask(this.getEl())}),tl.fullMask.removeMask=!1,tl.on({load:function(){this.fullMask.hide()},loadexception:function(){this.fullMask.hide()},beforeload:function(){this.fullMask.show()},scope:tl})},scope:this},MODx.tree.Tree.superclass.constructor.call(this,config),this.addEvents("afterSort","beforeSort","refresh"),this.cm=new Ext.menu.Menu(config.menuConfig),this.on("contextmenu",this._showContextMenu,this),this.on("beforenodedrop",this._handleDrop,this),this.on("nodedragover",this._handleDrop,this),this.on("nodedrop",this._handleDrag,this),this.on("click",this._saveState,this),this.on("contextmenu",this._saveState,this),this.on("click",this._handleClick,this),this.treestate_id=this.config.id||Ext.id(),this.on("load",this._initExpand,this,{single:!0}),this.on("expandnode",this._saveState,this),this.on("collapsenode",this._saveState,this),this.on("expandnode",(function(){var cnt=Ext.getCmp("modx-content");cnt&&cnt.doLayout()}),this)},_initExpand:function(){var treeState=Ext.state.Manager.get(this.treestate_id);if(Ext.isEmpty(treeState)&&this.root)this.root.expand(),this.root.firstChild&&this.config.expandFirst&&this.root.firstChild.expand();else for(var i=0;i<treeState.length;i++)this.expandPath(treeState[i])},addContextMenuItem:function(items){for(var a=items,l=a.length,i=0;i<l;i++)a[i].scope=a[i].scope||this,a[i].handler&&"string"==typeof a[i].handler&&(a[i].handler=eval(a[i].handler)),this.cm.add(a[i])},prepareNodes:function(node){var params={};if(location.search)for(var parts=location.search.substring(1).split("&"),i=0;i<parts.length;i++){var nv=parts[i].split("=");nv[0]&&(params[nv[0]]=nv[1]||!0)}var activeFile=params.file;Ext.each(node.childNodes,(function(node){(node.attributes.selected||node.id==activeFile)&&node.ui.addClass("x-tree-selected"),this.addNodeButtons(node)}),this)},addNodeButtons:function(node){var elId=node.ui.elNode.id+"_tools",el=document.createElement("div");if(el.id=elId,el.className="modx-tree-node-btn-create",!node.attributes.pseudoroot&&node.ui.hasClass("pnew_modDocument")){node.ui.elNode.appendChild(el);MODx.load({xtype:"modx-button",text:"",scope:this,tooltip:new Ext.ToolTip({title:_("create_document_inside")+" <strong>"+node.attributes.text+"</strong>",target:this}),node,handler:function(btn,evt){evt.stopPropagation(evt),node.getOwnerTree().handleDirectCreateClick(node)},iconCls:"icon-plus-circle",renderTo:elId,listeners:{mouseover:function(button,e){button.tooltip.onTargetOver(e)},mouseout:function(button,e){button.tooltip.onTargetOut(e)}}})}},_showContextMenu:function(node,e){var m;this.cm.activeNode=node,this.cm.removeAll();var handled=!1;if(!Ext.isEmpty(node.attributes.treeHandler)||node.isRoot&&!Ext.isEmpty(node.childNodes[0].attributes.treeHandler)){var h=Ext.getCmp(node.isRoot?node.childNodes[0].attributes.treeHandler:node.attributes.treeHandler);h&&(node.isRoot&&(node.attributes.type="root"),m=h.getMenu(this,node,e),handled=!0)}handled||(this.getMenu?m=this.getMenu(node,e):node.attributes.menu&&node.attributes.menu.items&&(m=node.attributes.menu.items)),m&&m.length>0&&(this.addContextMenuItem(m),this.cm.showAt(e.xy)),e.preventDefault(),e.stopEvent()},hasNode:function(t,n){return t.findChild("id",n.id)||!0===t.leaf&&t.parentNode.findChild("id",n.id)},refresh:function(func,scope,args){var treeState=Ext.state.Manager.get(this.treestate_id);return this.root.reload(),this.fireEvent("refresh",{}),void 0===treeState?this.root.expand():Ext.isArray(treeState)&&Ext.each(treeState,(function(path,idx){this.expandPath(path)}),this),func&&(scope=scope||this,args=args||[],this.root.on("load",(function(){Ext.callback(func,scope,args)}),scope)),!0},removeChildren:function(node){for(;node.firstChild;){var c=node.firstChild;node.removeChild(c),c.destroy()}},loadRemoteData:function(data){for(var c in this.removeChildren(this.getRootNode()),data)"object"==typeof data[c]&&this.getRootNode().appendChild(data[c])},reloadNode:function(n){this.getLoader().load(n),n.expand()},remove:function(text,substr,split){if(this.destroying)return MODx.tree.Tree.superclass.remove.apply(this,arguments);var node=this.cm.activeNode,id=this._extractId(node.id,substr,split),p={action:this.config.removeAction||"remove"},pk=this.config.primaryKey||"id";p[pk]=id,MODx.msg.confirm({title:this.config.removeTitle||_("warning"),text:_(text),url:this.config.url,params:p,listeners:{success:{fn:this.refresh,scope:this}}})},_extractId:function(id,substr,split){return split=split||!1,!1!==(substr=substr||!1)&&(id=node.id.substr(substr)),!1!==split&&(id=(id=node.id.split("_"))[split]),id},expandNodes:function(){this.root&&(this.root.expand(),this.root.expandChildNodes(!0))},collapseNodes:function(){this.root&&(this.root.collapseChildNodes(!0),this.root.collapse())},_saveState:function(n){if(!this.stateful)return!0;var i,s=Ext.state.Manager.get(this.treestate_id),p=n.getPath();if(s=Ext.isObject(s)||Ext.isArray(s)?s.slice():[s],!Ext.isEmpty(p)&&null!=p){if(n.expanded){if(Ext.isString(p)&&-1===s.indexOf(p)){var sr,f=!1;for(i=0;i<s.length;i++)null!=s[i]&&"string"==typeof s[i]?-1!==(sr=s[i].search(p))&&s[sr]&&s[sr].length>s[i].length&&(f=!0):s.splice(i,1);f||s.push(p)}}else for(s=s.remove(p),i=0;i<s.length;i++)null!=s[i]&&"string"==typeof s[i]?-1!==s[i].search(p)&&delete s[i]:s.splice(i,1);for(i=0;i<s.length;i++)null!=s[i]&&"string"==typeof s[i]||s.splice(i,1);Ext.state.Manager.set(this.treestate_id,s)}},_handleClick:function(n,e){if(e.stopEvent(),e.preventDefault(),this.disableHref)return!0;if(n.attributes.page&&""!==n.attributes.page){if(1==e.button)return window.open(n.attributes.page,"_blank");if(1==e.ctrlKey||1==e.metaKey||1==e.shiftKey)return window.open(n.attributes.page);"SPAN"==e.target.tagName?MODx.loadPage(n.attributes.page):n.isExpandable()?n.toggle():MODx.loadPage(n.attributes.page)}else n.attributes.type&&"dir"===n.attributes.type?n.expanded||n.toggle():n.isExpandable()&&n.toggle();return!0},encode:function(node){node||(node=this.getRootNode());var _encode=function(node){for(var resultNode={},kids=node.childNodes,i=0;i<kids.length;i+=1){var n=kids[i];resultNode[n.id]={id:n.id,checked:n.ui.isChecked(),type:n.attributes.type||"",data:n.attributes.data||{},children:_encode(n)}}return resultNode},nodes=_encode(node);return Ext.encode(nodes)},_handleDrag:function(dropEvent){var encNodes=Ext.encode(function simplifyNodes(node){for(var resultNode={},kids=node.childNodes,len=kids.length,i=0;i<len;i++)resultNode[kids[i].id]=simplifyNodes(kids[i]);return resultNode}(dropEvent.tree.root)),source=dropEvent.dropNode;this.fireEvent("beforeSort",encNodes),MODx.Ajax.request({url:this.config.url,params:{data:encodeURIComponent(encNodes),action:this.config.sortAction||"sort",source_pk:source.attributes.pk,source_type:source.attributes.type},listeners:{success:{fn:function(r){var el=dropEvent.dropNode.getUI().getTextEl();el&&(1===dropEvent.target.childNodes.length&&dropEvent.dropNode.ensureVisible(),Ext.get(el).frame()),this.fireEvent("afterSort",{event:dropEvent,result:r})},scope:this},failure:{fn:function(r){return MODx.form.Handler.errorJSON(r),this.refresh(),!1},scope:this}}})},_handleDrop:function(dropEvent){var node=dropEvent.dropNode;if(node.isRoot)return!1;if(!Ext.isEmpty(node.attributes.treeHandler)){var h=Ext.getCmp(node.attributes.treeHandler);if(h)return h.handleDrop(this,dropEvent)}},_guid:function(prefix){return prefix+(new Date).getTime()},redirect:function(loc){MODx.loadPage(loc)},loadAction:function(p){var id="";this.cm.activeNode&&this.cm.activeNode.id&&(id="id="+this.cm.activeNode.id.split("_")[1]);MODx.loadPage("?"+id+"&"+p)},_loadToolbar:function(){},refreshNode:function(id,self){var node=this.getNodeById(id);if(node){var n=self?node:node.parentNode;this.getLoader().load(n,(function(){n.expand()}),this)}},refreshActiveNode:function(){this.cm.activeNode?this.getLoader().load(this.cm.activeNode,this.cm.activeNode.expand):this.refresh()},refreshParentNode:function(){this.cm.activeNode?this.getLoader().load(this.cm.activeNode.parentNode||this.cm.activeNode,this.cm.activeNode.expand):this.refresh()},removeNode:function(id){var node=this.getNodeById(id);node&&node.remove()},removeActiveNode:function(){this.cm.activeNode.remove()},getToolbar:function(){var iu=MODx.config.manager_url+"templates/default/images/restyle/icons/";return[{icon:iu+"arrow_down.png",cls:"x-btn-icon arrow_down",tooltip:{text:_("tree_expand")},handler:this.expandNodes,scope:this},{icon:iu+"arrow_up.png",cls:"x-btn-icon arrow_up",tooltip:{text:_("tree_collapse")},handler:this.collapseNodes,scope:this},{icon:iu+"refresh.png",cls:"x-btn-icon refresh",tooltip:{text:_("tree_refresh")},handler:this.refresh,scope:this}]},_formatToolbar:function(a){for(var l=a.length,i=0;i<l;i++)a[i].handler&&(a[i].handler=eval(a[i].handler)),Ext.applyIf(a[i],{scope:this,cls:this.config.toolbarItemCls||"x-btn-icon"});return a},_onAppend:function(tree,parent,node){if(node.attributes.pseudoroot)return setTimeout(function(tree){return function(){var elId=node.ui.elNode.id+"_tools",el=document.createElement("div");el.id=elId,el.className="modx-tree-node-tool-ct",node.ui.elNode.appendChild(el);var inlineButtonsLang=tree.getInlineButtonsLang(node),btn=MODx.load({xtype:"modx-button",text:"",scope:this,tooltip:new Ext.ToolTip({title:inlineButtonsLang.add,target:this}),node,handler:function(btn,evt){evt.stopPropagation(evt),node.getOwnerTree().handleCreateClick(node)},iconCls:"icon-plus-circle",renderTo:elId,listeners:{mouseover:function(button,e){button.tooltip.onTargetOver(e)},mouseout:function(button,e){button.tooltip.onTargetOut(e)}}});btn=MODx.load({xtype:"modx-button",text:"",scope:this,tooltip:new Ext.ToolTip({title:inlineButtonsLang.refresh,target:this}),node,handler:function(btn,evt){evt.stopPropagation(evt),node.reload()},iconCls:"icon-refresh",renderTo:elId,listeners:{mouseover:function(button,e){button.tooltip.onTargetOver(e)},mouseout:function(button,e){button.tooltip.onTargetOut(e)}}});window.BTNS.push(btn)}}(this),200),!1},handleCreateClick:function(node){},getInlineButtonsLang:function(node){var langs={};if(null!=node.id){var type=node.id.substr(2).split("_");"type"==type[0]?langs.add=_("new_"+type[1]):"category"==type[0]?langs.add=_("new_"+type[0]):langs.add=_("new_document")}return langs.refresh=_("ext_refresh"),langs},expandTreePath(dir="/"){const path=this.getRootNode().getPath("text").replace(/\/$/,"")+"/"+dir.replace(/^\//,"");this.expandPath(path,"text",(()=>{let node=this.getNodeById(encodeURIComponent(dir));node||(node=this.getRootNode()),node.select(),this.cm.activeNode=node}))}}),Ext.reg("modx-tree",MODx.tree.Tree),window.BTNS=[],MODx.tree.TreeLoader=function(config){(config=config||{}).id=config.id||Ext.id(),Ext.applyIf(config,{}),MODx.tree.TreeLoader.superclass.constructor.call(this,config)},Ext.extend(MODx.tree.TreeLoader,Ext.tree.TreeLoader,{processResponse:function(response,node,callback,scope){var json=response.responseText;if("string"==typeof json&&(json=Ext.decode(json)),void 0!==json.results?response.responseText=Ext.encode(json.results):void 0!==json.object&&(response.responseText=Ext.encode(json.object)),void 0!==json.success&&void 0!==json.message&&0==json.success){if("object"==typeof json.message){var msg=[];for(var i in json.message)json.message.hasOwnProperty(i)&&msg.push(json.message[i]);json.message=msg.join("\n")}MODx.msg.alert(_("alert"),json.message)}Ext.tree.TreeLoader.prototype.processResponse.call(this,response,node,callback,scope)}}),Ext.reg("modx-tree-treeloader",MODx.tree.TreeLoader),Ext.dd.DragDropMgr.getZIndex=function(element){var z,body=document.body,zIndex=-1,overTargetEl=element;for(element=Ext.getDom(element);element!==body;){if(!element){this._remove(overTargetEl);break}isNaN(z=Number(Ext.fly(element).getStyle("zIndex")))||(zIndex=z),element=element.parentNode}return zIndex},MODx.TreeDrop=function(config){config=config||{},Ext.applyIf(config,{id:"modx-treedrop",ddGroup:"modx-treedrop-dd"}),MODx.TreeDrop.superclass.constructor.call(this,config),this.config=config,this.setup()},Ext.extend(MODx.TreeDrop,Ext.Component,{setup:function(){var ddTarget=this.config.target,ddTargetEl=this.config.targetEl,cfg=this.config;this.targetEl=new Ext.dd.DropTarget(this.config.targetEl,{ddGroup:this.config.ddGroup,notifyEnter:function(ddSource,e,data){if(ddTarget.getEl){var el=ddTarget.getEl();el&&el.isVisible()&&(el.frame(),el.focus())}},notifyDrop:function(ddSource,e,data){if(!data.node||!data.node.attributes||!data.node.attributes.type)return!1;if("MODX\\Revolution\\modResource"!=data.node.attributes.type&&1!=data.node.attributes.leaf)return!1;var v="",win=!1;switch(data.node.attributes.type){case"MODX\\Revolution\\modResource":v="[[~"+data.node.attributes.pk+"]]";break;case"snippet":case"chunk":case"tv":win=!0;break;case"file":v=data.node.attributes.url;break;default:var dh=Ext.getCmp(data.node.attributes.type+"-drop-handler");return!!dh&&dh.handle(data,{ddTargetEl,cfg,iframe:cfg.iframe,iframeEl:cfg.iframeEl,onInsert:cfg.onInsert,panel:cfg.panel})}if(win)MODx.loadInsertElement({pk:data.node.attributes.pk,classKey:data.node.attributes.classKey,name:data.node.attributes.name,output:v,ddTargetEl,cfg,iframe:cfg.iframe,iframeEl:cfg.iframeEl,onInsert:cfg.onInsert,panel:cfg.panel});else if(cfg.iframe)MODx.insertForRTE(v,cfg);else{var el=Ext.get(ddTargetEl);if("modx-static-content"==el.dom.id&&(v=v.substring(1),Ext.getCmp(el.dom.id).setValue("")),"modx-symlink-content"==el.dom.id||"modx-weblink-content"==el.dom.id)Ext.getCmp(el.dom.id).setValue(""),void 0!==typeof data.node.attributes.pk&&void 0!==data.node.attributes.pk?MODx.insertAtCursor(ddTargetEl,data.node.attributes.pk,cfg.onInsert):MODx.insertAtCursor(ddTargetEl,v,cfg.onInsert);else if("modx-resource-parent"==el.dom.id){v=data.node.attributes.pk;var p,pf=Ext.getCmp("modx-resource-parent");if(v==pf.currentid)return MODx.msg.alert("",_("resource_err_own_parent")),!1;pf.setValue(v),Ext.getCmp(pf.parentcmp).setValue(v),(p=Ext.getCmp(pf.formpanel))&&p.markDirty()}else MODx.insertAtCursor(ddTargetEl,v,cfg.onInsert);if(cfg.panel)(p=Ext.getCmp(cfg.panel))&&p.markDirty()}return!0}}),this.targetEl.addToGroup("modx-treedrop-elements-dd"),this.targetEl.addToGroup("modx-treedrop-sources-dd")}}),Ext.reg("modx-treedrop",MODx.TreeDrop),MODx.loadInsertElement=function(r){MODx.InsertElementWindow&&(MODx.InsertElementWindow.hide(),MODx.InsertElementWindow.destroy()),MODx.InsertElementWindow=MODx.load({xtype:"modx-window-insert-element",record:r,listeners:{success:{fn:function(){},scope:this},hide:{fn:function(){this.destroy()}}}}),MODx.InsertElementWindow.setValues(r),MODx.InsertElementWindow.show()},MODx.insertAtCursor=function(myField,myValue,h){if(!Ext.isEmpty(h)){var z=h(myValue);null!=z&&(myValue=z)}if(myField.blur(),document.selection)sel=document.selection.createRange(),sel.text=myValue;else if(myField.selectionStart||"0"==myField.selectionStart){var startPos=myField.selectionStart,endPos=myField.selectionEnd;myField.value=myField.value.substring(0,startPos)+myValue+myField.value.substring(endPos,myField.value.length),myField.selectionStart=startPos+myValue.length,myField.selectionEnd=myField.selectionStart}else myField.value+=myValue;myField.focus()},MODx.insertForRTE=function(v,cfg){var fn=cfg.onInsert||!1;if(fn)fn(v,cfg);else{if("object"==typeof cfg.iframeEl)var doc=cfg.iframeEl;else doc=window.frames[0].document.getElementById(cfg.iframeEl);doc.value?doc.value=doc.value+v:doc.innerHTML=doc.innerHTML+v}},MODx.insertIntoContent=function(v,opt){opt.iframe?MODx.insertForRTE(v,opt.cfg):MODx.insertAtCursor(opt.ddTargetEl,v)},MODx.window.InsertElement=function(config){config=config||{};var resourceCmp=Ext.get("modx-resource-id"),resourceId=null!==resourceCmp?resourceCmp.getValue():0;Ext.applyIf(config,{title:_("select_el_opts"),id:"modx-window-insert-element",width:522,labelAlign:"left",labelWidth:160,url:MODx.config.connector_url,action:"Element/Template/Create",fields:[{xtype:"hidden",name:"pk",id:"modx-dise-pk"},{xtype:"hidden",name:"classKey",id:"modx-dise-classkey"},{xtype:"xcheckbox",fieldLabel:_("cached"),name:"cached",id:"modx-dise-cached",inputValue:1,checked:!0},{xtype:"modx-combo-property-set",fieldLabel:_("property_set"),name:"propertyset",id:"modx-dise-propset",width:300,baseParams:{action:"Element/PropertySet/GetList",showAssociated:!0,elementId:config.record.pk,elementType:config.record.classKey},listeners:{render:{fn:function(){Ext.getCmp("modx-dise-propset").getStore().load(),Ext.getCmp("modx-dise-propset").value="0"},scope:this},select:{fn:this.changePropertySet,scope:this}}},{id:"modx-dise-proplist",autoLoad:{url:MODx.config.connector_url,params:{action:"Element/GetInsertProperties",classKey:config.record.classKey,pk:config.record.pk,resourceId,propertySet:0},scripts:!0,callback:this.onPropFormLoad,scope:this},style:"display: none;"},{xtype:"fieldset",title:_("properties"),height:.6*Ext.getBody().getViewSize().height,collapsible:!0,autoScroll:!0,items:[{html:'<div id="modx-iprops-form"></div>',id:"modx-iprops-container"}]}],modps:[]}),MODx.window.InsertElement.superclass.constructor.call(this,config),this.on("show",(function(){this.center(),this.mask=new Ext.LoadMask(Ext.get("modx-iprops-container"),{msg:_("loading")}),this.mask.show()}),this)},Ext.extend(MODx.window.InsertElement,MODx.Window,{changePropertySet:function(cb){var fp=Ext.getCmp("modx-iprops-fp");fp&&fp.destroy();var resourceCmp=Ext.get("modx-resource-id"),resourceId=null!==resourceCmp?resourceCmp.getValue():0;Ext.getCmp("modx-dise-proplist").getUpdater().update({url:MODx.config.connector_url,params:{action:"Element/GetInsertProperties",classKey:this.config.record.classKey,pk:this.config.record.pk,resourceId,propertySet:cb.getValue()},scripts:!0,callback:this.onPropFormLoad,scope:this}),this.modps=[],this.mask.show()},createStore:function(data){return new Ext.data.SimpleStore({fields:["v","d"],data})},onPropFormLoad:function(el,s,r){this.mask.hide();var vs=Ext.decode(r.responseText);if(!vs||vs.length<=0)return!1;for(var i=0;i<vs.length;i++)vs[i].store&&(vs[i].store=this.createStore(vs[i].store));MODx.load({xtype:"panel",id:"modx-iprops-fp",layout:"form",autoHeight:!0,autoScroll:!0,labelWidth:150,border:!1,items:vs,renderTo:"modx-iprops-form"})},submit:function(){var v="[[",n=this.config.record.name,f=this.fp.getForm();switch(1!=f.findField("cached").getValue()&&(v+="!"),this.config.record.classKey){case"MODX\\Revolution\\modSnippet":v+=n;break;case"MODX\\Revolution\\modChunk":v=v+"$"+n;break;case"MODX\\Revolution\\modTemplateVar":v=v+"*"+n}var ps=f.findField("propertyset").getValue();0!=ps&&""!==ps&&(v=v+"@"+f.findField("propertyset").getRawValue()),v+="?";for(var i=0;i<this.modps.length;i++){var fld=this.modps[i],val="function"==typeof Ext.getCmp("modx-iprop-"+fld).getValue?Ext.getCmp("modx-iprop-"+fld).getValue():Ext.getCmp("modx-iprop-"+fld).value;1==val&&(val=1),0==val&&(val=0),v=v+"\n\t&"+fld+"=`"+val+"`"}return v+="\n]]",this.config.record.iframe?MODx.insertForRTE(v,this.config.record.cfg):MODx.insertAtCursor(this.config.record.ddTargetEl,v),this.hide(),!0},changeProp:function(k){-1==this.modps.indexOf(k)&&this.modps.push(k)}}),Ext.reg("modx-window-insert-element",MODx.window.InsertElement),MODx.tree.AsyncTreeNode=function(config){(config=config||{}).id=config.id||Ext.id(),Ext.applyIf(config,{}),MODx.tree.AsyncTreeNode.superclass.constructor.call(this,config)},Ext.extend(MODx.tree.AsyncTreeNode,Ext.tree.AsyncTreeNode,{}),Ext.reg("modx-tree-asynctreenode",MODx.tree.AsyncTreeNode),MODx.tree.Resource=function(config){config=config||{},Ext.applyIf(config,{url:MODx.config.connector_url,action:"Resource/GetNodes",title:"",rootVisible:!1,expandFirst:!0,enableDD:"0"!=MODx.config.enable_dragdrop,ddGroup:"modx-treedrop-dd",sortAction:"Resource/Sort",sortBy:this.getDefaultSortBy(config),tbarCfg:{id:config.id?config.id+"-tbar":"modx-tree-resource-tbar"},baseParams:{sortBy:this.getDefaultSortBy(config),currentResource:MODx.request.id||0,currentAction:MODx.request.a||0}}),MODx.tree.Resource.superclass.constructor.call(this,config),this.addEvents("loadCreateMenus","emptyTrash"),this.on("afterSort",this._handleAfterDrop,this)},Ext.extend(MODx.tree.Resource,MODx.tree.Tree,{forms:{},windows:{},stores:{},getToolbar:function(){return[]},_initExpand:function(){var treeState=Ext.state.Manager.get(this.treestate_id);if((Ext.isString(treeState)||Ext.isEmpty(treeState))&&this.root){this.root&&this.root.expand();var wn=this.getNodeById("web_0");wn&&this.config.expandFirst&&(wn.select(),wn.expand())}else{if("1"!==MODx.config.context_tree_sort&&void 0!==this.root&&void 0!==this.root.childNodes)for(var i=0;i<this.root.childNodes.length;i++)this.root.childNodes[i].draggable=!1;for(i=0;i<treeState.length;i++)this.expandPath(treeState[i])}},_showContextMenu:function(n,e){if(this.cm.activeNode=n,this.cm.removeAll(),n.attributes.menu&&n.attributes.menu.items)this.addContextMenuItem(n.attributes.menu.items);else{var m=[];switch(n.attributes.type){case"MODX\\Revolution\\modResource":case"MODX\\Revolution\\modDocument":m=this._getModResourceMenu(n);break;case"MODX\\Revolution\\modContext":m=this._getModContextMenu(n)}this.addContextMenuItem(m)}this.cm.showAt(e.xy),e.stopEvent()},duplicateResource:function(item,e){var node=this.cm.activeNode,id=node.id.split("_");id=id[1];var name=Ext.util.Format.htmlEncode(node.ui.textNode.innerText),r={resource:id,is_folder:node.getUI().hasClass("folder")},w=MODx.load({xtype:"modx-window-resource-duplicate",resource:id,pagetitle:name,hasChildren:node.attributes.hasChildren,childCount:node.attributes.childCount,redirect:!1,listeners:{success:{fn:function(r){var response=Ext.decode(r.a.response.responseText);response.object.redirect?MODx.loadPage("resource/update","id="+response.object.id):(node.parentNode.attributes.childCount=parseInt(node.parentNode.attributes.childCount)+1,this.refreshNode(node.id))},scope:this}}});w.config.hasChildren=node.attributes.hasChildren,w.setValues(r),w.show(e.target)},duplicateContext:function(itm,e){var r={key:this.cm.activeNode.attributes.pk,newkey:""};MODx.load({xtype:"modx-window-context-duplicate",record:r,listeners:{success:{fn:function(){this.refresh()},scope:this}}}).show(e.target)},removeContext:function(itm,e){var key=this.cm.activeNode.attributes.pk;MODx.msg.confirm({title:_("remove_context"),text:_("context_remove_confirm"),url:MODx.config.connector_url,params:{action:"Context/Remove",key},listeners:{success:{fn:function(){var cmp=Ext.getCmp("modx-grid-context");cmp&&cmp.refresh(),this.refresh()},scope:this}}})},preview:function(){window.open(this.cm.activeNode.attributes.preview_url)},deleteDocument:function(){const node=this.cm.activeNode,id=node.id.split("_")[1],resource=Ext.util.Format.htmlEncode(node.ui.textNode.innerText);MODx.msg.confirm({text:_("resource_delete_confirm",{resource}),url:MODx.config.connector_url,params:{action:"Resource/Delete",id},listeners:{success:{fn:data=>{const deletedCount=+data.object.deletedCount;Ext.getCmp("modx-trash-link")?.updateState(deletedCount);const nodeUI=node.getUI();nodeUI.addClass("deleted"),node.cascade((childNode=>childNode.getUI().addClass("deleted")),this),Ext.getCmp("modx-trash-resources")?.refresh(),Ext.get(nodeUI.getEl()).frame();const updatePanel=Ext.getCmp("modx-panel-resource");updatePanel&&"resource/update"===MODx.request.a&&MODx.request.id===id&&updatePanel.handleDeleted(!0)},scope:this}}})},undeleteDocument:function(){const node=this.cm.activeNode,id=node.id.split("_")[1];MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Resource/Undelete",id},listeners:{success:{fn:function(response){const deletedCount=+response.object.deletedCount;Ext.getCmp("modx-trash-link")?.updateState(deletedCount);const activeNodeUI=node.getUI();activeNodeUI.removeClass("deleted"),node.cascade((childNode=>childNode.getUI().removeClass("deleted")),this);const trashResourcesPanel=Ext.getCmp("modx-trash-resources");trashResourcesPanel&&trashResourcesPanel.refresh(),Ext.get(activeNodeUI.getEl()).frame();const updatePanel=Ext.getCmp("modx-panel-resource");updatePanel&&"resource/update"===MODx.request.a&&MODx.request.id===id&&updatePanel.handleDeleted(!1)},scope:this}}})},purgeDocument:function(itm,e){const node=this.cm.activeNode,id=node.id.split("_")[1],name=Ext.util.Format.htmlEncode(node.ui.textNode.innerText);MODx.msg.confirm({text:_("resource_purge_confirm",{resource:name+" ("+id+")"}),url:MODx.config.connector_url,params:{action:"Resource/Trash/Purge",ids:id},listeners:{success:{fn:function(data){if("resource/update"===MODx.request.a&&MODx.request.id===id){const updatePanel=Ext.getCmp("modx-panel-resource");return updatePanel&&(updatePanel.warnUnsavedChanges=!1),void MODx.loadPage("?")}Ext.getCmp("modx-trash-link")?.updateState(+data.object.deletedCount),node.remove(),Ext.getCmp("modx-trash-resources")?.refresh(),MODx.msg.status({title:_("success"),message:data.message})},scope:this}}})},publishDocument:function(itm,e){var id=this.cm.activeNode.id.split("_");id=id[1],MODx.msg.confirm({title:_("resource_publish"),text:_("resource_publish_confirm"),url:MODx.config.connector_url,params:{action:"Resource/Publish",id},listeners:{success:{fn:function(){var ui=this.cm.activeNode.getUI();ui.removeClass("unpublished"),Ext.get(ui.getEl()).frame()},scope:this}}})},unpublishDocument:function(itm,e){var id=this.cm.activeNode.id.split("_");id=id[1],MODx.msg.confirm({title:_("resource_unpublish"),text:_("resource_unpublish_confirm"),url:MODx.config.connector_url,params:{action:"Resource/Unpublish",id},listeners:{success:{fn:function(){var ui=this.cm.activeNode.getUI();ui.addClass("unpublished"),Ext.get(ui.getEl()).frame()},scope:this}}})},getDefaultSortBy:function(config){var v="menuindex";Ext.isEmpty(config)||Ext.isEmpty(config.sortBy)?Ext.state.Manager.get(this.treestate_id+"-sort-default")!=MODx.config.tree_default_sort?(v=MODx.config.tree_default_sort,Ext.state.Manager.set(this.treestate_id+"-sort-default",v),Ext.state.Manager.set(this.treestate_id+"-sort",v)):v=Ext.state.Manager.get(this.treestate_id+"-sort")||MODx.config.tree_default_sort:v=config.sortBy;return v},filterSort:function(itm,e){this.getLoader().baseParams={action:this.config.action,sortBy:itm.sortBy,sortDir:itm.sortDir,node:this.cm.activeNode.ide},this.refreshActiveNode()},hideFilter:function(itm,e){this.filterBar.destroy(),this._filterVisible=!1},_handleAfterDrop:function(o,r){var targetNode=o.event.target,dropNode=o.event.dropNode;if("append"==o.event.point&&targetNode){var ui=targetNode.getUI();ui.addClass("haschildren"),ui.removeClass("icon-resource")}if("resource/update"===MODx.request.a){if(dropNode.attributes.pk==MODx.request.id){var parentFieldCmb=Ext.getCmp("modx-resource-parent"),parentFieldHidden=Ext.getCmp("modx-resource-parent-hidden");parentFieldCmb&&parentFieldHidden&&(parentFieldHidden.setValue(dropNode.parentNode.attributes.pk),parentFieldCmb.setValue(dropNode.parentNode.attributes.text.replace(/(<([^>]+)>)/gi,"")))}var menuindexField=Ext.getCmp("modx-resource-menuindex");menuindexField&&void 0!==o.result.object.menuindex&&menuindexField.setValue(o.result.object.menuindex);var isfolderFieldCmb=Ext.getCmp("modx-resource-isfolder");isfolderFieldCmb&&"boolean"==typeof o.result.object.isfolder&&isfolderFieldCmb.setValue(o.result.object.isfolder)}},_handleDrop:function(e){var dropNode=e.dropNode,targetParent=e.target;if(null!==targetParent.findChild("id",dropNode.attributes.id))return!1;if("modContext"==dropNode.attributes.type&&(targetParent.getDepth()>1||targetParent.attributes.id==targetParent.attributes.pk+"_0"&&"append"==e.point))return!1;if("modContext"!==dropNode.attributes.type&&targetParent.getDepth()<=1&&"append"!==e.point)return!1;if(null==MODx.config.resource_classes_drop[targetParent.attributes.classKey]){if(targetParent.attributes.hide_children_in_tree)return!1}else if(0==MODx.config.resource_classes_drop[targetParent.attributes.classKey])return!1;return"root"!=dropNode.attributes.text&&""!==dropNode.attributes.text&&"root"!=targetParent.attributes.text&&""!==targetParent.attributes.text},getContextSettingForNode:function(node,ctx,setting,dv){var val=dv||null;if("modContext"!=node.attributes.type){var cn=node.getOwnerTree().getRootNode().findChild("ctx",ctx,!1);cn&&(val=cn.attributes.settings[setting])}else val=node.attributes.settings[setting];return val},quickCreate:function(itm,e,cls,ctx,p){var r={class_key:cls=cls||"MODX\\Revolution\\modDocument",context_key:ctx||"web",parent:p||0,template:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"default_template",MODx.config.default_template)),richtext:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"richtext_default",MODx.config.richtext_default)),hidemenu:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"hidemenu_default",MODx.config.hidemenu_default)),searchable:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"search_default",MODx.config.search_default)),cacheable:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"cache_default",MODx.config.cache_default)),published:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"publish_default",MODx.config.publish_default)),content_type:parseInt(this.getContextSettingForNode(this.cm.activeNode,ctx,"default_content_type",MODx.config.default_content_type))};if("modContext"!=this.cm.activeNode.attributes.type){var cn=this.cm.activeNode.getOwnerTree().getRootNode().findChild("ctx",ctx,!1);cn&&(r.template=cn.attributes.settings.default_template)}else r.template=this.cm.activeNode.attributes.settings.default_template;var w=MODx.load({xtype:"modx-window-quick-create-modResource",record:r,listeners:{success:{fn:function(){this.refreshNode(this.cm.activeNode.id,this.cm.activeNode.childNodes.length>0)},scope:this},hide:{fn:function(){this.destroy()}},show:{fn:function(){this.center()}}}});w.setValues(r),w.show(e.target,(function(){Ext.isSafari?w.setPosition(null,30):w.center()}),this)},quickUpdate:function(itm,e,cls){MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Resource/Get",id:this.cm.activeNode.attributes.pk,skipFormatDates:!0},listeners:{success:{fn:function(r){var pr=r.object;pr.class_key=cls;var w=MODx.load({xtype:"modx-window-quick-update-modResource",record:pr,listeners:{success:{fn:function(r){this.refreshNode(this.cm.activeNode.id);var newTitle='<span dir="ltr">'+r.f.findField("pagetitle").getValue()+" ("+w.record.id+")</span>";w.setTitle(w.title.replace(/<span.*\/span>/,newTitle))},scope:this},hide:{fn:function(){this.destroy()}}}});w.title+=': <span dir="ltr">'+Ext.util.Format.htmlEncode(w.record.pagetitle)+" ("+w.record.id+")</span>",w.setValues(r.object),w.show(e.target,(function(){Ext.isSafari?w.setPosition(null,30):w.center()}),this)},scope:this}}})},_getModContextMenu:function(n){var a=n.attributes,ui=n.getUI(),m=[];return m.push({text:"<b>"+a.text+" ("+a.ctx+")</b>",handler:function(){return!1},header:!0}),m.push("-"),m.push({text:_("refresh_context"),handler:function(){this.refreshNode(this.cm.activeNode.id,!0)}}),ui.hasClass("pedit")&&m.push({text:_("edit_context"),handler:function(){var at=this.cm.activeNode.attributes;this.loadAction("a=context/update&key="+at.pk)}}),ui.hasClass("pnew")&&m.push({text:_("duplicate_context"),handler:this.duplicateContext}),ui.hasClass("pdelete")&&(m.push("-"),m.push({text:_("remove_context"),handler:this.removeContext})),ui.hasClass("pnewdoc")&&(m.push("-"),this._getCreateMenus(m,"0",ui)),ui.hasClass("x-tree-node-leaf")||(m.push("-"),m.push(this._getSortMenu())),m},overviewResource:function(){this.loadAction("a=resource/data")},quickUpdateResource:function(itm,e){this.quickUpdate(itm,e,itm.classKey)},editResource:function(){this.loadAction("a=resource/update")},_getModResourceMenu:function(n){var a=n.attributes,ui=n.getUI(),m=[];return m.push({text:"<b>"+a.text+"</b>",handler:function(){return!1},header:!0}),m.push("-"),ui.hasClass("pview")&&m.push({text:_("resource_overview"),handler:this.overviewResource}),ui.hasClass("pedit")&&m.push({text:_("resource_edit"),handler:this.editResource}),ui.hasClass("pqupdate")&&m.push({text:_("quick_update_resource"),classKey:a.classKey,handler:this.quickUpdateResource}),ui.hasClass("pduplicate")&&m.push({text:_("resource_duplicate"),handler:this.duplicateResource}),m.push({text:_("resource_refresh"),handler:this.refreshResource,scope:this}),ui.hasClass("pnew")&&(m.push("-"),this._getCreateMenus(m,null,ui)),ui.hasClass("psave")&&(m.push("-"),ui.hasClass("ppublish")&&ui.hasClass("unpublished")?m.push({text:_("resource_publish"),handler:this.publishDocument}):ui.hasClass("punpublish")&&m.push({text:_("resource_unpublish"),handler:this.unpublishDocument}),ui.hasClass("pundelete")&&ui.hasClass("deleted")?(m.push({text:_("resource_undelete"),handler:this.undeleteDocument}),m.push({text:_("resource_purge"),handler:this.purgeDocument})):ui.hasClass("pdelete")&&!ui.hasClass("deleted")&&m.push({text:_("resource_delete"),handler:this.deleteDocument})),ui.hasClass("x-tree-node-leaf")||(m.push("-"),m.push(this._getSortMenu())),ui.hasClass("pview")&&""!=a.preview_url&&(m.push("-"),m.push({text:_("resource_view"),handler:this.preview})),m},refreshResource:function(){this.refreshNode(this.cm.activeNode.id)},createResourceHere:function(itm){var at=this.cm.activeNode.attributes,parent=itm.usePk?itm.usePk:at.pk;parseInt(MODx.config.enable_template_picker_in_tree)?MODx.createResource({class_key:itm.classKey,parent,context_key:at.ctx||MODx.config.default_context}):this.loadAction("a=resource/create&class_key="+itm.classKey+"&parent="+parent+(at.ctx?"&context_key="+at.ctx:""))},createResource:function(itm,e){var at=this.cm.activeNode.attributes,p=itm.usePk?itm.usePk:at.pk;this.quickCreate(itm,e,itm.classKey,at.ctx,p)},_getCreateMenus:function(m,pk,ui){var types=MODx.config.resource_classes,o=this.fireEvent("loadCreateMenus",types);Ext.isObject(o)&&Ext.apply(types,o);var coreTypes=["MODXRevolutionmodDocument","MODXRevolutionmodWebLink","MODXRevolutionmodSymLink","MODXRevolutionmodStaticResource"],ct=[],qct=[];for(var k in types)(-1==coreTypes.indexOf(k)||ui.hasClass("pnew_"+k))&&(ct.push({text:types[k].text_create_here,classKey:k,usePk:pk||!1,handler:this.createResourceHere,scope:this}),ui&&ui.hasClass("pqcreate")&&qct.push({text:types[k].text_create,classKey:k,handler:this.createResource,scope:this}));return m.push({text:_("create"),handler:function(){return!1},menu:{items:ct}}),ui&&ui.hasClass("pqcreate")&&m.push({text:_("quick_create"),handler:function(){return!1},menu:{items:qct}}),m},_handleDrag:function(dropEvent){var encNodes=Ext.encode(function simplifyNodes(node){for(var resultNode={},kids=node.childNodes,len=kids.length,i=0;i<len;i++)resultNode[kids[i].id]=simplifyNodes(kids[i]);return resultNode}(dropEvent.tree.root));this.fireEvent("beforeSort",encNodes),MODx.Ajax.request({url:this.config.url,params:{target:dropEvent.target.attributes.id,activeTarget:"resource/update"===MODx.request.a?MODx.request.id:"",source:dropEvent.source.dragData.node.attributes.id,point:dropEvent.point,data:encodeURIComponent(encNodes),action:this.config.sortAction||"sort"},listeners:{success:{fn:function(r){var el=dropEvent.dropNode.getUI().getTextEl();el&&Ext.get(el).frame(),this.fireEvent("afterSort",{event:dropEvent,result:r})},scope:this},failure:{fn:function(r){return MODx.form.Handler.errorJSON(r),this.refresh(),!1},scope:this}}})},_getSortMenu:function(){return[{text:_("sort_by"),handler:function(){return!1},menu:{items:[{text:_("tree_order"),sortBy:"menuindex",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("recently_updated"),sortBy:"editedon",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("newest"),sortBy:"createdon",sortDir:"DESC",handler:this.filterSort,scope:this},{text:_("oldest"),sortBy:"createdon",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("publish_date"),sortBy:"pub_date",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("unpublish_date"),sortBy:"unpub_date",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("publishedon"),sortBy:"publishedon",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("title"),sortBy:"pagetitle",sortDir:"ASC",handler:this.filterSort,scope:this},{text:_("alias"),sortBy:"alias",sortDir:"ASC",handler:this.filterSort,scope:this}]}}]},handleCreateClick:function(node){this.cm.activeNode=node;this.createResourceHere({usePk:"0",classKey:"MODX\\Revolution\\modDocument"})},handleDirectCreateClick:function(node){this.cm.activeNode=node,this.createResourceHere({classKey:"MODX\\Revolution\\modDocument"})},renderItemText:function(item){return item.text}}),Ext.reg("modx-tree-resource",MODx.tree.Resource),MODx.window.QuickCreateResource=function(config){config=config||{},this.ident=config.ident||"qcr"+Ext.id(),Ext.applyIf(config,{title:_("quick_create_resource"),id:this.ident,bwrapCssClass:"x-window-with-tabs",width:700,layout:"anchor",url:MODx.config.connector_url,action:"Resource/Create",fields:[{xtype:"modx-tabs",bodyStyle:{background:"transparent"},border:!0,deferredRender:!1,autoHeight:!1,autoScroll:!1,anchor:"100% 100%",items:[{title:_("resource"),layout:"form",cls:"modx-panel",autoHeight:!1,anchor:"100% 100%",labelWidth:100,items:[{xtype:"hidden",name:"id"},{layout:"column",border:!1,items:[{columnWidth:.6,border:!1,layout:"form",items:[{xtype:"textfield",name:"pagetitle",id:"modx-"+this.ident+"-pagetitle",fieldLabel:_("resource_pagetitle"),description:"<b>[[*pagetitle]]</b><br />"+_("resource_pagetitle_help"),anchor:"100%",allowBlank:!1},{xtype:"textfield",name:"longtitle",id:"modx-"+this.ident+"-longtitle",fieldLabel:_("resource_longtitle"),description:"<b>[[*longtitle]]</b><br />"+_("resource_longtitle_help"),anchor:"100%"},{xtype:"textarea",name:"description",id:"modx-"+this.ident+"-description",fieldLabel:_("resource_description"),description:"<b>[[*description]]</b><br />"+_("resource_description_help"),anchor:"100%",grow:!1,height:50},{xtype:"textarea",name:"introtext",id:"modx-"+this.ident+"-introtext",fieldLabel:_("resource_summary"),description:"<b>[[*introtext]]</b><br />"+_("resource_summary_help"),anchor:"100%",height:50}]},{columnWidth:.4,border:!1,layout:"form",items:[{xtype:"modx-combo-template",name:"template",id:"modx-"+this.ident+"-template",fieldLabel:_("resource_template"),description:"<b>[[*template]]</b><br />"+_("resource_template_help"),editable:!1,anchor:"100%",baseParams:{action:"Element/Template/GetList",combo:!0},value:MODx.config.default_template},{xtype:"textfield",name:"alias",id:"modx-"+this.ident+"-alias",fieldLabel:_("resource_alias"),description:"<b>[[*alias]]</b><br />"+_("resource_alias_help"),anchor:"100%"},{xtype:"textfield",name:"menutitle",id:"modx-"+this.ident+"-menutitle",fieldLabel:_("resource_menutitle"),description:"<b>[[*menutitle]]</b><br />"+_("resource_menutitle_help"),anchor:"100%"},{xtype:"textfield",fieldLabel:_("resource_link_attributes"),description:"<b>[[*link_attributes]]</b><br />"+_("resource_link_attributes_help"),name:"link_attributes",id:"modx-"+this.ident+"-attributes",maxLength:255,anchor:"100%"},{xtype:"xcheckbox",boxLabel:_("resource_hide_from_menus"),description:"<b>[[*hidemenu]]</b><br />"+_("resource_hide_from_menus_help"),hideLabel:!0,name:"hidemenu",id:"modx-"+this.ident+"-hidemenu",inputValue:1,checked:"1"==MODx.config.hidemenu_default?1:0},{xtype:"xcheckbox",boxLabel:_("resource_published"),description:"<b>[[*published]]</b><br />"+_("resource_published_help"),hideLabel:!0,name:"published",id:"modx-"+this.ident+"-published",inputValue:1,checked:"1"==MODx.config.publish_default?1:0},{xtype:"xcheckbox",boxLabel:_("deleted"),description:"<b>[[*deleted]]</b><br />"+_("resource_delete"),hideLabel:!0,name:"deleted",id:"modx-"+this.ident+"-deleted",inputValue:1,checked:"1"==MODx.config.deleted_default?1:0}]}]},MODx.getQRContentField(this.ident,config.record.class_key)]},{id:"modx-"+this.ident+"-settings",title:_("settings"),layout:"form",cls:"modx-panel",autoHeight:!0,forceLayout:!0,labelWidth:100,defaults:{autoHeight:!0,border:!1},items:MODx.getQRSettings(this.ident,config.record)}]}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreateResource.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreateResource,MODx.Window),Ext.reg("modx-window-quick-create-modResource",MODx.window.QuickCreateResource),MODx.window.QuickUpdateResource=function(config){config=config||{},this.ident=config.ident||"qur"+Ext.id(),Ext.applyIf(config,{title:_("quick_update_resource"),id:this.ident,action:"Resource/Update",buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdateResource.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdateResource,MODx.window.QuickCreateResource),Ext.reg("modx-window-quick-update-modResource",MODx.window.QuickUpdateResource),MODx.getQRContentField=function(id,cls){id=id||"qur",cls=cls||"MODX\\Revolution\\modDocument";Ext.getBody().getViewSize();var o={};switch(cls){case"MODX\\Revolution\\modSymLink":o={xtype:"textfield",fieldLabel:_("symlink"),name:"content",id:"modx-"+id+"-content",anchor:"100%",maxLength:255};break;case"MODX\\Revolution\\modWebLink":o={xtype:"textfield",fieldLabel:_("weblink"),name:"content",id:"modx-"+id+"-content",anchor:"100%",maxLength:255,value:""};break;case"MODX\\Revolution\\modStaticResource":o={xtype:"modx-combo-browser",browserEl:"modx-browser",prependPath:!1,prependUrl:!1,fieldLabel:_("static_resource"),name:"content",id:"modx-"+id+"-content",anchor:"100%",maxLength:255,value:"",listeners:{select:{fn:function(data){"/"==data.url.substring(0,1)&&Ext.getCmp("modx-"+id+"-content").setValue(data.url.substring(1))},scope:this}}};break;default:o={xtype:"textarea",name:"content",id:"modx-"+id+"-content",fieldLabel:_("content"),labelSeparator:"",anchor:"100%",style:"min-height: 200px",grow:!0}}return o},MODx.getQRSettings=function(id,va){return[{layout:"column",border:!1,anchor:"100%",defaults:{labelSeparator:"",labelAlign:"top",border:!1,layout:"form"},items:[{columnWidth:.5,items:[{xtype:"hidden",name:"parent",id:"modx-"+(id=id||"qur")+"-parent",value:va.parent},{xtype:"hidden",name:"context_key",id:"modx-"+id+"-context_key",value:va.context_key},{xtype:"hidden",name:"class_key",id:"modx-"+id+"-class_key",value:va.class_key},{xtype:"hidden",name:"publishedon",id:"modx-"+id+"-publishedon",value:va.publishedon},{xtype:"modx-field-parent-change",fieldLabel:_("resource_parent"),description:"<b>[[*parent]]</b><br />"+_("resource_parent_help"),name:"parent-cmb",id:"modx-"+id+"-parent-change",value:va.parent||0,anchor:"100%",parentcmp:"modx-"+id+"-parent",contextcmp:"modx-"+id+"-context_key",currentid:va.id||0},{xtype:"modx-combo-class-derivatives",fieldLabel:_("resource_type"),description:"<b>[[*class_key]]</b><br />",name:"class_key",hiddenName:"class_key",id:"modx-"+id+"-class-key",anchor:"100%",value:null!=va.class_key?va.class_key:"MODX\\Revolution\\modDocument"},{xtype:"modx-combo-content-type",fieldLabel:_("resource_content_type"),description:"<b>[[*content_type]]</b><br />"+_("resource_content_type_help"),name:"content_type",hiddenName:"content_type",id:"modx-"+id+"-type",anchor:"100%",value:null!=va.content_type?va.content_type:MODx.config.default_content_type||1},{xtype:"modx-combo-content-disposition",fieldLabel:_("resource_contentdispo"),description:"<b>[[*content_dispo]]</b><br />"+_("resource_contentdispo_help"),name:"content_dispo",hiddenName:"content_dispo",id:"modx-"+id+"-dispo",anchor:"100%",value:null!=va.content_dispo?va.content_dispo:0},{xtype:"numberfield",fieldLabel:_("resource_menuindex"),description:"<b>[[*menuindex]]</b><br />"+_("resource_menuindex_help"),name:"menuindex",id:"modx-"+id+"-menuindex",width:75,value:va.menuindex||0}]},{columnWidth:.5,items:[{xtype:"xdatetime",fieldLabel:_("resource_publishedon"),description:"<b>[[*publishedon]]</b><br />"+_("resource_publishedon_help"),name:"publishedon",id:"modx-"+id+"-publishedon",allowBlank:!0,dateFormat:MODx.config.manager_date_format,timeFormat:MODx.config.manager_time_format,startDay:parseInt(MODx.config.manager_week_start),dateWidth:153,timeWidth:153,offset_time:MODx.config.server_offset_time,value:va.publishedon},{xtype:va.canpublish?"xdatetime":"hidden",fieldLabel:_("resource_publishdate"),description:"<b>[[*pub_date]]</b><br />"+_("resource_publishdate_help"),name:"pub_date",id:"modx-"+id+"-pub-date",allowBlank:!0,dateFormat:MODx.config.manager_date_format,timeFormat:MODx.config.manager_time_format,startDay:parseInt(MODx.config.manager_week_start),dateWidth:153,timeWidth:153,offset_time:MODx.config.server_offset_time,value:va.pub_date},{xtype:va.canpublish?"xdatetime":"hidden",fieldLabel:_("resource_unpublishdate"),description:"<b>[[*unpub_date]]</b><br />"+_("resource_unpublishdate_help"),name:"unpub_date",id:"modx-"+id+"-unpub-date",allowBlank:!0,dateFormat:MODx.config.manager_date_format,timeFormat:MODx.config.manager_time_format,startDay:parseInt(MODx.config.manager_week_start),dateWidth:153,timeWidth:153,offset_time:MODx.config.server_offset_time,value:va.unpub_date},{xtype:"xcheckbox",boxLabel:_("resource_folder"),description:_("resource_folder_help"),hideLabel:!0,name:"isfolder",id:"modx-"+id+"-isfolder",inputValue:1,checked:null!=va.isfolder&&va.isfolder},{xtype:"xcheckbox",boxLabel:_("resource_show_in_tree"),description:_("resource_show_in_tree_help"),hideLabel:!0,name:"show_in_tree",id:"modx-"+id+"-show_in_tree",inputValue:1,checked:null!=va.show_in_tree?va.show_in_tree:1},{xtype:"xcheckbox",boxLabel:_("resource_hide_children_in_tree"),description:_("resource_hide_children_in_tree_help"),hideLabel:!0,name:"hide_children_in_tree",id:"modx-"+id+"-hide_children_in_tree",inputValue:1,checked:null!=va.hide_children_in_tree&&va.hide_children_in_tree},{xtype:"xcheckbox",boxLabel:_("resource_alias_visible"),description:_("resource_alias_visible_help"),hideLabel:!0,name:"alias_visible",id:"modx-"+id+"-alias-visible",inputValue:1,checked:null!=va.alias_visible?va.alias_visible:1},{xtype:"xcheckbox",boxLabel:_("resource_uri_override"),description:_("resource_uri_override_help"),hideLabel:!0,name:"uri_override",id:"modx-"+id+"-uri-override",value:1,checked:!!parseInt(va.uri_override),listeners:{check:{fn:MODx.handleFreezeUri}}},{xtype:"textfield",fieldLabel:_("resource_uri"),description:"<b>[[*uri]]</b><br />"+_("resource_uri_help"),name:"uri",id:"modx-"+id+"-uri",maxLength:255,anchor:"100%",value:va.uri||"",hidden:!va.uri_override},{xtype:"xcheckbox",boxLabel:_("resource_richtext"),description:_("resource_richtext_help"),hideLabel:!0,name:"richtext",id:"modx-"+id+"-richtext",inputValue:1,checked:void 0!==va.richtext?va.richtext?1:0:"1"==MODx.config.richtext_default?1:0},{xtype:"xcheckbox",boxLabel:_("resource_searchable"),description:_("resource_searchable_help"),hideLabel:!0,name:"searchable",id:"modx-"+id+"-searchable",inputValue:1,checked:void 0!==va.searchable?va.searchable?1:0:"1"==MODx.config.search_default?1:0,listeners:{check:{fn:MODx.handleQUCB}}},{xtype:"xcheckbox",boxLabel:_("resource_cacheable"),description:_("resource_cacheable_help"),hideLabel:!0,name:"cacheable",id:"modx-"+id+"-cacheable",inputValue:1,checked:void 0!==va.cacheable?va.cacheable?1:0:"1"==MODx.config.cache_default?1:0},{xtype:"xcheckbox",name:"clearCache",id:"modx-"+id+"-clearcache",boxLabel:_("resource_syncsite"),description:_("resource_syncsite_help"),hideLabel:!0,inputValue:1,checked:void 0!==va.clearCache?va.clearCache?1:0:"1"==MODx.config.syncsite_default?1:0}]}]}]},MODx.handleQUCB=function(cb){var h=Ext.getCmp(cb.id+"-hd");cb.checked&&h?(cb.setValue(1),h.setValue(1)):h&&(cb.setValue(0),h.setValue(0))},MODx.handleFreezeUri=function(cb){var uri=Ext.getCmp(cb.id.replace("-override",""));if(!uri)return!1;cb.checked?uri.show():uri.hide()},Ext.override(Ext.tree.AsyncTreeNode,{listeners:{click:{fn:function(){return console.log("Clicked me!",arguments),!1},scope:this}}}),MODx.window.CreateResource=function(config={}){this.ident=config.ident||`tplpick${Ext.id()}`;const id=this.ident,requireAlias=parseInt(MODx.config.friendly_urls,10)&&!parseInt(MODx.config.automatic_alias,10),aliasLength=parseInt(MODx.config.friendly_alias_max_length,10)||0,resourceDetail=[{columnWidth:requireAlias?.33:.5,items:[{xtype:"modx-combo-class-derivatives",fieldLabel:_("resource_type"),description:MODx.expandHelp?"":_("resource_type_help"),name:"class_key",hiddenName:"class_key",anchor:"100%",allowBlank:!1,value:config.record.class_key||"MODX\\Revolution\\modDocument"}]},{columnWidth:requireAlias?.33:.5,items:[{xtype:"modx-field-parent-change",fieldLabel:_("resource_parent"),description:`<b>[[*parent]]</b><br>${_("resource_parent_help")}`,name:"parent-cmb",id:`modx-${id}-parent-change`,value:config.record.parent||0,anchor:"100%",parentcmp:"modx-template-picker-parent-id",contextcmp:"modx-template-picker-parent-context",currentid:id}]}];requireAlias&&resourceDetail.push({columnWidth:.34,defaults:{anchor:"100%",enableKeyEvents:!0,validationEvent:"change",validateOnBlur:!1,msgTarget:"under"},items:[{xtype:"textfield",fieldLabel:_("resource_alias"),name:"alias",allowBlank:!1,maxLength:aliasLength>191||0===aliasLength?191:aliasLength,value:config.record.alias||"",listeners:{afterrender:function(){this.clearInvalid()}}}]}),Ext.applyIf(config,{autoHeight:!0,title:_("document_new"),url:MODx.config.connector_url,baseParams:{action:"Resource/Create"},width:600,fields:[{xtype:"textfield",fieldLabel:_("resource_pagetitle"),description:MODx.expandHelp?"":_("resource_pagetitle_help"),name:"pagetitle",maxLength:191,anchor:"100%",allowBlank:!1,validationEvent:"change",validateOnBlur:!1,value:config.record.pagetitle||"",listeners:{afterrender:function(){this.clearInvalid()}}},{xtype:"hidden",name:"parent",id:"modx-template-picker-parent-id"},{xtype:"hidden",name:"context_key",id:"modx-template-picker-parent-context"},{layout:"column",defaults:{layout:"form",labelSeparator:""},items:resourceDetail},{xtype:"modx-panel-template-picker",fieldLabel:_("resource_template"),description:MODx.expandHelp?"":_("resource_template_help"),name:"template",value:config.record.template||MODx.config.default_template}]}),MODx.window.CreateResource.superclass.constructor.call(this,config)},Ext.extend(MODx.window.CreateResource,MODx.Window),Ext.reg("modx-window-create-resource",MODx.window.CreateResource),MODx.panel.TemplatePicker=function(config){config=config||{},Ext.applyIf(config,{xtype:"panel",layout:"form",labelSeparator:"",items:[{layout:"column",defaults:{layout:"form",labelSeparator:""},items:[{columnWidth:.4,items:[{xtype:"modx-combo-template-picker",id:"modx-resource-template-picker",name:"template",value:config.record||MODx.config.default_template,listeners:{select:{fn:this.setPreview,scope:this}}}]},{columnWidth:.6,items:[{xtype:"modx-panel-template-preview",id:"modx-resource-template-preview"}]}]}]}),MODx.panel.TemplatePicker.superclass.constructor.call(this,config)},Ext.extend(MODx.panel.TemplatePicker,Ext.Panel,{setPreview:function(record){Ext.getCmp("modx-resource-template-preview").setPreview(record)}}),Ext.reg("modx-panel-template-picker",MODx.panel.TemplatePicker),MODx.combo.TemplatePicker=function(config){config=config||{},Ext.applyIf(config,{cls:"x-form-template-picker",layout:"form",defaults:{hideLabel:!0},items:[{xtype:"textfield",itemCls:"x-form-template-picker-search",cls:"x-form-field-search",anchor:"100%",emptyText:_("search"),listeners:{keyup:{fn:this.filterItems,scope:this}},enableKeyEvents:!0}],store:new Ext.data.JsonStore({url:MODx.config.connector_url,baseParams:{action:"Element/Template/GetList",combo:!0,limit:0},root:"results",totalProperty:"total",fields:["id","templatename","description","category_name","preview"],errorReader:MODx.util.JSONReader,autoDestroy:!0,autoLoad:!0,listeners:{load:{fn:this.loadItems,scope:this},loadexception:{fn:function(o,trans,resp){var status=_("code")+": "+resp.status+" "+resp.statusText+"<br/>";MODx.msg.alert(_("error"),status+resp.responseText)}}}})}),MODx.combo.TemplatePicker.superclass.constructor.call(this,config)},Ext.extend(MODx.combo.TemplatePicker,Ext.Panel,{loadItems:function(store,data){var value=this.value,items=[],category="";Ext.each(data,(function(record){category!==record.data.category_name&&(Ext.isEmpty(record.data.category_name)||items.push({hideLabel:!0,boxLabel:record.data.category_name,disabled:!0,itemCls:"x-form-template-picker-category"})),items.push({hideLabel:!0,boxLabel:record.data.templatename,name:this.name||"template",inputValue:record.data.id,itemCls:"x-form-template-picker-item",record,checked:record.data.id==value}),category=record.data.category_name}),this),this.add({xtype:"radiogroup",id:"modx-template-picker-templates",itemCls:"x-form-template-picker-templates",columns:1,items,listeners:{render:{fn:function(cmp){const record=cmp.getValue()?.record;record&&this.fireEvent("select",record)},scope:this},change:{fn:function(cmp,checked){checked.record&&this.fireEvent("select",checked.record)},scope:this}}}),this.doLayout()},filterItems:function(tf){void 0!==(panel=Ext.getCmp("modx-template-picker-templates"))&&panel.items.each((function(object){if(!Ext.isEmpty(tf.getValue())&&object.record){var regex=new RegExp(tf.getValue(),"i");-1===object.record.data.templatename.search(regex)?object.hide():object.show()}else object.show()}))}}),Ext.reg("modx-combo-template-picker",MODx.combo.TemplatePicker),MODx.panel.TemplatePreview=function(config){config=config||{},Ext.applyIf(config,{cls:"x-form-template-preview"}),MODx.panel.TemplatePreview.superclass.constructor.call(this,config)},Ext.extend(MODx.panel.TemplatePreview,Ext.Panel,{setPreview:function(record){if(this.removeAll(),""==record.data.preview||void 0===record.data.preview){this.addClass("x-form-template-preview-empty");var html=""}else{this.removeClass("x-form-template-preview-empty");html='<img src="'+record.data.preview+'" alt="'+record.data.templatename+'" />'}this.add({xtype:"box",autoEl:{tag:"div",cls:"x-form-template-preview-image",html},hidden:""==record.data.image},{xtype:"box",autoEl:{tag:"div",cls:"x-form-template-preview-desc",html:"<p>"+record.data.description+"</p>"},hidden:""==record.data.description}),this.doLayout()}}),Ext.reg("modx-panel-template-preview",MODx.panel.TemplatePreview),MODx.tree.Element=function(config){config=config||{},Ext.applyIf(config,{rootVisible:!1,enableDD:!Ext.isEmpty(MODx.config.enable_dragdrop),ddGroup:"modx-treedrop-elements-dd",title:"",url:MODx.config.connector_url,action:"Element/GetNodes",sortAction:"Element/Sort",baseParams:{currentElement:MODx.request.id||0,currentAction:MODx.request.a||0}}),MODx.tree.Element.superclass.constructor.call(this,config),this.on("afterSort",this.afterSort)},Ext.extend(MODx.tree.Element,MODx.tree.Tree,{forms:{},windows:{},stores:{},getToolbar:function(){return[]},createCategory:function(n,e){var r={};this.cm.activeNode&&this.cm.activeNode.attributes.data&&(r.parent=this.cm.activeNode.attributes.data.id),MODx.load({xtype:"modx-window-category-create",record:r,listeners:{success:{fn:function(){var node=this.cm.activeNode?this.cm.activeNode.id:"n_category",self=-1!==node.indexOf("_category_");this.refreshNode(node,self)},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},renameCategory:function(itm,e){var r=this.cm.activeNode.attributes.data,w=MODx.load({xtype:"modx-window-category-rename",record:r,listeners:{success:{fn:function(r){var c=r.a.result.object,n=this.cm.activeNode;n.setText(c.category+" ("+c.id+")"),Ext.get(n.getUI().getEl()).frame(),n.attributes.data.id=c.id,n.attributes.data.category=c.category,n.attributes.data.rank=c.rank},scope:this},hide:{fn:function(){this.destroy()}}}});w.show(e.target)},removeCategory:function(itm,e){var id=this.cm.activeNode.attributes.data.id;MODx.msg.confirm({title:_("warning"),text:_("category_confirm_delete"),url:MODx.config.connector_url,params:{action:"Element/Category/Remove",id},listeners:{success:{fn:function(){this.cm.activeNode.remove()},scope:this}}})},duplicateElement:function(itm,e,id,type){MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"element/"+type+"/get",id},listeners:{success:{fn:function(results){var rec={id,type,name:_("duplicate_of",{name:this.cm.activeNode.attributes.name}),caption:_("duplicate_of",{name:this.cm.activeNode.attributes.caption}),category:results.object.category,source:results.object.source,static:results.object.static,static_file:results.object.static_file};MODx.load({xtype:"modx-window-element-duplicate",record:rec,redirect:!1,listeners:{success:{fn:function(r){var response=Ext.decode(r.a.response.responseText);response.object.redirect?MODx.loadPage("element/"+rec.type+"/update","id="+response.object.id):this.refreshNode(this.cm.activeNode.id)},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},scope:this}}})},extractElementIdentifiersFromActiveNode:function(activeNode){let startIndex;const extractedData={};switch(!0){case 0===activeNode.id.indexOf("n_type_"):startIndex=7;break;case 0===activeNode.id.indexOf("n_c_"):startIndex=4;break;default:startIndex=2}const identifiers=activeNode.id.substr(startIndex).split("_");switch([extractedData.type]=identifiers,identifiers.length){case 4:return{...extractedData,elementId:parseInt(identifiers[2],10),categoryId:parseInt(identifiers[3],10)};case 3:return{...extractedData,categoryId:parseInt(identifiers[2],10)};case 1:return extractedData}return!1},removeElement:function(itm,e){const elementIdentifiers=this.extractElementIdentifiersFromActiveNode(this.cm.activeNode);MODx.msg.confirm({title:_("warning"),text:_("remove_this_confirm",{type:_(elementIdentifiers.type),name:this.cm.activeNode.attributes.name}),url:MODx.config.connector_url,params:{action:`element/${elementIdentifiers.type}/remove`,id:elementIdentifiers.elementId},listeners:{success:{fn:function(){this.cm.activeNode.remove(),MODx.request.a===`element/${elementIdentifiers.type}/update`&&parseInt(MODx.request.id,10)===elementIdentifiers.elementId&&MODx.loadPage("welcome")},scope:this}}})},activatePlugin:function(itm,e){const elementIdentifiers=this.extractElementIdentifiersFromActiveNode(this.cm.activeNode);MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Element/Plugin/Activate",id:elementIdentifiers.elementId},listeners:{success:{fn:function(){this.refreshParentNode()},scope:this}}})},deactivatePlugin:function(itm,e){const elementIdentifiers=this.extractElementIdentifiersFromActiveNode(this.cm.activeNode);MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Element/Plugin/Deactivate",id:elementIdentifiers.elementId},listeners:{success:{fn:function(){this.refreshParentNode()},scope:this}}})},quickCreate:function(itm,e,type){var r={category:this.cm.activeNode.attributes.pk||""},w=MODx.load({xtype:"modx-window-quick-create-"+type,record:r,listeners:{success:{fn:function(){this.refreshNode(this.cm.activeNode.id,!0)},scope:this},hide:{fn:function(){this.destroy()}}}});w.setValues(r),w.show(e.target)},quickUpdate:function(itm,e,type){MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"element/"+type+"/get",id:this.cm.activeNode.attributes.pk},listeners:{success:{fn:function(r){var nameField="template"==type?"templatename":"name",w=MODx.load({xtype:"modx-window-quick-update-"+type,record:r.object,listeners:{success:{fn:function(r){this.refreshNode(this.cm.activeNode.id);var newTitle='<span dir="ltr">'+r.f.findField(nameField).getValue()+" ("+w.record.id+")</span>";w.setTitle(w.title.replace(/<span.*\/span>/,newTitle))},scope:this},hide:{fn:function(){this.destroy()}}}});w.title+=': <span dir="ltr">'+w.record[nameField]+" ("+w.record.id+")</span>",w.setValues(r.object),w.show(e.target)},scope:this}}})},_createElement:function(itm,e,t){const elementIdentifiers=this.extractElementIdentifiersFromActiveNode(this.cm.activeNode);return this.redirect(`?a=element/${elementIdentifiers.type}/create&category=${elementIdentifiers.categoryId}`),this.cm.hide(),!1},afterSort:function(o){var tn=o.event.target.attributes;if("category"==tn.type){var dn=o.event.dropNode.attributes;"n_category"!=tn.id&&"category"==dn.type?o.event.target.expand():(this.refreshNode(o.event.target.attributes.id,!0),this.refreshNode("n_type_"+o.event.dropNode.attributes.type,!0))}},_handleDrop:function(e){var target=e.target;return"above"!=e.point&&"below"!=e.point&&(("MODX\\Revolution\\modCategory"==target.attributes.classKey||"root"==target.attributes.classKey)&&(!!this.isCorrectType(e.dropNode,target)&&("category"==target.attributes.type&&"append"==e.point||target.getDepth()>0)))},isCorrectType:function(dropNode,targetNode){var r=!1;return targetNode.attributes.type==dropNode.attributes.type&&(targetNode.parentNode&&("folder"==dropNode.attributes.cls&&"folder"==targetNode.attributes.cls&&dropNode.parentNode.id==targetNode.parentNode.id||"file"==targetNode.attributes.cls)||(r=!0)),r},_showContextMenu:function(n,e){if(this.cm.activeNode=n,this.cm.removeAll(),n.attributes.menu&&n.attributes.menu.items)this.addContextMenuItem(n.attributes.menu.items),this.cm.show(n.getUI().getEl(),"t?");else{var m=[];switch(n.attributes.classKey){case"root":m=this._getRootMenu(n);break;case"MODX\\Revolution\\modCategory":m=this._getCategoryMenu(n);break;default:m=this._getElementMenu(n)}this.addContextMenuItem(m),this.cm.showAt(e.xy)}e.stopEvent()},_getQuickCreateMenu:function(n,m){for(var t,ui=n.getUI(),mn=[],types=["template","tv","chunk","snippet","plugin"],i=0;i<types.length;i++)t=types[i],ui.hasClass("pnew_"+t)&&mn.push({text:_(t),scope:this,type:t,handler:function(itm,e){this.quickCreate(itm,e,itm.type)}});return mn.length>0&&m.push({text:_("quick_create"),handler:function(){return!1},menu:{items:mn}}),m},_getElementMenu:function(n){var a=n.attributes,ui=n.getUI(),m=[];return m.push({text:"<b>"+a.text+"</b>",handler:function(){return!1},header:!0}),m.push("-"),ui.hasClass("pedit")&&(m.push({text:_("edit_"+a.type),type:a.type,pk:a.pk,handler:function(itm,e){MODx.loadPage("element/"+itm.type+"/update","id="+itm.pk)}}),m.push({text:_("quick_update_"+a.type),type:a.type,handler:function(itm,e){this.quickUpdate(itm,e,itm.type)}}),"MODX\\Revolution\\modPlugin"===a.classKey&&(a.active?m.push({text:_("plugin_deactivate"),type:a.type,handler:this.deactivatePlugin}):m.push({text:_("plugin_activate"),type:a.type,handler:this.activatePlugin}))),ui.hasClass("pnew")&&m.push({text:_("duplicate_"+a.type),pk:a.pk,type:a.type,handler:function(itm,e){this.duplicateElement(itm,e,itm.pk,itm.type)}}),ui.hasClass("pdelete")&&(m.push("-"),m.push({text:_("remove_"+a.type),handler:this.removeElement})),m.push("-"),ui.hasClass("pnew")&&m.push({text:_("add_to_category_"+a.type),handler:this._createElement}),ui.hasClass("pnewcat")&&m.push({text:_("category_create"),handler:this.createCategory}),m},_getCategoryMenu:function(n){var a=n.attributes,ui=n.getUI(),m=[];return m.push({text:"<b>"+a.text+"</b>",handler:function(){return!1},header:!0}),m.push("-"),ui.hasClass("pnewcat")&&m.push({text:_("category_create"),handler:this.createCategory}),ui.hasClass("peditcat")&&m.push({text:_("category_rename"),handler:this.renameCategory}),m.length>2&&m.push("-"),ui.hasClass("pnew_"+a.type)&&m.push({text:_("add_to_category_"+a.type),handler:this._createElement}),this._getQuickCreateMenu(n,m),ui.hasClass("pdelcat")&&(m.push("-"),m.push({text:_("category_remove"),handler:this.removeCategory})),m},_getRootMenu:function(n){var a=n.attributes,ui=n.getUI(),m=[];if(ui.hasClass("pnew")&&(m.push({text:_("new_"+a.type),handler:this._createElement}),m.push({text:_("quick_create_"+a.type),type:a.type,handler:function(itm,e){this.quickCreate(itm,e,itm.type)}})),ui.hasClass("pnewcat")&&(ui.hasClass("pnew")&&m.push("-"),m.push({text:_("category_create"),handler:this.createCategory})),n.isLoaded()){var childNodes=n.childNodes;childNodes.some((function(child){return!child.leaf}))&&(m.push("-"),n.isExpanded()&&childNodes.some((function(child){return child.isExpanded()}))&&m.push({text:_("collapse_all"),handler:function(){n.collapseChildNodes()}}),m.push({text:_("expand_all"),handler:function(){n.isExpandable()&&n.expand(!0)}}))}return m},handleCreateClick:function(node){this.cm.activeNode=node,"category"!=this.cm.activeNode.id.substr(2).split("_")[0]?this._createElement(null,null,null):this.createCategory(null,{target:this})}}),Ext.reg("modx-tree-element",MODx.tree.Element),MODx.tree.Directory=function(config){(config=config||{}).id=config.id||Ext.id(),Ext.applyIf(config,{rootVisible:!0,rootName:"Filesystem",rootId:"/",title:_("files"),ddAppendOnly:!0,ddGroup:"modx-treedrop-sources-dd",url:MODx.config.connector_url,hideSourceCombo:!1,baseParams:{hideFiles:config.hideFiles||!1,hideTooltips:config.hideTooltips||!1,wctx:MODx.ctx||"web",currentAction:MODx.request.a||0,currentFile:MODx.request.file||"",source:config.source||0},action:"Browser/Directory/GetList",primaryKey:"dir",useDefaultToolbar:!0,autoExpandRoot:!1,tbar:[{cls:"x-btn-icon icon-folder",tooltip:{text:_("file_folder_create")},handler:this.createDirectory,scope:this,hidden:!MODx.perm.directory_create},{cls:"x-btn-icon icon-page_white",tooltip:{text:_("file_create")},handler:this.quickCreateFile,scope:this,hidden:!MODx.perm.file_create},{cls:"x-btn-icon icon-file_upload",tooltip:{text:_("upload_files")},handler:this.uploadFiles,scope:this,hidden:!MODx.perm.file_upload},"->",{cls:"x-btn-icon icon-file_manager",tooltip:{text:_("modx_browser")},handler:this.loadFileManager,scope:this,hidden:!(MODx.perm.file_manager&&!MODx.browserOpen)}],tbarCfg:{id:config.id+"-tbar"}}),MODx.tree.Directory.superclass.constructor.call(this,config),this.addEvents({beforeUpload:!0,afterUpload:!0,afterQuickCreate:!0,afterRename:!0,afterRemove:!0,fileBrowserSelect:!0,changeSource:!0,afterSort:!0}),this.on("click",(function(n,e){n.select(),this.cm.activeNode=n}),this),this.on("render",(function(){var el=Ext.get(this.config.id);el.createChild({tag:"div",id:this.config.id+"_tb"}),el.createChild({tag:"div",id:this.config.id+"_filter"}),this.addSourceToolbar()}),this),this.on("show",(function(){if(!this.config.hideSourceCombo)try{this.sourceCombo.show()}catch(e){}}),this),this._init(),this.on("afterrender",this.showRefresh,this),this.on("afterSort",this._handleAfterDrop,this),this.on("click",(function(e){null!=this.uploader&&this.uploader.setBaseParams({path:e.id})})),this.uploader=new MODx.util.MultiUploadDialog.Upload({url:MODx.config.connector_url,base_params:{action:"Browser/File/Upload",wctx:MODx.ctx||"",source:this.getSource()}}),this.uploader.on("beforeupload",this.beforeUpload,this),this.uploader.on("uploadsuccess",this.uploadSuccess,this),this.uploader.on("uploaderror",this.uploadError,this),this.uploader.on("uploadfailed",this.uploadFailed,this)},Ext.extend(MODx.tree.Directory,MODx.tree.Tree,{windows:{},getRootMenu:function(node){var menu=[];return MODx.perm.directory_create&&menu.push({text:_("file_folder_create"),handler:this.createDirectory,scope:this}),MODx.perm.file_create&&menu.push({text:_("file_create"),handler:this.createFile,scope:this}),MODx.perm.file_upload&&menu.push({text:_("upload_files"),handler:this.uploadFiles,scope:this}),node.ownerTree.el.hasClass("pupdate")&&menu.push(["-",{text:_("edit"),handler:function(){MODx.loadPage("source/update","id="+node.ownerTree.source)}}]),menu},_showContextMenu:function(node,e){this.cm.activeNode=node,this.cm.removeAll();var m=[];m.push({text:"<b>"+node.attributes.text+"</b>",handler:function(){return!1},header:!0}),m.push("-"),node.isRoot?m=m.concat(this.getRootMenu(node)):node.attributes.menu&&node.attributes.menu.items&&(m=m.concat(node.attributes.menu.items)),m&&m.length>0&&(this.addContextMenuItem(m),this.cm.showAt(e.xy)),e.preventDefault(),e.stopEvent()},showRefresh:function(){var node=this.getRootNode(),inlineButtonsLang=this.getInlineButtonsLang(node),elId=node.ui.elNode.id+"_tools",el=document.createElement("div");el.id=elId,el.className="modx-tree-node-tool-ct",node.ui.elNode.appendChild(el),MODx.load({xtype:"modx-button",text:"",scope:this,tooltip:new Ext.ToolTip({title:inlineButtonsLang.refresh,target:this}),node,handler:function(btn,evt){evt.stopPropagation(evt),node.reload()},iconCls:"icon-refresh",renderTo:elId,listeners:{mouseover:function(button,e){button.tooltip.onTargetOver(e)},mouseout:function(button,e){button.tooltip.onTargetOut(e)}}})},addSourceToolbar:function(){if(this.sourceCombo=new MODx.combo.MediaSource({value:this.config.source||MODx.config.default_media_source,listWidth:236,listeners:{select:{fn:this.changeSource,scope:this},loaded:{fn:function(combo){var rec=combo.store.getById(this.config.source),rn=this.getRootNode();rn&&rec&&rn.setText(rec.data.name)},scope:this}}}),this.searchBar=new Ext.Toolbar({renderTo:this.tbar,id:this.config.id+"-sourcebar",items:[this.sourceCombo]}),this.on("resize",(function(){this.sourceCombo.setWidth(this.getWidth()-12)}),this),this.config.hideSourceCombo)try{this.sourceCombo.hide()}catch(e){}},changeSource:function(sel){this.cm.activeNode="";var s=sel.getValue(),rn=this.getRootNode();rn&&rn.setText(sel.getRawValue()),this.config.baseParams.source=s,this.fireEvent("changeSource",s),this.refresh()},_init:function(){var treeState=Ext.state.Manager.get(this.treestate_id);this.root.getPath("text")!==treeState&&this.root.expand()},_initExpand:function(){var treeState=Ext.state.Manager.get(this.treestate_id);Ext.isEmpty(this.config.openTo)?this.expandPath(treeState,"text"):this.selectPath("/"+_("files")+"/"+this.config.openTo,"text")},_saveState:function(n){n.expanded||n.isRoot||(n=n.parentNode),n.id==this.config.openTo&&n.select();var p=n.getPath("text");Ext.state.Manager.set(this.treestate_id,p)},_handleAfterDrop:function(o,r){var targetNode=o.event.target,dropNode=o.event.dropNode;if("append"==o.event.point&&targetNode){var ui=targetNode.getUI();ui.addClass("haschildren"),ui.removeClass("icon-resource")}if("resource/update"===MODx.request.a&&dropNode.attributes.pk==MODx.request.id){var parentFieldCmb=Ext.getCmp("modx-resource-parent"),parentFieldHidden=Ext.getCmp("modx-resource-parent-hidden");parentFieldCmb&&parentFieldHidden&&(parentFieldHidden.setValue(dropNode.parentNode.attributes.pk),parentFieldCmb.setValue(dropNode.parentNode.attributes.text.replace(/(<([^>]+)>)/gi,"")))}targetNode.reload(!0)},_handleDrag:function(dropEvent){var from=dropEvent.dropNode.attributes.id,to=dropEvent.target.attributes.id,orgSource="number"==typeof dropEvent.dropNode.attributes.sid?dropEvent.dropNode.attributes.sid:this.config.baseParams.source,destSource="number"==typeof dropEvent.target.attributes.sid?dropEvent.target.attributes.sid:0;destSource||(destSource=dropEvent.tree.source),MODx.Ajax.request({url:this.config.url,params:{source:orgSource,from,destSource,to,action:this.config.sortAction||"Browser/Directory/Sort",point:dropEvent.point},listeners:{success:{fn:function(r){var el=dropEvent.dropNode.getUI().getTextEl();el&&Ext.get(el).frame(),this.fireEvent("afterSort",{event:dropEvent,result:r})},scope:this},failure:{fn:function(r){return MODx.form.Handler.errorJSON(r),this.refresh(),""!=r.message?MODx.msg.alert(_("error"),r.message):r.data&&r.data[0]&&MODx.msg.alert(r.data[0].id,r.data[0].msg),!1},scope:this}}})},getPath:function(node){let path=node?.attributes?.path||"";return path=path.replace(/^[\/\.]*/,""),path+"/"},editFile:function(itm,e){MODx.loadPage("system/file/edit","file="+this.cm.activeNode.attributes.id+"&source="+this.config.source)},openFile:function(itm,e){this.cm.activeNode.attributes.urlExternal&&window.open(this.cm.activeNode.attributes.urlExternal)},quickUpdateFile:function(itm,e){var node=this.cm.activeNode;MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Browser/File/Get",file:node.attributes.id,wctx:MODx.ctx||"",source:this.getSource()},listeners:{success:{fn:function(response){var r={file:node.attributes.id,name:node.text,path:node.attributes.pathRelative,source:this.getSource(),content:response.object.content};MODx.load({xtype:"modx-window-file-quick-update",record:r,listeners:{hide:{fn:function(){this.destroy()}}}}).show(e.target)},scope:this}}})},createFile:function(itm,e){var active=this.cm.activeNode,dir="";if(active&&active.attributes)if(active.isRoot||"dir"===active.attributes.type)dir=active.attributes.id;else if("file"===active.attributes.type){var path=active.attributes.path;dir=path.substr(0,path.lastIndexOf("/")+1)}MODx.loadPage("system/file/create","directory="+dir+"&source="+this.getSource())},quickCreateFile:function(itm,e){var node=this.cm.activeNode,r={directory:node?decodeURIComponent(node.attributes.id):"/",source:this.getSource()};MODx.load({xtype:"modx-window-file-quick-create",record:r,listeners:{success:{fn:function(r){this.fireEvent("afterQuickCreate"),this.refreshActiveNode()},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},browser:null,loadFileManager:function(btn,e){var refresh=!1;null===this.browser?this.browser=MODx.load({xtype:"modx-browser",hideFiles:MODx.config.modx_browser_tree_hide_files,rootId:"/",wctx:MODx.ctx,source:this.config.baseParams.source,listeners:{select:{fn:function(data){this.fireEvent("fileBrowserSelect",data)},scope:this}}}):refresh=!0,this.browser&&(this.browser.setSource(this.config.baseParams.source),refresh&&this.browser.win.tree.refresh(),this.browser.show())},renameNode:function(field,nv,ov){MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Browser/File/Rename",new_name:nv,old_name:ov,file:this.treeEditor.editNode.id,wctx:MODx.ctx||"",source:this.getSource()},listeners:{success:{fn:function(r){this.fireEvent("afterRename"),this.refreshActiveNode()},scope:this}}})},renameDirectory:function(item,e){var node=this.cm.activeNode,r={old_name:node.text,name:node.text,path:node.attributes.pathRelative,source:this.getSource()};MODx.load({xtype:"modx-window-directory-rename",record:r,listeners:{success:{fn:this.refreshParentNode,scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},renameFile:function(item,e){var node=this.cm.activeNode,r={old_name:node.text,name:node.text,path:node.attributes.pathRelative,source:this.getSource()};MODx.load({xtype:"modx-window-file-rename",record:r,listeners:{success:{fn:function(r){this.fireEvent("afterRename"),this.refreshParentNode()},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},createDirectory:function(item,e){var node=!(!this.cm||!this.cm.activeNode)&&this.cm.activeNode,r={parent:node&&"dir"==node.attributes.type?node.attributes.pathRelative:"/",source:this.getSource()};MODx.load({xtype:"modx-window-directory-create",record:r,listeners:{success:{fn:function(){var parent=Ext.getCmp("folder-parent").getValue();this.cm.activeNode&&"constructor"===this.cm.activeNode.constructor.name||""===parent||"/"===parent?this.refresh():this.refreshActiveNode()},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e?e.target:Ext.getBody())},setVisibility:function(item,e){var node=this.cm.activeNode,r={path:node.attributes.path,visibility:node.attributes.visibility,source:this.getSource()};MODx.load({xtype:"modx-window-set-visibility",record:r,listeners:{success:{fn:this.refreshParentNode,scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},removeDirectory:function(item,e){var node=this.cm.activeNode,directory=node.attributes.text;MODx.msg.confirm({text:_("file_folder_remove_confirm",{directory}),url:MODx.config.connector_url,params:{action:"Browser/Directory/Remove",dir:node.attributes.path,wctx:MODx.ctx||"",source:this.getSource()},listeners:{success:{fn:this._afterRemove,scope:this}}})},removeFile:function(item,e){var node=this.cm.activeNode,fileName=node.attributes.text,filePath=node.attributes.pathRelative;MODx.msg.confirm({text:_("file_remove_confirm",{file:fileName}),url:MODx.config.connector_url,params:{action:"Browser/File/Remove",file:filePath,wctx:MODx.ctx||"",source:this.getSource()},listeners:{success:{fn:this._afterRemove,scope:this}}})},_afterRemove:function(){this.fireEvent("afterRemove"),this.refreshParentNode(),this.cm.activeNode=null},unpackFile:function(item,e){var node=this.cm.activeNode;MODx.msg.confirm({text:_("file_download_unzip")+" "+node.attributes.id,url:MODx.config.connectors_url,params:{action:"Browser/File/Unpack",file:node.attributes.id,wctx:MODx.ctx||"",source:this.getSource(),path:node.attributes.directory},listeners:{success:{fn:this.refreshParentNode,scope:this}}})},downloadFile:function(item,e){var node=this.cm.activeNode;MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Browser/File/Download",file:node.attributes.pathRelative,wctx:MODx.ctx||"",source:this.getSource()},listeners:{failure:{fn:function(r){MODx.msg.alert(_("alert"),r.message)},scope:this},success:{fn:function(r){Ext.isEmpty(r.object.url)||(location.href=MODx.config.connector_url+"?action=Browser/File/Download&download=1&file="+r.object.url+"&HTTP_MODAUTH="+MODx.siteId+"&source="+this.getSource()+"&wctx="+MODx.ctx)},scope:this}}})},copyRelativePath:function(item,e){var node=this.cm.activeNode,dummyRelativePathInput=document.createElement("input");document.body.appendChild(dummyRelativePathInput),dummyRelativePathInput.setAttribute("value",node.attributes.pathRelative),dummyRelativePathInput.select(),document.execCommand("copy"),document.body.removeChild(dummyRelativePathInput)},getSource:function(){return this.config.baseParams.source},uploadFiles:function(){this.uploader.setBaseParams({source:this.getSource()}),this.uploader.browser=MODx.config.browserview,this.uploader.show()},uploadError:function(dlg,file,data,rec){},uploadFailed:function(dlg,file,rec){},uploadSuccess:function(){if(this.cm.activeNode){var node=this.cm.activeNode;if(node.isLeaf()){var pn=node.isLeaf()?node.parentNode:node;pn?pn.reload():node.id.match(/.*?\/$/)&&this.refreshActiveNode(),this.fireEvent("afterUpload",node)}else this.refreshActiveNode()}else this.refresh(),this.fireEvent("afterUpload")},beforeUpload:function(){var path=this.config.openTo||this.config.rootId||"/";this.cm.activeNode&&(path=this.getPath(this.cm.activeNode),this.cm.activeNode.isLeaf()&&(path=this.getPath(this.cm.activeNode.parentNode))),this.uploader.setBaseParams({action:"Browser/File/Upload",path,wctx:MODx.ctx||"",source:this.getSource()}),this.fireEvent("beforeUpload",this.cm.activeNode)}}),Ext.reg("modx-tree-directory",MODx.tree.Directory),MODx.window.CreateDirectory=function(config){config=config||{},Ext.applyIf(config,{title:_("file_folder_create"),url:MODx.config.connector_url,action:"Browser/Directory/Create",fields:[{xtype:"hidden",name:"wctx",value:MODx.ctx||""},{xtype:"hidden",name:"source"},{fieldLabel:_("name"),name:"name",xtype:"textfield",anchor:"100%",allowBlank:!1},{fieldLabel:_("file_folder_parent"),id:"folder-parent",name:"parent",xtype:"textfield",anchor:"100%"},{xtype:"label",forId:"folder-parent",html:_("file_folder_parent_desc"),cls:"desc-under"}]}),MODx.window.CreateDirectory.superclass.constructor.call(this,config)},Ext.extend(MODx.window.CreateDirectory,MODx.Window),Ext.reg("modx-window-directory-create",MODx.window.CreateDirectory),MODx.window.SetVisibility=function(config){config=config||{},Ext.applyIf(config,{title:_("file_folder_visibility"),url:MODx.config.connector_url,action:"Browser/Visibility",fields:[{xtype:"hidden",name:"wctx",value:MODx.ctx||""},{xtype:"hidden",name:"source"},{name:"path",fieldLabel:_("file_folder_path"),xtype:"statictextfield",anchor:"100%",submitValue:!0},{fieldLabel:_("file_folder_visibility_label"),name:"visibility",xtype:"modx-combo-visibility",anchor:"100%",allowBlank:!1},{hideLabel:!0,xtype:"displayfield",value:_("file_folder_visibility_desc"),anchor:"100%",allowBlank:!1}]}),MODx.window.SetVisibility.superclass.constructor.call(this,config)},Ext.extend(MODx.window.SetVisibility,MODx.Window),Ext.reg("modx-window-set-visibility",MODx.window.SetVisibility),MODx.window.RenameDirectory=function(config){config=config||{},Ext.applyIf(config,{title:_("rename"),url:MODx.config.connector_url,action:"Browser/Directory/Rename",fields:[{xtype:"hidden",name:"wctx",value:MODx.ctx||""},{xtype:"hidden",name:"source"},{fieldLabel:_("path"),name:"path",xtype:"statictextfield",submitValue:!0,anchor:"100%"},{fieldLabel:_("old_name"),name:"old_name",xtype:"statictextfield",anchor:"100%"},{fieldLabel:_("new_name"),name:"name",xtype:"textfield",anchor:"100%",allowBlank:!1}]}),MODx.window.RenameDirectory.superclass.constructor.call(this,config)},Ext.extend(MODx.window.RenameDirectory,MODx.Window),Ext.reg("modx-window-directory-rename",MODx.window.RenameDirectory),MODx.window.RenameFile=function(config){config=config||{},Ext.applyIf(config,{title:_("rename"),url:MODx.config.connector_url,action:"Browser/File/Rename",fields:[{xtype:"hidden",name:"wctx",value:MODx.ctx||""},{xtype:"hidden",name:"source"},{fieldLabel:_("path"),name:"path",xtype:"statictextfield",submitValue:!0,anchor:"100%"},{fieldLabel:_("old_name"),name:"old_name",xtype:"statictextfield",anchor:"100%"},{fieldLabel:_("new_name"),name:"name",xtype:"textfield",anchor:"100%",allowBlank:!1},{name:"dir",xtype:"hidden"}]}),MODx.window.RenameFile.superclass.constructor.call(this,config)},Ext.extend(MODx.window.RenameFile,MODx.Window),Ext.reg("modx-window-file-rename",MODx.window.RenameFile),MODx.window.QuickUpdateFile=function(config){config=config||{},Ext.applyIf(config,{title:_("file_quick_update"),width:600,layout:"anchor",url:MODx.config.connector_url,action:"Browser/File/Update",fields:[{xtype:"hidden",name:"wctx",value:MODx.ctx||""},{xtype:"hidden",name:"source"},{xtype:"hidden",name:"file"},{fieldLabel:_("name"),name:"name",xtype:"statictextfield",anchor:"100%"},{fieldLabel:_("path"),name:"path",xtype:"statictextfield",anchor:"100%"},{fieldLabel:_("content"),xtype:"textarea",name:"content",anchor:"100%",height:200}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}],buttons:[{text:config.cancelBtnText||_("cancel"),scope:this,handler:function(){this.hide()}},{text:config.saveBtnText||_("save"),scope:this,handler:function(){this.submit(!1)}},{text:config.saveBtnText||_("save_and_close"),cls:"primary-button",scope:this,handler:this.submit}]}),MODx.window.QuickUpdateFile.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickUpdateFile,MODx.Window),Ext.reg("modx-window-file-quick-update",MODx.window.QuickUpdateFile),MODx.window.QuickCreateFile=function(config){config=config||{},Ext.applyIf(config,{title:_("file_quick_create"),width:600,layout:"anchor",url:MODx.config.connector_url,action:"Browser/File/Create",fields:[{xtype:"hidden",name:"wctx",value:MODx.ctx||""},{xtype:"hidden",name:"source"},{fieldLabel:_("directory"),name:"directory",submitValue:!0,xtype:"statictextfield",anchor:"100%"},{xtype:"label",html:_("file_folder_parent_desc"),cls:"desc-under"},{fieldLabel:_("name"),name:"name",xtype:"textfield",anchor:"100%",allowBlank:!1},{fieldLabel:_("content"),xtype:"textarea",name:"content",anchor:"100%",height:200}],keys:[{key:Ext.EventObject.ENTER,shift:!0,fn:this.submit,scope:this}]}),MODx.window.QuickCreateFile.superclass.constructor.call(this,config)},Ext.extend(MODx.window.QuickCreateFile,MODx.Window),Ext.reg("modx-window-file-quick-create",MODx.window.QuickCreateFile),MODx.panel.FileTree=function(config){config=config||{},Ext.applyIf(config,{_treePrefix:"source-tree-",autoHeight:!0,defaults:{autoHeight:!0,border:!1}}),MODx.panel.FileTree.superclass.constructor.call(this,config),this.on("render",this.getSourceList,this)},Ext.extend(MODx.panel.FileTree,Ext.Container,{getSourceList:function(){MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Source/GetList",limit:0},listeners:{success:{fn:function(data){this.onSourceListReceived(data.results)},scope:this},failure:{fn:function(data){return data.total>0&&null!=data.results&&this.onSourceListReceived(data.results),!1},scope:this}}})},onSourceListReceived:function(sources){for(var k=0;k<sources.length;k++){var source=sources[k],exists=this.getComponent(this._treePrefix+source.id);if(!exists)var tree=this.loadTree(source);this.add(tree),tree=exists=void 0}this.doLayout()},loadTree:function(source){var params={};if(location.search)for(var parts=location.search.substring(1).split("&"),i=0;i<parts.length;i++){var nv=parts[i].split("=");nv[0]&&(params[nv[0]]=nv[1]||!0)}var activeSource=params.source,expandSource=!1;return source.id==activeSource&&(expandSource=!0),MODx.load({xtype:"modx-tree-directory",autoExpandRoot:expandSource,itemId:this._treePrefix+source.id,stateId:this._treePrefix+source.id,id:this._treePrefix+source.id,cls:source.cls||"",rootName:source.name,rootQtip:source.description||"",hideSourceCombo:!0,source:source.id,rootIconCls:source.iconCls||"",tbar:!1,tbarCfg:{hidden:!0}})}}),Ext.reg("modx-panel-filetree",MODx.panel.FileTree),Ext.namespace("MODx.browser"),MODx.Browser=function(config){if(MODx.browserOpen&&!config.multiple)return!1;config.multiple||(MODx.browserOpen=!0),config=config||{},Ext.applyIf(config,{onSelect:function(data){},scope:this,source:config.source||1,cls:"modx-browser",closeAction:"hide"}),MODx.Browser.superclass.constructor.call(this,config),this.config=config,this.win=new MODx.browser.Window(config),this.win.reset()},Ext.extend(MODx.Browser,Ext.Component,{show:function(el){this.win&&this.win.show(el)},hide:function(){this.win&&this.win.hide()},setSource:function(source){this.config.source=source,this.win.tree.config.baseParams.source=source,this.win.view.config.baseParams.source=source}}),Ext.reg("modx-browser",MODx.Browser),MODx.browser.View=function(config){config=config||{},this.ident=config.ident+"-view"||"modx-browser-"+Ext.id()+"-view",this._initTemplates(),Ext.applyIf(config,{url:MODx.config.connector_url,id:this.ident,fields:[{name:"name",sortType:Ext.data.SortTypes.asUCString},"cls","url","relativeUrl","fullRelativeUrl","image","original_width","original_height","image_width","image_height","thumb","thumb_width","thumb_height","pathname","pathRelative","ext","disabled","preview",{name:"size",type:"float"},"lastmod","menu","visibility"],baseParams:{action:"Browser/Directory/GetFiles",prependPath:config.prependPath||null,prependUrl:config.prependUrl||null,source:config.source||1,allowedFileTypes:config.allowedFileTypes||"",wctx:config.wctx||"web",dir:config.openTo||""},tpl:"list"===MODx.config.modx_browser_default_viewmode?this.templates.list:this.templates.thumb,itemSelector:"list"===MODx.config.modx_browser_default_viewmode?"div.modx-browser-list-item":"div.modx-browser-thumb-wrap",thumbnails:[],lazyLoad:function(){for(var height=this.getEl().parent().getHeight()+100,i=0;i<this.thumbnails.length;i++){var image=this.thumbnails[i];if(void 0!==image){var rect=image.getBoundingClientRect();rect.top>=0&&rect.left>=0&&rect.top<=height&&(image.src=image.getAttribute("data-src"),delete this.thumbnails[i])}}},refresh:function(){MODx.DataView.prototype.refresh.call(this),this.thumbnails=Array.prototype.slice.call(document.querySelectorAll("img[data-src]")),this.lazyLoad()},listeners:{selectionchange:{fn:this.showDetails,scope:this,buffer:100},dblclick:config.onSelect||{fn:Ext.emptyFn,scope:this},render:{fn:this.sortStore,scope:this},afterrender:{fn:function(){this.getEl().parent().on("scroll",(function(){this.lazyLoad()}),this),null!=this.tree&&null!=this.tree.uploader&&this.tree.uploader.addDropZone(this.ownerCt,this),MODx.config.browserview=this},scope:this}},prepareData:this.formatData.createDelegate(this),multiSelect:!0}),MODx.browser.View.superclass.constructor.call(this,config)},Ext.extend(MODx.browser.View,MODx.DataView,{templates:{},run:function(p){(p=p||{}).dir&&(this.dir=p.dir),Ext.applyIf(p,{action:"Browser/Directory/GetFiles",dir:this.dir,source:this.config.source||MODx.config.default_media_source}),this.mask=new Ext.LoadMask(Ext.getBody(),{msg:_("loading")}),this.mask.show(),this.store.load({params:p,callback:function(rec,options,success){this.mask.hide(),this.refresh(),Ext.getCmp(this.ident+"-filepath").setValue(""),this.select(0)},scope:this})},editFile:function(item,e){var node=this.cm.activeNode,data=this.lookup[node.id];MODx.loadPage("system/file/edit","file="+data.pathRelative+"&source="+this.config.source)},quickUpdateFile:function(item,e){var node=this.cm.activeNode,data=this.lookup[node.id];MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Browser/File/Get",file:data.pathRelative,wctx:MODx.ctx||"",source:this.config.source},listeners:{success:{fn:function(response){var r={file:data.pathRelative,name:data.name,path:decodeURIComponent(data.pathRelative),source:this.config.source,content:response.object.content};MODx.load({xtype:"modx-window-file-quick-update",record:r,listeners:{hide:{fn:function(){this.destroy()}}}}).show(e.target)},scope:this}}})},renameFile:function(item,e){var node=this.cm.activeNode,data=this.lookup[node.id],r={old_name:data.name,name:data.name,path:data.pathRelative,source:this.config.source};MODx.load({xtype:"modx-window-file-rename",record:r,listeners:{success:{fn:function(r){this.config.tree.refreshParentNode(),this.run()},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},downloadFile:function(item,e){var node=this.cm.activeNode,data=this.lookup[node.id];MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Browser/File/Download",file:data.pathRelative,wctx:MODx.ctx||"",source:this.config.source},listeners:{failure:{fn:function(r){MODx.msg.alert(_("alert"),r.message)},scope:this},success:{fn:function(r){Ext.isEmpty(r.object.url)||(location.href=MODx.config.connector_url+"?action=Browser/File/Download&download=1&file="+r.object.url+"&HTTP_MODAUTH="+MODx.siteId+"&source="+this.config.source+"&wctx="+MODx.ctx)},scope:this}}})},copyRelativePath:function(item,e){var node=this.cm.activeNode,data=this.lookup[node.id],dummyRelativePathInput=document.createElement("input");document.body.appendChild(dummyRelativePathInput),dummyRelativePathInput.setAttribute("value",data.pathRelative),dummyRelativePathInput.select(),document.execCommand("copy"),document.body.removeChild(dummyRelativePathInput)},removeFile:function(){var files=[],filesNames=[],selected=this.getSelectedRecords();for(var i in selected)selected.hasOwnProperty(i)&&(files.push(selected[i].id),filesNames.push(selected[i].data.name));MODx.msg.confirm({text:_("file_remove_confirm",{file:filesNames.pop()}),url:MODx.config.connector_url,params:{action:"Browser/File/Remove",file:files.pop(),source:this.config.source,wctx:this.config.wctx||"web"},listeners:{success:{fn:function(r){this.config.tree&&(this.config.tree.cm.activeNode&&this.config.tree.cm.activeNode.id.match(/.*?\/$/)?this.config.tree.refreshParentNode():this.config.tree.refresh()),this.run()},scope:this}}})},setTemplate:function(tpl){"list"===tpl?(this.tpl=this.templates.list,this.itemSelector="div.modx-browser-list-item"):(this.tpl=this.templates.thumb,this.itemSelector="div.modx-browser-thumb-wrap"),this.refresh(),this.select(0)},setVisibility:function(item,e){var node=this.cm.activeNode,data=this.lookup[node.id],r={path:decodeURIComponent(data.pathRelative),visibility:data.visibility,source:this.config.source};MODx.load({xtype:"modx-window-set-visibility",record:r,listeners:{success:{fn:function(){this.run()},scope:this},hide:{fn:function(){this.destroy()}}}}).show(e.target)},sortStore:function(){var v=MODx.config.modx_browser_default_sort||"name";this.store.sort(v,"name"==v?"ASC":"DESC"),this.select(0)},showDetails:function(){var node=this.getSelectedNodes(),detailPanel=Ext.getCmp(this.config.ident+"-img-detail-panel").body,okBtn=Ext.getCmp(this.ident+"-ok-btn"),keys=Object.keys(node);if(node&&node.length>0){node=node[keys[keys.length-1]],okBtn&&okBtn.enable();var data=this.lookup[node.id];this.config.tree.getNodeById(data.pathRelative)&&(this.config.tree.cm.activeNode=this.config.tree.getNodeById(data.pathRelative),this.config.tree.getSelectionModel().select(this.config.tree.getNodeById(data.pathRelative))),Ext.getCmp(this.ident+"-filepath").setValue((-1===data.fullRelativeUrl.indexOf("http")?"/":"")+data.fullRelativeUrl),detailPanel.hide(),this.templates.details.overwrite(detailPanel,data),detailPanel.slideIn("l",{stopFx:!0,duration:".2"})}else okBtn&&okBtn.disable(),detailPanel.update("")},showFullView:function(name,ident){var data=this.lookup[name];if(data){this.fvWin||(this.fvWin=new Ext.Window({layout:"fit",width:600,height:450,bodyStyle:"padding: 0;",closeAction:"hide",plain:!0,items:[{id:this.ident+"modx-view-item-full",cls:"modx-browser-fullview",html:""}],buttons:[{text:_("close"),cls:"primary-button",handler:function(){this.fvWin.hide()},scope:this}]})),this.fvWin.show();var ratio=data.image_width>800?800/data.image_width:1,w=data.image_width<250?250:data.image_width>800?800:data.image_width,hfit=data.image_height*ratio+this.fvWin.footer.dom.clientHeight+1+this.fvWin.header.dom.clientHeight+1,h=data.image_height<200?200:data.image_height>600?hfit>600?600:hfit:data.image_height;this.fvWin.setSize(w,h),this.fvWin.center(),this.fvWin.setTitle(data.name),Ext.get(this.ident+"modx-view-item-full").update('<img src="'+data.image+'" loading="lazy" width="'+data.image_width+'" height="'+data.image_height+'" alt="'+data.name+'" title="'+data.name+'" class="modx-browser-fullview-img" onclick="Ext.getCmp(\''+ident+"').fvWin.hide();\" />")}},formatData:function(data){var size;return data.shortName=Ext.util.Format.ellipsis(data.name,18),data.sizeString=0!=data.size?(size=data.size)<1024?size+" "+_("file_size_bytes"):Math.round(10*size/1024)/10+" "+_("file_size_kilobytes"):0,data.imageSizeString=0!=data.preview?data.original_width+"x"+data.original_height+"px":0,data.imageSizeString="xpx"===data.imageSizeString?0:data.imageSizeString,this.lookup[data.name]=data,data},_initTemplates:function(){this.templates.thumb=new Ext.XTemplate('<tpl for=".">','<div class="modx-browser-thumb-wrap" id="{name:htmlEncode}" title="{name:htmlEncode}">','<tpl if="preview === 1">','  <div class="modx-browser-thumb">','      <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="{thumb:htmlEncode}" loading="lazy" width="{thumb_width}" height="{thumb_height}" alt="{name:htmlEncode}" title="{name:htmlEncode}" />',"  </div>","</tpl>",'<tpl if="preview === 0">','  <div class="modx-browser-thumb">',' \t  <div class="modx-browser-placeholder">.{ext}</div>',"  </div>","</tpl>","  <span>{shortName:htmlEncode}</span>","</div>","</tpl>"),this.templates.thumb.compile(),this.templates.list=new Ext.XTemplate('<tpl for=".">','<div class="modx-browser-list-item" id="{name:htmlEncode}">','  <span class="icon icon-file {cls}">','      <span class="file-name">{name:htmlEncode}</span>','      <tpl if="sizeString !== 0">','      <span class="file-size">{sizeString}</span>',"      </tpl>",'      <tpl if="imageSizeString !== 0">','      <span class="image-size">{imageSizeString}</span>',"      </tpl>","  </span>","</div>","</tpl>"),this.templates.list.compile(),this.templates.details=new Ext.XTemplate('<div class="details">','  <tpl for=".">','  <tpl if="preview === 1">','      <div class="modx-browser-detail-thumb preview" onclick="Ext.getCmp(\''+this.ident+"').showFullView('{name:htmlEncode}','"+this.ident+"'); return false;\">",'          <img src="{image:htmlEncode}" loading="lazy" width="{image_width}" height="{image_height}" alt="{name:htmlEncode}" title="{name:htmlEncode}" />',"      </div>","  </tpl>",'  <tpl if="preview === 0">','      <div class="modx-browser-detail-thumb">','        <div class="modx-browser-placeholder">.{ext}</div>',"      </div>","  </tpl>",'  <div class="modx-browser-details-info">',"      <b>"+_("file_name")+":</b>","      <span>{name:htmlEncode}</span>",'  <tpl if="sizeString !== 0">',"      <b>"+_("file_size")+":</b>","      <span>{sizeString}</span>","  </tpl>",'  <tpl if="imageSizeString !== 0">',"      <b>"+_("image_size")+":</b>","      <span>{imageSizeString}</span>","  </tpl>",'  <tpl if="lastmod !== 0">',"      <b>"+_("file_last_modified")+":</b>","      <span>{lastmod}</span>","  </tpl>",'  <tpl if="visibility">',"      <b>"+_("visibility")+":</b>","      <span>{visibility}</span>","  </tpl>","  </div>","  </tpl>","</div>"),this.templates.details.compile()},_showContextMenu:function(v,i,n,e){e.preventDefault(),this.select(n.id);var data=this.lookup[n.id],m=this.cm;if(m.removeAll(),data.menu){var menu=[];if(this.getSelectedRecords().length>1)for(var ii=0;ii<data.menu.length;ii++)null!=data.menu[ii].handler&&data.menu[ii].handler.match(/removeFile/i)&&menu.push(data.menu[ii]);else menu=data.menu;if(!menu.length)return!1;this._addContextMenuItem(menu),m.showAt(e.xy)}m.activeNode=n}}),Ext.reg("modx-browser-view",MODx.browser.View),MODx.browser.Window=function(config){config=config||{},this.ident=Ext.id(),MODx.browserOpen=!0,this.tree=MODx.load({xtype:"modx-tree-directory",onUpload:function(){this.view.run()},scope:this,source:config.source||MODx.util.UrlParams.get().source||MODx.config.default_media_source,originalSource:config.source||MODx.config.default_media_source,hideFiles:config.hideFiles||MODx.config.modx_browser_tree_hide_files,hideTooltips:config.hideTooltips||MODx.config.modx_browser_tree_hide_tooltips||!0,openTo:config.openTo||MODx.util.UrlParams.get().dir||"",ident:this.ident,rootIconCls:MODx.config.mgr_source_icon,rootId:config.rootId||"/",rootName:_("files"),rootVisible:null==config.rootVisible||!Ext.isEmpty(config.rootId),id:this.ident+"-tree",hideSourceCombo:config.hideSourceCombo||!1,useDefaultToolbar:!1,listeners:{afterUpload:{fn:function(){this.view.run()},scope:this},afterQuickCreate:{fn:function(){this.view.run()},scope:this},afterRename:{fn:function(){this.view.run()},scope:this},afterRemove:{fn:function(){this.view.run()},scope:this},changeSource:{fn:function(s){this.config.source=s,this.view.config.source=s,this.view.baseParams.source=s,this.view.dir="/",this.view.run(),MODx.util.UrlParams.set({...MODx.util.UrlParams.get(),source:s,dir:"/"})},scope:this},afterrender:{fn:function(tree){tree.root.expand()},scope:this},beforeclick:{fn:function(node,e){if(node.leaf)return this.view.select(this.view.store.indexOfId("/"+node.attributes.url)),this.view.dir!==node.parentNode.id&&this.load(node.parentNode.id),!1;this.load(node.id)},scope:this},load:{fn:function(){const dir=MODx.util.UrlParams.get().dir;dir&&this.tree.expandTreePath(dir)},scope:this}}}),this.view=MODx.load({xtype:"modx-browser-view",onSelect:{fn:this.onSelect,scope:this},source:config.source||MODx.util.UrlParams.get().source||MODx.config.default_media_source,allowedFileTypes:config.allowedFileTypes||"",wctx:config.wctx||"web",openTo:config.openTo||MODx.util.UrlParams.get().dir||"",multiSelect:config.multiSelect||!1,ident:this.ident,id:this.ident+"-view",tree:this.tree}),window.onpopstate=e=>{MODx.browser.onPopState(e,this)},Ext.applyIf(config,{title:_("modx_browser")+" ("+(MODx.ctx?MODx.ctx:"web")+")",cls:"modx-browser modx-browser-window",layout:"border",minWidth:500,minHeight:300,width:"90%",height:.9*Ext.getBody().getViewSize().height,modal:!1,closeAction:"hide",border:!1,items:[{id:this.ident+"-browser-tree",cls:"modx-browser-tree",region:"west",width:250,height:"100%",items:this.tree,autoScroll:!0,split:!0,border:!1},{id:this.ident+"-browser-view",cls:"modx-browser-view-ct",region:"center",autoScroll:!0,border:!1,items:this.view,tbar:this.getToolbar(),bbar:this.getPathbar()},{id:this.ident+"-img-detail-panel",cls:"modx-browser-details-ct",region:"east",split:!0,border:!1,width:250}],buttons:[{id:this.ident+"-cancel-btn",text:_("cancel"),handler:this.close,scope:this},{id:this.ident+"-ok-btn",text:_("ok"),cls:"primary-button",handler:this.onSelect,scope:this}],keys:{key:27,handler:this.hide,scope:this}}),MODx.browser.Window.superclass.constructor.call(this,config),this.config=config,this.addEvents({select:!0,hide:!0}),this.on("hide",(()=>{MODx.util.UrlParams.remove("source"),MODx.util.UrlParams.remove("dir")}))},Ext.extend(MODx.browser.Window,Ext.Window,{returnEl:null,filter:function(){var filter=Ext.getCmp(this.ident+"filter");this.view.store.filter("name",filter.getValue(),!0),this.view.select(0)},load:function(dir){dir=dir||(Ext.isEmpty(this.config.openTo)?"":this.config.openTo),MODx.util.UrlParams.set({...MODx.util.UrlParams.get(),dir:decodeURIComponent(dir)}),this.view.run({dir,source:this.config.source,allowedFileTypes:this.config.allowedFileTypes||"",wctx:this.config.wctx||"web"}),this.sortStore()},sortStore:function(){var v=Ext.getCmp(this.ident+"sortSelect").getValue();this.view.store.sort(v,"name"==v?"ASC":"DESC"),this.view.select(0)},changeViewmode:function(){var v=Ext.getCmp(this.ident+"viewSelect").getValue();this.view.setTemplate(v),this.view.select(0)},reset:function(){this.rendered&&(Ext.getCmp(this.ident+"filter").reset(),this.view.getEl().dom.scrollTop=0),this.view.store.clearFilter(),this.view.select(0)},getToolbar:function(){return[{text:_("filter")+":",xtype:"label"},{xtype:"textfield",id:this.ident+"filter",selectOnFocus:!0,width:200,listeners:{render:{fn:function(){Ext.getCmp(this.ident+"filter").getEl().on("keyup",(function(){this.filter()}),this,{buffer:500})},scope:this}}},{text:_("sort_by")+":",xtype:"label"},{id:this.ident+"sortSelect",xtype:"combo",typeAhead:!0,triggerAction:"all",width:130,editable:!1,mode:"local",displayField:"desc",valueField:"name",lazyInit:!1,value:MODx.config.modx_browser_default_sort||"name",store:new Ext.data.SimpleStore({fields:["name","desc"],data:[["name",_("name")],["size",_("file_size")],["lastmod",_("last_modified")]]}),listeners:{select:{fn:this.sortStore,scope:this}}},"-",{text:_("files_viewmode")+":",xtype:"label"},"-",{id:this.ident+"viewSelect",xtype:"combo",typeAhead:!1,triggerAction:"all",width:100,editable:!1,mode:"local",displayField:"desc",valueField:"type",lazyInit:!1,value:MODx.config.modx_browser_default_viewmode||"grid",store:new Ext.data.SimpleStore({fields:["type","desc"],data:[["grid",_("files_viewmode_grid")],["list",_("files_viewmode_list")]]}),listeners:{select:{fn:this.changeViewmode,scope:this}}}]},getPathbar:function(){return{cls:"modx-browser-pathbbar",items:[{xtype:"textfield",id:this.ident+"-filepath",cls:"modx-browser-filepath",listeners:{focus:{fn:function(el){setTimeout((function(){var field=el.getEl().dom;if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(!0),selRange.moveStart("character",0),selRange.moveEnd("character",field.value.length),selRange.select()}else field.setSelectionRange?field.setSelectionRange(0,field.value.length):field.selectionStart&&(field.selectionStart=0,field.selectionEnd=field.value.length)}),50)},scope:this}}}]}},setReturn:function(el){this.returnEl=el},onSelect:function(){const selNodes=this.view.getSelectedNodes(),callback=this.config.onSelect||this.onSelectHandler,lookup=this.view.lookup,scope=this.config.scope,source=parseInt(this.config.source||MODx.config.default_media_source);this.hide(this.config.animEl||null,(function(){callback&&selNodes.forEach((selNode=>{try{let selData=lookup[selNode.id];selData.source=source,Ext.callback(callback,scope||this,[selData]),this.fireEvent("select",selData)}catch(e){console.error("Error processing MODx.Browser onSelect callback:",e)}}))}),scope)},onSelectHandler:function(data){Ext.get(this.returnEl).dom.value=unescape(data.url)}}),Ext.reg("modx-browser-window",MODx.browser.Window),MODx.Media=function(config){config=config||{},this.ident=config.ident||Ext.id(),MODx.browserOpen=!0,this.tree=MODx.load({xtype:"modx-tree-directory",onUpload:function(){this.view.run()},scope:this,source:config.source||MODx.util.UrlParams.get().source||MODx.config.default_media_source,originalSource:config.source||MODx.config.default_media_source,hideFiles:config.hideFiles||MODx.config.modx_browser_tree_hide_files,hideTooltips:config.hideTooltips||MODx.config.modx_browser_tree_hide_tooltips||!0,openTo:config.openTo||MODx.util.UrlParams.get().dir||"",ident:this.ident,rootIconCls:MODx.config.mgr_source_icon,rootId:config.rootId||"/",rootName:_("files"),rootVisible:null==config.rootVisible||!Ext.isEmpty(config.rootId),id:this.ident+"-tree",hideSourceCombo:config.hideSourceCombo||!1,useDefaultToolbar:!1,listeners:{afterUpload:{fn:function(){this.view.run()},scope:this},afterQuickCreate:{fn:function(){this.view.run()},scope:this},afterRename:{fn:function(){this.view.run()},scope:this},afterRemove:{fn:function(){this.view.run()},scope:this},changeSource:{fn:function(s){this.config.source=s,this.view.config.source=s,this.view.baseParams.source=s,this.view.dir="/",this.view.run(),MODx.util.UrlParams.set({...MODx.util.UrlParams.get(),source:s,dir:"/"})},scope:this},afterrender:{fn:function(tree){tree.root.expand()},scope:this},beforeclick:{fn:function(node,e){if(node.leaf)return this.view.select(this.view.store.indexOfId("/"+node.attributes.url)),this.view.dir!==node.parentNode.id&&this.load(node.parentNode.id),!1;this.load(node.id)},scope:this},load:{fn:function({childNodes}){const dir=MODx.util.History.get().dir;if(dir)for(const childNode of childNodes)if(dir===decodeURIComponent(childNode.id)){childNode.on("load",(()=>{childNode.select(),this.tree.cm.activeNode=childNode}));break}},scope:this},load:{fn:function(){const dir=MODx.util.UrlParams.get().dir;dir&&this.tree.expandTreePath(dir)},scope:this}}}),this.view=MODx.load({xtype:"modx-browser-view",onSelect:{fn:this.onSelect,scope:this},source:config.source||MODx.util.UrlParams.get().source||MODx.config.default_media_source,originalSource:config.source||MODx.config.default_media_source,allowedFileTypes:config.allowedFileTypes||"",wctx:config.wctx||"web",openTo:config.openTo||MODx.util.UrlParams.get().dir||"",ident:this.ident,id:this.ident+"-view",tree:this.tree}),window.onpopstate=e=>{MODx.browser.onPopState(e,this)},Ext.applyIf(config,{cls:"modx-browser modx-browser-panel",layout:"border",width:"100%",height:"100%",style:"background-color: transparent",border:!1,items:[{region:"west",width:250,items:this.tree,id:this.ident+"-browser-tree",cls:"modx-browser-tree",autoScroll:!0,split:!0,margins:"10 0 10 18"},{region:"center",layout:"fit",items:this.view,id:this.ident+"-browser-view",cls:"modx-browser-view-ct",autoScroll:!0,border:!1,tbar:this.getToolbar(),bbar:this.getPathbar(),margins:"10 0 10 0"},{region:"east",width:250,id:this.ident+"-img-detail-panel",cls:"modx-browser-details-ct",split:!0,margins:"10 10 10 0"}]}),MODx.Media.superclass.constructor.call(this,config),this.config=config},Ext.extend(MODx.Media,Ext.Container,{returnEl:null,filter:function(){var filter=Ext.getCmp(this.ident+"filter");this.view.store.filter("name",filter.getValue(),!0),this.view.select(0)},load:function(dir){dir=dir||(Ext.isEmpty(this.config.openTo)?"":this.config.openTo),MODx.util.UrlParams.set({...MODx.util.UrlParams.get(),dir:decodeURIComponent(dir)}),this.view.run({dir,source:this.config.source,allowedFileTypes:this.config.allowedFileTypes||"",wctx:this.config.wctx||"web"}),this.sortStore()},sortStore:function(){var v=Ext.getCmp(this.ident+"sortSelect").getValue();this.view.store.sort(v,"name"==v?"ASC":"DESC"),this.view.select(0)},changeViewmode:function(){var v=Ext.getCmp(this.ident+"viewSelect").getValue();this.view.setTemplate(v),this.view.select(0)},reset:function(){this.rendered&&(Ext.getCmp(this.ident+"filter").reset(),this.view.getEl().dom.scrollTop=0),this.view.store.clearFilter(),this.view.select(0)},getToolbar:function(){return[{text:_("filter")+":",xtype:"label"},{xtype:"textfield",id:this.ident+"filter",selectOnFocus:!0,width:200,listeners:{render:{fn:function(){Ext.getCmp(this.ident+"filter").getEl().on("keyup",(function(){this.filter()}),this,{buffer:500})},scope:this}}},{text:_("sort_by")+":",xtype:"label"},{id:this.ident+"sortSelect",xtype:"combo",typeAhead:!0,triggerAction:"all",width:130,editable:!1,mode:"local",displayField:"desc",valueField:"name",lazyInit:!1,value:MODx.config.modx_browser_default_sort||"name",store:new Ext.data.SimpleStore({fields:["name","desc"],data:[["name",_("name")],["size",_("file_size")],["lastmod",_("last_modified")]]}),listeners:{select:{fn:this.sortStore,scope:this}}},"-",{text:_("files_viewmode")+":",xtype:"label"},"-",{id:this.ident+"viewSelect",xtype:"combo",typeAhead:!1,triggerAction:"all",width:100,editable:!1,mode:"local",displayField:"desc",valueField:"type",lazyInit:!1,value:MODx.config.modx_browser_default_viewmode||"grid",store:new Ext.data.SimpleStore({fields:["type","desc"],data:[["grid",_("files_viewmode_grid")],["list",_("files_viewmode_list")]]}),listeners:{select:{fn:this.changeViewmode,scope:this}}}]},getPathbar:function(){return{cls:"modx-browser-pathbbar",items:[{xtype:"textfield",id:this.ident+"-filepath",cls:"modx-browser-filepath",listeners:{focus:{fn:function(el){setTimeout((function(){var field=el.getEl().dom;if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(!0),selRange.moveStart("character",0),selRange.moveEnd("character",field.value.length),selRange.select()}else field.setSelectionRange?field.setSelectionRange(0,field.value.length):field.selectionStart&&(field.selectionStart=0,field.selectionEnd=field.value.length)}),50)},scope:this}}}]}},setReturn:function(el){this.returnEl=el},onSelect:function(data){},onSelectHandler:function(data){Ext.get(this.returnEl).dom.value=unescape(data.url)}}),Ext.reg("modx-media-view",MODx.Media),MODx.browser.RTE=function(config){config=config||{},this.ident=config.ident||Ext.id(),MODx.browserOpen=!0,Ext.Ajax.defaultHeaders={modAuth:config.auth},Ext.Ajax.extraParams={HTTP_MODAUTH:config.auth},this.tree=MODx.load({xtype:"modx-tree-directory",onUpload:function(){this.view.run()},scope:this,source:config.source||MODx.config.default_media_source,hideFiles:config.hideFiles||MODx.config.modx_browser_tree_hide_files,hideTooltips:config.hideTooltips||MODx.config.modx_browser_tree_hide_tooltips||!0,openTo:config.openTo||"",ident:this.ident,rootIconCls:MODx.config.mgr_source_icon,rootId:config.rootId||"/",rootName:_("files"),rootVisible:null==config.rootVisible||!Ext.isEmpty(config.rootId),id:this.ident+"-tree",hideSourceCombo:config.hideSourceCombo||!1,useDefaultToolbar:!1,listeners:{afterUpload:{fn:function(){this.view.run()},scope:this},afterQuickCreate:{fn:function(){this.view.run()},scope:this},afterRename:{fn:function(){this.view.run()},scope:this},afterRemove:{fn:function(){this.view.run()},scope:this},changeSource:{fn:function(s){this.config.source=s,this.view.config.source=s,this.view.baseParams.source=s,this.view.dir="/",this.view.run()},scope:this},afterrender:{fn:function(tree){tree.root.expand()},scope:this},beforeclick:{fn:function(node,e){if(node.leaf)return this.view.select(this.view.store.indexOfId("/"+node.attributes.url)),this.view.dir!==node.parentNode.id&&this.load(node.parentNode.id),!1;this.load(node.id)},scope:this}}}),this.view=MODx.load({xtype:"modx-browser-view",onSelect:{fn:this.onSelect,scope:this},source:config.source||MODx.config.default_media_source,allowedFileTypes:config.allowedFileTypes||"",wctx:config.wctx||"web",openTo:config.openTo||"",multiSelect:config.multiSelect||!1,ident:this.ident,id:this.ident+"-view",tree:this.tree}),Ext.applyIf(config,{title:_("modx_browser"),cls:"modx-browser modx-browser-rte",layout:"border",renderTo:document.body,id:this.ident+"-viewport",onSelect:MODx.onBrowserReturn||function(data){},items:[{id:this.ident+"-browser-tree",cls:"modx-browser-tree",region:"west",width:250,height:"100%",split:!0,items:this.tree,autoScroll:!0},{id:this.ident+"-browser-view",cls:"modx-browser-view-ct",region:"center",autoScroll:!0,width:450,items:this.view,tbar:this.getToolbar(),bbar:this.getPathbar()},{id:this.ident+"-img-detail-panel",cls:"modx-browser-details-ct",region:"east",split:!0,width:200,minWidth:200,maxWidth:300},{id:this.ident+"-south",cls:"modx-browser-rte-buttons",region:"south",split:!1,bbar:["->",{xtype:"button",id:this.ident+"-cancel-btn",text:_("cancel"),minWidth:75,handler:this.onCancel,scope:this},{xtype:"button",id:this.ident+"-ok-btn",text:_("ok"),cls:"primary-button",minWidth:75,handler:this.onSelect,scope:this}]}]}),MODx.browser.RTE.superclass.constructor.call(this,config),this.config=config},Ext.extend(MODx.browser.RTE,Ext.Viewport,{returnEl:null,filter:function(){var filter=Ext.getCmp(this.ident+"filter");this.view.store.filter("name",filter.getValue(),!0),this.view.select(0)},load:function(dir){dir=dir||(Ext.isEmpty(this.config.openTo)?"":this.config.openTo),this.view.run({dir,source:this.config.source,allowedFileTypes:this.config.allowedFileTypes||"",wctx:this.config.wctx||"web"}),this.sortStore()},sortStore:function(){var v=Ext.getCmp(this.ident+"sortSelect").getValue();this.view.store.sort(v,"name"==v?"ASC":"DESC"),this.view.select(0)},changeViewmode:function(){var v=Ext.getCmp(this.ident+"viewSelect").getValue();this.view.setTemplate(v),this.view.select(0)},reset:function(){this.rendered&&(Ext.getCmp(this.ident+"filter").reset(),this.view.getEl().dom.scrollTop=0),this.view.store.clearFilter(),this.view.select(0)},getToolbar:function(){return[{text:_("filter")+":",xtype:"label"},{xtype:"textfield",id:this.ident+"filter",selectOnFocus:!0,width:200,listeners:{render:{fn:function(){Ext.getCmp(this.ident+"filter").getEl().on("keyup",(function(){this.filter()}),this,{buffer:500})},scope:this}}},{text:_("sort_by")+":",xtype:"label"},{id:this.ident+"sortSelect",xtype:"combo",typeAhead:!0,triggerAction:"all",width:130,editable:!1,mode:"local",displayField:"desc",valueField:"name",lazyInit:!1,value:MODx.config.modx_browser_default_sort||"name",store:new Ext.data.SimpleStore({fields:["name","desc"],data:[["name",_("name")],["size",_("file_size")],["lastmod",_("last_modified")]]}),listeners:{select:{fn:this.sortStore,scope:this}}},"-",{text:_("files_viewmode")+":",xtype:"label"},"-",{id:this.ident+"viewSelect",xtype:"combo",typeAhead:!1,triggerAction:"all",width:100,editable:!1,mode:"local",displayField:"desc",valueField:"type",lazyInit:!1,value:MODx.config.modx_browser_default_viewmode||"grid",store:new Ext.data.SimpleStore({fields:["type","desc"],data:[["grid",_("files_viewmode_grid")],["list",_("files_viewmode_list")]]}),listeners:{select:{fn:this.changeViewmode,scope:this}}}]},getPathbar:function(){return{cls:"modx-browser-pathbbar",items:[{xtype:"textfield",id:this.ident+"-filepath",cls:"modx-browser-filepath",listeners:{focus:{fn:function(el){setTimeout((function(){var field=el.getEl().dom;if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(!0),selRange.moveStart("character",0),selRange.moveEnd("character",field.value.length),selRange.select()}else field.setSelectionRange?field.setSelectionRange(0,field.value.length):field.selectionStart&&(field.selectionStart=0,field.selectionEnd=field.value.length)}),50)},scope:this}}}]}},setReturn:function(el){this.returnEl=el},onSelect:function(){const selNodes=this.view.getSelectedNodes(),callback=this.config.onSelect||this.onSelectHandler,lookup=this.view.lookup,scope=this.config.scope,source=parseInt(this.config.source||MODx.config.default_media_source);callback&&selNodes.forEach((selNode=>{try{let selData=lookup[selNode.id];selData.source=source,Ext.callback(callback,scope||this,[selData]),this.fireEvent("select",selData)}catch(e){console.error("Error processing MODx.Browser onSelect callback:",e)}})),window.top.opener&&(window.top.close(),window.top.opener.focus())},onCancel:function(){var callback=this.config.onSelect||this.onSelectHandler,scope=this.config.scope;Ext.callback(callback,scope||this,[null]),this.fireEvent("select",null),window.top.opener&&(window.top.close(),window.top.opener.focus())},onSelectHandler:function(data){Ext.get(this.returnEl).dom.value=unescape(data.url)}}),Ext.reg("modx-browser-rte",MODx.browser.RTE),MODx.browser.onPopState=function({state},{tree,view}){const params=MODx.util.UrlParams.parse(state),defaultSource=view.config.originalSource,source=params.source||defaultSource;tree.sourceCombo&&!tree.config.hideSourceCombo&&source!==tree.sourceCombo.getValue()?(tree.config.source=source,tree.baseParams.source=source,tree.dir=params.dir||"/",tree.sourceCombo.getStore().load({scope:tree,callback(){tree.sourceCombo.setValue(source),tree.refresh();const root=tree.getRootNode();root&&root.setText(tree.sourceCombo.getRawValue()),view.run({dir:params.dir||"/",source,allowedFileTypes:view.config.allowedFileTypes||"",wctx:view.config.wctx||"web"}),tree.expandTreePath(params.dir||"/")}})):(view.run({dir:params.dir||"/",source,allowedFileTypes:view.config.allowedFileTypes||"",wctx:view.config.wctx||"web"}),tree.expandTreePath(params.dir||"/"))},Ext.apply(Ext,{isFirebug:window.console&&window.console.firebug}),MODx.Layout=function(config={}){Ext.BLANK_IMAGE_URL=MODx.config.manager_url+"assets/ext3/resources/images/default/s.gif",Ext.Ajax.defaultHeaders={modAuth:config.auth},Ext.Ajax.extraParams={HTTP_MODAUTH:config.auth},MODx.siteId=config.auth,MODx.expandHelp=!!+MODx.config.inline_help;const sp=new MODx.HttpProvider;Ext.state.Manager.setProvider(sp),sp.initState(MODx.defaultState),config.showTree=!1,config.search&&new MODx.SearchBar,Ext.applyIf(config,{layout:"border",id:"modx-layout",stateSave:!0,items:this.buildLayout(config)}),MODx.Layout.superclass.constructor.call(this,config),this.config=config,this.addEvents({afterLayout:!0,loadKeyMap:!0,loadTabs:!0}),this.loadKeys(),config.showTree||Ext.getCmp("modx-leftbar-tabs").collapse(!1),this.fireEvent("afterLayout")},Ext.extend(MODx.Layout,Ext.Viewport,{menuBarWidth:70,splitBarMargin:8,focusRestoreEls:[],subNavOpen:!1,getSplitBarMargin:function(){return this.splitBarMargin},buildLayout:function(config){var items=[],north=this.getNorth(config),west=this.getWest(config),center=this.getCenter(config),south=this.getSouth(config),east=this.getEast(config);return north&&Ext.isObject(north)&&items.push(north),west&&Ext.isObject(west)&&items.push(west),center&&Ext.isObject(center)&&items.push(center),south&&Ext.isObject(south)&&items.push(south),east&&Ext.isObject(east)&&items.push(east),items},getNorth:function(config){return window.innerWidth<=640&&{xtype:"box",region:"north",applyTo:"modx-header",listeners:{afterrender:this.initPopper,scope:this}}},getWest:function(config){return window.innerWidth<=640?this.getTree(config):{region:"west",xtype:"box",id:"modx-header",applyTo:"modx-header",width:this.menuBarWidth,listeners:{afterrender:{fn:this.initPopper,scope:this}}}},getCenter:function(config){const center={region:"center",applyTo:"modx-content",padding:"0 1px 0 0",margins:{top:0,right:0,bottom:0,left:0},style:"width:100%",bodyStyle:"background-color:transparent;",id:"modx-content",autoScroll:!0};if(window.innerWidth<=640)return center;const tree=this.getTree(config);return center.margins.right=-this.menuBarWidth,tree.margins={left:this.menuBarWidth},{region:"center",layout:"border",id:"modx-split-wrapper",items:[tree,center],listeners:{render:{fn:function(cmp){cmp.collapsed||(cmp.items.map["modx-content"].margins.left=-this.getSplitBarMargin())},scope:this}}}},getSouth:function(config){},getEast:function(config){},getTree:function(config){const tabs=[],layout=this;MODx.perm.resource_tree&&(tabs.push({title:_("resources"),xtype:"modx-tree-resource",id:"modx-resource-tree"}),config.showTree=!0),MODx.perm.element_tree&&(tabs.push({title:_("elements"),xtype:"modx-tree-element",id:"modx-tree-element"}),config.showTree=!0),MODx.perm.file_tree&&(tabs.push({title:_("files"),xtype:"modx-panel-filetree",id:"modx-file-tree"}),config.showTree=!0);return{region:"west",applyTo:"modx-leftbar",id:"modx-leftbar-tabs",split:!0,width:300,minSize:280,autoScroll:!0,unstyled:!0,useSplitTips:!0,monitorResize:!0,layout:"anchor",headerCfg:window.innerWidth<=640?{}:{tag:"div",cls:"none",id:"modx-leftbar-header",html:MODx.config.site_name},items:[{xtype:"modx-tabs",plain:!0,defaults:{autoScroll:!0,fitToFrame:!0},id:"modx-leftbar-tabpanel",border:!1,activeTab:0,stateful:!0,stateEvents:["tabchange"],getState:function(){return{activeTab:this.items.indexOf(this.getActiveTab())}},items:tabs,listeners:{afterrender:function(){const baseTabs=this,header=Ext.get("modx-leftbar-header");if(MODx.Ajax.request({url:MODx.config.connector_url,params:{action:"Resource/GetToolbar"},listeners:{success:{fn:function(response){const trashTrigger=Object.values(response.object).find((item=>"emptifier"===item.id));if(trashTrigger){const trashTab=baseTabs.add({id:"modx-trash-link",title:'<a href="?resource/trash"><i class="icon icon-trash-o"></i></a>',updateState(deletedCount=0){const tab=this,tabEl=tab.tabEl,tooltipTarget=new Ext.Element(tabEl);0===deletedCount?(tab.disable(),tabEl.classList.remove("active")):(tab.enable(),tabEl.classList.add("active")),tab.tooltip=new Ext.ToolTip({target:tooltipTarget,title:_("trash.manage_recycle_bin_tooltip",{count:deletedCount})})}});trashTrigger.disabled||trashTab.tabEl.classList.add("active"),trashTrigger.tooltip&&(trashTab.tooltip=new Ext.ToolTip({target:new Ext.Element(trashTab.tabEl),title:trashTrigger.tooltip}))}},scope:this}}}),header){let html="";const el=document.createElement("a");""!==MODx.config.manager_logo&&void 0!==MODx.config.manager_logo&&(html+='<img src="'+MODx.config.manager_logo+'">'),el.href=MODx.config.default_site_url||MODx.config.site_url,el.title=MODx.config.site_name,el.innerText=Ext.util.Format.ellipsis(MODx.config.site_name,45,!0),el.target="_blank",html+=el.outerHTML,header.dom.innerHTML=html}},beforetabchange:{fn:function(panel,tab){if(tab&&"modx-trash-link"==tab.id){if(tab.tabEl.classList.contains("active")){var tree=Ext.getCmp("modx-resource-tree");tree&&tree.redirect("?a=resource/trash")}return!1}},scope:this}}}],getState:function(){return{collapsed:this.collapsed,width:this.width}},collapse:function(animate){if(this.collapsed||this.el.hasFxBlock()||!1===this.fireEvent("beforecollapse",this,animate))return;const contentRegion=Ext.getCmp("modx-content");if(contentRegion&&(contentRegion.margins.left=0,Ext.getCmp("modx-layout").doLayout()),animate&&window.innerWidth>960){Ext.getCmp("modx-leftbar-tabpanel").getEl().dom.style.opacity=0,this.el.dom.style.left="-"+this.el.dom.style.width}else this.el.dom.style.display="none";return this.collapsed=!0,this.saveState(),this.fireEvent("collapse",this),this},expand:function(animate){if(!this.collapsed||this.el.hasFxBlock()||!1===this.fireEvent("beforeexpand",this,animate))return;const contentRegion=Ext.getCmp("modx-content");if(contentRegion&&(contentRegion.margins.left=-layout.getSplitBarMargin()),animate&&window.innerWidth>960){const tree=Ext.getCmp("modx-leftbar-tabpanel").getEl();window.setTimeout((()=>{tree.dom.style.visibility="visible",tree.dom.style.opacity=1}),100)}else this.el.dom.style.display="";return this.collapsed=!1,this.saveState(),this.fireEvent("expand",this),this},listeners:{beforestatesave:{fn:this.onBeforeSaveState,scope:this},afterrender:function(){const trigger=Ext.get("modx-leftbar-trigger");this.collapsed&&trigger.addClass("collapsed"),trigger.on("click",(function(){this.collapsed?(trigger.removeClass("collapsed"),this.expand(!0)):(trigger.addClass("collapsed"),this.collapse(!0))}),this)}}}},initPopper:function(){for(var el=this,buttons=document.getElementById("modx-navbar").getElementsByClassName("top"),position=window.innerWidth<=960?"bottom":"right",i=0;i<buttons.length;i++){var submenu=document.getElementById(buttons[i].id+"-submenu");submenu&&(new Popper(buttons[i],submenu,{placement:position,modifiers:{arrow:{element:submenu.getElementsByClassName("modx-subnav-arrow")[0]},flip:{enabled:!1},applyStyle:{enabled:!0,fn:function(data){for(var i in data.offsets.popper)"bottom"!==i&&"right"!==i&&data.offsets.popper.hasOwnProperty(i)&&(data.instance.popper.style[i]=isNaN(parseFloat(data.offsets.popper[i]))?data.offsets.popper[i]:data.offsets.popper[i]+"px"),""!==data.offsets.arrow.top&&(data.arrowElement.style.top=data.offsets.arrow.top+"px"),data.offsets.arrow.left&&(data.arrowElement.style.left=data.offsets.arrow.left+"px")}},preventOverflow:{boundariesElement:document.getElementById("modx-container"),priority:"right"===position?["bottom","top"]:["left","right"]}}}),buttons[i].addEventListener("click",(function(e){e.stopPropagation(),el.focusRestoreEls.push(this.querySelectorAll("a")[0]),el.showMenu(this)})))}window.addEventListener("click",(function(){el.hideMenu()})),window.innerWidth>960&&this.initSubPopper()},showMenu:function(el){var submenu=document.getElementById(el.id+"-submenu");if(submenu.classList.contains("active"))submenu.classList.remove("active");else{this.hideMenu(),submenu.classList.add("active"),setTimeout((()=>{submenu.querySelectorAll("a")[0].focus()}),50);var focusRestore=e=>{setTimeout((()=>{this.subNavOpen||submenu.contains(document.activeElement)||(this.focusRestoreEls?.pop()?.focus(),this.hideMenu(),window.removeEventListener("focusout",focusRestore))}),1)},menuArrowKeysNavigation=e=>{"Escape"==e.code&&(this.hideMenu(),this.focusRestoreEls[0]?.focus(),this.focusRestoreEls=[],window.removeEventListener("keyup",menuArrowKeysNavigation))};window.addEventListener("focusout",focusRestore),window.addEventListener("keyup",menuArrowKeysNavigation)}this.hideSubMenu()},hideMenu:function(){for(var submenus=document.getElementsByClassName("modx-subnav"),i=0;i<submenus.length;i++)submenus[i].classList.remove("active")},initSubPopper:function(){for(var buttons=document.querySelectorAll("#modx-header .sub, #modx-footer .sub"),position=window.innerWidth<=960?"bottom":"right",_this=this,i=0;i<buttons.length;i++){let popperInstance=null;function create(button,submenu){popperInstance=new Popper(button,submenu,{placement:position,modifiers:{flip:{enabled:!1},applyStyle:{enabled:!0,fn:function(data){for(var i in data.offsets.popper)"bottom"!==i&&"right"!==i&&data.offsets.popper.hasOwnProperty(i)&&(data.instance.popper.style[i]=isNaN(parseFloat(data.offsets.popper[i]))?data.offsets.popper[i]:data.offsets.popper[i]+"px")}},preventOverflow:{boundariesElement:document.getElementById("modx-container"),priority:"right"===position?["bottom","top"]:["left","right"]}}})}function show(button){var menu=button.getElementsByTagName("ul")[0];button.classList.add("active"),menu.classList.add("active"),_this.focusRestoreEls.push(button.querySelectorAll("a")[0]),_this.subNavOpen=!0,create(button,menu);var focusRestore=e=>{requestAnimationFrame((()=>{menu.contains(document.activeElement)||(_this.focusRestoreEls?.pop()?.parentNode?.nextSibling?.focus(),hide(button),window.removeEventListener("focusout",focusRestore))}))};window.addEventListener("focusout",focusRestore)}function hide(button){var parentmenu=button.closest("ul");button.classList.remove("active");for(var buttons=parentmenu.querySelectorAll(".sub"),i=0;i<buttons.length;i++){var submenu=buttons[i].getElementsByTagName("ul")[0];submenu.classList.remove("active"),submenu.removeAttribute("style"),buttons[i].classList.remove("active")}_this.subNavOpen=!1,popperInstance&&(popperInstance.destroy(),popperInstance=null)}buttons[i].addEventListener("mouseenter",(function(e){e.stopPropagation(),show(this)})),buttons[i].querySelectorAll("a")[0].addEventListener("focus",(function(e){e.stopPropagation(),show(this.parentNode)})),buttons[i].addEventListener("mouseleave",(function(e){e.stopPropagation(),hide(this)}))}},hideSubMenu:function(){for(var buttons=document.getElementById("modx-footer").querySelectorAll(".sub"),i=0;i<buttons.length;i++){buttons[i].getElementsByTagName("ul")[0].classList.remove("active"),buttons[i].classList.remove("active")}},getLeftBar:function(){var nav=Ext.getCmp("modx-leftbar-tabpanel");return nav||null},addToLeftBar:function(items){var nav=this.getLeftBar();nav&&items&&(nav.add(items),this.onAfterLeftBarAdded(nav,items))},onAfterLeftBarAdded:function(nav,items){},loadKeys:function(){Ext.KeyMap.prototype.stopEvent=!0;var k=new Ext.KeyMap(Ext.get(document));k.addBinding({key:Ext.EventObject.H,ctrl:!0,shift:!0,fn:this.toggleLeftbar,scope:this,stopEvent:!0}),k.addBinding({key:Ext.EventObject.N,ctrl:!0,shift:!0,fn:function(){var t=Ext.getCmp("modx-resource-tree");t&&t.quickCreate(document,{},"MODX\\Revolution\\modDocument","web",0)},stopEvent:!0}),k.addBinding({key:Ext.EventObject.U,ctrl:!0,shift:!0,alt:!1,fn:MODx.clearCache,scope:this,stopEvent:!0}),this.fireEvent("loadKeyMap",{keymap:k})},refreshTrees:function(){var t;(t=Ext.getCmp("modx-resource-tree"))&&t.rendered&&t.refresh(),(t=Ext.getCmp("modx-tree-element"))&&t.rendered&&t.refresh(),(t=Ext.getCmp("modx-file-tree"))&&t.rendered&&t.items.each((function(tree,idx){tree.refresh()}))},leftbarVisible:!0,toggleLeftbar:function(){this.leftbarVisible?this.hideLeftbar(!0):this.showLeftbar(!0),this.leftbarVisible=!this.leftbarVisible},hideLeftbar:function(anim,state){Ext.getCmp("modx-leftbar-tabs").collapse(anim),Ext.isBoolean(state)&&(this.stateSave=state)},showLeftbar:function(anim){Ext.getCmp("modx-leftbar-tabs").expand(anim)},onBeforeSaveState:function(component,state){var collapsed=state.collapsed;if(collapsed&&!this.stateSave)return this.stateSave=!0,!1;if(!collapsed){var wrap=Ext.get("modx-leftbar").down("div");wrap.isVisible()||(wrap.setVisible(!0),Ext.getCmp("modx-leftbar-tabpanel").expand(!0))}}}),MODx.LayoutMgr=function(){var _activeMenu="menu0";return{getPage:function(action,parameters){var parts=[];if(action&&(!isNaN(parseInt(action))||"?"!=action.substr(0,1)&&"index.php?"!=action.substr(0,"index.php?".length)?parts.push("?a="+(""+action).toLowerCase()):parts.push(action)),parameters)if("object"==typeof parameters)for(var name in parameters)parameters.hasOwnProperty(name)&&parts.push(name+"="+parameters[name]);else parts.push(parameters);return parts.join("&")},loadPage:function(action,parameters){var url=MODx.LayoutMgr.getPage(action,parameters);if(MODx.fireEvent("beforeLoadPage",url)){var e=window.event,middleMouseButtonClick=e&&(4===e.button||2===e.which),keyboardKeyPressed=e&&(1===e.button||!0===e.ctrlKey||!0===e.metaKey||!0===e.shiftKey);if(middleMouseButtonClick||keyboardKeyPressed)return window.open(url);location.href=url}return!1},changeMenu:function(a,sm){if(sm===_activeMenu)return!1;Ext.get(sm).addClass("active");var om=Ext.get(_activeMenu);return om&&om.removeClass("active"),_activeMenu=sm,!1}}}(),MODx.getPage=MODx.LayoutMgr.getPage,MODx.loadPage=MODx.LayoutMgr.loadPage,MODx.showDashboard=MODx.LayoutMgr.showDashboard,MODx.hideDashboard=MODx.LayoutMgr.hideDashboard,MODx.changeMenu=MODx.LayoutMgr.changeMenu;