File: /volume1/@appstore/MailClient/ui/mailclient.js
/* Copyright (c) 2022 Synology Inc. All rights reserved. */
Ext.define("SYNO.SDS.MailClient.AttachmentViewer",{extend:"Ext.util.Observable",VIEWER_ENUM:{PHOTO:"image",VIDEO:"video",AUDIO:"audio",TEXT:"text",GOOGLE:"google",SYNO_DOC:"syno_doc",OFFICE:"office",NEW_WINDOW:"new_window"},constructor:function(){this.callParent(arguments),this.can_load_js=!Ext.isEmpty(Ext.getClassByName("SYNO.SDS.JSLoad")),this.quickconnect_href="";try{_S("standalone")||(SYNO.SDS.JSLoad("SYNO.SDS.ACEEditor.Utils.checkFn"),SYNO.SDS.JSLoad("SYNO.SDS.VideoPlayer2.Application")),SYNO.SDS.QuickConnect.Utils.getPortalUrl(SYNO.SDS.QuickConnect.Utils.TYPES.DIRECT,function(t,e){!0===t&&(this.quickconnect_href=e),SYNO.SDS.JSLoad("SYNO.SDS.GoogleDocsViewer.FBExt"),SYNO.SDS.JSLoad("SYNO.SDS.OfficeViewer.FBExt"),SYNO.SDS.AppUtil.isValidApp("SYNO.SDS.PDFViewer.Application")&&SYNO.SDS.JSLoad("SYNO.SDS.DocumentViewer.Application"),this.support_ext_collect=this.createSupportExtCollect()},this)}catch(t){this.can_load_js=!1}},createSupportExtCollect:function(){var t=function(t,e){return-1!==SYNO.SDS.MailClient.Tool.imageFormat.indexOf(e)},e=function(t){SYNO.SDS.AppLaunch("SYNO.SDS.PhotoViewer.Application",{simple_viewer:!0,url:t.url,filename:t.filename},!1)},i=function(t,e){var i="SYNO.SDS.ACEEditor.Application",n=SYNO.SDS.Config.FnMap[i].config;return SYNO.SDS.ACEEditor.Utils.checkFn({baseURL:n.jsBaseURL,className:i,data:n.fb_extern[0]},[new Ext.data.Record({isdir:!1,filename:t},t)])},n=function(t){SYNO.SDS.JSLoad("SYNO.SDS.ACEEditor.Application",function(){Ext.Ajax.request({url:t.url,callback:function(e,i,n){!0===i&&SYNO.SDS.AppLaunch("SYNO.SDS.ACEEditor.Application",{simple_viewer:!0,filename:t.filename,text:n.responseText},!1)}})})},a=function(t,e){return-1!==SYNO.SDS.Config.FnMap["SYNO.SDS.VideoPlayer2.Application"].config.fb_extern[0].file.indexOf(e)},o=function(t){SYNO.SDS.WindowLaunch("SYNO.SDS.VideoPlayer2.Application",{url:t.url,filename:t.filename},!0)},s=function(t,e){var i;return SYNO.SDS.MailClient.Window._S("version")>4943&&(i=SYNO.SDS.Config.FnMap["SYNO.SDS.AudioPlayer.Application"].config.fb_extern[0].file,-1!==i.indexOf(e))},l=function(t){SYNO.SDS.AppLaunch("SYNO.SDS.AudioPlayer.Application",{url_recs:[{url:t.url,title:t.filename}]},!1)},r=function(t){var e,i,n,a,o,s=SYNO.SDS.MailClient.Window;n=t.filename.split(".").pop(),i=t.allowExt[n];var l=function(t,e,i){var n=window.location.port,a="/";i._S("rewrite_mode")?a=window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/"))+"/":n="https:"===window.location.protocol?i._S("external_port_dsm_https")&&""!==i._S("external_port_dsm_https")?i._S("external_port_dsm_https"):window.location.port:i._S("external_port_dsm_http")&&""!==i._S("external_port_dsm_http")?i._S("external_port_dsm_http"):window.location.port,n&&(n=":"+n);var o;return!t&&i._S("external_host_ip")&&""!==i._S("external_host_ip")?o=window.location.protocol+"//"+i._S("external_host_ip")+n+a:!t&&i._S("ddns_hostname")&&""!==i._S("ddns_hostname")?o=window.location.protocol+"//"+i._S("ddns_hostname")+n+a:e&&""!==e?o=e:t||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("127.")||window.location.hostname.startsWith("10.")||(o=window.location.protocol+"//"+window.location.hostname+n+a),o}(t.isOfficeOnline,this.quickconnect_href,s);if(Ext.isEmpty(l)){o=new SYNO.SDS.MessageBoxV5({owner:s});var r=_S("is_admin")&&!_S("standalone"),d=r?_T("error","quickcnt_alert"):_T("error","quickcnt_warning");return void o.alert(_T("filebrowser","oviewer"),d,function(){r&&SYNO.SDS.AppLaunch("SYNO.SDS.AdminCenter.Application",{fn:"SYNO.SDS.AdminCenter.QuickConnect.Main"})})}a=l+t.url,e="https:"+t.extURL+encodeURIComponent(a),t.filesize>i?this.owner.findWindow().getMsgBox().confirm(_T("filebrowser","gviewer"),_T("filebrowser","gviewer_bigsize"),function(){window.open(e)}):window.open(e)}.createDelegate(this),d=function(t,e){var i="SYNO.SDS.GoogleDocsViewer.FBExt",n=SYNO.SDS.Config.FnMap[i].config;return SYNO.SDS.GoogleDocsViewer.FBExt.checkFn({baseURL:n.jsBaseURL,className:i,data:n.fb_extern[0]},[new Ext.data.Record({isdir:!1,filename:t,type:e},t)])},c=function(t){SYNO.SDS.JSLoad("SYNO.SDS.GoogleDocsViewer.FBExt",function(){t.extURL=SYNO.SDS.GoogleDocsViewer.FBExt.extURL,t.allowExt=SYNO.SDS.GoogleDocsViewer.FBExt.AllowExt,t.isOfficeOnline=!1,r(t)})},h=function(t,e){return!!Ext.getClassByName("SYNO.SDS.DocumentViewer.FBExt.avaiViewTypes")&&-1!==SYNO.SDS.DocumentViewer.FBExt.avaiViewTypes.indexOf(e.toLowerCase())},u=function(t){var e=window.open("about:blank"),i=function(i,n){if(!i)return e.close(),void SYNO.SDS.MailClient.Window.getMsgBox().alert("",SYNO.SDS.MailClient._T("api_error","document_viewer_has_error"));SYNO.SDS.JSLoad("SYNO.SDS.DocumentViewer.LaunchHelper",function(){SYNO.SDS.DocumentViewer.LaunchHelper.windowLaunchToWindow({name:t.filename,task_id:n.task_id},e)})};SYNO.SDS.MailClient.OP.getAppTaskId({id:t.file_id},i,this)},S=function(t,e){var i=SYNO.SDS.Config.FnMap["SYNO.SDS.OfficeViewer.FBExt"].config;return SYNO.SDS.OfficeViewer.FBExt.checkFn({baseURL:i.jsBaseURL,className:"SYNO.SDS.OfficeViewer.FBExt",data:i.fb_extern[0]},[new Ext.data.Record({isdir:!1,filename:t,type:e},t)])},m=function(t){SYNO.SDS.JSLoad("SYNO.SDS.OfficeViewer.FBExt",function(){t.extURL=SYNO.SDS.OfficeViewer.FBExt.extURL,t.allowExt=SYNO.SDS.OfficeViewer.FBExt.AllowExt,t.isOfficeOnline=!0,r(t)})},f=function(t){window.open(t.urlWithoutFileHash)};return{image:{check:t,launch:e,doc:SYNO.SDS.MailClient._T("mail","open_in_photo")},video:{check:a,launch:o,doc:SYNO.SDS.MailClient._T("mail","open_in_video")},audio:{check:s,launch:l,doc:SYNO.SDS.MailClient._T("mail","open_in_audio")},text:{check:i,launch:n,doc:SYNO.SDS.MailClient._T("mail","open_in_text")},google:{check:d,launch:c,doc:SYNO.SDS.MailClient._T("mail","open_in_google")},syno_doc:{check:h,launch:u,doc:SYNO.SDS.MailClient._T("mail","open_in_syno_doc")},office:{check:S,launch:m,doc:SYNO.SDS.MailClient._T("mail","open_in_office")},new_window:{check:Ext.emptyFn,launch:f,doc:SYNO.SDS.MailClient._T("mail","open_in_new_window")}}},launchViewer:function(t){if(!this.can_load_js)return void SYNO.Debug("Cannot launch viewer");if(!(Ext.isObject(t)&&Ext.isString(t.type)&&Ext.isString(t.url)&&Ext.isString(t.filename)))return void SYNO.Debug("Invalid configuration!");var e=Ext.copyTo({},t,"url,urlWithoutFileHash,filename,filesize,object_id,ver,file_id,encrypt");t.type in this.support_ext_collect?this.support_ext_collect[t.type].launch(e):SYNO.Debug("Not supported viewer",t.type)},getSupportExt:function(t){if(!this.can_load_js)return SYNO.Debug("Cannot launch viewer"),!1;var e=t.split(".");if(e.length<2)return!1;var i=e.pop().toLowerCase(),n=[];if(Ext.iterate(this.support_ext_collect,function(e,a){if((!_S("standalone")||"google"===e||"office"===e||"syno_doc"===e)&&!0===a.check(t,i)){if("pdf"===i&&SYNO.SDS.MailClient.Tool.isSupportPDFViewer())return;n.push(e)}}),-1!==n.indexOf(this.VIEWER_ENUM.GOOGLE)||-1!==n.indexOf(this.VIEWER_ENUM.OFFICE))n.push(this.VIEWER_ENUM.NEW_WINDOW);else if(_S("standalone"))return this.VIEWER_ENUM.NEW_WINDOW;return 1<n.length?n:1===n.length&&n[0]},_getAttachmentUrl:function(t,e){if(t.url)return t.url;var i={type:"original"};return Ext.isEmpty(t.id)||(i.id=t.id),Ext.isEmpty(t.md5)||(i.md5=t.md5),e&&(i.uid=t.uid,i.file_hash=t.file_hash,i.download_token=SYNO.SDS.MailClient.Info.download_token),Ext.urlAppend(SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Attachment","download",6,!0,SYNO.SDS.MailClient.Format.toAttachmentName(t)),Ext.urlEncode(SYNO.API.EncodeParams(i)))},show:function(t,e){var i={filename:SYNO.SDS.MailClient.Format.toAttachmentName(t),filesize:t.size,url:this._getAttachmentUrl(t,!0),urlWithoutFileHash:this._getAttachmentUrl(t,!1),file_id:t.id},n=this.getSupportExt(i.filename),a=[];if(Ext.isString(n))i.type=n,this.launchViewer(i);else if(Ext.isArray(n)){if(Ext.each(n,function(t){a.push({text:this.support_ext_collect[t].doc,handler:this.launchViewer.createDelegate(this,[Ext.apply({type:t},i)])})},this),!e)return a;this.menu||(this.menu=new SYNO.ux.Menu),this.menu.removeAll(!0),Ext.each(a,function(t){this.menu.add(t)},this),e instanceof Ext.Element?this.menu.show(e):Ext.isArray(e)&&this.menu.showAt(e)}else window.open(i.url)}}),Ext.define("SYNO.SDS.MailClient.BasePanel",{extend:"SYNO.ux.Panel",activated:!1,constructor:function(t){this.callParent([t]),this.on("activate",function(t){this.activated=!0,t.arm()}),this.on("deactivate",function(t){this.activated=!1,t.disarm()})},arm:Ext.emptyFn,disarm:Ext.emptyFn,layoutChange:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.DraftLib.DraftProcessor",{extend:"Ext.util.Observable",singleton:!0,requires:[],updateImage:function(t,e,i){if(!(!e.inline||Ext.isEmpty(e.name)||Ext.isEmpty(e.temp_id)||Ext.isEmpty(e.cid)||Ext.isEmpty(e.ref))){var n=String.format('img[data-ref="{0}"]',e.ref),a=i?i.getEditor().getBody():this._getBodyNode(t),o=a.querySelectorAll(n);0!==o.length&&(this._updateImageAttribute(o,e),i||(t.body=a.innerHTML))}},_getBodyNode:function(t){var e,i,n=this.getSavingValidateDataWithoutReplacingImage(t),a=n.body;return!Ext.isIE||Ext.isModernIE&&!Ext.isIE9?(e=(new DOMParser).parseFromString(a,"text/html"),e.body):(i=document.createElement("div"),i.innerHTML=a,i)},_updateImageAttribute:function(t,e){var i,n,a=[];for(i=0;i<t.length;++i)t[i].getAttribute("cid")||a.push(t[i]);var o=SYNO.SDS.MailClient.Format.getAttachmentTempUrl(e),s={src:o,"data-mce-src":o,cid:e.cid};for(Ext.isEmpty(e.temp_id)||(s["data-temp-id"]=e.temp_id),i=0;i<a.length;++i)n=a[i],Ext.fly(n).set(s,!0),n.getAttribute("data-synomc-external")&&(n.removeAttribute("data-synomc-external"),n.style.display=n.getAttribute("data-synomc-display")?n.getAttribute("data-synomc-display"):null,n.removeAttribute("data-synomc-display"),n.removeAttribute("data-mce-src"),n.removeAttribute("data-mce-style")),n.removeAttribute("data-temp"),n.removeAttribute("data-synomc-uploading-img")},getSavingValidateData:function(t){var e=this._getValidateData(!1,t);return e&&(e.body=this.replaceInlineImageToIMAPFormat(e.body)),e},getSavingValidateDataWithoutReplacingImage:function(t){return this._getValidateData(!1,t)},getSendingValidateData:function(t){return this._getValidateData(!0,t)},_getValidateData:function(t,e){var i,n,a,o=Ext.apply({},e),s=Object.keys(o),l={},r="";for(i=0;i<s.length;i++)if("subject"===(a=s[i]))Ext.isString(o[a])||(l[a]="format",r=r||"format");else if("from"===a)SYNO.SDS.MailClient.Format.isValidEmail(o[a])||(l[a]="format",r=r||"format");else if("to"===a||"cc"===a||"bcc"===a)for(n=0;n<o[a].length;n++)if(!SYNO.SDS.MailClient.Format.isValidEmail(o[a][n])){l[a]="format",r=r||"format";break}t&&(o.to.length||o.cc.length||o.bcc.length||(l.to=l.cc=l.bcc="empty",r=r||"empty"));var d=Object.keys(l);if(t&&d.length)return{invalid:l,invalidStr:r};for(i=0;i<d.length;i++)delete o[d[i]];return Object.keys(o).length?o:{invalid:[]}},checkDirty:function(t,e){return this._checkDirtyAndUpdateDraft(t,e)},checkDirtyAndUpdateDraft:function(t,e){return this._checkDirtyAndUpdateDraft(t,e,!0)},_checkDirtyAndUpdateDraft:function(t,e,i){var n,a,o,s,l,r=!1;for(n in t)if(t.hasOwnProperty(n)){if(s=[],l=[],"attachment"===n){for(o=0;o<e[n].length;++o)s.push(e[n][o].id);for(o=0;o<t[n].length;++o)l.push(t[n][o].id);this.isSame(s,l)||(this.logDirty(n,s.join(),l.join()),r=!0),i&&(e[n]=t[n]);continue}if("temp_attachment"===n){if(t[n].length){for(o=0;o<e[n].length;++o)s.push(e[n][o].temp_id);for(o=0;o<t[n].length;++o)l.push(t[n][o].temp_id);this.logDirty(n,s.join(),l.join()),r=!0,i&&(e[n]=t[n])}continue}if("copied_attachment"===n){if(t[n].length){for(o=0;o<t[n].length;++o)l.push(Ext.encode(t[n][o]));this.logDirty(n,"",l.join()),r=!0}continue}a=t[n],Ext.isArray(a)?a.join()!==e[n].join()&&(this.logDirty(n,e[n],a.join()),i&&(e[n]=a),r=!0):a!==e[n]&&(this.logDirty(n,e[n],a),i&&(e[n]=a),r=!0)}return t.clearReplyTo&&(r=!0),r},isSame:function(t,e){return Ext.isArray(t)&&Ext.isArray(e)?t.sort().join()===e.sort().join():t===e},logDirty:function(t,e,i){},replaceInlineImageToIMAPFormat:function(t){var e,i,n,a=SYNO.SDS.MailClient.Format,o=(new DOMParser).parseFromString(t,"text/html");do{e="syno-mc-src-"+Math.random().toString()}while(-1!=t.indexOf(e));return o.querySelectorAll("img[data-temp]").forEach(function(t){t.remove(!0)}),o.querySelectorAll("img[cid]").forEach(function(t){i=t.getAttribute("cid"),t.removeAttribute("data-ref"),t.removeAttribute("data-temp-id"),t.removeAttribute("cid"),t.removeAttribute("data-mce-src"),t.removeAttribute("id"),t.removeAttribute("src"),t.setAttribute(e,String.format("cid:{0}",i))}),o.querySelectorAll("img[syno-mc-cid]").forEach(function(t){null!==t.getAttribute("src")&&-1!==t.getAttribute("src").indexOf("download_token")&&(n=a.removeURLParameter(t.getAttribute("src"),"download_token"),t.setAttribute("src",n),t.removeAttribute("id"),t.removeAttribute("data-ref"))}),o.body.innerHTML.split(e).join("src")},updateAttachments:function(t,e,i){if(e.length){var n,a,o,s,l=SYNO.SDS.MailClient.Editor.DDUpload.prototype.isMatch;for(n=0;n<e.length;n++)for(o=e[n],a=0;a<t.attachment.length;a++)if(s=t.attachment[a],l(o,s)){t.attachment[a]=Ext.apply({},o);break}if(i.length){var r,d=this.getAttachmentIds(i,!0);for(n=0;t.temp_attachment[n];)if(r=t.temp_attachment[n],-1!==d.indexOf(r.temp_id)){for(t.temp_attachment.splice(n,1),a=0;a<e.length;a++)if(o=e[a],o.content_id===r.cid){t.attachment.push(Ext.apply({},o));break}}else n++}}},getAttachmentIds:function(t,e){var i,n=[];for(i=0;i<t.length;i++)e?Ext.isNumber(t[i])?n.push(t[i]):n.push(t[i].temp_id):(n.push(t[i].id),delete t[i].fromIncludeOrig);return n},getCurrentMailboxIfNeedCopyTo:function(t,e){if(0!==t.subject.indexOf("Re:")||Ext.isEmpty(t.reply_to))return[];var i=SYNO.SDS.MailClient.Format,n=SYNO.SDS.MailClient.Switch,a=[];return e=Ext.isDefined(e)?e:n.inMailboxId,i.isMailboxNeedCopyTo(e)&&a.push(e),a},updateReplyQuoteForSet:function(t){var e=document.createElement("div");return e.innerHTML=t,Ext.get(e).select("div.syno-mc-reply-content").each(function(t,e,i){t.removeClass("syno-mc-reply-content")},this),e.innerHTML}}),Ext.define("SYNO.SDS.MailClient.DraftLib.Saver",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.DraftLib.DraftProcessor"],constructor:function(){this.callParent(arguments)},createDraft:function(t,e,i,n){var a,o=this._getDraftParam(t,null,e,i,n),s=o[0],l=o[1];return a=SYNO.SDS.MailClient.WebAPI.send("createDraft",s),this._makeAbortable(a,function(t){return[t,l]}.bind(this))},setDraft:function(t,e,i){var n,a=this._getDraftParam(t,e,null,null,i),o=a[0],s=a[1];return n=SYNO.SDS.MailClient.WebAPI.send("setDraft",o),this._makeAbortable(n,function(t){return[t,s]}.bind(this))},_makeAbortable:function(t,e){var i=t.then(e);return i.abort=function(){t.abort()},i},getDraft:function(t){return SYNO.SDS.MailClient.WebAPI.send("getDraft",{id:t}).then(function(t){return t.draft[0]=SYNO.SDS.MailClient.Format.formatAddrsOfMsgToNormal(t.draft[0]),t}.bind(this))},_getDraftParam:function(t,e,i,n,a){var o,s=SYNO.SDS.MailClient.DraftLib.DraftProcessor,l=SYNO.SDS.MailClient.Define.DraftType,r=t.temp_attachment;return t.attachment=s.getAttachmentIds(t.attachment),t.temp_attachment=s.getAttachmentIds(t.temp_attachment,!0),o=t,o=SYNO.SDS.MailClient.Format.formatAddrsOfMsgToRFC822(o),e?o.id=e:(i&&(o.refer_to=i.id),n&&(o.draft_type="forward"===n?l.FORWARD:l.REPLY)),a&&(o.draft_type=l.NEW_THREAD),[o,r]}}),Ext.define("SYNO.SDS.MailClient.BaseThreadPanel",{extend:"SYNO.SDS.MailClient.BasePanel",requires:["SYNO.SDS.MailClient.DraftLib.Saver"],checkListView:function(t){if(this.from_self)return void(this.from_self=!1);t.length||this.view.uncheckAll()},clearSelections:function(){this.toolbar.checkNone(),this.view.refresh(),this.view.uncheckAll(),this.notifyChange([])},onViewDisplayed:function(t,e,i){var n,a=SYNO.SDS.MailClient.Window,o=SYNO.SDS.MailClient.DraftLib.Saver,s=i.get("message"),l=i.get("draft"),r=[];return s.length?void SYNO.SDS.MailClient.Control.Mail.loadMessage(i.id):(this.openingDrafts=this.openingDrafts||[],l.forEach(function(t){if(a.draftManager.draftHash.hasOwnProperty(t.id))return void((n=a.popOutWinManager.getItem(t.id))&&!n.win.isVisible()&&a.popOutWinManager.toggleItem(n));-1===this.openingDrafts.indexOf(t.id)&&(this.openingDrafts.push(t.id),r.push(t.id))}.bind(this)),Ext.isEmpty(r)?Promise.resolve():o.getDraft(r).then(function(t){t.draft.forEach(function(t){this.openingDrafts.remove(t.id),a.popOutWinManager.openComposer(t)}.bind(this))}.bind(this)).catch(function(t){this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t))}.bind(this)))},clickNext:function(){var t;if(Ext.isDefined(this.view.removedIdx))t=this.view.removedIdx;else{if(!Ext.isDefined(this.view.lastChecked))return;t=this.view.lastChecked}this.view.removedIdx=this.view.lastChecked=void 0,this.clickByIdx(t)},clickByIdx:function(t){var e=this.threadStore.getAt(t);this.clickByRecord(e)},clickByThreadId:function(t){var e=this.threadStore.getById(t);this.clickByRecord(e)},clickByRecord:function(t){if(t){var e=t.get("message"),i=t.get("draft");(e.length||i.length>1)&&this.view.onDisplayNode(t)}},onViewStarred:function(t,e,i){this.threadAction.setStar([e.data],i)},onViewContextMenu:function(t,e,i,n,a){var o=t.getCheckedItemRecords();t.contextMenu&&(t.contextMenu.setThreadInfo(o,this.getInMailboxId()),t.contextMenu.showAt(n.getXY()))},getInMailboxId:function(){return SYNO.SDS.MailClient.Switch.inMailboxId}}),Ext.define("SYNO.SDS.MailClient.SplitThreadPanel",{extend:"SYNO.SDS.MailClient.BaseThreadPanel",xtype:"mc_SplitThreadPanel",constructor:function(t){this.callParent([this.fillConfig(t)]);var e=SYNO.SDS.MailClient.KeyNavigator.ShortCut;SYNO.SDS.MailClient.Window.regShortCut(this,[e.STAR,e.UP_THREAD,e.DOWN_THREAD]),this.addEvents("togglelist")},fillConfig:function(t){var e=!!t.smallLayout;this.threadStore=SYNO.SDS.MailClient.Lib.PriorityMailbox.getStoreByIdx(t.sectionIdx),this.threadAction=SYNO.SDS.MailClient.Lib.ThreadAction,this.view=new SYNO.SDS.MailClient.ThreadListView({smallLayout:e,boxMinWidth:e?void 0:600,threadAction:this.threadAction,previewLineLayout:SYNO.SDS.MailClient.Settings.preview_layout,displayDensity:SYNO.SDS.MailClient.Settings.display_density,enableFloatingButton:SYNO.SDS.MailClient.Settings.enable_floating_button,disableSelectAllButton:!0,autoFlexcroll:!1,autoHeight:!0,autoWidth:!0,sectionIdx:t.sectionIdx,owner:this,listeners:{scope:this,starred:this.onViewStarred,displayed:this.onViewDisplayed,checked:this.onViewChecked,contextmenu:this.onViewContextMenu,selectionchange:this.onViewSelectionchange}}),this.toolbar=new SYNO.SDS.MailClient.SplitThreadToolbar({displayInfo:!0,hideCheckMenu:!0,sectionIdx:t.sectionIdx,pageSize:SYNO.SDS.MailClient.Lib.PriorityMailbox.getSectionByIdx(t.sectionIdx).page_size,listeners:{scope:this,beforechange:function(t,e){SYNO.SDS.MailClient.Switch.offsetChange(e.offset),SYNO.SDS.MailClient.Control.Mail.clearMessage(),SYNO.SDS.MailClient.Control.Selection.selectThread([])},togglelist:this.onToggleList,displaysection:this.onDisplaySection}});var i={layout:"fit",border:!1,autoFlexcroll:!1,cls:"syno-mc-split-thread-panel",items:[this.view],tbar:{xtype:"container",items:[this.toolbar]}};return Ext.apply(i,t)},arm:function(){this.view.bindStore(this.threadStore),this.toolbar.bindStore(this.threadStore)},disarm:function(){this.view.bindStore(null),this.toolbar.bindStore(null),SYNO.SDS.MailClient.Control.Selection.selectThread([]),SYNO.SDS.MailClient.Window.navigator.regGroupSelection(this.view.navigationGroup,-1),SYNO.SDS.MailClient.Window.navigator.regGroupLastFocus(this.view.navigationGroup,-1)},onToggleList:function(t){this.view.isVisible()?(this.view.hide(),t.addClass("toggle-hide"),this.addClass("list-view-hide")):(this.view.show(),t.removeClass("toggle-hide"),this.removeClass("list-view-hide")),this.fireEvent("togglelist")},onDisplaySection:function(){var t=SYNO.SDS.MailClient.Lib.PriorityMailbox.getConditionBySectionIdx(this.sectionIdx),e=t.get();1==e.length?"mailbox"==e[0].name?SYNO.SDS.MailClient.Control.Sidebar.openMailbox(e[0].value):e[0].name==SYNO.SDS.MailClient.Define.starredId?SYNO.SDS.MailClient.Control.Sidebar.openMailbox(SYNO.SDS.MailClient.Define.starredId):SYNO.SDS.MailClient.Control.Sidebar.openLabel(e[0].value):(t.addCondition("is_search",!0),SYNO.SDS.MailClient.Control.Mail.loadThread(t))},onViewSelectionchange:function(t,e){e.length>0&&this.fireEvent("sectionselectionchange",e[0])},getTotalCheckedItemRecords:function(){return this.owner.getTotalCheckedItemRecords()},adjustSectionTitleText:function(t,e){for(var i,n,a=t.dom.innerText=this.sectionName,o=0;Ext.util.TextMetrics.measure(t,t.dom.innerText).width>e&&(o+=3,i=a.lastIndexOf(":"),!((n=i-o)<=0));)t.dom.innerText=a.slice(0,n)+"..."+a.slice(i)},updateToolbar:function(t){if(this.toolbar.el&&0!==this.toolbar.el.getWidth()){var e=this.toolbar.el.child(".section-name");this.adjustSectionTitleText(e,t-220)}},updateTitle:function(){var t=SYNO.SDS.MailClient.Lib.PriorityMailbox.getSectionTitle(this.sectionIdx);this.toolbar.updateTitle(t),this.sectionName=t},notifyChange:function(t){this.from_self=!0,SYNO.SDS.MailClient.Control.Selection.selectThreadOnPriority(t)},onViewChecked:function(t,e,i,n){this.owner.onViewChecked(n)},getInMailboxId:function(){return SYNO.SDS.MailClient.Lib.PriorityMailbox.getInMailboxIdBySectionIdx(this.sectionIdx)},onViewDisplayed:function(t,e,i){SYNO.SDS.MailClient.Lib.Thread.setCurrentThreadStore(this.sectionIdx),this.fireEvent("sectionDisplayed",this.sectionIdx),SYNO.SDS.MailClient.Window.navigator.regGroupSelection(this.view.navigationGroup,this.sectionIdx),this.callParent(arguments)},onShortCut:function(t){if(!this.ownerCt.ownerCt.activated||!this.ownerCt.activated)return!1;var e=SYNO.SDS.MailClient.Window.navigator.getGroupSelection(this.view.navigationGroup),i=SYNO.SDS.MailClient.Window.navigator.getGroupLastFocus(this.view.navigationGroup);if(this.smallLayout){if(e>=0&&this.sectionIdx!=e)return!1}else if(i>=0&&this.sectionIdx!=i)return!1;var n=SYNO.SDS.MailClient.KeyNavigator.ShortCut;return n.STAR===t?this.view.onShortCutStar():-1!==[n.UP_THREAD,n.DOWN_THREAD].indexOf(t)?this.view.onShortCutThread(t,this.handleShortCutThread):void 0}}),Ext.define("SYNO.SDS.MailClient.PriorityThreadPanel",{extend:"SYNO.SDS.MailClient.BasePanel",requires:["SYNO.SDS.MailClient.SplitThreadPanel"],xtype:"mc_PriorityThreadPanel",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){this.smallLayout=!!t.smallLayout,this.threadStore=SYNO.SDS.MailClient.Lib.Thread.store,this.threadAction=SYNO.SDS.MailClient.Lib.ThreadAction,this.sections=[],Ext.each(SYNO.SDS.MailClient.Lib.PriorityMailbox.getSections(),function(e,i){var n=new SYNO.SDS.MailClient.SplitThreadPanel({sectionIdx:i,smallLayout:this.smallLayout,handleShortCutThread:t.handleShortCutThread,displayInfo:!0,owner:this,listeners:{scope:this,togglelist:this.updateFleXcroll,sectionDisplayed:this.onSectionViewDisplayed,sectionselectionchange:this.onSectionSelectionChange}});this.sections.push(n)},this);var e=this.sections.concat([{xtype:"container",itemId:"emptyEl",cls:"empty-el"},this.emptyIcon=new SYNO.SDS.MailClient.ThreadEmptyView({hidden:!0})]),i={border:!1,items:e,tbar:this.toolbar=new SYNO.SDS.MailClient.PriorityThreadToolbar({displayInfo:!1,hidePrevNext:!0,hideFirstLast:!0,smallLayout:this.smallLayout,listeners:{scope:this,resize:this.onPanelResize,beforechange:function(t,e){SYNO.SDS.MailClient.Switch.offsetChange(e.offset),SYNO.SDS.MailClient.Control.Mail.clearMessage(),SYNO.SDS.MailClient.Control.Selection.selectThread([])},selectall:function(){var t=[];Ext.each(this.sections,function(e,i){e.view.checkAll(),t=t.concat(e.view.getCheckedItemRecords())},this),this.notifyChange(t)},selectnone:function(){var t=[];Ext.each(this.sections,function(e,i){e.view.uncheckAll(),t=t.concat(e.view.getCheckedItemRecords())},this),this.notifyChange(t)},selectcondition:function(t,e){var i=Ext.emptyFn,n=[];"unread"===e||"starred"===e?i=function(e){return e.get(t)>=1}:"read"!==e&&"unstarred"!==e||(i=function(e){return!e.get(t)}),Ext.each(this.sections,function(t,e){t.view.checkByCondition(i,this),n=n.concat(t.view.getCheckedItemRecords())},this),this.notifyChange(n)}}})};return Ext.apply(i,t)},arm:function(){this.mon(SYNO.SDS.MailClient.Switch,"settingchange",this.settingChange,this),this.mon(SYNO.SDS.MailClient.Lib.PriorityMailbox,"viewchecked",this.onViewChecked,this),this.mon(SYNO.SDS.MailClient.Lib.PriorityMailbox,"prioritydataload",this.onPriorityDataLoad,this),this.mon(SYNO.SDS.MailClient.Lib.PriorityMailbox,"prioritydatabeforeload",this.onPriorityDataBeforeLoad,this),Ext.each(this.sections,function(t,e){t.arm()},this),this.settingChange(SYNO.SDS.MailClient.Settings),this.updateSections()},disarm:function(){this.mun(SYNO.SDS.MailClient.Switch,"settingchange",this.settingChange,this),this.mun(SYNO.SDS.MailClient.Lib.PriorityMailbox,"viewchecked",this.onViewChecked,this),this.mun(SYNO.SDS.MailClient.Lib.PriorityMailbox,"prioritydataload",this.onPriorityDataLoad,this),this.mun(SYNO.SDS.MailClient.Lib.PriorityMailbox,"prioritydatabeforeload",this.onPriorityDataBeforeLoad,this),Ext.each(this.sections,function(t,e){t.disarm()},this)},onPriorityDataLoad:function(t){this.updateSectionTitle(t),this.updateEmptyIcon(),this.updateFleXcroll()},onPriorityDataBeforeLoad:function(){this.updateSections(!0)},getTotalCheckedItemRecords:function(){var t=[];return Ext.each(this.sections,function(e,i){t=t.concat(e.view.getCheckedItemRecords())},this),t},getTotalRecordsCount:function(){var t=0;return Ext.each(this.sections,function(e,i){t+=e.view.store.getCount()},this),t},updateEmptyIcon:function(){var t=!1;Ext.each(this.sections,function(e,i){if(e.isVisible())return t=!0,!1},this),t?(this.emptyIcon.setVisible(!1),this.getComponent("emptyEl").setVisible(!0)):(this.emptyIcon.setVisible(!0),this.emptyIcon.updateText(SYNO.SDS.MailClient._T("mail","no_mail_hint")),this.getComponent("emptyEl").setVisible(!1)),this.emptyIcon.updateSizePosition()},settingChange:function(t){Ext.isNumber(t.preview_layout)&&Ext.isNumber(t.display_density)&&Ext.isBoolean(t.enable_floating_button)&&Ext.each(this.sections,function(e,i){e.view.switchViewLayout(t.preview_layout,t.display_density,t.enable_floating_button)},this),this.updateFleXcroll()},loadPriorityThread:function(t){return Ext.each(this.sections,function(t,e){t.view.clearDisplay(),t.view.clearSelections()},this),new Promise(function(e,i){SYNO.SDS.MailClient.Lib.PriorityMailbox.loadData().then(function(){t||this.updateFleXcroll(!0),e()}.bind(this))}.bind(this))},onPanelResize:function(){this.smallLayout&&Ext.each(this.sections,function(t,e){t.updateToolbar(this.getWidth())},this),this.updateFleXcroll()},onSectionViewDisplayed:function(t){SYNO.SDS.MailClient.Lib.PriorityMailbox.setDisplayingSectionIdx(t),Ext.each(this.sections,function(e,i){i!=t&&(e.view.clearDisplay(),e.view.clearSelections())},this)},onSectionSelectionChange:function(t){var e=this.body.dom,i=e.clientHeight,n=parseInt(e.fleXdata.scrollPosition[1][0],10)||0,a=n+i,o=Ext.fly(t).parent(".x-panel-body").dom.offsetTop+t.offsetTop,s=o+t.offsetHeight;o<n?e.fleXcroll.setScrollPos(!1,o):s>a&&e.fleXcroll.setScrollPos(!1,s-i)},clearSelections:function(){Ext.each(this.sections,function(t,e){t.clearSelections()},this),this.toolbar.checkNone(),this.notifyChange([])},notifyChange:function(t){this.ownerCt.activated&&this.activated&&(this.from_self=!0,SYNO.SDS.MailClient.Control.Selection.selectThreadOnPriority(t))},clickNext:function(){Ext.each(this.sections,function(t,e){if(Ext.isDefined(t.view.removedIdx)||Ext.isDefined(t.view.lastChecked))return t.clickNext(),!1})},onViewChecked:function(t){if(!t){var e=this.getTotalCheckedItemRecords();this.updateToolbarCheckStatus(e),this.notifyChange(e)}},updateToolbarCheckStatus:function(t){t.length?t.length==this.getTotalRecordsCount()?this.toolbar.checkAll():this.toolbar.checkPartial():this.toolbar.checkNone()},updateSections:function(t){Ext.each(this.sections,function(e,i){e.rendered&&this.updateSectionTitle(i,t)},this),this.updateEmptyIcon(),this.updateFleXcroll()},updateSectionTitle:function(t,e){var i=SYNO.SDS.MailClient.Lib.PriorityMailbox.getSectionByIdx(t),n=this.sections[t];0===i.type?n.setVisible(!1):e?n.setVisible(!0):n.setVisible(n.threadStore.getCount()>0||!i.hide_when_empty),n.updateTitle(),n.updateToolbar(this.getWidth())}}),Ext.define("SYNO.SDS.MailClient.ConditionObject",{extend:"Object",constructor:function(t,e,i){var n,a;Ext.isObject(t)?(n=t.name,e=t.value,i=t.not_operator,a=!0):n=t,n.startsWith("not")&&(n=n.substr(3),i=!0),"mailbox"==n&&e==SYNO.SDS.MailClient.Define.starredId&&(n=SYNO.SDS.MailClient.Define.starredId,e=!0),"mailbox"==n&&e==SYNO.SDS.MailClient.Define.priorityId&&(n=SYNO.SDS.MailClient.Define.priorityId,e=!0),Ext.isString(e)&&(-1!==["larger","smaller"].indexOf(n)?e=parseInt(e,10):-1!==["mailbox","label"].indexOf(n)?e=a?parseInt(e,10):this.convertToId(n,e):-1!==["before","after"].indexOf(n)?(isNaN(Date.parse(e))&&(e=1e3*parseInt(e,10)),e=new Date(e).valueOf()/1e3):-1!==["has_attachment","unread","starred"].indexOf(n)&&(e="true"===e.toLowerCase())),this.name=n,this.value=e,!0===i&&(this.not_operator=!0)},key:function(){return this.not_operator?"not"+this.name:this.name},toString:function(){var t={};return this.not_operator?t["not"+this.name]=this.getValue():t[this.name]=this.getValue(),Ext.urlEncode(t)},convertToId:function(t,e){var i,n;return"mailbox"===t?(n=SYNO.SDS.MailClient.Switch.getMailboxStore(),i=n.findExact("path",e)):(n=SYNO.SDS.MailClient.Switch.getLabelStore(),i=n.findExact("full_name",e)),!(i<0)&&n.getAt(i).get("id")},getValue:function(){return this._getValue()},getValueForURL:function(){return this._getValue(!0,!1)},getValueForSyntax:function(){return this._getValue(!1,!0)},_getValue:function(t,e){var i,n,a,o=this.name,s=this.value,l=SYNO.SDS.MailClient.Format,r=SYNO.SDS.MailClient.SearchLib.SyntaxParser;if(!(t||"larger"!==o&&"smaller"!==o))return Ext.util.Format.fileSize(s).replace(/\s/g,"");if("mailbox"===o){if(0!==s)return a=SYNO.SDS.MailClient.Control.Model.getMailboxRecordByAttr("id",s),e?(i=r.getDisplayMailboxPath(a),i.search(/\s|"|\(|\)/g)>=0?l.quote(i):i):a?a.get("path"):""}else{if("label"===o)return n=SYNO.SDS.MailClient.Control.Model.getLabelFullNameById(s),e&&n.search(/\s|"|\(|\)/g)>=0?l.quote(n):n;if("after"===o||"before"===o)return new Date(1e3*s).format("Y/m/d")}return s}}),Ext.define("SYNO.SDS.MailClient.Condition",{extend:"Object",requires:["SYNO.SDS.MailClient.ConditionObject"],constructor:function(t){this.reservedNames=["is_search"],this.conditions=[],this.length=this.conditions.length,t&&(t instanceof SYNO.SDS.MailClient.Condition||t.hasOwnProperty("conditions"))?(this.conditions=[].concat(t.get()),this.length=this.conditions.length):t&&this.addCondition.apply(this,arguments),this.callParent(arguments)},get:function(){return this.conditions},equals:function(t){return t.length===this.length&&(t.conditions.sort(),this.conditions.sort(),t.toString()==this.toString())},addCondition:function(t,e,i){var n,a;if(Ext.isArray(t))return void this.addCondition.apply(this,t);if(Ext.isObject(t))for(n=0;n<arguments.length;++n)if(arguments[n].name)this.conditionPush(arguments[n]);else for(a in arguments[n])arguments[n].hasOwnProperty(a)&&this.conditionPush(a,arguments[n][a]);else this.conditionPush(t,e,i)},addUnreadCondition:function(){this.hasUnread()||this.addCondition({name:"unread",value:!0})},concat:function(t){if(Ext.isArray(t))return void this.conditions.concat.apply(this,t);var e,i=new SYNO.SDS.MailClient.Condition(this);for(e=0;e<arguments.length;++e)arguments[e]instanceof SYNO.SDS.MailClient.Condition&&i.conditionConcat(arguments[e].get());return i},conditionPush:function(t,e,i){this.conditions.push(new SYNO.SDS.MailClient.ConditionObject(t,e,i)),this.length=this.conditions.length},conditionConcat:function(t){this.conditions=this.conditions.concat(t),this.length=this.conditions.length},_hasOperator:function(t){return this.conditions.some(function(e){
return e.name===t&&-1!==["true",!0].indexOf(e.value)})},getMailboxId:function(){var t=this._getConditionByName("mailbox");return!t&&this.hasStar()?SYNO.SDS.MailClient.Define.starredId:t?t.value:null},getLabelId:function(){var t=this._getConditionByName("label");return t?t.value:null},_getConditionByName:function(t){return this.conditions.find(function(e){return e.name===t})},isStar:function(){return 1===this.length&&this.conditions[0].name===SYNO.SDS.MailClient.Define.starredId},isDraft:function(){return 1===this.length&&"mailbox"===this.conditions[0].name&&this.conditions[0].value===SYNO.SDS.MailClient.Define.draftsId},isSearch:function(){return this._hasOperator("is_search")},isPriorityMailbox:function(){return 1==this.length&&this.conditions[0].name===SYNO.SDS.MailClient.Define.priorityId},isPriorityMailboxType:function(){var t=this.toObj();return 2===this.conditions.length?!0===t.unread||"true"===t.unread:this.isOnlyMailboxOrLabel()},isOnlyMailboxOrLabel:function(){var t=["mailbox","label","starred",SYNO.SDS.MailClient.Define.priorityId];return 1===this.conditions.length&&-1!==t.indexOf(this.conditions[0].name)},hasMailboxId:function(t){return this.conditions.some(function(e){return t===SYNO.SDS.MailClient.Define.starredId&&"starred"===e.name||"mailbox"===e.name&&e.value===t})},hasAnyMailboxId:function(t){return t.some(function(t){return this.hasMailboxId(t)}.bind(this))},hasLabelId:function(t){return this.conditions.some(function(e){return"label"===e.name&&e.value===t})},hasAnyLabelId:function(t){return t.some(function(t){return this.hasLabelId(t)}.bind(this))},hasAnyMailboxOrLabelId:function(t,e){return this.hasAnyMailboxId(t)||this.hasAnyLabelId(e)},hasUnread:function(){return this.conditions.some(function(t){return"unread"===t.name&&(!0===t.value||"true"===t.value)})},hasStar:function(){return this.conditions.some(function(t){return"starred"===t.name&&(!0===t.value||"true"===t.value)})},isInSentAndNotSearch:function(){return this.hasMailboxId(SYNO.SDS.MailClient.Define.sentId)&&!this.isSearch()},toObj:function(){var t={};return this.conditions.forEach(function(e){"mailbox"===e.name&&0===e.value||"is_search"!==e.name&&(t[e.key()]=e.getValueForURL())}),t},toString:function(){return Ext.urlEncode(this.toObj())},toWebAPIParams:function(){var t,e,i=[];for(t=0;t<this.length;++t)e={name:this.conditions[t].name,value:this.conditions[t].value.toString()},Ext.isDefined(this.conditions[t].not_operator)&&(e.not_operator=this.conditions[t].not_operator),-1===this.reservedNames.indexOf(this.conditions[t].name)&&i.push(e);return i},toSyntaxString:function(){var t,e=["larger","smaller","before","after","mailbox"],i=["has_attachment","starred","unread"],n=["is_search","priority"],a={mailbox:"in:",keyword:"",has_attachment:"has:attachment",starred:"is:starred",unread:"is:unread"},o=[],s=[],l=this.conditions;return l=l.filter(function(t){return-1===n.indexOf(t.name)}),l.forEach(function(n,l,r){var d,c=n.name,h=n.getValueForSyntax(),u=n.not_operator;"mailbox"!==c&&"starred"!==c&&("label"===c?s.push(h):(d=a[c],t=Ext.isDefined(d)?d:c+":","keyword"===c?t=!0===u?"-("+h+")":h:e.indexOf(c)>=0?t+=h:-1===i.indexOf(c)&&(t=!0===u?String.format("{0}(-({1}))",t,h):String.format("{0}({1})",t,h)),o.push(t)))},this),s.length>0&&o.push(1==s.length?"label:"+s[0]:"label:("+s.join(" ")+")"),o.join(" ")},toURLString:function(){var t=SYNO.SDS.MailClient.Define,e="";if(1===this.length)if(this.conditions[0].name===t.starredId)e=t.starredId;else if(this.conditions[0].name===t.priorityId)e=t.priorityId;else if("mailbox"===this.conditions[0].name){var i={"-1":"inbox","-2":"archived","-3":"drafts","-4":"sent","-5":"junk","-6":"trash"};e=this.conditions[0].value<0?i[this.conditions[0].value]:"mailbox/"+encodeURIComponent(this.conditions[0].getValue())}else"label"===this.conditions[0].name&&(e="label/"+encodeURIComponent(this.conditions[0].getValue()));return e||"search/"+encodeURIComponent(this.toString())}}),Ext.define("SYNO.SDS.MailClient.SplitButton",{extend:"SYNO.ux.SplitButton",xtype:"syno_mc_split_button",arrowBtnSelector:"em",constructor:function(t){this.callParent(arguments),this.addClass("syno-mc-button")},onRender:function(t,e){this.menu?this.template=new Ext.Template('<span id="{4}" cellspacing="0" class="x-btn {3}">','<button type="{0}" class="arrow"></button>','<em class="{2} x-unselectable" unselectable="on">',"</em>","</span>"):this.template=new Ext.Template('<span id="{4}" cellspacing="0" class="x-btn {3}">','<em class="{2} x-unselectable" unselectable="on">','<button type="{0}"></button>','<button type="{0}" class="arrow"></button>',"</em>","</span>"),SYNO.ux.SplitButton.superclass.onRender.call(this,t,e),SYNO.ux.Utils.setFormItemIndent(this),this.arrowBtnEl=this.el.child(this.arrowBtnSelector)}}),Ext.define("SYNO.SDS.MailClient.PagingToolbar",{extend:"SYNO.ux.PagingToolbar",xtype:"syno_mc_paging_toolbar",requires:["SYNO.SDS.MailClient.SplitButton"],constructor:function(t){var e={buttonAlign:"left",jumpOffset:1,displayButtons:!1,showRefreshBtn:!1,hideFirstLast:!0,nextText:SYNO.SDS.MailClient._T("common","next_page"),prevText:SYNO.SDS.MailClient._T("common","pre_page"),displayMsg:String.format(SYNO.SDS.MailClient._T("common","display_page"),'<span class="number">{0}</span> - <span class="number">{1}</span>','<span class="number">{2}</span>'),prependButtons:!0,pageSize:100};this.callParent([Ext.apply(e,t)]),this.addClass("syno-mc-paging-toolbar"),this.on({scope:this,afterrender:function(){this.items.each(function(t){"tbspacer"===t.xtype&&t.hide()},this)},resize:function(t,e,i,n,a){if(t.layout.leftTr&&t.layout.rightTr&&t.displayItem){t.displayItem.setWidth("auto");var o=t.displayItem.offsetWidth,s=t.layout.leftTr.offsetWidth+t.layout.rightTr.offsetWidth-e;s>0&&t.displayItem.setWidth(o-s)}}}),this.addEvents("selectall","selectnone","selectcondition")},getMenuItemsConfig:function(){return[{itemId:"all",text:SYNO.SDS.MailClient._T("thread","all")},{itemId:"none",text:SYNO.SDS.MailClient._T("thread","none")},{itemId:"read",hidden:!1===this.enableRead,text:SYNO.SDS.MailClient._T("thread","read")},{itemId:"unread",hidden:!1===this.enableRead,text:SYNO.SDS.MailClient._T("thread","unread")},{itemId:"starred",text:SYNO.SDS.MailClient._T("thread","starred")},{itemId:"unstarred",text:SYNO.SDS.MailClient._T("thread","unstarred")}]},initComponent:function(){var t=SYNO.SDS.MailClient,e=!this.displayButtons,i=[this.first=new t.Button({cls:"syno-mc-tbar-page-first",tooltip:this.firstText,overflowText:this.firstText,iconCls:"x-tbar-page-first",disabled:!0,hidden:this.hideFirstLast,handler:this.moveFirst,scope:this}),this.prev=new t.Button({cls:"syno-mc-tbar-page-prev",tooltip:this.prevText,overflowText:this.prevText,iconCls:"x-tbar-page-prev",disabled:!0,hidden:this.hidePrevNext,handler:this.jumpPageHandler,scope:this}),{xtype:"tbspacer",width:28},this.btn1=new t.Button({iconCls:"syno-ux-page-btn",hidden:e,handler:this.jumpPageHandler,scope:this}),this.btn2=new t.Button({iconCls:"syno-ux-page-btn",hidden:e,handler:this.jumpPageHandler,scope:this}),this.btn3=new t.Button({iconCls:"syno-ux-page-btn-focus",hidden:e,handler:this.jumpPageHandler,scope:this}),this.btn4=new t.Button({iconCls:"syno-ux-page-btn",hidden:e,handler:this.jumpPageHandler,scope:this}),this.btn5=new t.Button({iconCls:"syno-ux-page-btn",hidden:e,handler:this.jumpPageHandler,scope:this}),{xtype:"tbspacer",width:28},this.inputItem=new Ext.form.NumberField({cls:"x-tbar-page-number",allowDecimals:!1,allowNegative:!1,enableKeyEvents:!0,selectOnFocus:!0,submitValue:!1,hidden:!0,listeners:{scope:this,keydown:this.onPagingKeyDown,blur:this.onPagingBlur}}),this.afterTextItem=new Ext.Toolbar.TextItem({hidden:!0,text:String.format(this.afterPageText,1)}),this.next=new t.Button({cls:"syno-mc-tbar-page-next",tooltip:this.nextText,overflowText:this.nextText,iconCls:"x-tbar-page-next",disabled:!0,hidden:this.hidePrevNext,handler:this.jumpPageHandler,scope:this}),this.last=new t.Button({cls:"syno-mc-tbar-page-last",tooltip:this.lastText,overflowText:this.lastText,iconCls:"x-tbar-page-last",disabled:!0,hidden:this.hideFirstLast,handler:this.moveLast,scope:this})];this.checkMenu=new SYNO.SDS.MailClient.SplitButton({itemId:"checkMenu",cls:"syno-mc-check-menu-btn",iconCls:"syno-mc-check-menu-btn-icon",scope:this,handler:function(t,e){t.toggle(),t.pressed?(t.removeClass("select-partial").addClass("select-all"),this.checkAll(),this.fireEvent("selectall",{})):(t.removeClass("select-partial").removeClass("select-all"),this.checkNone(),this.fireEvent("selectnone",{}))},menu:{cls:"syno-mc-menu",items:this.getMenuItemsConfig(),listeners:{scope:this,itemclick:this.checkMenuClick}}});var n=[];this.hideCheckMenu||(n=[this.checkMenu]);var a=this.rightItems||[],o=["->"].concat(a);this.displayInfo&&(o=["->"].concat(a,[this.displayItem=new Ext.Toolbar.TextItem({cls:"syno-mc-tb-info"})]));var s=this.items||this.buttons||[];this.prependButtons?this.items=n.concat(s,o,i):this.items=n.concat(o,i,s),this.refresh=new t.Button({tooltip:this.refreshText,overflowText:this.refreshText,iconCls:"x-tbar-loading",handler:this.doRefresh,scope:this,hidden:!this.showRefreshBtn}),this.showRefreshBtn&&(this.items.push("-"),this.items.push(this.refresh),this.items.push(this.loading=new t.Button({tooltip:_JSLIBSTR("uicommon","searching"),overflowText:_JSLIBSTR("uicommon","searching"),iconCls:"x-tbar-loading-process",hidden:!0}))),delete this.buttons,Ext.PagingToolbar.superclass.initComponent.call(this),this.addEvents("change","beforechange"),this.on("afterlayout",this.onFirstLayout,this,{single:!0}),this.cursor=0,this.bindStore(this.store,!0)},bindStore:function(t,e){var i;if(!e&&this.store&&(t!==this.store&&this.store.autoDestroy?this.store.destroy():(this.store.un("beforeload",this.beforeload,this),this.store.un("load",this.onLoad,this),this.store.un("datachanged",this.onDataChanged,this),this.store.un("remove",this.onDataChanged,this),this.store.un("exception",this.onLoadError,this)),t||(this.store=null)),t&&(t=Ext.StoreMgr.lookup(t),t.on({scope:this,beforeload:this.beforeLoad,load:this.onLoad,datachanged:this.onDataChanged,remove:this.onDataChanged,exception:this.onLoadError}),i=!0),this.store=t,i&&this.onLoad(t,null,{}),t&&t.lastOptions&&t.lastOptions.params){this.cursor=t.lastOptions.params.offset;var n=this.getPageData(),a=n.activePage,o=n.pages;this.prev.setDisabled(1==a),this.next.setDisabled(a==o),this.updateInfo()}},onLoad:function(t,e,i){if(!this.rendered)return void(this.dsLoaded=[t,e,i]);var n=this.getParams();this.cursor=i.params&&i.params[n.start]?i.params[n.start]:0;var a=this.getPageData(),o=a.activePage,s=a.pages;this.afterTextItem.setText(String.format(this.afterPageText,a.pages)),this.inputItem.setValue(o),this.first.setDisabled(1==o),this.prev.setDisabled(1==o),this.next.setDisabled(o>=s),this.last.setDisabled(o>=s),this.refresh.enable(),this.updateInfo(),this.fireEvent("change",this,a)},getStoreCount:function(){return this.store.getCount()},checkMenuClick:function(t,e){var i,n=0;switch(t.itemId){case"all":this.checkAll(),this.fireEvent("selectall");break;case"none":this.checkNone(),this.fireEvent("selectnone");break;case"starred":case"unstarred":case"read":case"unread":case"pgp":var a=this.checkFn(t.itemId);if(!1===a)return;n=a[0],i=a[1],n?n==this.getStoreCount()?this.checkAll():this.checkPartial():this.checkNone(),this.fireEvent("selectcondition",i,t.itemId)}},checkFn:Ext.emptyFn,checkAll:function(){this.checkMenu.toggle(!0),this.checkMenu.removeClass("select-partial").addClass("select-all")},checkPartial:function(){this.checkMenu.toggle(!0),this.checkMenu.removeClass("select-all").addClass("select-partial")},checkNone:function(){this.checkMenu.toggle(!1),this.checkMenu.removeClass("select-all").removeClass("select-partial")},onDataChanged:function(){this.updateInfo()},updateInfo:function(){var t,e=this.store.getCount(),i=this.store.getTotalCount(),n=this.getPageData(),a=n.activePage,o=n.pages;i<=this.cursor&&(this.cursor=Math.max(0,this.cursor-SYNO.SDS.MailClient.Switch.getRegister("limit")),a--,this.prev.setDisabled(1==a||!i)),this.next.setDisabled(a>=o||!i),this.displayItem&&(t=0===e?this.emptyMsg:String.format(this.displayMsg,this.cursor+1,this.cursor+e,this.store.getTotalCount()),this.displayItem.setText(t)),this.checkMenu.setDisabled(!e)}}),Ext.define("SYNO.SDS.MailClient.ThreadToolbar",{extend:"SYNO.SDS.MailClient.PagingToolbar",requires:[],constructor:function(t){SYNO.SDS.MailClient.ThreadToolbar.superclass.constructor.call(this,this.fillConfig(t)),this.mon(SYNO.SDS.MailClient.Switch,"settingchange",this.onSettingChange,this)},fillConfig:function(t){var e,i=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId;e=t.smallLayout?[{type:"Button",actionId:i.Reload}]:[{type:"Button",actionId:i.Reload},{type:"Button",actionId:i.RemoveLabel},{type:"Button",actionId:i.Archive},{type:"SplitButton",actionId:i.Spam},{type:"SplitButton",actionId:i.NotSpam},{type:"Button",actionId:i.DeleteMail},{type:"Button",actionId:i.DeleteForever},{type:"Button",actionId:i.DiscardDraft},{type:"Button",actionId:i.ArchiveInLabel},{type:"Button",actionId:i.MoveTo},{type:"Button",actionId:i.Label},{type:"Button",actionId:i.More}];var n={hideFirstLast:!1,items:SYNO.SDS.MailClient.Lib.Factory.createActionButtonsByInfo(e)};return Ext.apply(n,t)},doLoad:function(t){var e={},i=this.getParams();e[i.start]=t,e[i.limit]=this.pageSize,!1!==this.fireEvent("beforechange",this,e)&&this.store.load({params:e})},checkFn:function(t){var e,i=0,n={starred:"star",unstarred:"star",read:"unread",unread:"unread"}[t],a={starred:!0,unstarred:!1,read:!1,unread:!0}[t];if(!n)return!1;for(e=0;e<this.store.getCount();++e){a==!!this.store.getAt(e).get(n)&&i++}return[i,n]},checkListView:function(t){t.length||this.checkNone()},onSettingChange:function(t){this.pageSize=t.conversations_per_page},jumpPageHandler:function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),this.callParent(arguments)},moveFirst:function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),this.callParent(arguments)},moveLast:function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),this.callParent(arguments)}}),Ext.define("SYNO.SDS.MailClient.PriorityThreadToolbar",{extend:"SYNO.SDS.MailClient.ThreadToolbar",constructor:function(t){this.callParent(arguments)},getStoreCount:function(){return SYNO.SDS.MailClient.Lib.PriorityMailbox.getStoreCount()},checkFn:function(t){var e=0,i=SYNO.SDS.MailClient.Lib.PriorityMailbox.getStores(),n={starred:"star",unstarred:"star",read:"unread",unread:"unread"}[t],a={starred:!0,unstarred:!1,read:!1,unread:!0}[t];return!!n&&(Ext.each(i,function(t,i){for(i=0;i<t.getCount();++i){var o=t.getAt(i),s=!!o.get(n);a==s&&e++}},this),[e,n])}}),Ext.define("SYNO.SDS.MailClient.SplitThreadToolbar",{extend:"SYNO.SDS.MailClient.PagingToolbar",xtype:"mc_SplitThreadToolbar",constructor:function(t){SYNO.SDS.MailClient.ThreadToolbar.superclass.constructor.call(this,this.fillConfig(t)),this.addEvents("togglelist"),this.addClass("split-thread-toolbar"),this.displayItem&&this.displayItem.on({scope:this,afterrender:function(t){t.el.on("click",this.displaySection,this),Ext.QuickTips.register({target:t,text:SYNO.SDS.MailClient._T("priority_mailbox","show_more")})}})},fillConfig:function(t){var e={hideFirstLast:!1,items:[{xtype:"syno_mc_button",cls:"toggle-list-btn",itemId:"toggle_btn",scope:this,handler:this.toggleList},{xtype:"tbtext",cls:"section-name",itemId:"section_name",text:"",listeners:{scope:this,afterrender:function(t){t.el.on("click",this.toggleList,this)}}}]};return Ext.apply(e,t)},toggleList:function(){this.fireEvent("togglelist",this.getComponent("toggle_btn"))},displaySection:function(){this.fireEvent("displaysection")},onPriorityMailboxChange:function(){this.pageSize=SYNO.SDS.MailClient.Lib.PriorityMailbox.getSectionByIdx(this.sectionIdx).page_size},updateTitle:function(t){this.getComponent("section_name").setText(Ext.util.Format.htmlEncode(t))},jumpPageHandler:function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),this.callParent(arguments)},moveFirst:function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),this.callParent(arguments)},moveLast:function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),this.callParent(arguments)}}),Ext.define("SYNO.SDS.MailClient.ThreadEmptyView",{extend:"Ext.Container",constructor:function(t){var e={cls:"syno-mc-message-selection",items:[{xtype:"container",cls:"syno-mc-message-selection-inner",itemId:"inner",items:[{xtype:"box",cls:"syno-mc-empty-icon"},{xtype:"container",cls:"no-selection-text",itemId:"selectionText",html:""}]}]};this.callParent([Ext.apply(e,t)]),this.on("resize",function(t,e,i,n,a,o){this.updateSizePosition()},this)},arm:Ext.emptyFn,disarm:Ext.emptyFn,updateText:function(t){var e=this.getComponent("inner").getComponent("selectionText");e.rendered&&e.update(t)},updateSizePosition:function(){if(this.isVisible()){var t=SYNO.SDS.MailClient.Window.getPanel("SYNO.SDS.MailClient.CardPanel"),e=this.getComponent("inner"),i=.4*(t.getHeight()-12-200+33);e.el.setTop(i-33+2)}}}),Ext.define("SYNO.SDS.MailClient.BasicListViewDragZone",{extend:"Ext.dd.DragZone",constructor:function(t,e){this.view=t,this.callParent([t.getEl(),e])},getDragData:function(t){var e=t.getTarget(this.view.itemSelector),i=this.view.getCheckedItemIndexes();if(!e)return!1;var n,a=[],o=[];if(i.length)a=i,n=this.view.getNode(i[0]);else{if(!e)return!1;a=[this.view.indexOf(e)],n=e}var s,l=document.createElement("div");if(SYNO.SDS.MailClient.Switch.inPriority&&Ext.isFunction(this.view.getTotalCheckedItemRecords))o=this.view.getTotalCheckedItemRecords(),Ext.isEmpty(o)&&o.push(this.view.getStore().getAt(this.view.indexOf(e)));else for(s=0;s<a.length;++s)o.push(this.view.getStore().getAt(a[s]));return this.view.isSelectAll?l.innerHTML=Ext.util.Format.htmlEncode(String.format(this.view.dragString,this.view.selectAllCount||this.view.store.getTotalCount())):l.innerHTML=Ext.util.Format.htmlEncode(String.format(o.length>1?this.view.dragString:this.view.dragSingleString,o.length)),{ddel:l,source:this.dragSource,target:n,data:o,isSelectAll:this.view.isSelectAll}},getRepairXY:function(){return Ext.Element.fly(this.dragData.target).getXY()}}),Ext.define("SYNO.SDS.MailClient.BasicListViewDropZone",{extend:"Ext.dd.DropZone",constructor:function(t,e){this.view=t,this.callParent([t.getEl(),e])},getTargetFromEvent:function(t){return t.getTarget(this.view.itemSelector)},onNodeOver:function(t,e,i,n){return this.allowDrop(n)?this.dropAllowed:this.dropNotAllowed},onNodeDrop:function(t,e,i,n){return!!this.allowDrop(n)&&(this.view.drop(t,n),!0)},allowDrop:function(t){return-1!==this.dropSource.indexOf(t.source)}}),Ext.define("SYNO.SDS.MailClient.TemplateMenu",{extend:"SYNO.ux.Menu",constructor:function(t){t.tpl?this.tpl=t.tpl:this.tpl=new Ext.XTemplate("Need Template and Data"),this.addEvents("applytemplate"),this.callParent([t]),this.on("beforeshow",function(t){t.applyTpl()}),this.on("beforehide",this.onMenuBeforeHide,this)},onRender:function(t,e){this.callParent(arguments),this.mun(this.ul,{scope:this,click:this.onClick,mouseover:this.onMouseOver,mouseout:this.onMouseOut}),this.focusEl=this.ul=this.el,this.mon(this.el,{scope:this,click:this.onClick,mouseover:this.onMouseOver,mouseout:this.onMouseOut}),this.displayData&&this.tpl.overwrite(this.el,this.displayData)},show:function(t,e,i,n){this.displayData=t,this.callParent([e,i,n])},applyTpl:function(){this.displayData&&(this.tpl.overwrite(this.el,this.displayData),this.fireEvent("applytemplate",this),this.doLayout(!1,!0))},showAt:function(t,e){!1!==this.fireEvent("beforeshow",this)&&(this.parentMenu=e,this.el||this.render(),this.enableScrolling?(this.el.setXY(t),t[1]=this.constrainScroll(t[1]),t=[this.el.adjustForConstraints(t)[0],t[1]]):t=this.el.adjustForConstraints(t),this.el.setXY(t),this.el.show(),Ext.menu.Menu.superclass.onShow.call(this),Ext.isIE&&(this.fireEvent("autosize",this),Ext.isIE8||this.el.repaint()),this.hidden=!1,this.fireEvent("show",this))},onMenuBeforeHide:function(t){t.lastDom=null}}),Ext.define("SYNO.SDS.MailClient.NameCard",{extend:"SYNO.SDS.MailClient.TemplateMenu",defaultOffsets:[0,-2],constructor:function(t){var e={cls:"syno-mc-name-card selectabletext",starredCls:"syno-ux-cb-checked",tpl:this.getTemplate()};this.callParent([Ext.apply(e,t)]),this.on("applytemplate",function(t){t.addContactEl=Ext.get(t.el.query(".addcontact")[0]),t.syncEl=Ext.get(t.el.query(".sync-status")[0])})},getTemplate:function(){var t=SYNO.SDS.MailClient._T;return new Ext.XTemplate('<div class="star-ct">','<tpl if="existed">','<div class="star <tpl if="starred">syno-ux-cb-checked</tpl>"></div>',"</tpl>","</div>",'<div class="info-ct">','<div class="name">{full_name:htmlEncode}</div>','<div class="mail">{show_mail:htmlEncode}</div>','<div class="action">','<tpl if="!existed">','<span class="addcontact">',t("card","add"),"</span>","</tpl>",'<tpl if="existed">','<span class="info">',t("card","info"),"</span>","</tpl>",'<span class="listmail">',t("card","mails"),"</span>",'<div class="sync-status x-hide-display"></div>',"</div>",'<div class="action-buttons">','<tpl if="chat_valid">','<div class="chat" ext:qtip="',t("card","chat"),'"></div>',"</tpl>",'<div class="compose" ext:qtip="',t("card","compose"),'"></div>',"</div>","</div>")},onClick:function(t){var e=t.target,i=SYNO.SDS.MailClient.OP;if(e.classList.contains("info")){var n,a={};if(this.displayData.addressbook_id&&(a.aid=this.displayData.addressbook_id),this.displayData.id&&(a.cid=this.displayData.id),!(n=SYNO.SDS.WindowLauncher.Util.getStandaloneLaunchURL("SYNO.Contacts.AppInstance",a)))return;window.open(n),this.hide(!0)}else if(e.classList.contains("addcontact"))this.syncEl.addClass("syncing").removeClass("x-hide-display"),i.createContact({full_name:this.displayData.full_name,name:{given_name:this.displayData.full_name},mail:[{data:this.displayData.show_mail}],apply_default:!0},function(t,e,i,n){if(this.displayData.full_name==i.full_name){if(!t)return void this.syncEl.addClass("failed").removeClass("syncing");this.displayData.id=e.id,this.displayData.existed=!0,this.applyTpl()}},this);else if(e.classList.contains("listmail"))SYNO.SDS.MailClient.Control.Mail.searchWithAddress(this.displayData.show_mail),this.hide(!0);else if(e.classList.contains("star")){var o,s;if(!this.displayData.id)return;o=e.classList.contains(this.starredCls),s=o?i.labelRemoveMember:i.labelAddMember,e.classList.toggle(this.starredCls),s({contact_ids:[this.displayData.id],apply_default:!0},function(t,i,n,a){if(-1!=n.contact_ids.indexOf(this.displayData.id))return t?void(this.displayData.starred=!o):void e.classList.toggle(this.starredCls)},this)}else e.classList.contains("chat")?(SYNO.SDS.Chat.Integration.Export.initiateAnonymous(this.displayData.additional.extra_info.directory_object_id),this.hide(!0)):e.classList.contains("compose")&&(SYNO.SDS.MailClient.Window.popOutWinManager.openComposer({to:[this.displayData.show_mail]}),this.hide(!0))}}),Ext.define("SYNO.SDS.MailClient.NameCardPlugin",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.NameCard"],init:function(t){this.namecard=new SYNO.SDS.MailClient.NameCard({listeners:{scope:this,afterrender:function(t){t.mon(t.el,{scope:this,mouseover:function(){this.inNameCard=!0},mouseleave:function(){this.inNameCard=!1,t.hide()}})}}}),this.namecardDelayTask=new Ext.util.DelayedTask(function(t){var e=Ext.fly(t);if(e&&(e.getWidth()||e.getHeight())){if(this.overName!=t)return void(this.overName=this.outName=void 0);var i="textContent"in t?t.textContent:t.innerText,n=t.getAttribute("email"),a=t.getAttribute("displayname")||i;SYNO.SDS.MailClient.OP.listContact({keyword:[n],additional:["extra_info"]},function(e,i,o,s){if(this.overName==t&&e){var l,r=Ext.fly(t).findParent(".syno-ux-menu");r&&r.id&&(l=Ext.getCmp(r.id));var d=this.getPreciseContactByEmail(i.contact,n),c=Ext.apply({existed:Ext.isDefined(d),full_name:a,show_mail:n,chat_valid:Ext.isDefined(d)&&function(t){return SYNO.SDS.AppUtil.isValidApp("SYNO.SDS.Chat.Application")&&SYNO.SDS.MailClient.Define.isNormalMode&&SYNO.SDS.Chat.Integration.Export.canInitiateAnonymous(t)}(d.additional.extra_info.directory_object_id),starred:Ext.isDefined(d)&&d.additional.extra_info.is_starred},d);this.namecard.show(c,t,null,l)}},this)}},this),t.on({scope:this,afterrender:function(t){t instanceof SYNO.ux.FleXcroll.DataView?(t.mon(t.el,{mouseover:this.onMouseOver,mouseout:this.onMouseOut,contextmenu:this.cancel,scope:this}),t.mon(t.el,"mouseleave",function(){this.inNameCard||this.namecard.hide(),this.onMouseOut(arguments)},this,{delay:50})):t instanceof SYNO.ux.Menu&&t.mon(t.el,{mouseover:this.onMenuMouseOver,mouseout:this.onMenuMouseOut,mouseleave:this.cancel,click:this.cancel,scope:this})}})},cancel:function(){this.namecardDelayTask.cancel(),this.overName=void 0},onMenuMouseOver:function(t,e,i){this.onMouseOver(t)},onMenuMouseOut:function(t,e,i){this.onMouseOut(t)},onMouseOver:function(t){var e=t.target;e.hasAttribute("email")?this.namecardDelayTask.delay(500,null,null,[e]):(this.outName=this.overName,this.namecard.hide()),this.overName=e},onMouseOut:function(t){this.overName&&(this.outName=this.overName)},getPreciseContactByEmail:function(t,e){for(var i,n=t.filter(function(t){return-1!==t.additional.extra_info.mail.map(function(t){return t.toLowerCase()}).indexOf(e.toLowerCase())}),a=0;a<n.length;++a)if(i=n[a],i.additional.extra_info.directory_object_id>0)return i;return i}}),Ext.define("SYNO.SDS.MailClient.BasicListView",{extend:"SYNO.ux.FleXcroll.DataView",requires:["SYNO.SDS.MailClient.BasicListViewDragZone","SYNO.SDS.MailClient.BasicListViewDropZone","SYNO.SDS.MailClient.NameCardPlugin"],itemSelectorCls:"item-wrap",checkedAreaCls:"check-area",checkedItemList:[],selectAllDBCls:"select-all-db",contextMenu:null,keepChecked:!1,displayedNodeId:null,constructor:function(t){var e={selectedClass:"item-selected",checkedClass:"item-checked",displayedClass:"item-displayed",removeSelectedStyleClass:"item-selected-but-you-cant-see",singleSelect:!0,checkIconCls:"syno-ux-checkbox-icon",checkedCls:"syno-ux-cb-checked",updateScrollBarEventNames:["afterlayout","resize","show"]};this.callParent([Ext.apply(e,t)]),this.on({afterrender:function(t){t.addClass("syno-mc-basic-list-view"),t.dragZone||!t.enableDrag&&!t.enableDD||(t.dragZone=new SYNO.SDS.MailClient.BasicListViewDragZone(t,{ddGroup:t.ddGroup,dragSource:t.dragSource})),t.dropZone||!t.enableDrop&&!t.enableDD||(t.dropZone=new SYNO.SDS.MailClient.BasicListViewDropZone(t,{ddGroup:t.ddGroup,dropSource:t.dropSource})),Ext.isChrome&&this.el.on({scope:this,focus:function(t){}})},selectalldb:function(t){t.isSelectAll=!0},checked:function(t,e,i){i||(t.isSelectAll=!1,t.setSelectAllBtnVisible(!1))}}),this.isSelectAll=!1,this.lastCheckedIdx=null,this.restoreCheckedIds=[],this.addEvents("starred","displayed","checked","afterstoreload","datachange","selectalldb"),this.selectAllEl=this.selectedAllEl=void 0},bindStore:function(t,e){this.store&&(this.store.un("load",this.onStoreLoad,this),this.store.un("syncupdate",this.onStoreSync,this)),this.callParent(arguments),t&&(t.on("load",this.onStoreLoad,this),t.on("syncupdate",this.onStoreSync,this)),this.updateScroller(),this.clearCheckedItemList()},onBeforeLoad:function(){this.keepChecked&&(this.keepCheckedItem(),this.keepChecked=!1),this.loadingText&&this.clearCheckedItemList(),this.callParent(arguments)},onStoreSync:function(t,e,i){this.keepCheckedItem(),this.keepChecked=!1},onDataChanged:function(t,e){e&&this.keepCheckedItem(),this.callParent(arguments)},keepCheckedItem:function(){var t,e=[],i=this.getCheckedItemRecords();for(t=0;t<i.length;++t)i[t]&&e.push(i[t].get("id"));this.restoreCheckedIds=e},select:function(t){this.callParent(arguments),this.getNode(t)&&Ext.fly(this.getNode(t)).removeClass(this.removeSelectedStyleClass)},restoreCheckedItem:function(){var t,e,i;if(this.restoreCheckedIds.length){for(i=0;i<this.restoreCheckedIds.length;++i)(t=this.store.getById(this.restoreCheckedIds[i]))&&(e=this.store.indexOf(t),this.setCheckedItem(e,!0));this.restoreCheckedIds=[]}this.updateDisplayedItem()},needRemoveSelectedClass:function(t){var e=this.getNode(t);return e&&this.isSelected(e)&&Ext.fly(e).hasClass(this.removeSelectedStyleClass)},onUpdate:function(t,e){var i=this.needRemoveSelectedClass(e);this.callParent(arguments),i&&Ext.fly(this.getNode(e)).addClass(this.removeSelectedStyleClass);var n=this.store.indexOf(e);-1<this.checkedItemList.indexOf(n)&&(this.setCheckedItem(n,!0),this.fireEvent("checked",this,[e],!0,!0)),this.updateDisplayedItem()},onRemove:function(t,e,i){this.removeCheckedItemList(i),this.callParent(arguments)},refresh:function(){delete this.selectAllEl,delete this.selectedAllEl,this.isSelectAll=!1;var t,e;this.clearCheckedItemList(),this.callParent(arguments),this.restoreCheckedItem(),this.displayedNodeId&&(e=this.store.getById(this.displayedNodeId),t=this.needRemoveSelectedClass(e),SYNO.SDS.MailClient.Control.Main.isMessageMode()&&this.fireEvent("checked",this,this.getCheckedItemRecords(),!0),t&&Ext.fly(this.getNode(e)).addClass(this.removeSelectedStyleClass))},updateIndexes:function(t,e){var i,n=this.all.elements;t=t||0,e=e||(0===e?0:n.length-1);for(var a=t;a<=e;a++)-1<(i=this.checkedItemList.indexOf(n[a].viewIndex))&&(this.checkedItemList[i]=a),n[a].viewIndex=a},onStoreLoad:function(){this.fireEvent("afterstoreload",this)},onClick:function(t,e,i){var n=Ext.fly(e);if(n){var a,o,s,l,r,d=[];if(!(o=n.hasClass(this.itemSelectorCls)?n:n.parent("."+this.itemSelectorCls)))return void(n.hasClass(this.selectAllDBCls)&&(this.showSelectedAllItem(),this.fireEvent("selectalldb",this)));if(s=this.indexOf(o),l=this.store.getAt(s),n.hasClass("star"))this.onStar(l);else if(n.hasClass(this.checkIconCls)||n.hasClass(this.checkedAreaCls)){var c=n.hasClass(this.checkIconCls)?n:Ext.fly(n.query("."+this.checkIconCls)[0]);if(!c)return;if(a=c.hasClass(this.checkedCls),SYNO.SDS.MailClient.Settings.conversations_per_page===this.checkedItemList.length&&!0===a&&(this.refresh(),this.checkAll()),c.toggleClass(this.checkedCls),t.shiftKey&&null!==this.lastCheckedIdx){var h=this.lastCheckedIdx,u=h>s?s:h,S=h>s?h:s;for(r=u;r<=S;++r)this.setCheckedItem(r,!a),d.push(this.store.getAt(r))}else this.setCheckedItem(s,!a),d.push(l);this.lastCheckedIdx=s,this.updateDisplayedItem(),this.fireEvent("checked",this,d,!a)}else n.parent(".floating-btns")?this._onFloatingBtnsClick(n,l):(this.callParent(arguments),this.onDisplayNode(l),this.store&&Ext.fly(this.getNode(l)).addClass(this.removeSelectedStyleClass))}},onStar:function(t){var e=this.getNode(t),i=Ext.fly(e);if(i){var n=i.child(".star"),a=n.hasClass(this.checkedCls);n.toggleClass(this.checkedCls),this.fireEvent("starred",this,t,!a)}},_onFloatingBtnsClick:function(t,e){if(!t.parent(".x-item-disabled")){var i=SYNO.SDS.MailClient.Lib.ThreadAction;t.hasClass("archive")?i.setMailbox([e],SYNO.SDS.MailClient.Settings.archive_mailbox):t.hasClass("delete")?i.setMailbox([e],SYNO.SDS.MailClient.Define.trashId):t.hasClass("delete-forever")?i.deleteForever([e.get("id")]):t.hasClass("discard")?i.discard([e.data]):t.hasClass("read")?i.markRead([e.data],!0):t.hasClass("unread")?i.markRead([e.data],!1):t.hasClass("add-todo")&&i.addToTodoList([e.data])}},clearDisplay:function(){if(this.displayedNodeId&&this.store){var t=this.getNode(this.store.getById(this.displayedNodeId));t&&Ext.fly(t).removeClass(this.displayedClass),this.displayedNodeId=null}},onDisplayNode:function(t){SYNO.SDS.MailClient.Settings.conversations_per_page===this.checkedItemList.length&&this.refresh(),this.clearDisplay(),Ext.fly(this.getNode(t)).addClass(this.displayedClass),this.displayedNodeId=t.id,this.ensureVisible(this.store.indexOf(t)),this.fireEvent("displayed",this,this.store,t)},onKeySpace:function(t){this.onKeySpaceEnter()},onKeyEnter:function(t){this.onKeySpaceEnter()},onKeySpaceEnter:function(){var t=this.getSelectedRecords();1===t.length&&this.onDisplayNode(t[0])},onContextMenu:function(t){var e=t.getTarget(this.itemSelector,this.getTemplateTarget());if(e){var i=this.indexOf(e)
;-1==this.checkedItemList.indexOf(i)&&(this.clearCheckedItemList(),this.setCheckedItem(i,!0),this.lastCheckedIdx=i,this.updateDisplayedItem(),this.fireEvent("checked",this,[this.store.getAt(i)],!0)),this.fireEvent("contextmenu",this,i,e,t)}else this.fireEvent("containercontextmenu",this,t)},updateDisplayedItem:function(){var t=this.store.getById(this.displayedNodeId),e=this.store.indexOf(t),i=this.getNode(e);i?this.checkedItemList.length&&-1===this.checkedItemList.indexOf(e)?Ext.fly(i).removeClass(this.displayedClass):Ext.fly(i).addClass(this.displayedClass):this.displayedNodeId=null},setCheckedItem:function(t,e){e?this.addCheckedItemList(t):this.removeCheckedItemList(t),this.setCheckedNodeCls(t,e)},setCheckedNodeCls:function(t,e){var i=e?"addClass":"removeClass",n=this.getNode(t);n&&Ext.fly(n)[i](this.checkedClass).child("."+this.checkIconCls)[i](this.checkedCls)},getCheckedItemIndexes:function(){return this.checkedItemList},getCheckedItemRecords:function(){var t=[],e=0;for(e=0;e<this.checkedItemList.length;++e)t.push(this.store.getAt(this.checkedItemList[e]));return t},clearCheckedItemList:function(){Ext.each(this.checkedItemList,function(t){this.setCheckedNodeCls(t,!1)},this),this.checkedItemList=[],this.fireEvent("datachange",this.checkedItemList)},addCheckedItemList:function(t){t<0||(0>this.checkedItemList.indexOf(t)&&this.checkedItemList.push(t),this.fireEvent("datachange",this.checkedItemList))},removeCheckedItemList:function(t){t<0||(this.checkedItemList.remove(t),this.fireEvent("datachange",this.checkedItemList))},checkAll:function(){var t=0;for(t=0;t<this.getNodes().length;++t)this.setCheckedItem(t,!0);this.setSelectAllBtnVisible(!0)},uncheckAll:function(){if(this.store){var t=0;for(t=0;t<this.getNodes().length;++t)this.setCheckedItem(t,!1);this.updateDisplayedItem(),this.clearCheckedItemList(),this.setSelectAllBtnVisible(!1)}},checkByCondition:function(t,e){var i=0;for(i=0;i<this.getNodes().length;++i)this.setCheckedItem(i,t.call(this,this.store.getAt(i)));this.updateDisplayedItem(),this.selectAllEl&&this.selectAllEl.setVisible(!1),this.selectedAllEl&&this.selectedAllEl.setVisible(!1)},setSelectAllBtnVisible:Ext.emptyFn,showSelectedAllItem:function(){this.selectAllEl&&this.selectAllEl.hide(),this.selectedAllEl&&this.selectedAllEl.show(),this.updateScroller()},drop:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.ModalWindow",{extend:"SYNO.SDS.ModalWindow",owner:null,constructor:function(t){var e=Ext.isString(t.cls)?t.cls+" syno-mc-modal-window":"syno-mc-modal-window";t.cls=e;var i=[{key:Ext.EventObject.ENTER,scope:this,fn:this.onApply},{key:Ext.EventObject.ESC,scope:this,fn:this.onCancel}];t.keys?Ext.isArray(t.keys)?t.keys.concat(i):Ext.isObject(t.keys)&&(t.keys=i.push(t.keys)):t.keys=i,t.owner=t.owner||SYNO.SDS.MailClient.Window,this.callParent([t])},onApply:Ext.emptyFn,onCancel:function(){this.close()},onShow:function(){this.callParent(arguments),this.owner===SYNO.SDS.MailClient.Window&&SYNO.SDS.MailClient.Window.popOutWinManager.disableComposer()},onHide:function(){this.callParent(arguments),this.owner===SYNO.SDS.MailClient.Window&&SYNO.SDS.MailClient.Window.popOutWinManager.enableComposer()}}),Ext.define("SYNO.SDS.MailClient.PGP.ConfirmSendPanel",{extend:"SYNO.SDS.Utils.FormPanel",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply","error")},fillConfig:function(t){var e={cls:"syno-mc-import-form-panel",height:230,items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("pgp","plain_confirm")},{xtype:"syno_checkbox",itemId:"dontRemind",boxLabel:SYNO.SDS.MailClient._T("pgp","dont_remind")}]};return Ext.apply(e,t),e},getValue:function(){return this.getComponent("dontRemind").getValue()},onApply:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.PGP.ConfirmSendDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.PGP.ConfirmSendPanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply","cancel")},fillConfig:function(t){this.formPanel=new SYNO.SDS.MailClient.PGP.ConfirmSendPanel;var e={border:!1,width:450,height:230,minWidth:450,minHeight:230,title:SYNO.SDS.MailClient._T("pgp","open_pgp"),items:[this.formPanel],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","ok"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),keys:[{key:27,scope:this,handler:this.onCancel}]};return Ext.apply(e,t)},onApply:function(){this.formPanel.onApply(),this.fireEvent("apply",this.formPanel.getValue()),this.close()},onCancel:function(){this.fireEvent("cancel"),this.close()}}),Ext.define("SYNO.SDS.MailClient.PGP.GeneratePanel",{extend:"SYNO.SDS.Utils.FormPanel",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply","error"),this.encryption=SYNO.SDS.MailClient.PGP.Encryption},fillConfig:function(t){var e={height:300,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"name",name:"name",allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("common","name")},{xtype:"syno_textfield",itemId:"email",name:"email",allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("common","email")},{xtype:"syno_textfield",itemId:"password",name:"password",inputType:"password",allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pgp","passphrase")}]};return Ext.apply(e,t),e},getValue:function(t){return this.getComponent(t).getValue()},onApply:function(){var t=this.getValue("name"),e=this.getValue("email"),i=this.getValue("password"),n=function(){this.unmaskAppWin()}.bind(this);return this.ownerCt.setStatusBusy({text:SYNO.SDS.MailClient._T("pgp","generating_key")}),this.encryption.generateKey(t,e,i).then(function(t){return Promise.all([this.encryption.remoteAddKeys(t.publicKeyArmored),this.encryption.remoteAddKeys(t.privateKeyArmored)])}.bind(this)).then(function(t){return n(),this.ownerCt.owner.gridPanel.refresh(),this.ownerCt.close(),t}.bind(this)).catch(function(t){return n(),this.fireEvent("error",{text:SYNO.SDS.MailClient._T("pgp","generate_key_fail")}),Promise.reject(t)}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.PGP.GenerateDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.PGP.GeneratePanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){this.formPanel=new SYNO.SDS.MailClient.PGP.GeneratePanel({listeners:{scope:this,error:function(t){this.setStatusError({text:t.text?t.text:SYNO.SDS.MailClient.Error.getErrorString(t)})}}});var e={border:!1,width:530,height:300,minWidth:530,minHeight:300,title:SYNO.SDS.MailClient._T("pgp","generate_key"),items:[this.formPanel],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","ok"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),keys:[{key:27,scope:this,handler:this.onCancel}]};return Ext.apply(e,t)},onApply:function(){this.formPanel.onApply()},onCancel:function(){this.close()}}),Ext.define("SYNO.SDS.MailClient.PGP.ImportPanel",{extend:"SYNO.SDS.Utils.FormPanel",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply","error"),this.encryption=SYNO.SDS.MailClient.PGP.Encryption},fillConfig:function(t){var e={height:300,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pgp","paste_key")},{xtype:"syno_textarea",itemId:"content",hideLabel:!0,width:400},{xtype:"syno_filebutton",itemId:"file",name:"file",inputType:"file",buttonText:SYNO.SDS.MailClient._T("pgp","read_from_file"),hideLabel:!0,buttonOnly:!0,listeners:{scope:this,change:this.onSelectFile}}]};return Ext.apply(e,t),e},onSelectFile:function(){var t=this.getComponent("file"),e=this.getComponent("content"),i=t.el.dom.files;return i.length<1?Promise.resolve():i[0].size>1048576?Promise.resolve():this.encryption.readFile(i[0]).then(function(t){e.setValue(t)})},addKey:function(t){return this.remoteAdd(t)},localAddCore:function(t){return this.encryption.addKeys(t)},localAdd:function(t){return this.localAddCore(t)?Promise.resolve():Promise.reject("localAdd failed")},remoteAdd:function(t){return this.encryption.remoteAddKeys(t)},onApply:function(){var t=this.getComponent("content"),e=t.getValue();this.addKey(e).then(function(){this.fireEvent("apply")}.bind(this)).catch(function(t){this.fireEvent("error",{text:SYNO.SDS.MailClient._T("pgp","invalid_key")})}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.PGP.ImportDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.PGP.ImportPanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){this.formPanel=new SYNO.SDS.MailClient.PGP.ImportPanel({listeners:{scope:this,apply:function(){this.owner.gridPanel.refresh(),this.close()},error:function(t){this.setStatusError({text:t.text?t.text:SYNO.SDS.MailClient.Error.getErrorString(t)})}}});var e={border:!1,width:530,height:300,minWidth:530,minHeight:300,title:SYNO.SDS.MailClient._T("pgp","import_key"),items:[this.formPanel],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","ok"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),keys:[{key:27,scope:this,handler:this.onCancel}]};return Ext.apply(e,t)},onApply:function(){this.formPanel.onApply()},onCancel:function(){this.close()}}),Ext.define("SYNO.SDS.MailClient.Setting.GridPanel",{extend:"SYNO.ux.GridPanel",emptyString:"",checkEmptyState:function(){this.callParent(arguments),this.store&&this.rendered&&this.emptyString&&(0===this.store.getCount()?this.mask(this.emptyString):this.unmask())},mask:function(t){this.view.el.mask(t,"syno-ux-grid-mask-info"),this.view.focusEl.set({tabIndex:-1}),this.view.setHeaderFocusTabbable(!1)},unmask:function(){this.view.el.unmask(),this.view.focusEl.set({tabIndex:0}),this.view.setHeaderFocusTabbable(!0)},renderCheckBox:function(t,e,i){var n="disabled"===t?"disabled":t?"checked":"unchecked",a="disabled"!==n&&"checked"===n,o=i?i.id+"_"+this.dataIndex:Ext.id(),s="disabled"===n?_T("common","disabled"):_JSLIBSTR("uicommon","enable_column_"+n),l="disabled"===n;return e=e||{},e.cellAttr=String.format('aria-label="{0} {1}" aria-checked="{2}" aria-disabled="{3}" role="checkbox"',Ext.util.Format.stripTags(this.orgHeader),s,a,l),String.format('<div class="syno-ux-grid-enable-column-{0}" id="{1}"></div>',n,o)}}),Ext.define("SYNO.SDS.MailClient.Setting.EditorGridPanel",{extend:"SYNO.ux.EditorGridPanel",emptyString:"",checkEmptyState:function(){this.callParent(arguments),this.store&&this.rendered&&this.emptyString&&(0===this.store.getCount()?this.mask(this.emptyString):this.unmask())},mask:function(t){this.view.el.mask(t||_T("common","loading"),"syno-ux-grid-mask-info"),this.view.focusEl.set({tabIndex:-1}),this.view.setHeaderFocusTabbable(!1)},unmask:function(){this.view.el.unmask(),this.view.focusEl.set({tabIndex:0}),this.view.setHeaderFocusTabbable(!0)}}),Ext.define("SYNO.SDS.MailClient.Setting.DDGridPanel",{extend:"SYNO.ux.DDGridPanel",emptyString:"",constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this,"rowmousedown",this.onRowMouseDown,this)},checkEmptyState:function(){this.callParent(arguments),this.store&&this.rendered&&this.emptyString&&(0===this.store.getCount()?this.mask(this.emptyString):this.unmask())},mask:function(t){this.view.el.mask(t,"syno-ux-grid-mask-info"),this.view.focusEl.set({tabIndex:-1}),this.view.setHeaderFocusTabbable(!1)},unmask:function(){this.view.el.unmask(),this.view.focusEl.set({tabIndex:0}),this.view.setHeaderFocusTabbable(!0)},onRowMouseDown:function(t,e,i){i.ctrlKey||i.shiftKey||t.getSelectionModel().selectRow(e)}}),Ext.define("SYNO.SDS.MailClient.PGP.KeyMgrGridPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.PGP.GenerateDialog","SYNO.SDS.MailClient.PGP.ImportDialog"],constructor:function(t){this.encryption=SYNO.SDS.MailClient.PGP.Encryption,this.emptyString=SYNO.SDS.MailClient._T("setting","empty_mailbox"),this.callParent([this.fillConfig(t)]),this.loadData()},fillConfig:function(t){var e=[],i=(new SYNO.ux.EnableColumn({header:_T("common","hide"),dataIndex:"hide",width:50,menuDisabled:!0}),new Ext.grid.RowSelectionModel({singleSelect:!0,listeners:{scope:this,selectionchange:function(t){var e=t.hasSelection(),i=this.getTopToolbar(),n=i.getComponent("delete"),a=i.getComponent("export");n.setDisabled(!e),a.setDisabled(!e)}}})),n=[{header:SYNO.SDS.MailClient._T("pgp","key_name"),dataIndex:"name",width:150,renderer:function(t,e,i){return t}},{header:SYNO.SDS.MailClient._T("pgp","key_type"),dataIndex:"type",width:150,renderer:function(t,e,i){return 1===t?SYNO.SDS.MailClient._T("pgp","public"):2===t?SYNO.SDS.MailClient._T("pgp","private"):t}},{header:_T("common","email"),dataIndex:"email",width:240},{header:SYNO.SDS.MailClient._T("pgp","key_id"),dataIndex:"key_id",width:240}],a=new Ext.grid.ColumnModel({columns:n}),o={autoExpandColumn:"email",enableColumnMove:!1,tbar:this.getTbarCfg(),store:this.getStore(),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),sm:i,colModel:a,plugins:e};return Ext.apply(o,t),o},createStore:function(){return this.encryption.createPGPKeyStore()},getStore:function(){return this.store=this.store||this.createStore(),this.store},refresh:function(){this.loadData()},getLocalData:function(){return{key:this.encryption.getKeys()}},loadDataCore:function(t){t=t||{},t.data?this.store.loadData(t.data):this.store.load()},loadFromLocal:function(){this.loadDataCore({data:this.getLocalData()})},loadFromRemote:function(t){t?this.loadDataCore({data:SYNO.SDS.MailClient.PGPKey}):this.loadDataCore()},loadData:function(){this.loadFromRemote()},isDirty:function(){return this.store.getModifiedRecords().length>0},onGenerateKey:function(){new SYNO.SDS.MailClient.PGP.GenerateDialog({owner:this.findWindow()}).open()},localDeleteKey:function(){var t=this.getSelectionModel().getSelections();t.length<1||(Ext.each(t,function(t){var e=t.get("key_id");this.encryption.removeKey(e)},this),this.refresh())},onDeleteKey:function(){var t,e=this.getSelectionModel().getSelections();if(!(e.length<1)){t={key_id:e[0].get("key_id"),type:e[0].get("type")};var i=function(){this.refresh()}.bind(this);return SYNO.SDS.MailClient.WebAPI.deletePGPKey(t).then(function(t){return i(),t}.bind(this)).catch(function(t){return i(),Promise.reject(t)}.bind(this))}},onImportKey:function(){new SYNO.SDS.MailClient.PGP.ImportDialog({owner:this.findWindow()}).open()},onExportKey:function(){var t,e,i,n,a=this.getSelectionModel().getSelections();a.length<1||(t=a[0].get("name"),e=a[0].get("type"),i=a[0].get("text"),n=String.format("{0}_{1}.asc",t,1===e?"pub":"priv"),SYNO.SDS.MailClient.FileOP.saveTextToFile(i,n))},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this},items:[{itemId:"generate",text:SYNO.SDS.MailClient._T("pgp","generate"),handler:this.onGenerateKey},{itemId:"delete",text:_T("common","delete"),disabled:!0,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("pgp","delete_key_confirm"),function(t){"yes"===t&&this.onDeleteKey()},this)}},{itemId:"import",text:SYNO.SDS.MailClient._T("common","import"),handler:this.onImportKey},{itemId:"export",text:SYNO.SDS.MailClient._T("common","export"),handler:this.onExportKey,disabled:!0}]}}}),Ext.define("SYNO.SDS.MailClient.PGP.KeyMgrDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.PGP.KeyMgrGridPanel"],constructor:function(t){var e=Ext.apply(t,{title:SYNO.SDS.MailClient._T("pgp","key_management"),height:500,width:780,resizable:!1,layout:"fit",items:[this.gridPanel=new SYNO.SDS.MailClient.PGP.KeyMgrGridPanel],buttons:[{xtype:"syno_button",text:_T("common","alt_finish"),handler:this.close,scope:this}]});this.callParent([e])}}),Ext.define("SYNO.SDS.MailClient.PGP.SelectKeyPanel",{extend:"SYNO.SDS.Utils.FormPanel",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply","error"),this.encryption=SYNO.SDS.MailClient.PGP.Encryption},fillConfig:function(t){this.keyData=t.keyData;var e={height:300,defaults:{width:250},items:[{xtype:"syno_displayfield",html:SYNO.SDS.MailClient._T("pgp","select_sign_key")},{xtype:"syno_mc_combobox",itemId:"key",tabindex:-1,hideLabel:!0,allowBlank:!1,store:new Ext.data.JsonStore({fields:["key","keyId","userId"],data:this.keyData}),displayField:"userId",valueField:"key",value:this.keyData[0].key,tpl:'<tpl for="."><div class="x-combo-list-item" ext:qtip="{keyId:htmlEncode}">{userId:htmlEncode}</div></tpl>',listeners:{scope:this,select:Ext.emptyFn}}]};return Ext.apply(e,t),e},getValue:function(){return this.getComponent("key").getValue()},onApply:function(){}}),Ext.define("SYNO.SDS.MailClient.PGP.SelectKeyDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.PGP.SelectKeyPanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply","cancel")},fillConfig:function(t){this.formPanel=new SYNO.SDS.MailClient.PGP.SelectKeyPanel({keyData:t.keyData,listeners:{scope:this,error:function(t){this.setStatusError({text:t.text?t.text:SYNO.SDS.MailClient.Error.getErrorString(t)})}}});var e={border:!1,width:350,height:200,minWidth:350,minHeight:200,title:SYNO.SDS.MailClient._T("pgp","select_sign_key"),items:[this.formPanel],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","ok"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),keys:[{key:27,scope:this,handler:this.onCancel}]};return Ext.apply(e,t)},onApply:function(){this.formPanel.onApply(),this.fireEvent("apply",this.formPanel.getValue()),this.close()},onCancel:function(){this.fireEvent("cancel"),this.close()}}),Ext.define("SYNO.SDS.MailClient.PGP.UnlockPanel",{extend:"SYNO.ux.FormPanel",constructor:function(t){this.encryption=SYNO.SDS.MailClient.PGP.Encryption,this.callParent([this.fillConfig(t)]),this.addEvents("apply","error")},fillConfig:function(t){var e={items:[{xtype:"syno_displayfield",html:SYNO.SDS.MailClient._T("pgp","enter_passphrase_desc")+"<br>"+Ext.util.Format.htmlEncode(t.userId)+" ["+t.keyId+"]"},{xtype:"syno_textfield",itemId:"password",textType:"password",fieldLabel:SYNO.SDS.MailClient._T("pgp","passphrase"),width:100}]};return Ext.apply(e,t),e},onApply:function(){var t=this.getComponent("password"),e=t.getValue();this.encryption.unlockKey(this.key,e).then(function(){this.fireEvent("success")}.bind(this)).catch(function(){this.fireEvent("error",{text:SYNO.SDS.MailClient._T("pgp","invalid_passphrase")})}.bind(this))},onCancel:function(){this.fireEvent("fail")}}),Ext.define("SYNO.SDS.MailClient.PGP.UnlockDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.PGP.UnlockPanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){this.formPanel=new SYNO.SDS.MailClient.PGP.UnlockPanel({key:t.key,keyId:t.keyId,userId:t.userId,listeners:{scope:this,error:function(t){this.setStatusError({text:t.text?t.text:SYNO.SDS.MailClient.Error.getErrorString(t)})},success:function(){this.fireEvent("success"),this.close()},fail:function(){this.fireEvent("fail"),this.close()}}});var e={layout:"fit",border:!1,title:SYNO.SDS.MailClient._T("pgp","enter_passphrase"),width:450,height:230,items:[this.formPanel],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","ok"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),keys:[{key:27,scope:this,handler:this.onCancel}]};return Ext.apply(e,t)},onApply:function(){this.formPanel.onApply()},onCancel:function(){this.formPanel.onCancel(),this.close()}}),Ext.define("SYNO.SDS.MailClient.PGP.Encryption",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.PGP.ConfirmSendDialog","SYNO.SDS.MailClient.PGP.GenerateDialog","SYNO.SDS.MailClient.PGP.ImportDialog","SYNO.SDS.MailClient.PGP.KeyMgrDialog","SYNO.SDS.MailClient.PGP.SelectKeyDialog","SYNO.SDS.MailClient.PGP.UnlockDialog"],singleton:!0,basePath:"webman/3rdparty/MailClient/js/openpgpjs/",constructor:function(){window.enc=this,this.callParent(arguments),this.addEvents("initialize"),this.init()},init:function(){return window.openpgp?this.initCmps():new Promise(function(t,e){var i=document.createElement("script");i.type="text/javascript",i.src=this.basePath+"openpgp.min.js",Ext.fly(i).on({scope:this,load:function(){this.initCmps()},error:function(){e()}},this),document.head.appendChild(i)}.bind(this))},initCmps:function(){return(openpgp.getWorker()?Promise.resolve():openpgp.initWorker({path:this.basePath+"openpgp.worker.min.js"})).then(function(){return this.keyring=new openpgp.Keyring,this.keyring.load()}.bind(this)).then(function(){SYNO.SDS.MailClient.PGPKey&&this.reloadFromWebAPIResp(SYNO.SDS.MailClient.PGPKey),this.fireEvent("initialize")}.bind(this)).catch(function(t){SYNO.Debug.error(t)})},readFile:function(t,e){return t.size>SYNO.SDS.MailClient.Define.PGPKeyFileSizeLimit?Promise.reject("file too large"):new Promise(function(i,n){var a=new FileReader,o="binary"===e;a.onload=function(){var t=a.result;o&&(t=new Uint8Array(t)),i(t)},a.onerror=function(){n(a)},a[o?"readAsArrayBuffer":"readAsText"](t)})},readKey:function(t){return openpgp.key.readArmored(t).then(function(t){return 0===t.keys.length?Promise.reject("readKey failed."):t.keys[0]})},decode:function(t){return openpgp.armor.decode(t).catch(function(t){return{type:-1}})},detectContentType:function(t){return this.decode(t).then(function(t){switch(t.type){case-1:return SYNO.SDS.MailClient.Define.EncryptionStat.NONE;case 2:return SYNO.SDS.MailClient.Define.EncryptionStat.SIGNED;case 3:return SYNO.SDS.MailClient.Define.EncryptionStat.ENCRYPTED;default:return SYNO.SDS.MailClient.Define.EncryptionStat.NONE}})},parseUserId:function(t){var e=SYNO.SDS.MailClient.Format.addressWithDisplayNameRegExp,i=e.exec(t);return i?{name:i[1],email:i[3]}:null},parseMultipleArmoredText:function(t){for(var e,i,n,a,o=/^-----END[^-]+-----$/gm,s=[0],l=[];i=o.exec(t);)s.push(i.index+i[0].length);for(e=0;e<s.length-1;++e)n=s[e],a=s[e+1],l.push(t.substr(n,a-n));return l},getRemainingText:function(t){var e=/-----END PGP MESSAGE-----/,i=e.exec(t);return i?t.substr(i.index+i[0].length):""},addKey:function(t){return this.readKey(t).then(function(e){return e.isPublic()?this.importKey(t,!0):e.isPrivate()?this.importKey(t,!1):Promise.reject()}.bind(this)).catch(function(t){SYNO.Debug.error(t)})},addKeys:function(t){var e=this.parseMultipleArmoredText(t);return Promise.all(e.map(function(t){return this.addKey(t)},this))},remoteAddKeys:function(t){return this.addKeys(t).then(function(t){if(0===t.length)return Promise.reject("no available keys");var e=t.map(function(t){var e=this.parseUserId(t.getUserIds().join());return e?{apiType:"addPGPKey",params:{type:t.isPublic()?1:2,key_id:t.primaryKey.getKeyId().toHex(),name:e.name,email:e.email,text:t.armor()}}:Promise.reject("parse userIds failed")},this);return SYNO.SDS.MailClient.WebAPI.send(e)}.bind(this)).then(function(t){return t}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this))},removeKey:function(t){var e=this.keyring.removeKeysForId(t);return this.keyring.store(),e},generateKey:function(t,e,i,n){return n=n||2048,t&&SYNO.SDS.MailClient.Format.isNonEAIAddrSpec(e)&&n&&i?openpgp.generateKey({userIds:[{name:SYNO.SDS.MailClient.Tool.encode_utf8(t),email:e}],numBits:n,passphrase:i}).then(function(t){return this.importKey(t.publicKeyArmored,!0),this.importKey(t.privateKeyArmored,!1),t}.bind(this)):Promise.reject("format")},importKey:function(t,e){e=!!e;var i=this,n=i.keyring[e?"publicKeys":"privateKeys"];return n.importKey(t).then(function(t){if(t)return Promise.reject("import key failed");var a=n.keys[n.keys.length-1];return e!==a.isPublic()?(n.keys.remove(a),Promise.reject("key type error")):(i.keyring.store(),a)}.bind(this)).catch(function(t){SYNO.Debug.error(t)})},isKeyLocked:function(t){return t.primaryKey.isEncrypted},unlockKey:function(t,e){return Ext.isString(t)&&(t=this.getPrivateKeyById(t)),t instanceof openpgp.key.Key?t.decrypt(e):Promise.reject()},mapKeyToData:function(t){var e=t.primaryKey.getKeyId().toHex(),i=t.getUserIds().sort().join(),n=this.parseUserId(i);return{key_id:e,name:n.name,email:n.email,key:t}},mapKeysToData:function(t){return t.map(this.mapKeyToData,this)},showUnlockDialog:function(t,e){return new Promise(function(i,n){new SYNO.SDS.MailClient.PGP.UnlockDialog({key:t,keyId:t.primaryKey.getKeyId().toHex(),userId:t.getUserIds().sort().join(),owner:e||SYNO.SDS.MailClient.Window,listeners:{success:function(){i()},fail:function(){n({code:SYNO.SDS.MailClient.Define.PGPStat.CANCEL})}}}).show()}.bind(this))},showSelectKeyDialog:function(t,e){return new Promise(function(i,n){var a=this.getPrivateKeyByEmail(t);if(0===a.length)return void n({code:SYNO.SDS.MailClient.Define.PGPStat.NO_AVAILABLE_KEY});if(1===a.length)return void i(a[0]);var o=a.map(function(t){return{key:t,userId:t.getUserIds().sort().join(),keyId:t.primaryKey.getKeyId().toHex()}},this);new SYNO.SDS.MailClient.PGP.SelectKeyDialog({keyData:o,owner:e||SYNO.SDS.MailClient.Window,listeners:{apply:function(t){i(t)},cancel:function(){n({code:SYNO.SDS.MailClient.Define.PGPStat.CANCEL})}}}).show()}.bind(this))},showSendConfirmDialog:function(t){return SYNO.SDS.MailClient.UserSettingProperty.getPGPDontRemind()?Promise.resolve():new Promise(function(e,i){new SYNO.SDS.MailClient.PGP.ConfirmSendDialog({owner:t||SYNO.SDS.MailClient.Window,listeners:{apply:function(t){t&&SYNO.SDS.MailClient.UserSettingProperty.setPGPDontRemind(!0),e()},cancel:function(){i({code:SYNO.SDS.MailClient.Define.PGPStat.CANCEL})}}}).show()}.bind(this))},createPGPKeyStore:function(){return new Ext.data.JsonStore({autoDestroy:!0,root:"key",idProperty:"id",fields:["id","key_id","type","name","email","text"],data:SYNO.SDS.MailClient.PGPKey,proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.PGPKey",method:"list",version:1,listeners:{load:function(t,e,i,n){return SYNO.SDS.MailClient.PGP.Encryption.reloadFromWebAPIResp(e).then(function(){SYNO.SDS.MailClient.PGPKey=e,SYNO.SDS.MailClient.Switch.PGPKeyChange()}.bind(this))}}})})},getContactData:function(t){var e=this.getPublicKeyByEmails(t);return this.mapKeysToData(e)},getSigningKey:function(t,e){return this.showSelectKeyDialog(t,e)},ensureKeyUnlocked:function(t,e){return this.isKeyLocked(t)?this.showUnlockDialog(t,e):Promise.resolve()},ensureKeysUnlocked:function(t,e){return t.map(function(t){return this.ensureKeyUnlocked.bind(this,t,e)},this).reduce(function(t,e){return t.then(e)},Promise.resolve())},getKeyMap:function(){var t={},e=this.keyring.publicKeys.keys.concat(this.keyring.privateKeys.keys);return Ext.each(e,function(e){var i=e.getUserIds().sort().join(),n=e.primaryKey.getKeyId().toHex(),a={};t[n]?(a=t[n],a.type="pair"):(t[n]=a,a.type=e.isPublic()?"public":"private",a.userId=i)}),t},getKeys:function(){var t=this.getKeyMap(),e=[];return Ext.iterate(t,function(t,i){var n=this.parseUserId(i.userId);n&&e.push({key_id:t,type:i.type,name:n.name,email:n.email})}),e},getMessage:function(t,e){return openpgp.message[e?"read":"readArmored"](t).catch(function(t){})},getPublicKeyByEmail:function(t){return this.keyring.publicKeys.getForAddress(t)},getPrivateKeyByEmail:function(t){return this.keyring.privateKeys.getForAddress(t)},getPublicKeyById:function(t,e){return this.keyring.publicKeys.getForId(t,e)},getPrivateKeyById:function(t,e){return this.keyring.privateKeys.getForId(t,e)},getPublicKeyByEmails:function(t){var e=t.map(function(t){return this.getPublicKeyByEmail(t)},this);return[].concat.apply([],e)},isPGPAvailable:function(t){return this.getPublicKeyByEmails(t).length>0},getEncryptionKeyIds:function(t){return t.getEncryptionKeyIds().map(function(t){return t.toHex()},this)},getDecryptableKey:function(t){var e=null;return t instanceof openpgp.message.Message?(Ext.each(t.getEncryptionKeyIds(),function(t){if(e=this.keyring.privateKeys.getForId(t.toHex(),!0))return!1},this),e):null},getNoAvailableKeyReject:function(t){return Promise.reject({code:SYNO.SDS.MailClient.Define.PGPStat.NO_AVAILABLE_KEY,msg:"no available key, need "+this.getEncryptionKeyIds(t).join(" "),info:this.getEncryptionKeyIds(t)})},decrypt:function(t){var e,i;return this.getMessage(t).then(function(t){return e=t,i=this.getDecryptableKey(e),i?this.ensureKeyUnlocked(i):this.getNoAvailableKeyReject(e)}.bind(this)).then(function(){return openpgp.decrypt({message:e,publicKeys:this.keyring.publicKeys.keys,privateKeys:[i]})}.bind(this)).then(function(t){var e={raw:t,data:t.data,encryptionStat:SYNO.SDS.MailClient.Define.EncryptionStat.DECRYPTED};return t.signatures&&t.signatures.length>0&&(e.verifyInfo=this.processSignatures(t.signatures),e.verifyInfo.valid?e.encryptionStat=SYNO.SDS.MailClient.Define.EncryptionStat.DECRYPTED_VALID:e.encryptionStat=SYNO.SDS.MailClient.Define.EncryptionStat.DECRYPTED_INVALID),e}.bind(this)).catch(function(t){return Promise.reject(t)})},encrypt:function(t,e,i){i=i||[];var n={message:openpgp.message.fromText(t),publicKeys:e,armor:!0};return Ext.isEmpty(i)||(n.privateKeys=i),this.ensureKeysUnlocked(i).then(openpgp.encrypt.bind(this,n)).then(function(t){return n.armor?t.data:t.message})},getClearTextMessage:function(t){return openpgp.cleartext.readArmored(t).catch(function(t){})},isSigned:function(t){return!!t.getSigningKeyIds().length},verify:function(t){return window.lastVerify=t,this.getClearTextMessage(t).then(function(t){return openpgp.verify({message:t,publicKeys:this.keyring.publicKeys.keys})}.bind(this)).then(function(t){return this.processSignatures(t.signatures)}.bind(this)).catch(function(t){SYNO.Debug.error(t)})},processSignatures:function(t){var e=this.parseSignatures(t),i=e.filter(function(t){return!0===t.valid}),n=this.getVerifyInfos(t),a=null,o="";return Ext.each(n,function(t){if(t.valid)return a=t,!1},this),e.length>0&&(o=e[0].keyid),{signatures:t,parsedSignatures:e,validSignatures:i,valid:i.length>0,verifyInfos:n,verifiedInfo:a,keyId:o}},parseSignatures:function(t){var e=[];return Ext.each(t,function(t){var i=t.keyid.toHex(),n=this.getPublicKeyById(i,!0),a=n?n.getUserIds():[];e.push({keyid:i,usersIds:a,valid:t.valid})},this),e},getVerifyInfos:function(t){var e=this.parseSignatures(t),i=[];return Ext.each(e,function(t){var e=t.keyid;Ext.each(t.usersIds,function(n){var a=this.parseUserId(n);i.push({userId:n,keyId:e,name:a.name,email:a.email,valid:t.valid})},this)},this),i},sign:function(t,e){return this.ensureKeysUnlocked(e).then(function(){return openpgp.sign({message:openpgp.cleartext.fromText(t),privateKeys:e,armor:!0})})},clearAllKeys:function(){this.keyring.clear(),this.keyring.store()},firePGPKeyChange:function(){SYNO.SDS.MailClient.Switch.PGPKeyChange()},loadFromWebAPIResp:function(t){return this.keyring?Promise.all(t.key.map(function(t){return this.addKey(t.text)},this)):Promise.resolve()},reloadFromWebAPIResp:function(t){return this.clearAllKeys(),this.loadFromWebAPIResp(t)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Util",{singleton:!0,requires:["SYNO.SDS.MailClient.PGP.Encryption"],shouldShowMsg:function(t){var e=SYNO.SDS.MailClient.Switch,i=SYNO.SDS.MailClient.Define,n=i.trashId===e.inMailboxId,a=i.junkId===e.inMailboxId,o=!1;return o=e.syntaxMailboxes.some(function(t){var e=t.toLowerCase();return"trash"===e||"junk"===e}),!(0!==e.inMailboxId||!o)||!(n&&t.mailbox_id!=i.trashId||a&&t.mailbox_id!=i.junkId||!n&&!a&&-1<[i.trashId,i.junkId].indexOf(t.mailbox_id))},isMsgMovable:function(t,e,i,n){var a=SYNO.SDS.MailClient.Define,o=i===a.trashId||i===a.junkId,s=e===a.trashId||e===a.junkId,l=e===a.draftsId,r=t.mailbox_id===a.sentId,d=t.mailbox_id===a.junkId,c=t.mailbox_id===a.trashId,h=SYNO.SDS.MailClient.Format.isSharedMailbox(t.mailbox_id),u=a.isReadOnlyMailbox(t.mailbox_id);if(l||u)return!1;if(void 0===t.mailbox_id)return!1;if(n){if((d||c||h)&&i!==t.mailbox_id)return!1;if(o&&i!==t.mailbox_id)return!1
;if(!s&&r&&i!==t.mailbox_id)return!1}return!0},isUnread:function(t){return!t.read},hasStar:function(t){return t.star},msgToId:function(t){return t.id},getMostSuitableMsg:function(t){function e(t){return t.attachment&&1===t.attachment.length&&"winmail.dat"===t.attachment[0]}function i(t){var i=t.mailbox_id,r=a.getMailboxStore().getById(i),d=r?o.getDisplayMailboxPath(r):"",c=0;return i!==s&&i!==a.inMailboxId||(c+=2),-1!==l.indexOf(d)&&(c+=1),2===t.type&&(a.inMailboxId===n.sentId?c+=1:c-=1),e(t)&&(c-=10),c}var n=SYNO.SDS.MailClient.Define,a=SYNO.SDS.MailClient.Switch,o=SYNO.SDS.MailClient.SearchLib.SyntaxParser,s=SYNO.SDS.MailClient.Control.Main.getPriorityMailboxId(),l=a.syntaxMailboxes,r=t;return void 0===s&&(s=null),void 0===l&&(l=[]),r.sort(function(t,e){return i(e)-i(t)}),r[0]},isMsgIdInDraftManager:function(t){return SYNO.SDS.MailClient.Window.draftManager.draftHash.hasOwnProperty(t)},fillEncryptionInfo:function(t){return SYNO.SDS.MailClient.PGPSettings.enable_pgp&&!Ext.isDefined(t.pgp_encryption)&&t.body&&t.body.plain?SYNO.SDS.MailClient.PGP.Encryption.detectContentType(t.body.plain).then(function(e){return t.pgp_encryption=e,t.pgp_encryption===SYNO.SDS.MailClient.Define.EncryptionStat.SIGNED?this._verify(t):t}.bind(this)).catch(function(t){}):Promise.resolve(t)},fillEncryptionInfoForMsgs:function(t){return Promise.all(t.map(function(t){return this.fillEncryptionInfo(t)},this))},_verify:function(t){var e=SYNO.SDS.MailClient.PGP.Encryption,i=t.body.plain;return e.verify(i).then(function(e){return t.pgp_verify_info=e,e.verifiedInfo?t.pgp_encryption=SYNO.SDS.MailClient.Define.EncryptionStat.VALID_SIGN:t.pgp_encryption=SYNO.SDS.MailClient.Define.EncryptionStat.INVALID_SIGN,t}.bind(this)).catch(function(t){})}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Normalizer",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.Util"],constructor:function(){this.callParent(arguments)},normalizeMsgs:function(t){var e,i=SYNO.SDS.MailClient.Define.MessageStat,n=SYNO.SDS.MailClient.MessageHouseLib.Util;return e=this._classifyMsgByRfcMsgId(t),Object.keys(e).map(function(t){var a=e[t],o=n.getMostSuitableMsg(a);return o=SYNO.SDS.MailClient.Array.deepCopy(o),o.operation_ids=a.map(n.msgToId),o.message_status=n.isMsgIdInDraftManager(o.id)?i.FROM_DRAFT:i.PREVIEW,o.read=!a.some(n.isUnread),o.star=a.some(n.hasStar),o},this)},_classifyMsgByRfcMsgId:function(t){function e(t,e){return!!Ext.isArray(e)&&(e.length>0&&e[0].body_preview!==t.body_preview)}var i=SYNO.SDS.MailClient.MessageHouseLib.Util,n=SYNO.SDS.MailClient.enableAdvancedRfcMsgIdGrouping,a={};return t=t.filter(function(t){return i.shouldShowMsg(t)}),t.forEach(function(t){var i=t.rfc_message_id;if(n)for(;e(t,a[i]);)i=i+"_"+Math.random().toString(36).substr(2,3);a[i]=a[i]||[],a[i].push(t)},this),a}}),Ext.define("SYNO.SDS.MailClient.ThreadListViewDragZone",{extend:"SYNO.SDS.MailClient.BasicListViewDragZone",getDragData:function(t){if(SYNO.SDS.MailClient.Switch.inMailboxId===SYNO.SDS.MailClient.Define.draftsId)return!1;var e=this.callParent(arguments);return!1!==e&&(e.threadAction=this.view.threadAction),e}}),Ext.define("SYNO.SDS.MailClient.ThreadListContextMenu",{extend:"SYNO.ux.Menu",threadAction:null,constructor:function(t){if(!t.threadAction)throw"should have threadAction object";this.threadAction=t.threadAction;var e={items:[{itemId:"archive-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("common","archive")},{itemId:"mark-read-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("filter","mark_as_read")},{itemId:"mark-unread-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("common","mark_unread")},{itemId:"move-to-inbox-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("common","move_to_inbox")},{itemId:"spam-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("common","mark_spam")},{xtype:"menuseparator",itemId:"sep"},{itemId:"discard-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("composer","discard")},{itemId:"delete-forever-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("common","delete_forever")},{itemId:"delete-node",xtype:"menuitem",text:SYNO.SDS.MailClient._T("common","delete")}],listeners:{scope:this,hide:function(){this.info=void 0,this.currentMailboxId=0},beforeshow:function(){var t,e=SYNO.SDS.MailClient.Define,i=[];if(SYNO.SDS.MailClient.Lib.ThreadAction.isThreadModifiable(this.info))if(0!==this.currentMailboxId)switch(this.currentMailboxId){case e.inboxId:case e.sentId:i=["move-to-inbox-node","discard-node","delete-forever-node"];break;case e.draftsId:i=["archive-node","move-to-inbox-node","spam-node","delete-node","delete-forever-node"];break;case e.trashId:i=["archive-node","delete-node","discard-node"];break;case e.junkId:i=["archive-node","spam-node","delete-node","discard-node"];break;case SYNO.SDS.MailClient.Settings.archive_mailbox:i=["archive-node","discard-node","delete-forever-node"];break;case e.starredId:i=["move-to-inbox-node","archive-node","discard-node","delete-forever-node"];break;default:i=["discard-node","delete-forever-node"]}else i=["move-to-inbox-node","archive-node","discard-node","delete-forever-node"];else i=["sep","spam-node","move-to-inbox-node","archive-node","discard-node","delete-forever-node","delete-node"];this.items.each(function(t){-1<i.indexOf(t.itemId)?t.setVisible(!1):t.setVisible(!0)},this);var n=!1;for(t=0;t<this.info.length;++t)if(!this.info[t].unread){n=!0;break}this.getComponent("mark-read-node").setVisible(!n),this.getComponent("mark-unread-node").setVisible(n)},itemclick:function(t){if(this.info){var e,i=[],n=[],a=SYNO.SDS.MailClient.Define;for(e=0;e<this.info.length;++e)i.push(this.info[e].id);switch(t.itemId){case"archive-node":this.threadAction.setMailbox(this.records,SYNO.SDS.MailClient.Settings.archive_mailbox);break;case"move-to-inbox-node":this.threadAction.setMailbox(this.records,a.inboxId);break;case"mark-read-node":for(i=[],e=0;e<this.info.length;++e)0!==this.info[e].unread&&(i.push(this.info[e].id),n.push(this.info[e]));this.threadAction.markRead(n,!0);break;case"mark-unread-node":for(i=[],e=0;e<this.info.length;++e)0===this.info[e].unread&&(i.push(this.info[e].id),n.push(this.info[e]));this.threadAction.markRead(n,!1);break;case"spam-node":this.threadAction.reportSpam(this.records);break;case"discard-node":this.threadAction.discard(this.info);break;case"delete-forever-node":this.threadAction.deleteForever(i);break;case"delete-node":this.threadAction.setMailbox(this.records,a.trashId)}}}}};this.callParent([Ext.apply(e,t)]),this.addClass("syno-mc-menu syno-mc-op-menu")},setThreadInfo:function(t,e){this.currentMailboxId=e,this.info=t.map(function(t){return t.data}),this.records=t}}),Ext.define("SYNO.SDS.MailClient.ThreadListView",{extend:"SYNO.SDS.MailClient.BasicListView",requires:["SYNO.SDS.MailClient.BasicListView","SYNO.SDS.MailClient.MessageHouseLib.Normalizer","SYNO.SDS.MailClient.ThreadListViewDragZone","SYNO.SDS.MailClient.ThreadListContextMenu"],smallLayout:!1,previewLineLayout:1,displayDensity:1,enableFloatingButton:!1,densityClsMap:{0:"comfortable",1:"cozy",2:"compact"},lineLayoutClsMap:{0:"line-layout-0",1:"line-layout-1",2:"line-layout-2"},restoreSelectionState:!0,disableSelectAllButton:!1,constructor:function(t){this.callParent([this.fillConfig(t)]),this.on({scope:this,render:function(t){t.dragZone=new SYNO.SDS.MailClient.ThreadListViewDragZone(t,{ddGroup:"threadDDGroup",dragSource:"thread"})},show:function(t){t.updateFleXcroll()}}),this.addEvents("emptyclicked")},fillConfig:function(t){var e=["syno-mc-thread-list-view"],i=SYNO.SDS.MailClient.Settings.conversation_view;if(Ext.isNumber(t.previewLineLayout)&&(this.previewLineLayout=t.previewLineLayout),Ext.isNumber(t.displayDensity)&&(this.displayDensity=t.displayDensity),Ext.isBoolean(t.smallLayout)&&(this.smallLayout=t.smallLayout,t.smallLayout&&(e.push("small-layout"),this.previewLineLayout=2)),Ext.isBoolean(t.enableFloatingButton)&&(this.enableFloatingButton=t.enableFloatingButton,t.enableFloatingButton&&e.push("with-floating-btns")),Ext.isBoolean(t.disableSelectAllButton)&&(this.disableSelectAllButton=t.disableSelectAllButton),this.lineLayoutCls=this.lineLayoutClsMap[this.previewLineLayout]||"line-layout-2",e.push(this.lineLayoutCls,this.densityClsMap[this.displayDensity]),!t.threadAction)throw"should have threadAction object";this.threadAction=t.threadAction;var n={tpl:this.createTpl(),prepareData:this.prepareTplData,cls:e.join(" "),itemSelector:".item-wrap",itemSelectorCls:"item-wrap",checkIconCls:"syno-ux-checkbox-icon",checkedCls:"syno-ux-cb-checked",enableDD:!0,ddGroup:"threadDDGroup",dragSource:"thread",dropSource:["label"],plugins:new SYNO.SDS.MailClient.NameCardPlugin,contextMenu:new SYNO.SDS.MailClient.ThreadListContextMenu({threadAction:this.threadAction}),dragString:SYNO.SDS.MailClient._T("common",i?"selected_conversation_count":"selected_message_count"),dragSingleString:SYNO.SDS.MailClient._T("common",i?"selected_conversation":"selected_message")};return Ext.apply(n,t)},getSmallTemplate:function(){return new Ext.XTemplate('<tpl for=".">','<div tid={id} class="item-wrap <tpl if="values.unread">item-unread</tpl>">','<div class="item-icon">','<div class="check-area">','<div class="align"></div>','<div class="syno-ux-checkbox-icon"></div>',"</div>","</div>",'<div class="summary">','<div class="from-time-floating">','<tpl if="values.showReplyForwardIcon">','<div class="<tpl if="values.replied">replied</tpl> <tpl if="values.forwarded">forwarded</tpl>"></div>',"</tpl>",'<div class="from">',"{[values.showRecipient ?","SYNO.SDS.MailClient.Format.templateReceiverFromMessageDraft(values.message, values.draft) :","SYNO.SDS.MailClient.Format.templateSenderFromMessageDraft(values.message, values.draft)","]}","</div>",'<tpl if="!values.inDraft">','<div class="arrival-time" title="{[SYNO.SDS.MailClient.Format.templateTimeString(values.message, true)]}">',"{[SYNO.SDS.MailClient.Format.templateTimeString(values.message, false)]}</div>","</tpl>",'<tpl if="values.inDraft">','<div class="arrival-time" title="{[SYNO.SDS.MailClient.Format.templateTimeString(values.draft, true)]}">',"{[SYNO.SDS.MailClient.Format.templateTimeString(values.draft, false)]}</div>","</tpl>",'<div class="floating-btns">',"{[this.getFloatingBtnsTpl(values)]}","</div>","</div>",'<div class="subject">{[SYNO.SDS.MailClient.Format.templateSubjectFromMessageDraft(values.message, values.draft)]}</div>','<div class="star <tpl if="values.star">syno-ux-cb-checked</tpl>"></div>','<div class="body-label" {[this.getStyle(values.message, values.draft)]}>','<div class="label-area">','<tpl for="values.label">','<div class="label" ext:qtip="{full_name:htmlEncode}" style="color: #{text_color}; background-color: #{background_color}">{[SYNO.SDS.MailClient.Control.Model.getLabelDisplayNameById(values.id)]}</div>',"</tpl>","</div>",'<div class="preview">{[SYNO.SDS.MailClient.Format.templateBodyPreviewFromMessageDraft(values.message, values.draft)]}</div>',"</div>","{[SYNO.SDS.MailClient.Format.templateAttachment(values.message, values.draft)]}","</div>","</div>","</tpl>",'<div class="x-clear"></div>',{getStyle:function(t,e){return SYNO.SDS.MailClient.Format.templateAttachment(t,e)?'style="margin-right: 24px;"':""},getFloatingBtnsTpl:function(t){return this.getFloatingBtnsTpl(t)}.bind(this)})},getNormalTemplate:function(){return 2!==this.previewLineLayout?new Ext.XTemplate("<table>",'<tpl for=".">','<tr tid={id} class="item-wrap <tpl if="values.unread">item-unread</tpl>">','<td class="check-area"><div class="syno-ux-checkbox-icon"></div></td>','<td class="icon-ct"><div class="star <tpl if="values.star">syno-ux-cb-checked</tpl>"></div></td>','<tpl if="values.showReplyForwardIcon">','<td class="icon-ct"><div class="<tpl if="values.replied">replied</tpl> <tpl if="values.forwarded">forwarded</tpl>"></div></td>',"</tpl>",'<td class="from-ct <tpl if="values.showReplyForwardIcon">with-reply-forward-icon</tpl>">','<div class="from">',"{[values.showRecipient ?","SYNO.SDS.MailClient.Format.templateReceiverFromMessageDraft(values.message, values.draft) :","SYNO.SDS.MailClient.Format.templateSenderFromMessageDraft(values.message, values.draft)","]}","</div>","</td>",'<td class="ct">','<div class="labels">','<tpl for="values.label">','<div class="label" ext:qtip="{full_name:htmlEncode}" style="color: #{text_color}; background-color: #{background_color}">{[SYNO.SDS.MailClient.Control.Model.getLabelDisplayNameById(values.id)]}</div>',"</tpl>","</div>",'<div class="content-ct">','<span class="subject">{[SYNO.SDS.MailClient.Format.templateSubjectFromMessageDraft(values.message, values.draft)]}</span>','<span class="preview"> - {[SYNO.SDS.MailClient.Format.templateBodyPreviewFromMessageDraft(values.message, values.draft)]}</span>',"</div>","</td>",'<td class="attachment-ct">',"{[SYNO.SDS.MailClient.Format.templateAttachment(values.message, values.draft)]}","</td>",'<td class="time-ct">','<tpl if="!values.inDraft">','<div class="arrival-time" title="{[SYNO.SDS.MailClient.Format.templateTimeString(values.message, true)]}">',"{[SYNO.SDS.MailClient.Format.templateTimeString(values.message, false)]}</div>","</tpl>",'<tpl if="values.inDraft">','<div class="arrival-time" title="{[SYNO.SDS.MailClient.Format.templateTimeString(values.draft, true)]}">',"{[SYNO.SDS.MailClient.Format.templateTimeString(values.draft, false)]}</div>","</tpl>","</td>",'<td class="floating-btns">',"{[this.getFloatingBtnsTpl(values)]}","</td>","</tpl>",'</table><div class="x-clear"></div>',{getFloatingBtnsTpl:function(t){return this.getFloatingBtnsTpl(t)}.bind(this)}):new Ext.XTemplate('<tpl for=".">','<div tid={id} class="item-wrap <tpl if="values.unread">item-unread</tpl>">','<div class="item-icon">','<div class="check-area">','<div class="align"></div>','<div class="syno-ux-checkbox-icon"></div>',"</div>",'<div class="star <tpl if="values.star">syno-ux-cb-checked</tpl>"></div>','<tpl if="values.showReplyForwardIcon">','<div class="<tpl if="values.replied">replied</tpl> <tpl if="values.forwarded">forwarded</tpl>"></div>',"</tpl>","</div>",'<div class="summary">','<div class="info-ct">','<div class="from <tpl if="values.showReplyForwardIcon">with-reply-forward-icon</tpl>">',"{[values.showRecipient ?","SYNO.SDS.MailClient.Format.templateReceiverFromMessageDraft(values.message, values.draft) :","SYNO.SDS.MailClient.Format.templateSenderFromMessageDraft(values.message, values.draft)","]}","</div>",'<div class="subject-label">','<div class="subject">{[SYNO.SDS.MailClient.Format.templateSubjectFromMessageDraft(values.message, values.draft)]}</div>','<div class="label-area">','<tpl for="values.label">','<div class="label" ext:qtip="{full_name:htmlEncode}" style="color: #{text_color}; background-color: #{background_color}">{[SYNO.SDS.MailClient.Control.Model.getLabelDisplayNameById(values.id)]}</div>',"</tpl>","</div>","</div>","{[SYNO.SDS.MailClient.Format.templateAttachment(values.message, values.draft)]}",'<tpl if="!values.inDraft">','<div class="arrival-time" title="{[SYNO.SDS.MailClient.Format.templateTimeString(values.message, true)]}">',"{[SYNO.SDS.MailClient.Format.templateTimeString(values.message, false)]}</div>","</tpl>",'<tpl if="values.inDraft">','<div class="arrival-time" title="{[SYNO.SDS.MailClient.Format.templateTimeString(values.draft, true)]}">',"{[SYNO.SDS.MailClient.Format.templateTimeString(values.draft, false)]}</div>","</tpl>",'<div class="floating-btns">',"{[this.getFloatingBtnsTpl(values)]}","</div>","</div>",'<div class="preview">{[SYNO.SDS.MailClient.Format.templateBodyPreviewFromMessageDraft(values.message, values.draft)]}</div>',"</div>","</div>","</tpl>",'<div class="x-clear"></div>',{getFloatingBtnsTpl:function(t){return this.getFloatingBtnsTpl(t)}.bind(this)})},getFloatingBtnsTpl:function(t){var e,i,n,a=SYNO.SDS.MailClient.Switch,o=SYNO.SDS.MailClient.Define,s=SYNO.SDS.MailClient._T,l=t.message.length<=0,r=SYNO.SDS.MailClient.Lib.ThreadAction.isThreadModifiable([t]);switch(a.inMailboxId){case o.trashId:case o.junkId:e=!0,n="delete-forever",i=s("common","delete_forever");break;case o.draftsId:e=!0,n="discard",i=s("composer","discard");break;case SYNO.SDS.MailClient.Settings.archive_mailbox:e=!0,n="delete",i=s("common","delete");break;default:e=!1,n="delete",i=s("common","delete")}return['<span class="x-btn syno-ux-button x-btn-icon syno-mc-button ',e||!r?"x-item-disabled":"",'">','<button class="x-btn-text syno-mc-archive-icon archive" ext:qtip="',s("common","archive"),'"></button>',"</span>",'<span class="x-btn syno-ux-button x-btn-icon syno-mc-button ',r?"":"x-item-disabled",'">','<button class="x-btn-text syno-mc-delete-icon ',n,'" ext:qtip="',i,'"></button>',"</span>",t.unread?['<span class="x-btn syno-ux-button x-btn-icon syno-mc-button ',l?"x-item-disabled":"",'">','<button class="x-btn-text syno-mc-read-icon read" ext:qtip="',s("filter","mark_as_read"),'"></button>',"</span>"].join(""):['<span class="x-btn syno-ux-button x-btn-icon syno-mc-button ',l?"x-item-disabled":"",'">','<button class="x-btn-text syno-mc-unread-icon unread" ext:qtip="',s("common","mark_unread"),'"></button>',"</span>"].join(""),SYNO.SDS.MailClient.Define.isSupportTodoPlugin()?['<span class="x-btn syno-ux-button x-btn-icon syno-mc-button ',l?"x-item-disabled":"",'">','<button class="x-btn-text syno-mc-add-todo-list-icon add-todo" ext:qtip="',s("calendar","add_to_todo_list"),'"></button>',"</span>"].join(""):""].join("")},createTpl:function(){return this.smallLayout?this.getSmallTemplate():this.getNormalTemplate()},onClick:function(t,e,i){this.callParent(arguments),Ext.fly(e).hasClass("clear-message-text")&&this.fireEvent("emptyclicked")},onDisplayNode:function(t){this.callParent(arguments),this.fireEvent("navigate","right")},setSelectAllBtnVisible:function(t){this.disableSelectAllButton||(this.selectAllEl||this.addExtraAction(),this.selectAllEl&&this.selectAllEl.setVisible(t),this.selectedAllEl&&this.selectedAllEl.setVisible(!1),this.updateScroller())},addExtraAction:function(t){var e=SYNO.SDS.MailClient.Switch,i=SYNO.SDS.MailClient.Define,n=i.trashId==e.inMailboxId,a=i.junkId==e.inMailboxId,o=i.draftsId==e.inMailboxId,s=SYNO.SDS.MailClient.Settings.conversation_view,l=SYNO.SDS.MailClient._T("thread",s?"all_thread":"all_message"),r=SYNO.SDS.MailClient._T("thread",s?"all_thread_selected":"all_message_selected");"clear_message"===t&&e.inMailbox&&(n||a)?this.clearMessageEl=this.getTemplateTarget().insertFirst({tag:"div",cls:"clear-message",html:'<div class="clear-message-text">'+SYNO.SDS.MailClient._T("common","clear_message")+"</div>"}):this.store.getTotalCount()<=SYNO.SDS.MailClient.Settings.conversations_per_page||e.inMailbox&&(n||a||o)||(this.selectAllEl=this.getTemplateTarget().insertFirst({tag:"div",cls:"select-message",html:'<div class="select-all-db">'+String.format(l,this.store.getTotalCount())+"</div>"}).setVisibilityMode(Ext.Element.DISPLAY).hide(),this.selectedAllEl=this.getTemplateTarget().insertFirst({tag:"div",cls:"select-message",html:"<div>"+String.format(r,this.store.getTotalCount())+"</div>"}).setVisibilityMode(Ext.Element.DISPLAY).hide())},prepareTplData:function(t){var e,i=SYNO.Util.copy(t),n=[],a=SYNO.SDS.MailClient.Switch,o=SYNO.SDS.MailClient.Define,s=o.draftsId==a.inMailboxId,l=o.sentId==a.inMailboxId;if(i.inDraft=s,i.showRecipient=l,i.showReplyForwardIcon=!SYNO.SDS.MailClient.Settings.conversation_view&&(i.replied||i.forwarded),a.inLabel){for(e=0;e<t.label.length;++e)t.label[e].id!=a.inLabelId&&n.push(t.label[e]);i.label=n}return i.message=SYNO.SDS.MailClient.MessageHouseLib.Normalizer.normalizeMsgs(i.message),0===i.message.length&&0===i.draft.length?t:i},switchViewLayout:function(t,e,i){var n=!1;this.smallLayout||t===this.previewLineLayout&&e===this.displayDensity||(n=!0,this.el.removeClass([this.lineLayoutCls,"comfortable","cozy","compact"]),this.lineLayoutCls=this.lineLayoutClsMap[t]||"line-layout-2",this.previewLineLayout=t,this.displayDensity=e,this.addClass([this.lineLayoutCls,this.densityClsMap[e]].join(" "))),i!==this.enableFloatingButton&&(n=!0,this.enableFloatingButton=i,this.enableFloatingButton?this.el.addClass("with-floating-btns"):this.el.removeClass("with-floating-btns")),n&&(this.tpl=this.createTpl(),this.refresh(),Ext.each(this.checkedItemList,function(t){Ext.fly(this.getNode(t)).child("."+this.checkIconCls).addClass(this.checkedCls)},this),this.updateScroller())},drop:function(t,e){this.callParent(arguments);var i=this.store.getAt(this.indexOf(t));if(i&&"label"===e.source){var n,a=i.get("label"),o=[];for(n=0;n<a.length;++n)o.push(a[n].id);if(-1<o.indexOf(e.data.id))return;var s={id:[i.id],label_id:[e.data.id]};return SYNO.SDS.MailClient.WebAPI.threadAddLabel(s).then(function(t){SYNO.SDS.MailClient.Control.Thread.addLabel(s.id,[{id:e.data.id,name:e.data.name,full_name:e.data.full_name,path:e.data.path,background_color:e.data.background_color,text_color:e.data.text_color}]),SYNO.SDS.MailClient.Window.showToast(String.format(SYNO.SDS.MailClient._T("notification","apply_label"),'"'+Ext.util.Format.htmlEncode(e.data.name)+'"'))}.bind(this)).catch(function(t){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient.Error.getErrorString(t),[],!0)}.bind(this))}},onBeforeLoad:function(t,e){e=e||{},this.loadCondition&&(this.keepChecked=SYNO.SDS.MailClient.Tool.isSameThreadCondition(this.loadCondition,this.store.baseParams.condition)),this.lastChecked=this.removedIdx=void 0,(Ext.isDefined(e.keepScroll)?e.keepScroll:this.keepScroll())||(this.clearDisplay(),this.clearSelections()),this.loadCondition=this.store.baseParams.condition,this.callParent(arguments)},onStoreLoad:function(t,e,i){this.callParent(arguments),this.el.dom.fleXcroll&&!i.keepScroll&&this.autoUpdateScrollbar(!0)},onAdd:function(t,e,i){this.callParent(arguments);var n;for(n=0;n<e.length;++n)this.resizeThread(this.all.item(i+n))},onUpdate:function(t,e){this.callParent(arguments);var i=this.store.indexOf(e);-1<i&&this.resizeThread(this.all.item(i))},onRemove:function(t,e,i){this.lastChecked=Math.max.apply(null,this.getCheckedItemIndexes()),this.removedIdx=i,this.callParent(arguments)},refresh:function(){var t=Ext.get(this.getNode(0));this.keepScroll()&&t&&this.el.dom.fleXdata&&(this.updateScrollbarInfo={},this.updateScrollbarInfo.nodeId=parseInt(t.getAttribute("tid"),10),this.updateScrollbarInfo.domOffsetTop=t.dom.offsetTop,this.updateScrollbarInfo.yScrollPosition=this.el.dom.fleXdata.scrollPosition[1]),this.callParent(arguments),this.resizeAllThread(),this.addExtraAction("clear_message")},onResize:function(t){t!==this.width&&(this.width=t,this.maxBodyWidth=t-58-36,this.maxSubjectWidth=t-82-224-8,this.resizeAllThread())},autoUpdateScrollbar:function(t){if(this.autoFlexcroll&&(this.callParent(arguments),this.updateScrollbarInfo)){if(this.store&&this.store.lastOptions){var e=this.store.indexOfId(this.updateScrollbarInfo.nodeId),i=Ext.get(this.getNode(e));if(i&&e<this.store.lastOptions.params.limit&&this.el.dom.fleXdata){var n=this.el.dom.fleXdata.scrollPosition[1],a=i.dom.offsetTop-this.updateScrollbarInfo.domOffsetTop+this.updateScrollbarInfo.yScrollPosition[0];a=a<0?0:a>n[1]?n[1]:a,this.el.dom.fleXcroll.setScrollPos(null,a)}}delete this.updateScrollbarInfo}},resizeAllThread:function(){var t,e=this.all.elements;for(this.labelWidthMap={},t=0;t<this.all.getCount();t++)this.resizeThread(e[t])},resizeThread:function(t){var e,i,n,a=Ext.get(t);if(this.smallLayout);else if(2===this.previewLineLayout){if(n=this.maxSubjectWidth-a.child(".subject-label").getMargins().right,!(e=a.child(".label")))return void a.child(".subject").setStyle("max-width",n-10+"px");var o="textContent"in e.dom?e.dom.textContent:e.dom.innerText;i=this.labelWidthMap[o]?this.labelWidthMap[o]:this.labelWidthMap[o]=e.getWidth(),a.child(".subject").setStyle("max-width",n-i-10+"px")}},scrollToElement:function(t){this.fleXcrollTo(this.all.elements[t])},onKeyLeft:function(t){this.fireEvent("navigate","left")},onKeyRight:function(t){var e=this.getSelectedRecords();1===e.length&&this.onDisplayNode(e[0])},onKeyUp:function(t,e){var i;i=this.getSelectedRecords().length>0?this.indexOf(this.getSelectedRecords()[0]):0,this.callParent(arguments),this.focus();var n=this.getSelectedRecords();1===n.length&&0===i&&0===this.indexOf(n[0])&&this.fireEvent("navigate","up",e)},onKeyDown:function(t,e){var i,n;i=this.getSelectedRecords().length>0?this.indexOf(this.getSelectedRecords()[0]):0,this.callParent(arguments),this.focus();var a=this.getSelectedRecords();a.length&&(n=this.indexOf(a[0]),1===a.length&&i===n&&n===this.store.getCount()-1&&this.fireEvent("navigate","down",e))},onNavigateOut:function(){this.clearSelections(!0)},onNavigateIn:function(t,e){if(!(this.ownerCt.ownerCt.ownerCt.isVisible()&&this.ownerCt.ownerCt.isVisible()&&this.ownerCt.isVisible()&&this.isVisible()))return!1;var i,n,a;return"right"!==t&&"left"!==t||(e&&e.clearSelections?this.clearSelections():this.all.getCount()&&!this.getSelectedNodes().length&&(i=this.getNode(this.store.getById(this.displayedNodeId)),this.select(i||0))),"down"!==t&&"up"!==t||(a="down"===t?0:this.store.getCount()-1,this.select(a),e&&e.displayNode&&(n=this.store.getAt(a))&&this.onDisplayNode(n)),this.navigationGroup&&SYNO.SDS.MailClient.Window.navigator.regGroupLastFocus(this.navigationGroup,this.store.sectionIdx),this.focus(),!0},keepScroll:function(){var t=!1;return this.el&&this.el.dom&&this.el.dom.fleXdata?((this.smallLayout&&this.displayedNodeId||this.getCheckedItemRecords().length||0!==this.el.dom.fleXdata.scrollPosition[1][0])&&(t=!0),t):t},onShortCutStar:function(){var t=this.getSelectedRecords();if(0===t.length);else if(1===t.length)return this.onStar(t[0]),!0},onShortCutThread:function(t,e){var i="up_thread"===t,n=i?"onKeyUp":"onKeyDown";if(!e)return this.focus(),this[n]({shiftKey:!1}),!0;var a=this.store.getById(this.displayedNodeId),o=this.store.indexOf(a),s=this.getSelectedIndexes(),l=-1;if(a?l=o+("up_thread"===t?-1:1):1===s.length?l=s[0]:this.store.getCount()&&(l=0),Ext.isDefined(this.store.sectionIdx)){if(l>=this.store.getCount())return this.fireEvent("navigate","down",{displayNode:!0}),!0;if(l<0)return this.fireEvent("navigate","up",{displayNode:!0}),!0}var r=this.store.getAt(l);return r&&this.onDisplayNode(r),!0},getTotalCheckedItemRecords:function(){return this.owner.getTotalCheckedItemRecords()}}),Ext.define("SYNO.SDS.MailClient.ThreadPanel",{extend:"SYNO.SDS.MailClient.BaseThreadPanel",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.PriorityThreadToolbar","SYNO.SDS.MailClient.SplitThreadToolbar","SYNO.SDS.MailClient.ThreadEmptyView","SYNO.SDS.MailClient.ThreadListView","SYNO.SDS.MailClient.ThreadToolbar"],xtype:"mc_ThreadPanel",constructor:function(t){window.tp=this,this.callParent([this.fillConfig(t)]),this.on("resize",function(t,e,i,n,a,o){this.emptyIcon.setSize(e-12,i-this.toolbar.getHeight()-12)},this);var e=SYNO.SDS.MailClient.KeyNavigator.ShortCut;SYNO.SDS.MailClient.Window.regShortCut(this,[e.STAR,e.UP_THREAD,e.DOWN_THREAD])},fillConfig:function(t){var e=!!t.smallLayout;this.threadStore=SYNO.SDS.MailClient.Lib.Thread.store,this.threadAction=SYNO.SDS.MailClient.Lib.ThreadAction,this.view=new SYNO.SDS.MailClient.ThreadListView({smallLayout:e,boxMinWidth:e?void 0:600,threadAction:this.threadAction,previewLineLayout:SYNO.SDS.MailClient.Settings.preview_layout,displayDensity:SYNO.SDS.MailClient.Settings.display_density,enableFloatingButton:SYNO.SDS.MailClient.Settings.enable_floating_button,listeners:{scope:this,starred:this.onViewStarred,displayed:this.onViewDisplayed,checked:this.onViewChecked,contextmenu:this.onViewContextMenu,emptyclicked:this.onViewEmptyClicked,selectalldb:function(){this.notifyChange("allthread")}}});var i={layout:"fit",border:!1,items:[this.view,this.emptyIcon=new SYNO.SDS.MailClient.ThreadEmptyView({hidden:!0})],tbar:this.toolbar=new SYNO.SDS.MailClient.ThreadToolbar({displayInfo:t.displayInfo,smallLayout:e,pageSize:SYNO.SDS.MailClient.Settings.conversations_per_page,listeners:{scope:this,beforechange:function(t,e){SYNO.SDS.MailClient.Switch.offsetChange(e.offset),SYNO.SDS.MailClient.Control.Mail.clearMessage(),SYNO.SDS.MailClient.Control.Selection.selectThread([])},selectall:function(){this.view.checkAll(),this.notifyChange(this.view.getCheckedItemRecords())},selectnone:function(){this.view.uncheckAll(),this.notifyChange(this.view.getCheckedItemRecords())},selectcondition:function(t,e){var i=Ext.emptyFn;"unread"===e||"starred"===e?i=function(e){return e.get(t)>=1}:"read"!==e&&"unstarred"!==e||(i=function(e){return!e.get(t)}),this.view.checkByCondition(i,this),this.notifyChange(this.view.getCheckedItemRecords())}}})};return Ext.apply(i,t)},arm:function(){this.view.bindStore(this.threadStore),this.mon(this.threadStore,"datachanged",this.updateEmptyIcon,this),this.getTopToolbar().bindStore(this.threadStore),this.mon(SYNO.SDS.MailClient.Switch,"settingchange",this.settingChange,this),this.settingChange(SYNO.SDS.MailClient.Settings),this.updateEmptyIcon()},disarm:function(){this.view.bindStore(null),this.mun(this.threadStore,"datachanged",this.updateEmptyIcon,this),this.getTopToolbar().bindStore(null),this.mun(SYNO.SDS.MailClient.Switch,"settingchange",this.settingChange,this),SYNO.SDS.MailClient.Control.Selection.selectThread([]),this.updateEmptyIcon()},settingChange:function(t){Ext.isNumber(t.preview_layout)&&Ext.isNumber(t.display_density)&&Ext.isBoolean(t.enable_floating_button)&&this.view.switchViewLayout(t.preview_layout,t.display_density,t.enable_floating_button)},keepScroll:function(){var t=!1;return this.view.el&&this.view.el.dom&&this.view.el.dom.fleXdata?((this.view.getCheckedItemRecords().length||0!==this.view.el.dom.fleXdata.scrollPosition[1][0])&&(t=!0),t):t},notifyChange:function(t){this.ownerCt.activated&&this.activated&&(this.from_self=!0,SYNO.SDS.MailClient.Control.Selection.selectThreadOnNormal(t))},updateEmptyIcon:function(){if(!this.view.isVisible()&&0<this.threadStore.getCount())this.view.show(),this.emptyIcon.hide();else if(this.view.isVisible()&&0===this.threadStore.getCount()){var t=SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition");if(!(t instanceof SYNO.SDS.MailClient.Condition))return;SYNO.SDS.MailClient.Switch.inSearch?this.emptyIcon.updateText(SYNO.SDS.MailClient._T("search","no_search_result")):this.emptyIcon.updateText(SYNO.SDS.MailClient._T("mail","no_mail_hint")),this.emptyIcon.show(),this.view.hide()}},onViewChecked:function(t,e,i,n){var a=t.getCheckedItemIndexes();a.length?a.length==t.store.getCount()?this.toolbar.checkAll():this.toolbar.checkPartial():this.toolbar.checkNone(),n||this.notifyChange(t.getCheckedItemRecords())},onViewDisplayed:function(t,e,i){SYNO.SDS.MailClient.Lib.Thread.setCurrentThreadStore(-1),this.callParent(arguments)},onViewEmptyClicked:function(){SYNO.SDS.MailClient.Switch.inMailbox&&this.findWindow().getMsgBox().confirm("",SYNO.SDS.MailClient._T("common","confirm_remove_message"),function(t){if("yes"==t){if(this.threadStore.getTotalCount()<=SYNO.SDS.MailClient.Define.smallBatchOpLimit)return SYNO.SDS.MailClient.WebAPI.clearMessage({id:[SYNO.SDS.MailClient.Switch.inMailboxId]}).then(function(){SYNO.SDS.MailClient.Control.Selection.clearSelect(),SYNO.SDS.MailClient.Control.Thread.modifyThread("refresh"),SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList(),this.findWindow().clearStatusBusy()}.bind(this)).catch(function(){this.findWindow().getMsgBox().alert("","mailbox clear message failed")}.bind(this));var e=new SYNO.SDS.MailClient.Condition("mailbox",SYNO.SDS.MailClient.Switch.inMailboxId);SYNO.SDS.MailClient.WebAPI.addTask({condition:e.toWebAPIParams(),action:[SYNO.SDS.MailClient.Format.makeAction("delete","")]}).then(function(t){if(!t.task_key)return this.findWindow().clearStatusBusy(),void this.findWindow().getMsgBox().alert("","mailbox clear message failed, no task key");var e={owner:this.findWindow(),msg:SYNO.SDS.MailClient._T("common","delete_wait_msg"),progress:!0,progressText:"0/"+this.threadStore.getTotalCount(),buttons:Ext.Msg.CANCEL,fn:function(){return SYNO.SDS.MailClient.WebAPI.cancelTask({task_key:t.task_key}).catch(function(t){}.bind(this))
}.bind(this)};this.findWindow().getMsgBox().msg=e.msg,this.findWindow().getMsgBox().show(e)}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy(),this.findWindow().getMsgBox().alert("","mailbox clear message failed")}.bind(this))}},this)},onShortCut:function(t){var e=SYNO.SDS.MailClient.KeyNavigator.ShortCut;if(this.ownerCt.activated&&this.activated){if(e.STAR===t)return this.view.onShortCutStar();if(-1!==[e.UP_THREAD,e.DOWN_THREAD].indexOf(t))return this.view.onShortCutThread(t,this.handleShortCutThread)}},getCount:function(){return this.threadStore.getCount()},refreshPageByToolbar:function(){this.toolbar.doRefresh()}}),Ext.define("SYNO.SDS.MailClient.ThreadCardPanel",{extend:"SYNO.SDS.MailClient.BasePanel",requires:["SYNO.SDS.MailClient.PriorityThreadPanel","SYNO.SDS.MailClient.ThreadPanel"],xtype:"mc_ThreadCardPanel",constructor:function(t){t=t||{},this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=[];this.threadPanel=new SYNO.SDS.MailClient.ThreadPanel({itemId:"threadPanel",cls:"syno-mc-thread-panel"+(t.smallLayout?" smalllayout":""),smallLayout:t.smallLayout,handleShortCutThread:t.handleShortCutThread,displayInfo:!0}),this.PriorityThreadPanel=new SYNO.SDS.MailClient.PriorityThreadPanel({itemId:"priorityMailboxThreadPanel",cls:"syno-mc-thread-panel priority"+(t.smallLayout?" smalllayout":""),smallLayout:t.smallLayout,handleShortCutThread:t.handleShortCutThread,displayInfo:!1}),e=[this.threadPanel,this.PriorityThreadPanel];var i={layout:"card",cls:"syno-mc-thread-card-panel",border:!1,activeItem:0,items:e,listeners:{activate:function(){SYNO.SDS.MailClient.Switch.inPriority?this.switchToPriorityMailbox():this.switchToNormalMailbox()}}};return Ext.apply(i,t)},clearSelections:function(){SYNO.SDS.MailClient.Switch.inPriority?this.PriorityThreadPanel.clearSelections():this.threadPanel.clearSelections()},clickNext:function(){SYNO.SDS.MailClient.Switch.inPriority?this.PriorityThreadPanel.clickNext():this.threadPanel.clickNext()},switchToPriorityMailbox:function(){"threadPanel"===this.layout.activeItem.itemId&&this.layout.setActiveItem("priorityMailboxThreadPanel")},switchToNormalMailbox:function(){this.layout.activeItem&&"priorityMailboxThreadPanel"===this.layout.activeItem.itemId&&this.layout.setActiveItem("threadPanel")},arm:Ext.emptyFn,disarm:Ext.emptyFn,layoutChange:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.MessageToolbar",{extend:"SYNO.SDS.MailClient.PagingToolbar",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("backclick","expandclick","collapseclick","printclick","openclick")},fillConfig:function(t){var e=t.hideOpen,i=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,n={hideMode:"visibility",hideCheckMenu:!0,displayInfo:!0,displayMsg:SYNO.SDS.MailClient._T("common","display_page"),nextText:SYNO.SDS.MailClient._T("common","next_mail"),prevText:SYNO.SDS.MailClient._T("common","pre_mail"),cls:t.hideBack?"syno-mc-paging-back-hide":"",items:SYNO.SDS.MailClient.Lib.Factory.createActionButtonsByInfo([{type:"Button",actionId:i.RemoveLabel},{type:"Button",actionId:i.Archive},{type:"SplitButton",actionId:i.Spam},{type:"SplitButton",actionId:i.NotSpam},{type:"Button",actionId:i.DeleteMail},{type:"Button",actionId:i.DeleteForever},{type:"Button",actionId:i.DiscardDraft},{type:"Button",actionId:i.ArchiveInLabel},{type:"Button",actionId:i.MoveTo},{type:"Button",actionId:i.Label},{type:"Button",actionId:i.AddToTodoList},{type:"Button",actionId:i.More}]),rightItems:[{itemId:"expand",xtype:"syno_mc_button",cls:"syno-mc-expand",iconCls:"syno-mc-expand-icon",tooltip:SYNO.SDS.MailClient._T("mail","expand"),disabled:!0,hidden:!SYNO.SDS.MailClient.Settings.conversation_view,scope:this,handler:function(t){this.setExpandCollapseVisible(!1,!0),this.fireEvent("expandclick")}},{itemId:"collapse",xtype:"syno_mc_button",cls:"syno-mc-collapse",iconCls:"syno-mc-collapse-icon",tooltip:SYNO.SDS.MailClient._T("mail","collapse"),disabled:!0,hidden:!0,scope:this,handler:function(t){this.setExpandCollapseVisible(!0,!1),this.fireEvent("collapseclick")}},{itemId:"print",xtype:"syno_mc_button",cls:"syno-mc-print",iconCls:"syno-mc-print-icon",tooltip:SYNO.SDS.MailClient._T("mail","print"),scope:this,disabled:!0,handler:function(){this.fireEvent("printclick")}},{itemId:"open",xtype:"syno_mc_button",cls:"syno-mc-open",iconCls:"syno-mc-open-icon",tooltip:SYNO.SDS.MailClient._T("mail","open_in_new_tab"),scope:this,hidden:e,disabled:!0,handler:function(){this.fireEvent("openclick")}}]},a=[];return t.hidePrevNext||n.rightItems.push(new Ext.Toolbar.Separator({cls:"syno-mc-prev-next-sep"})),t.hideBack?a.push("syno-mc-paging-hide-back"):n.items.unshift({xtype:"syno_mc_button",itemId:"back",tooltip:_T("common","back_to_prev"),cls:"syno-mc-back",iconCls:"syno-mc-back-icon",handler:function(){this.fireEvent("backclick")},scope:this},new Ext.Toolbar.Separator({cls:"syno-mc-back-sep"})),a.length&&(n.cls=a.join(" ")),Ext.apply(n,t)},arm:function(){this.hide()},disarm:function(){this.reset()},reset:function(){this.setExpandCollapseVisible(!0,!1),this.getComponent("expand").setDisabled(!0),this.getComponent("print").setDisabled(!0),this.getComponent("open").setDisabled(!0),delete this.rec},setExpandCollapseVisible:function(t,e){SYNO.SDS.MailClient.Settings.conversation_view&&(this.getComponent("expand").setDisabled(!t).setVisible(t),this.getComponent("collapse").setDisabled(!e).setVisible(e))},loadMessage:function(t,e,i){if(t){this.rec=t,this.getComponent("print").setDisabled(!1),this.getComponent("open").setDisabled(!1);var n=e.getCount();this.getComponent("expand").setDisabled(1===n),this.updateInfo(t)}},updateInfo:function(){var t,e,i,n=this.rec,a=this.store;if(this.displayItem&&a){if(-1===(t=n?a.indexOfId(n.id):-1))return this.displayItem.setText(""),this.prev.disable(),void this.next.disable();e=a&&a.lastOptions&&a.lastOptions.params?a.lastOptions.params.offset:0,i=a.getTotalCount(),1===i?(this.displayItem.hide(),this.prev.hide(),this.next.hide()):(this.displayItem.show(),this.prev.show(),this.next.show(),this.displayItem.setText(String.format(this.displayMsg,'<span class="number">'+(e+t+1)+"</span>",'<span class="number">'+i+"</span>")),this.prev.setDisabled(0===t+e),this.next.setDisabled(i-1===t+e))}},loadMessageByIdxDiff:function(t){SYNO.SDS.MailClient.Switch.loadMessageByIdxDiff(this.rec.id,t)},jumpPageHandler:function(t,e){SYNO.SDS.MailClient.Control.View.hideToast(),t===this.prev?this.loadMessageByIdxDiff(-1):t===this.next&&this.loadMessageByIdxDiff(1)}}),Ext.define("SYNO.SDS.MailClient.LabelItem",{extend:"Ext.Container",constructor:function(t){var e={};t.data&&(e=t.data),delete t.data;var i=SYNO.SDS.MailClient.Define.bgColors.indexOf(e.background_color),n=i<11?"top":i<22?"middle":"bottom",a={cls:"syno-mc-label-item "+n,data:e,style:"label"===t.type?String.format("background-color: #{0}; color: #{1}",e.background_color,e.text_color):"",items:[{xtype:"container",cls:"label-name",overCls:"label"===t.type?"item-over":"",html:Ext.util.Format.htmlEncode(t.text),qtip:Ext.util.Format.htmlEncode(t.qtipText),itemId:"name",listeners:{scope:this,afterrender:function(t){t.el.on("click",function(){this.fireEvent("click",this,this.data)},this),Ext.QuickTips.register({target:t,text:t.qtip})}}},{xtype:"container",cls:"delete",overCls:"label"===t.type?"item-over":"",itemId:"delete",listeners:{scope:this,afterrender:function(t){t.el.on("click",function(){this.fireEvent("delete",this,this.data)},this)}}}]};this.callParent([Ext.apply(a,t)]),this.on("afterrender",function(t){t.el.addClassOnOver("label-item-over"),t.el.addClassOnClick("label-item-click")},this),this.addEvents("delete","click")},setColor:function(t,e){this.el.setStyle({color:"#"+t,"background-color":"#"+e})},setName:function(t){this.getComponent("name").update(Ext.util.Format.htmlEncode(t))}}),Ext.define("SYNO.SDS.MailClient.MessageSubject",{extend:"SYNO.ux.Panel",constructor:function(t){if(!t.threadAction)return!1;this.threadAction=t.threadAction,this.callParent([this.fillConfig(t)]),window.ms?window.ms2=this:window.ms=this,this.addEvents("contentchange"),this.labelHash={}},fillConfig:function(t){var e={cls:"syno-mc-message-subject selectabletext",hidden:!0,items:[{itemId:"subjectLabel",cls:"subject-label",xtype:"container",items:[{itemId:"subject",xtype:"box",cls:"subject",autoEl:{tag:"span"}},{xtype:"box",itemId:"splitter",cls:"subject-splitter",html:" "}]}]};return Ext.apply(e,t)},arm:Ext.emptyFn,disarm:function(){this.reset()},reset:function(){delete this.threadRec,this.labelHash={},this.setVisible(!1)},storeUpdate:function(){this.threadRec&&this.renderLabels()},renderLabels:function(){this.labelHash={};var t=this.getComponent("subjectLabel"),e=1;for(e=t.items.getCount()-1;e>1;e--)t.remove(t.items.itemAt(e),!0);var i,n=this.threadRec.get("label"),a=[];n.sort(function(t,e){var i=t.full_name.toLowerCase(),n=e.full_name.toLowerCase();return i===n?t.id>e.id?1:-1:i>n?1:-1}),t.getComponent("splitter").setVisible(n.length>0),Ext.each(n,function(t,e,n){t.display_name=SYNO.SDS.MailClient.Control.Model.getLabelDisplayNameById(t.id,!0),i=new SYNO.SDS.MailClient.LabelItem({type:"label",data:t,text:t.display_name,qtipText:t.full_name,listeners:{scope:this,delete:function(t,e){this.threadAction.threadChangeLabel([this.threadRec.data],[],[e])},click:function(t,e){SYNO.SDS.MailClient.Define.isMessageMode||SYNO.SDS.MailClient.Control.Sidebar.openLabel(e.id)}}}),this.labelHash[t.id]=i,a.push(i)},this),t.add(a),t.doLayout(),this.fireEvent("contentchange",this)},loadMessage:function(t,e,i){if(t){this.setVisible(!0),this.threadRec=t;var n=this.getComponent("subjectLabel").getComponent("subject"),a="";if(t.get("message").length?a=t.get("message")[0].subject:t.get("draft").length&&(a=t.get("draft")[0].subject),n.update(""),Ext.isEmpty(a))n.update(Ext.util.Format.htmlEncode("("+SYNO.SDS.MailClient._T("mail","empty_subject")+")"));else{var o=document.createElement("div");o.innerHTML=Ext.util.Format.htmlEncode(a),this.findKeywordAndHighlight(o),this.findDateAndHighlight(o,e),n.update(o.innerHTML)}this.renderLabels()}},findKeywordAndHighlight:function(t){this.highlightKeywords&&this.highlightKeywords.forEach(function(e){SYNO.SDS.MailClient.TextHighlighter.highlight(e,t)},this)},findDateAndHighlight:function(t,e){SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")&&(SYNO.SDS.MailClient.SynoCalendarPlugin.parseDateAndReplace(t.innerText,new Date(1e3*e.getAt(0).data.arrival_time),t),SYNO.SDS.MailClient.SynoCalendarPlugin.setMessage({message_id:e.getAt(e.getCount()-1).data.id,subject:e.getAt(e.getCount()-1).data.subject,body:e.getAt(e.getCount()-1).data.body,inline_image:e.getAt(e.getCount()-1).data.inline_image||[],rfc_message_id:e.getAt(e.getCount()-1).data.rfc_message_id}))}}),Ext.define("SYNO.SDS.MailClient.MessageDetailMenu",{extend:"SYNO.SDS.MailClient.TemplateMenu",requires:["SYNO.SDS.MailClient.NameCardPlugin"],constructor:function(t){var e={cls:"syno-mc-detail-menu selectabletext",tpl:this.getTemplate(),plugins:new SYNO.SDS.MailClient.NameCardPlugin,autoFlexcroll:!0};this.callParent([Ext.apply(e,t)]),this.on("applytemplate",function(t){t.ul=t.el.child(".content"),t.setWidth(t.getWidth())})},getTemplate:function(){var t=SYNO.SDS.MailClient._T;return new Ext.XTemplate('<div class="content">','<tpl for=".">',"<table>",'<tr><td class="title">',t("mail","sender"),":</td><td>{[this.getFrom(values.from)]}</td></tr>",'<tr><td class="title">',t("mail","receiver"),":</td><td>",'<tpl for="to">','{[SYNO.SDS.MailClient.Format.toEmailSpan(values, "", true)]}','{[xindex < xcount ? ",<br>" : ""]}',"</tpl>","</td></tr>",'<tpl if="cc.length">','<tr><td class="title">',t("mail","copy"),":</td><td>",'<tpl for="cc">','{[SYNO.SDS.MailClient.Format.toEmailSpan(values, "", true)]}','{[xindex < xcount ? ",<br>" : ""]}',"</tpl>","</td></tr>","</tpl>",'<tpl if="bcc.length">','<tr><td class="title">',t("mail","blind_copy"),":</td><td>",'<tpl for="bcc">','{[SYNO.SDS.MailClient.Format.toEmailSpan(values, "", true)]}','{[xindex < xcount ? ",<br>" : ""]}',"</tpl>","</td></tr>","</tpl>",'<tr><td class="title">',t("search","date"),":</td><td>{[SYNO.SDS.MailClient.Format.toFullTimeString(values.arrival_time)]}</td></tr>",'<tr><td class="title">',t("mail","subject"),":</td><td>{subject:htmlEncode}</td></tr>","</table>","</tpl>","</div>",{getFrom:function(t){var e=SYNO.SDS.MailClient.Format.addressWithDisplayNameRegExp,i=e.exec(t);return i&&i[1]?SYNO.SDS.MailClient.Format.toEmailSpan(t,"bold")+Ext.util.Format.htmlEncode(i[2]):SYNO.SDS.MailClient.Format.toEmailSpan(t,"bold",!0)}})}}),Ext.define("SYNO.SDS.MailClient.Mixin.Constructable",{singleton:!0,constructConfig:function(t){var e,i=[];for(t&&t.config&&(i.unshift(t.config),delete t.config),e=this;Ext.isFunction(e.superclass);e=e.superclass())i.unshift(e.config);return i.reduce(function(t,e){return Ext.apply(t,e)},{})}}),Ext.define("SYNO.SDS.MailClient.Mixin.Queryable",{singleton:!0,cmpQuery:function(t,e){return e=null===e?void 0:[this],SYNO.SDS.MailClient.Framework.query(t,e)},down:function(t){return this.cmpQuery(t,[this])[0]||null}}),Ext.define("SYNO.SDS.MailClient.FrameworkLib.CmpQuery",{singleton:!0,constructor:function(){window.cq=this},query:function(t,e){var i;return e||(e=Ext.ComponentMgr.all.getRange()),Ext.isArray(e)||(e=[e]),i=this.parse(t),this.execute(i,e)},parse:function(t,e){var i;return t?(i=t.split(/[ >]+/),i.map(function(t){var e,i,n=[];return e=t.match(/^(#?)(\w+)/),"#"===e[1]?n.push({fn:this.getFilteredCmpById,args:[e[2]]}):n.push({fn:this.getFilteredCmpByXtype,args:[e[2]]}),i=t.match(/\w+(\[(!?)(\w+)\])/),i&&n.push({fn:this.getFilteredCmpByHasAttr,args:[i[3],""===i[2]]}),n},this)):[]},execute:function(t,e){var i=t.reduce(function(t,e){var i=this.getCmpsChildren(t);return e.reduce(function(t,e){var i=[t].concat(e.args);return e.fn.apply(this,i)}.bind(this),i)}.bind(this),e);return SYNO.SDS.MailClient.Array.unique(i)},getMcMainWindowRelatedCmp:function(){var t=[];return SYNO.SDS.MailClient.Window.cascade(function(e){t.push(e)}),t.push(SYNO.SDS.MailClient.Window),t},getMcCmps:function(){return Ext.ComponentMgr.all.getRange().filter(function(t){return Ext.isString(t.xtype)&&0===t.xtype.indexOf("mc_")})},getCmpItems:function(t){return Ext.isFunction(t.getRefItems)?t.getRefItems():t.items&&Ext.isFunction(t.items.getRange)?t.items.getRange():[]},getDeepCmpItems:function(t){},getCmpsChildren:function(t){var e;return e=t.map(function(t){return this.getCmpItems(t)},this),[].concat.apply([],e)},isIdMatched:function(t,e){return t.itemId===e||t.id===e},isXtypeMatched:function(t,e){return t.xtype===e},hasAttr:function(t,e,i){return i?!!t[e]:!t[e]},getFilteredCmpById:function(t,e){return t.filter(function(t){return this.isIdMatched(t,e)},this)},getFilteredCmpByXtype:function(t,e){return t.filter(function(t){return this.isXtypeMatched(t,e)},this)},getFilteredCmpByHasAttr:function(t,e,i){return t.filter(function(t){return this.hasAttr(t,e,i)},this)},getMcMainWindow:function(){return this.mcMainWindow||(this.mcMainWindow=this.getMcMainWindowWithoutCache()),this.mcMainWindow},getMcMainWindowWithoutCache:function(){return Ext.ComponentMgr.all.find(function(t){return"mc_MainWindow"===t.xtype})}}),Ext.override(Ext.Element,{unselectable:function(){if(!this.hasClass("x-window-header")||null===this.parent(".sds-standalone-main-window"))return this.dom.unselectable="on",this.swallowEvent("selectstart",!0).addClass("x-unselectable")}}),Ext.define("SYNO.SDS.MailClient.FrameworkImpl",{singleton:!0,evalName:function(t){return t.split(".").reduce(function(t,e){return t[e]},window)},applyMixin:function(){function t(t){var e=n(t),i=e.$isClass?e.prototype:Object.getPrototypeOf(e);Ext.override(this,i)}var e,i=SYNO.SDS.MailClient.FrameworkImpl,n=i.evalName;e=this.$isClass?this.prototype:this,e.mixins&&e.mixins.forEach(function(e){t.call(this,e)},this)}}),Ext.define("SYNO.SDS.MailClient.Framework",{singleton:!0,postDefine:function(){SYNO.SDS.MailClient.FrameworkImpl.applyMixin.apply(this,arguments)},query:function(t,e){return SYNO.SDS.MailClient.FrameworkLib.CmpQuery.query(t,e)},isAccessible:function(t){var e=!0,i=t.split(".");return"window"===i[0]&&i.shift(),i.reduce(function(t,i){return t&&t[i]?t[i]:(e=!1,null)},window),e}}),Ext.define("SYNO.SDS.MailClient.TextHighlighterBase",{extend:"Ext.Component",mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{ignoringList:["SCRIPT","STYLE","TEXTAREA"],ignoringCls:"skip-highlight",highlightMatcher:function(t,e){return this.defaultHighlightMatcher(t,e)},highlightContainer:{tag:"span",cls:"highlight",style:"background: #FA0;"},highlightContainerDataset:{},bindingEl:void 0,listeners:{click:function(t,e,i){},highlightclick:function(t,e,i){}}},basicHighlightMatcher:function(t,e){return t.toLowerCase().indexOf(e.toLowerCase())},latinHighlightMatcher:function(t,e){var i=this.escapeRE(e),n=String.format("(^|[^{0}])({1})($|[^{2}])","A-Za-zÀ-ÖØ-öø-ɏЁёА-я",i,"A-Za-zÀ-ÖØ-öø-ɏЁёА-я"),a=new RegExp(n,"i"),o=a.exec(t);if(o)return o.index+o[1].length},defaultHighlightMatcher:function(t,e){return/^[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u0401\u0451\u0410-\u044F]+$/.test(e)?this.latinHighlightMatcher(t,e):this.basicHighlightMatcher(t,e)},constructor:function(t){var e;this.config=this.constructConfig(t),e="."+this.config.highlightContainer.cls.split(" ").join("."),this.config.highlightSelector=this.config.highlightContainer.tag+e,this.callParent(arguments),this.config.bindingEl&&this.bind(this.config.bindingEl)},bind:function(t){var e;this.config.listeners&&(e={click:function(t,e,i,n){var a=this.config.listeners,o=a.click||Ext.emptyFn,s=a.highlightclick||Ext.emptyFn;e.matches(this.config.highlightSelector)?s.call(a.scope||window,t,e,i,n):o.call(a.scope||window,t,e,i,n)},scope:this},this.mon(t,e))},escapeRE:function(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isTextNode:function(t){return 3===t.nodeType},isElementNode:function(t){return 1===t.nodeType},isIgnoringTag:function(t){return-1!==this.config.ignoringList.indexOf(t.tagName)},isHighlightableNode:function(t){return this.isElementNode(t)&&t.hasChildNodes()&&!this.isIgnoringTag(t)},hasCls:function(t,e){return(" "+t.className+" ").indexOf(" "+e+" ")>-1},getNodes:function(t,e){return Ext.DomQuery.jsSelect(t,e)},extractFirstChild:function(t){var e=t.parentNode;return e.replaceChild(t.firstChild,t),e},createTextNode:function(t){return document.createTextNode(t)},createColoredNode:function(t){var e=Ext.DomHelper.createDom(this.config.highlightContainer),i=this.config.highlightContainerDataset;return e.appendChild(t.cloneNode(!0)),Ext.iterate(i,function(t,i){e.dataset[t]=i},this),e},getMatchedInfo:function(t,e){var i=this.config.highlightMatcher.call(this,t.nodeValue,e);return-1===i||void 0===i?null:{from:i,len:e.length}},highlightTextNode:function(t,e,i){var n,a;n=t.splitText(e),n.splitText(i),a=this.createColoredNode(n),n.parentNode.replaceChild(a,n)},doHighlight:function(t,e){var i,n,a=this.hasCls(t,this.config.highlightContainer.cls),o=this.hasCls(t,this.config.ignoringCls),s=!1;if(a||o)return!1;if(this.isTextNode(t))(i=this.getMatchedInfo(t,e))&&(this.highlightTextNode(t,i.from,i.len),s=!0);else if(this.isHighlightableNode(t))for(n=0;n<t.childNodes.length;++n)this.doHighlight(t.childNodes[n],e)&&++n;return s},highlightByNode:function(t,e){e=Ext.isArray(e)?e:[e],e.forEach(function(e){this.doHighlight(e,t)},this)},highlightBySelector:function(t,e,i){var n=this.getNodes(e||"body",i);this.highlightByNode(t,n)},highlight:function(t,e,i){""!==t&&(void 0===e&&(e="body"),Ext.isString(e)?this.highlightBySelector(t,e,i):this.highlightByNode(t,e))},mergeTextNode:function(t){var e,i,n=t.nextSibling,a=t.parentNode;return!(null===n||!this.isTextNode(n))&&(e=t.nodeValue+n.nodeValue,i=this.createTextNode(e),a.insertBefore(i,t),a.removeChild(t),a.removeChild(n),!0)},mergeUnhighlightedNode:function(t){var e,i,n=t.childNodes;for(i=0;i<t.childNodes.length;++i)e=n[i],this.isElementNode(e)?this.mergeUnhighlightedNode(e):this.isTextNode(e)&&this.mergeTextNode(e)&&--i},unhighlight:function(t,e){this.getNodes(t||this.config.highlightSelector,e).forEach(function(t){t=this.extractFirstChild(t),this.mergeUnhighlightedNode(t)},this)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.TextHighlighter",{extend:"SYNO.SDS.MailClient.TextHighlighterBase",singleton:!0,config:{ignoringCls:"syno-mc-skip-highlight",highlightMatcher:function(t,e){return this.defaultHighlightMatcher(t,e)},highlightContainer:{tag:"span",cls:"syno-mc-highlight",style:"background: rgba(255,245,0,0.7);"}}}),Ext.define("SYNO.SDS.MailClient.SynoCalendarPlugin",{extend:"SYNO.SDS.MailClient.TextHighlighterBase",singleton:!0,config:{ignoringCls:"syno-mc-skip-date-highlight",highlightMatcher:function(t,e){return this.defaultHighlightMatcher(t,e)},highlightContainer:{tag:"span",cls:"date-action-bubble-win"},listeners:{scope:this,highlightclick:function(t,e,i){var n={dtstart:new Date(e.dataset.start),dtend:Ext.isEmpty(e.dataset.end)?"":new Date(e.dataset.end),is_all_day:"true"===e.dataset.is_all_day,summary:SYNO.SDS.MailClient.SynoCalendarPlugin.message.subject,profile_time_zone:SYNO.SDS.MailClient.PersonalProfile.timezone,from_syno_app_url:{app:"SYNO.SDS.MailClient.Application",msg_id:SYNO.SDS.MailClient.SynoCalendarPlugin.message.rfc_message_id}},a=new SYNO.Cal.Create.Popup.Container({data:n,autoFlexcroll:!1,addBtnCfg:{btnStyle:"blue"},titleWidth:373,evtNameWidth:373,labelWidth:100,height:277,width:415,arrowOffsetX:3,arrowOffsetY:8,formOffsetX:-20,calPickerWidth:252,calPickerListWidth:268,dateFieldWidth:160,timeFieldWidth:100});SYNO.SDS.MailClient.SynoCalendarPlugin.mon(a,"eventaddsucceed",function(){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("calendar","event_created"))}),a.alignTo(t.getPageX(),t.getPageY()),a.mon(SYNO.SDS.MailClient.Window.el,"mousedown",function(t,e){a.destroy()})}}},parseDateAndReplace:function(t,e,i){if(!SYNO.SDS.MailClient.Settings.disable_date_highlight){this.findFirstLineInReplyPart(i);var n=t.split("\n"),a=n.map(function(t){var i=Date.now()-432e5,n=[];return chrono.parse(t,e).forEach(function(t){if(!(t.tags.hasOwnProperty("ExtractTimezoneOffsetRefiner")||t.tags.hasOwnProperty("ENDeadlineFormatParser")||t.tags.hasOwnProperty("ESDeadlineFormatParser"))&&"now"!==t.text)if(t.hasOwnProperty("end")&&t.end.date().getTime()>i)n.push(t);else{if(!(t.hasOwnProperty("start")&&t.start.date().getTime()>i))return;n.push(t)}}),n},this);a=[].concat.apply([],a),a=a.sort(function(t,e){return e.text.length-t.text.length}),a=function(t,e){var i={};return t.filter(function(t){var n=e(t);return!i.hasOwnProperty(n)&&(i[n]=!0)})}(a,function(t){return t.text}),a.forEach(function(t){this.dateReplace(t,i)},this)}},isAllDay:function(t){var e=t.start.impliedValues,i=t.start.knownValues,n=!i.hasOwnProperty("hour")&&!i.hasOwnProperty("minute")&&e.hasOwnProperty("hour")&&12===e.hour;if(t.hasOwnProperty("end")){var a=t.end.impliedValues,o=t.start.knownValues;n=n&&!o.hasOwnProperty("hour")&&!o.hasOwnProperty("minute")&&a.hasOwnProperty("hour")&&12===a.hour}return n},dateReplace:function(t,e){this.config.highlightContainerDataset={start:t.start.date(),end:Ext.isEmpty(t.end)?"":t.end.date(),is_all_day:this.isAllDay(t)},this.highlight(t.text,e)},setMessage:function(t){var e,i;if(Ext.isObject(t.body))e=SYNO.SDS.MailClient.MessageLib.BodyProcessor.getImageProcessedHtml(t.body.html,t.inline_image),i=this.preRenderMessage(e),SYNO.SDS.MailClient.SynoCalendarPlugin.message={message_id:t.message_id,subject:t.subject,body:i.length>256?i.substr(0,255):i,rfc_message_id:t.rfc_message_id};else{if(!Ext.isEmpty(SYNO.SDS.MailClient.SynoCalendarPlugin.message)&&SYNO.SDS.MailClient.SynoCalendarPlugin.message.message_id===t.message_id)return;SYNO.SDS.MailClient.SynoCalendarPlugin.message=t}},preRenderMessage:function(t){var e=document.createElement("div"),i="";return e.innerHTML=t,e.classList.add("body","reset"),Ext.getBody().appendChild(e),i=e.innerText,Ext.getBody().dom.removeChild(e),i},createCalendarAndAddEvent:function(){var t=function(t){var e=new Date,i=t||0;return e.setMinutes(0),e.setSeconds(0),new Date(e.getTime()+60*i*60*1e3)},e=chrono.parse(SYNO.SDS.MailClient.SynoCalendarPlugin.message.subject),i={fn:"add_evt",evt:Ext.encode({dtstart:Ext.isEmpty(e)?t().format("Y-m-d H:i:s"):e[0].start.date().format("Y-m-d H:i:s"),dtend:Ext.isEmpty(e)?t(1).format("Y-m-d H:i:s"):Ext.isEmpty(e[0].end)?"":e[0].end.date().format("Y-m-d H:i:s"),is_all_day:!Ext.isEmpty(e)&&this.isAllDay(e[0]),from_syno_app_url:{app:"SYNO.SDS.MailClient.Application",msg_id:SYNO.SDS.MailClient.SynoCalendarPlugin.message.rfc_message_id},summary:SYNO.SDS.MailClient.SynoCalendarPlugin.message.subject,description:SYNO.SDS.MailClient.SynoCalendarPlugin.message.body})};SYNO.SDS.MailClient.AppLib.WindowOpener.openCalendar(i)},findFirstLineInReplyPart:function(t){Ext.get(t).select(".blockquote-toggle, blockquote").each(function(t){t.dom.previousElementSibling&&t.dom.previousElementSibling.classList.add("syno-mc-skip-date-highlight")})},message:null},SYNO.SDS.MailClient.postDefine),Ext.define("SYNO.SDS.MailClient.Message.ClickRecognizer",{extend:"Ext.util.Observable",requires:[],constructor:function(t){this.callParent(arguments),this.store=t.store,this.list=t.list},onClick:function(t,e,i){var n,a,o,s=Ext.get(e),l=this.getClickActionMap(),r=this.list;if(s){if(s.hasClass("more")||s.parent(".more")){var d=s.hasClass("more")?s:s.parent(".more");return void r.clickMore(d)}var c,h=s.hasClass("item-wrap")?s:s.parent(".item-wrap");if(h&&(c=r.indexOf(h),s.hasClass("info-btn-icon")||s.hasClass("info")?r.clickDetail(c,s):(s.hasClass("item-toggle")||s.hasClass("item-toggle-img")||s.hasClass("item-title")||s.parent(".item-title")||s.hasClass("time"))&&c!==r.store.getCount()-1&&(r.toggleDetail(h,!0),r.fireEvent("toggled",this,r.toggledItemIds)),r.store.getAt(c).get("message_status")!==SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT||s.hasClass("blockquote-toggle"))){if((o="A"===s.dom.tagName?s:s.up("a"))&&(a=o.dom.getAttribute("href"))&&0===a.toLowerCase().indexOf("mailto:"))return t.preventDefault(),void SYNO.SDS.MailClient.ComposerLib.Action.openMailtoLink(a);if("img"===s.dom.tagName.toLowerCase())return void r.clickInlineImage(s);n=r.store.getAt(c),n&&Ext.iterate(l,function(e,i){if(s.hasClass(e))return i.call(this,n,s,h,c,r.threadRec,t),!1},this)}}},getClickActionMap:function(){return this.clickActionMap=this.clickActionMap||this.createClickActionMap(),this.clickActionMap},createClickActionMap:function(){var t=this.list,e=function(t,e){return e.select(".attachment-item").indexOf(t.parent(".attachment-item"))},i=function(e,i){t.ownerCt.getComponent("messageComposer").refwdMessage(e,i)}.bind(this);return{star:function(e,i,n,a,o){t.action.toggleStar(e,o)},"mailbox-label":function(t){SYNO.SDS.MailClient.Define.isMessageMode||SYNO.SDS.MailClient.Control.Sidebar.openMailbox(t.data.mailbox_id)},"attachment-action-download":function(e){t.action.downloadAll(e)},"attachment-item-download":function(i,n,a){var o=e(n,a);t.action.download(i,o)},"attachment-action-saveds":function(e){t.action.saveAllToDS(e)},"attachment-item-saveds":function(i,n,a){var o=e(n,a);t.action.saveToDS(i,o)},"attachment-item-mask":function(t,i,n,a,o,s){var l=e(i,n),r=t.get("attachment");Ext.isArray(r)&&Ext.isObject(r[l])&&SYNO.SDS.MailClient.Viewer.show(r[l],s.xy)},reply:function(t){i("reply",t)},"reply-all":function(t){i("reply_all",t)},forward:function(t){i("forward",t)},"more-action":function(e,i,n,a){t.moreMenu.getComponent("addtoblacklist").setVisible(e.data.mailbox_id!==SYNO.SDS.MailClient.Define.junkId),t.moreMenu.getComponent("addtowhitelist").setVisible(e.data.mailbox_id===SYNO.SDS.MailClient.Define.junkId),t.moreMenu.msgIdx=a,t.moreMenu.ownerBtn=i,t.moreMenu.showAt([i.getLeft(),i.getBottom()])},"blockquote-toggle":function(e,i,n){var a=i.next(".blockquote-content"),o=n;a&&(o.dom.externalInBlockquote&&o.select(".show-external-ct").item(0).hasClass("x-hide-display")&&o.select(".show-external-ct").item(0).removeClass("x-hide-display"),a.toggleClass("blockquote-hidden"),t.fireEvent("contentchange",this))},"show-external-text":function(e,i,n,a){var o,s=!1,l=Ext.fly(t.getNode(a)).select(".blockquote-content");for(o=0;o<l.getCount();++o)l.item(o).hasClass("blockquote-hidden")||(s=!0);t.fetchFullMessage(e,!0,s)},"pgp-text":function(e){return t.el.mask(),t.action.decrypt(e).then(function(){t.el.unmask()}.bind(this))},"message-clipped-hint":function(e,i,n,a){t.fireEvent("showallmessageclick",a)}}}}),Ext.define("SYNO.SDS.MailClient.Message.CalendarPanel",{extend:"SYNO.ux.Panel",eventFromCalendar:null,constructor:function(t){this.parsedData=this.parseIcsData(t.data),this.callParent([this.fillConfig(t)]),this.getEventFromCalendar()},fillConfig:function(t){var e=this.parsedData,i={border:!1,layout:"hbox",items:[this.getDatePanel(e),this.getCalendarDetailPanel(e)]};return Ext.apply(i,t)},parseIcsData:function(t){var e,i,n,a=ICAL.Component.fromString(t),o=a.getFirstSubcomponent("vtimezone");if(!Ext.isEmpty(o)){var s=new ICAL.Timezone(o);ICAL.TimezoneService.has(s.tzid)||ICAL.TimezoneService.register(s.tzid,s)}e=a.getFirstSubcomponent("vevent"),i=e.getFirstPropertyValue("sequence")||0,n=e.getFirstPropertyValue("dtstart")||new ICAL.Time,a.getAllSubcomponents("vevent").forEach(function(t){var a=t.getFirstPropertyValue("sequence"),o=t.getFirstPropertyValue("recurrence-id");Ext.isEmpty(a)||Ext.isEmpty(o)||o.toString()===n.toString()&&a>i&&(e=t,i=a)});var l=function(){var t=e.getFirstPropertyValue("organizer");return Ext.isEmpty(t)?t:t.substr(t.indexOf(":")+1)}();return{method:a.getFirstPropertyValue("method"),status:e.getFirstPropertyValue("status"),startDate:e.getFirstPropertyValue("dtstart").toJSDate(),endDate:e.getFirstPropertyValue("dtend").toJSDate(),summary:e.getFirstPropertyValue("summary"),description:e.getFirstPropertyValue("description"),location:e.getFirstPropertyValue("location"),organizer:l,attendees:function(t){var e=[];return t.getAllProperties("attendee").forEach(function(t){var i=t.getFirstValue();(Ext.isEmpty(i)||i.substr(i.indexOf(":")+1)!==l)&&e.push(Ext.isEmpty(i)?i:i.substr(i.indexOf(":")+1))}),e}(e),uid:e.getFirstPropertyValue("uid")}},getDatePanel:function(t){return this.datePanel=this.datePanel||new SYNO.ux.Panel({border:!1,cls:"syno-mc-calendar-date-panel",width:99,height:120,items:[{xtype:"container",cls:"date-shadow",items:[{xtype:"syno_displayfield",cls:"month-header",hideLabel:!0,value:t.startDate.format("M")},{xtype:"container",cls:"date-main",items:[{xtype:"syno_displayfield",cls:"date",indent:.5,hideLabel:!0,value:t.startDate.format("d")},{xtype:"syno_displayfield",cls:"day",indent:.5,hideLabel:!0,value:t.startDate.format("D")}]}]}]}),this.datePanel},getCalendarDetailPanel:function(t){return this.calendarDetailPanel=this.calendarDetailPanel||new SYNO.ux.FormPanel({cls:"syno-mc-calendar-detail-panel",autoFlexcroll:!1,autoScroll:!0,autoHeight:!0,flex:1,labelWidth:120,buttonAlign:"left",items:this.getItems(t),fbar:this.getFbar(t)}),this.calendarDetailPanel},getItems:function(t){this.event_detail_link=new SYNO.ux.Button({cls:"event-btn-link",hidden:!0,text:SYNO.SDS.MailClient._T("calendar","event_detail"),handler:function(){this.launchCalendarAndEdit(t)},scope:this});for(var e=[{xtype:"syno_compositefield",itemId:"event-summary-area",hideLabel:!0,items:[{xtype:"syno_displayfield",hideLabel:!0,cls:"event-summary",value:t.summary},this.event_detail_link]},{xtype:"syno_displayfield",cls:"event-description",htmlEncode:!1,hideLabel:!0,value:function(){var e=Ext.util.Format.htmlEncode(t.description);return Ext.isEmpty(e)?e:e.replace(/\r\n|\n|\r/g,"<br>").replace(/\s/g," ")}()},{xtype:"syno_compositefield",width:450,height:25,labelStyle:"padding:3px 0px",fieldLabel:_T("helptoc","time"),defaults:{style:{padding:"3px 0px"}},items:[{xtype:"syno_displayfield",value:String.format("{0}:{1} - {2}:{3}",t.startDate.format("D Y/m/d h"),t.startDate.format("ia"),t.endDate.format("D Y/m/d h"),t.endDate.format("ia"))},{xtype:"syno_displayfield",
cls:"event-organizer",hidden:Ext.isEmpty(t.endDate.format("T")),value:String.format("({0})",t.endDate.format("T"))}]},{xtype:"syno_displayfield",fieldLabel:SYNO.SDS.MailClient._T("calendar","event_location"),value:t.location,hidden:Ext.isEmpty(t.location)},{xtype:"syno_compositefield",labelStyle:"padding:3px 0px 0px 0px",defaults:{style:{padding:"3px 0px 0px 0px"}},fieldLabel:SYNO.SDS.MailClient._T("calendar","event_attendee"),items:[{xtype:"syno_displayfield",value:t.organizer},{xtype:"syno_displayfield",cls:"event-organizer",value:String.format("({0})",SYNO.SDS.MailClient._T("calendar","event_organizer"))}]}],i=0;i<t.attendees.length;i++){if(4===i){e.push(this.getExpandButton(t.attendees,i)),e.push(this.getMoreAttendeePanel(t.attendees,i));break}e.push({xtype:"syno_displayfield",indent:4.16667,cls:"event-invite",hideLabel:!0,value:t.attendees[i]})}return e},getExpandButton:function(t,e){return{xtype:"syno_button",cls:"event-invite event-and-other-people",indent:4.16667,text:String.format(SYNO.SDS.MailClient._T("calendar","event_and_other_people"),t.length-e),handler:function(t){t.hide(),this.moreAttendeePanel.show(),this.doLayout()},scope:this}},getMoreAttendeePanel:function(t,e){return this.moreAttendeePanel=this.moreAttendeePanel||new Ext.Container({hidden:!0,items:function(){var i,n=[];for(i=e;i<t.length;i++)n.push({xtype:"syno_displayfield",indent:4.16667,cls:"event-invite",hideLabel:!0,value:t[i]});return n}()}),this.moreAttendeePanel},getFbar:function(t){return[{xtype:"syno_button",text:SYNO.SDS.MailClient._T("calendar","add_to_calendar"),hidden:!0,cls:"event-btn-link",itemId:"add-to-calendar-btn",handler:function(){this.launchCalendarAndAdd(t)},scope:this},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("calendar","event_cancelled"),hidden:!0,itemId:"event-canceled-text"},{xtype:"syno_button",text:_T("common","yes"),hidden:!0,cls:"yes-btn",itemId:"yes-btn",handler:function(t,e){this.onReplyBtnClick(t,"ACCEPTED")},scope:this},{xtype:"syno_button",text:SYNO.SDS.MailClient._T("calendar","event_rsp_maybe"),hidden:!0,cls:"maybe-btn",itemId:"maybe-btn",handler:function(t,e){this.onReplyBtnClick(t,"TENTATIVE")},scope:this},{xtype:"syno_button",text:_T("common","no"),hidden:!0,cls:"no-btn",itemId:"no-btn",handler:function(t,e){this.onReplyBtnClick(t,"DECLINED")},scope:this}]},launchCalendarAndAdd:function(t){var e=String.format("#month/{0}",t.startDate.format("Y-m-d")),i={fn:"add_evt",evt:Ext.encode({dtstart:t.startDate.format("Y-m-d H:i:s"),dtend:t.endDate.format("Y-m-d H:i:s"),summary:t.summary,description:t.description.length>256?t.description.substr(0,255):t.description,location:t.location})};this.launchCalendar(i,e)},launchCalendarAndEdit:function(t){var e=String.format("#month/{0}",t.startDate.format("Y-m-d")),i={fn:"edit_evt",evt:Ext.encode({evt_id:this.eventFromCalendar.evt_id,cal_id:this.eventFromCalendar.original_cal_id})};this.launchCalendar(i,e)},onReplyBtnClick:function(t,e){if(!t.el.hasClass("select")){var i=this.calendarDetailPanel.getFooterToolbar();i.getComponent("yes-btn").removeClass("select"),i.getComponent("maybe-btn").removeClass("select"),i.getComponent("no-btn").removeClass("select"),t.addClass("select"),this.setReplyToCalendar(e)}},setReplyToCalendar:function(t){Ext.apply(this.eventFromCalendar,{invite_status:t}),SYNO.Cal.Controller.EventExternal.reply(this.eventFromCalendar)},getEventFromCalendar:function(){if("CANCEL"===this.parsedData.method||"CANCELLED"===this.parsedData.status)return void this.calendarDetailPanel.fbar.getComponent("event-canceled-text").show();var t=function(t,e,i){if(!t)return void this.calendarDetailPanel.fbar.getComponent("add-to-calendar-btn").show();this.onGetEventFromCalendar(e)};SYNO.API.Request({params:{ical_uid:this.parsedData.uid},api:"SYNO.Cal.Event",method:"get",version:1,callback:t,scope:this})},onGetEventFromCalendar:function(t){switch(this.eventFromCalendar=t,this.event_detail_link.show(),this.calendarDetailPanel.getComponent("event-summary-area").doLayout(),this.calendarDetailPanel.fbar.getComponent("yes-btn").show(),this.calendarDetailPanel.fbar.getComponent("maybe-btn").show(),this.calendarDetailPanel.fbar.getComponent("no-btn").show(),t.invite_status){case"ACCEPTED":this.calendarDetailPanel.fbar.getComponent("yes-btn").addClass("select");break;case"TENTATIVE":this.calendarDetailPanel.fbar.getComponent("maybe-btn").addClass("select");break;case"DECLINED":this.calendarDetailPanel.fbar.getComponent("no-btn").addClass("select");break;default:return}},launchCalendar:function(t,e){SYNO.SDS.MailClient.AppLib.WindowOpener.openCalendar(t,e)}}),Ext.define("SYNO.SDS.MailClient.Message.SharedMailboxSubscribePanel",{extend:"SYNO.ux.Panel",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={border:!1,layout:"hbox",items:[this.getIconPanel(),this.getDetailPanel(t.data)]};return Ext.apply(e,t)},getIconPanel:function(){return this.iconPanel=this.iconPanel||new SYNO.ux.Panel({border:!1,cls:"syno-mc-sharedmailbox-subscribe-icon-panel",width:99,height:120,items:[{xtype:"box",cls:"invitation-icon",width:80,height:80}]}),this.iconPanel},getDetailPanel:function(t){return this.detailPanel=this.detailPanel||new SYNO.ux.FormPanel({cls:"syno-mc-sharedmailbox-subscribe-detail-panel",labelWidth:120,autoFlexcroll:!1,autoScroll:!0,flex:1,buttonAlign:"left",items:this.getItems(t),fbar:this.getFbar(t)}),this.detailPanel},getItems:function(t){var e=SYNO.SDS.MailClient.Define;return[{xtype:"syno_displayfield",cls:"event-description",hideLabel:!0,value:"true"===t.is_modified?SYNO.SDS.MailClient._T("mailbox","modify_shared_mailbox_invitation"):SYNO.SDS.MailClient._T("mailbox","shared_mailbox_invitation")},{xtype:"syno_displayfield",fieldLabel:SYNO.SDS.MailClient._T("common","mailbox"),value:e.isSystemMailboxName(t.mailbox_name)?e.getSystemMailboxNameString(t.mailbox_name):t.mailbox_name},{xtype:"syno_displayfield",fieldLabel:SYNO.SDS.MailClient._T("common","owner"),value:t.owner},{xtype:"syno_displayfield",fieldLabel:SYNO.SDS.MailClient._T("mailbox","permission"),value:SYNO.SDS.MailClient.Format.getUIStringByPermission(t.permission)}]},getFbar:function(t){return[{xtype:"syno_button",text:SYNO.SDS.MailClient._T("mailbox","subscribe_mailbox"),itemId:"subscribe-mailbox-btn",cls:"subscribe-btn",btnStyle:"blue",height:28,hidden:this.isSubscribed(t),handler:function(){this.subscribeMailbox(t)},scope:this},{xtype:"syno_button",text:SYNO.SDS.MailClient._T("mailbox","mailbox_subscribed"),itemId:"mailbox-subscribed-btn",cls:"subscribe-btn",hidden:!this.isSubscribed(t),height:28,disabled:!0},{xtype:"syno_button",text:String.format("{0}...",SYNO.SDS.MailClient._T("common","processing")),itemId:"processing-btn",btnStyle:"blue",cls:"subscribe-btn",hidden:!0,height:28}]},isSubscribed:function(t){var e=SYNO.SDS.MailClient.Switch.getMailboxStore().getMailboxByPath(t.mailbox_path);return!SYNO.ux.Utils.checkObjectConsistency(e,{})&&e.get("subscribed")},subscribeMailbox:function(t){this.detailPanel.fbar.getComponent("subscribe-mailbox-btn").hide(),this.detailPanel.fbar.getComponent("processing-btn").show(),SYNO.SDS.MailClient.WebAPI.send("setSubscribeMailbox",{path:t.mailbox_path,subscribed:!0}).then(function(){return this.detailPanel.fbar.getComponent("processing-btn").hide(),this.detailPanel.fbar.getComponent("mailbox-subscribed-btn").show(),SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()}.bind(this)).catch(function(t){this.detailPanel.fbar.getComponent("processing-btn").hide(),this.detailPanel.fbar.getComponent("subscribe-mailbox-btn").setDisabled(!0),SYNO.SDS.MailClient.Window.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t))}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.Message.ExtraPanelMgr",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.Message.CalendarPanel","SYNO.SDS.MailClient.Message.SharedMailboxSubscribePanel"],constructor:function(){this.callParent(arguments),this.nodeMap={},this.calendarRequestMap={}},processCalendarPart:function(t,e){if(SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")&&!Ext.isEmpty(t.data.calendar_attachment)&&!this.calendarRequestMap[t.id]){this.calendarPanelMessageId=t.id;var i=this.getCalendarPanelByRecordId(t.id);if(this.nodeMap.hasOwnProperty(t.id)&&!Ext.isIE&&!Ext.isIE11&&i)return this.checkChildExistAndAppendChildDom(i,this.nodeMap[t.id]),this._applyExpandState(i,e),void this.adjCalendarPanelSize();i.firstChild||(this.calendarRequestMap[t.id]=!0,Ext.Ajax.request({url:SYNO.SDS.MailClient.MessageLib.UrlBuilder.getAttachmentDownloadUrl(t.data.calendar_attachment[0]),success:function(n,a){if(!Ext.isEmpty(n.responseText)){i=this.getCalendarPanelByRecordId(t.id),this._applyExpandState(i,e);var o=new SYNO.SDS.MailClient.Message.CalendarPanel({data:n.responseText,renderTo:i,listeners:{afterrender:function(t){t.doLayout()}}});this.nodeMap[t.id]=o.el.dom,this.calendarRequestMap[t.id]=!1}},failure:function(t,e){},scope:this}))}},processSharedMailboxSubscribePart:function(t,e){var i=document.createElement("div");i.innerHTML=SYNO.SDS.MailClient.MessageLib.BodyProcessor.getImageProcessedHtml(t.data.body.html,t.data.inline_image);var n=Ext.get(i).select('div[type="syno-sharedmailbox-notification-letter"]');if(0!==n.getCount()){this.subscribePanelMessageId=t.id;var a=this.getSubscribePanelByRecordId(t.id);if(this._applyExpandState(a,e),this.nodeMap.hasOwnProperty(t.id)&&!Ext.isIE&&!Ext.isIE11&&a)return this.checkChildExistAndAppendChildDom(a,this.nodeMap[t.id]),void this.adjSubscribePanelSize();if(!a.firstChild){var o=n.first(),s=new SYNO.SDS.MailClient.Message.SharedMailboxSubscribePanel({data:{mailbox_path:o.getAttribute("mailbox_path"),mailbox_name:o.getAttribute("mailbox_name"),owner:o.getAttribute("owner"),permission:o.getAttribute("permission"),is_modified:o.getAttribute("is_modified")},renderTo:a});this.nodeMap[t.id]=s.el.dom}}},checkChildExistAndAppendChildDom:function(t,e){t.firstChild||t.appendChild(e)},adjCalendarPanelSize:function(){if(!Ext.isEmpty(this.calendarPanelMessageId)&&!SYNO.SDS.MailClient.Tool.isEmptyObject(this.nodeMap)){var t=this.nodeMap[this.calendarPanelMessageId];if(t){Ext.getCmp(t.id).doLayout(!0)}}},adjSubscribePanelSize:function(){if(!Ext.isEmpty(this.subscribePanelMessageId)&&!SYNO.SDS.MailClient.Tool.isEmptyObject(this.nodeMap)){var t=this.nodeMap[this.subscribePanelMessageId];if(t){Ext.getCmp(t.id).doLayout(!0)}}},getCalendarPanelByRecordId:function(t){var e=SYNO.SDS.MailClient.Control.Main.get("MessagePanel");return Ext.DomQuery.jsSelect(String.format("[syno-mc-data-message-id={0}] .calendar-panel",t),e.el.dom)[0]},getSubscribePanelByRecordId:function(t){var e=SYNO.SDS.MailClient.Control.Main.get("MessagePanel");return Ext.DomQuery.jsSelect(String.format("[syno-mc-data-message-id={0}] .sharedmailbox-subscribe-panel",t),e.el.dom)[0]},_applyExpandState:function(t,e){e?t.classList.remove("x-hide-display"):t.classList.add("x-hide-display")}}),Ext.define("SYNO.SDS.MailClient.MessageLib.Action",{extend:"Ext.util.Observable",requires:[],constructor:function(t){this.callParent(arguments),this.store=t.store,this.list=t.list},toggleStar:function(t,e){var i,n;return t.get("star")?t.set("star",0):t.set("star",1),n=t.get("star"),i=t.get("operation_ids"),SYNO.SDS.MailClient.WebAPI.send("setStarEx",[i,n]).then(function(){var t={id:e.id,prop:{star:{value:n,id:i}}};SYNO.SDS.MailClient.Control.Thread.modifyThread("edit",[t])}.bind(this)).catch(function(e){SYNO.Debug.error(e),t.set("star",t.get("star")>0?0:1)}.bind(this))},decrypt:function(t){var e=SYNO.SDS.MailClient.PGP.Encryption,i=t.get("body").plain;return e.decrypt(i).then(function(n){var a=n.data;a&&(t.data.pgp_encryption=n.encryptionStat,t.data.pgp_verify_info=n.verifyInfo,t.data.pgp_decrypted_content=a+e.getRemainingText(i),t.commit())}.bind(this)).catch(function(e){e.code!==SYNO.SDS.MailClient.Define.PGPStat.CANCEL&&(t.data.pgp_encryption=SYNO.SDS.MailClient.Define.EncryptionStat.ERROR,t.data.pgp_error={info:e.info,code:e.code},t.commit())})},downloadAll:function(t){this._downloadWebAPI({webapi:{api:"SYNO.MailClient.Attachment",method:"download_all",version:6,params:{id:t.get("id")}},filename:"attachment.zip"})},download:function(t,e){var i=this._getAttachmentInfo(t,e);i&&this._downloadWebAPI({webapi:{api:"SYNO.MailClient.Attachment",method:"download",version:6,params:{id:i.attachmentId}},filename:i.filename})},saveAllToDS:function(t){var e=t.get("subject")+"_attachments",i=t.get("id"),n=this.list.findAppWindow();return SYNO.SDS.MailClient.MessageLib.Attachment.saveAllToDS(n,e,i)},saveToDS:function(t,e){var i=this._getAttachmentInfo(t,e),n=this.list.findAppWindow();if(i)return SYNO.SDS.MailClient.MessageLib.Attachment.saveToDS(n,i.filename,i.attachmentId)},_getAttachmentInfo:function(t,e){var i,n,a;return n=t.get("attachment"),Ext.isArray(n)&&Ext.isObject(n[e])?(a=n[e].id,i=SYNO.SDS.MailClient.Format.toAttachmentName(n[e]),{filename:i,attachmentId:a}):null},_downloadWebAPI:function(t){this.list.downloadWebAPI(t)}}),Ext.define("SYNO.SDS.MailClient.MessageList",{extend:"SYNO.ux.ExpandableListView",requires:["SYNO.SDS.MailClient.MessageHouseLib.Util"],fileIconPath:"webman/modules/FileBrowser/images/{1}/files_ext_64/",toggleWrapCls:"item-toggle",expandCls:"item-expanded",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("contentchange","toggled","printclick","singledelete","singleaddtoblacklist","singleaddtowhitelist","showallmessageclick"),this.action=new SYNO.SDS.MailClient.MessageLib.Action({store:this.store,list:this}),this.clickRecognizer=new SYNO.SDS.MailClient.Message.ClickRecognizer({list:this}),SYNO.SDS.MailClient.Switch.on("pgpkeychange",this.resetFailedEncryptionInfo,this)},fillConfig:function(t){var e=this.callParent(arguments);this.moreMenu=this.createMoreMenu(),this.detailMenu=new SYNO.SDS.MailClient.MessageDetailMenu;var i={cls:"syno-mc-message-list selectabletext",autoFlexcroll:!1,toggleOnDblClick:!1,useDefaultKeyNav:!1,autoWidth:!0,prepareData:this.prepareTplData,highlightText:null,plugins:new SYNO.SDS.MailClient.NameCardPlugin};return Ext.apply(i,e,t)},prepareTplData:function(t){var e=SYNO.SDS.MailClient.Define.MessageStat,i=t.message_status===e.FROM_DRAFT;return t.tpl_body,t.pgp_decrypted_content?t.tpl_body=this._processBody({plain:t.pgp_decrypted_content}):t.body?t.tpl_body=this._processBody(t.body,t.inline_image,t.show_blockquote,t.arrival_time,t.rfc_message_id,i):t.message_status!==e.NOT_EXIST&&(t.tpl_body='<div class="sending-hint"><div class="icon"></div><div class="text">'+_T("common","loading")+"</div></div>"),t},createTpl:function(){return SYNO.SDS.MailClient.Message.ListTpl.createTpl()},createMoreMenu:function(){return new SYNO.ux.Menu({cls:"syno-mc-menu",items:[{text:SYNO.SDS.MailClient._T("mail","print"),handler:function(t){this.fireEvent("printclick",t.parentMenu.msgIdx)},scope:this},{itemId:"delete",text:SYNO.SDS.MailClient._T("common","delete"),handler:function(t){this.fireEvent("singledelete",t.parentMenu.msgIdx)},scope:this},{itemId:"addtoblacklist",text:SYNO.SDS.MailClient._T("spam_rule","add_to_black_list"),handler:function(t){this.fireEvent("singleaddtoblacklist",t.parentMenu.msgIdx)},scope:this},{itemId:"addtowhitelist",text:SYNO.SDS.MailClient._T("spam_rule","add_to_white_list"),handler:function(t){this.fireEvent("singleaddtowhitelist",t.parentMenu.msgIdx)},scope:this},{text:SYNO.SDS.MailClient._T("mail","show_original"),handler:function(t){var e=this.getOriginalMessageUrl(t.parentMenu.msgIdx);window.open(e)},scope:this},{text:SYNO.SDS.MailClient._T("mail","download_original"),handler:function(t){var e=this.getOriginalMessageDownloadUrl(t.parentMenu.msgIdx);window.open(e)},scope:this},{text:SYNO.SDS.MailClient._T("mail","forward_original"),handler:function(t){var e=this.store.getAt(t.parentMenu.msgIdx).get("id");return SYNO.SDS.MailClient.ComposerLib.Action.forwardOriginalContent(e)},scope:this},{text:SYNO.SDS.MailClient._T("mail","save_to_note_station"),hidden:!SYNO.SDS.MailClient.MessageLib.NoteStation.checkNoteStationVersion(),handler:function(t){this.clickSaveToNoteStation(t.parentMenu.msgIdx)},scope:this},{text:SYNO.SDS.MailClient._T("mail","add_sender_to_contact"),hidden:!0,itemId:"addSenderToContact",handler:function(t){var e=this.store.getAt(t.parentMenu.msgIdx).get("from"),i=this.store.getAt(t.parentMenu.msgIdx).get("email"),n=SYNO.SDS.MailClient.Format.matchNameAddr(e),a=SYNO.SDS.MailClient.Format.isAddrSpec(e,!0),o=n?n[1]:a[1],s=function(t){t&&SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","contact_add"))};SYNO.SDS.MailClient.OP.createContact({full_name:o,name:{given_name:o},mail:[{data:i}],apply_default:!0},s)},scope:this}],listeners:{scope:this,beforeshow:function(t){var e,i=SYNO.SDS.MailClient.Define,n=this.store.getAt(t.msgIdx),a=n.get("from"),o=n.get("email"),s=n.get("rfc_message_id"),l=this.threadRec.get("message"),r=!1,d=n.data.mailbox_id,c=d===i.trashId||d===i.junkId,h=!1;l.forEach(function(t){if(t.rfc_message_id!=s)return h=!0,!0;e=t.mailbox_id,r=r||SYNO.SDS.MailClient.Define.isReadOnlyMailbox(e)}.bind(this)),h||SYNO.SDS.MailClient.Define.isInVirtaulOrLabel()?t.getComponent("delete").setVisible(!c&&!r):t.getComponent("delete").setVisible(!c&&!SYNO.SDS.MailClient.Define.isInReadOnlyMailbox());var u=SYNO.SDS.MailClient.Format.matchNameAddr(a),S=SYNO.SDS.MailClient.Format.isAddrSpec(a,!0);if(u||S){var m=SYNO.SDS.MailClient.Switch.hasEmailInContact(o);t.getComponent("addSenderToContact").setVisible(!m)}else t.getComponent("addSenderToContact").setVisible(!1)},show:function(t){t.ownerBtn&&t.ownerBtn.addClass("x-btn-menu-active")},hide:function(t){t.ownerBtn&&(t.ownerBtn.removeClass("x-btn-menu-active"),t.ownerBtn=null)}}})},clickSaveToNoteStation:function(t){var e,i,n,a,o=this.store.getAt(t),s=this.findWindow();if(o)return e=o.get("subject"),i=this._processBody(o.get("body")),n=o.get("attachment"),a=SYNO.SDS.MailClient.MessageLib.NoteStation.prepareParamsForNoteSataion(e,i,n),this.findWindow().setStatusBusy({text:_T("common","saving")}),SYNO.SDS.MailClient.WebAPI.send("createNote",a).then(function(){s.clearStatusBusy(),s.getMsgBox().alert("",SYNO.SDS.MailClient._T("mail","save_to_note_station_success"))}.bind(this)).catch(function(){s.clearStatusBusy(),s.getMsgBox().alert("",SYNO.SDS.MailClient._T("api_error","notestation_has_error"))}.bind(this))},getAttachmentDownloadUrl:function(t){return SYNO.SDS.MailClient.MessageLib.UrlBuilder.getAttachmentDownloadUrl(t)},getOriginalMessageUrl:function(t){var e=this.store.getAt(t);if(e)return SYNO.SDS.MailClient.MessageLib.UrlBuilder.getOriginalMessageUrl(e)},getOriginalMessageDownloadUrl:function(t){var e=this.store.getAt(t);if(e)return SYNO.SDS.MailClient.MessageLib.UrlBuilder.getOriginalMessageDownloadUrl(e)},refresh:function(){this.store&&(this.callParent(arguments),this.el.select(".body img").each(function(t){t.on("load",function(){this.fireEvent("contentchange",this)},this,{single:!0})},this),this.all.elements.forEach(function(t){var e=Ext.get(t),i=0;e.select("[syno-mc-block-src], [syno-mc-block-srcset], [syno-mc-block-style]").each(function(e){e.parent("blockquote")&&-1!==e.parent("blockquote").getAttribute("syno-mc-class").indexOf("syno-mc-blockquote")?t.externalInBlockquote=!0:i+=1}),i&&e.select(".show-external-ct").item(0).removeClass("x-hide-display")},this),this.setImageErrorHandler())},updateArrivalTime:function(){var t,e,i=this.store.getRange(),n=new Date;for(t=0;t<i.length;++t)n/1e3-i[t].data.arrival_time<1209600&&(e=this.el.query("[syno-mc-data-message-id="+i[t].data.id+"] .time"),e.length&&Ext.fly(e[0]).update(SYNO.SDS.MailClient.Format.toTimeString(i[t].data.arrival_time,!0)))},bufferRender:function(t,e){var i=this.callParent(arguments);return Ext.each(i,function(t){var e=Ext.get(t),i=0;e.select(".body img").each(function(t){t.on("load",function(){this.fireEvent("contentchange",this)},this,{single:!0})},this),e.select("[syno-mc-block-src], [syno-mc-block-srcset], [syno-mc-block-style]").each(function(e){e.parent("blockquote")&&-1!==e.parent("blockquote").getAttribute("syno-mc-class").indexOf("syno-mc-blockquote")?t.externalInBlockquote=!0:i+=1}),i&&e.select(".show-external-ct").item(0).removeClass("x-hide-display")},this),i},clickRecords:function(t){if(Ext.isArray(t))return this.clickRecords.apply(this,t);var e;for(e=0;e<arguments.length;++e)this.toggleDetail(Ext.fly(this.getNode(this.store.indexOf(arguments[e]))),!1)},onAdd:function(t,e,i){if(0===this.all.getCount())return void this.refresh();var n;for(n=0;n<e.length;++n)Ext.apply(e[n].data,{tpl_hide:!1,tpl_more:!1,tpl_more_count:0});var a=this.bufferRender(e,i),o=this.all.elements;i<this.all.getCount()?(this.all.item(i).insertSibling(a,"before",!0),o.splice.apply(o,[i,0].concat(a))):(this.all.last().insertSibling(a,"after",!0),o.push.apply(o,a)),this.updateIndexes(i),this.setImageErrorHandler()},onUpdate:function(t,e){this.store.indexOf(e)>-1&&Ext.apply(e.data,{tpl_hide:!1,tpl_more:!1,tpl_more_count:0}),this.callParent(arguments),this.fireEvent("contentchange",this),this.setImageErrorHandler()},onRemove:function(t,e,i){this.callParent(arguments);var n,a,o;if((n=this.store.getAt(i))?(a=Ext.fly(this.getNode(i)),o=a.next(".more")):(n=this.store.getAt(i-1))&&(a=Ext.fly(this.getNode(i-1)),o=a.prev(".more")),!n)return void this.fireEvent("contentchange",this);n.data.tpl_hide&&o&&(this.clickMore(o),a=Ext.fly(this.getNode(this.store.indexOf(n)))),a&&!a.hasClass(this.expandCls)&&this.toggleDetail(a,!0),this.fireEvent("contentchange",this)},onClick:function(t,e,i){this.clickRecognizer.onClick(t,e,i)},restoreUIState:function(t,e){var i,n,a,o=0;for(this.suspendUpdateScrollbar(),o=0;o<t.length;o++)(n=this.store.getById(t[o]))&&this.select(n,!0,!1);for(o=e.length-1;o>=0;o--)n=this.store.getById(e[o]),n?(i=this.getNode(n),(a=Ext.fly(i))&&!a.down(".item-toggle-expanded")&&this.toggleDetail(Ext.fly(i),!1)):e.remove(e[o]);this.resumeUpdateScrollbar(),this.autoFlexcroll&&this.updateFleXcroll()},doExpand:function(t,e){var i=e.child(".item-detail");if(i){i.setVisibilityMode(Ext.Element.DISPLAY),i[t?"show":"hide"]();var n=e.child("."+this.toggleWrapCls),a=this.getRecord(e.dom);n&&(n[t?"addClass":"removeClass"]("item-toggle-expanded"),t||1===this.store.data.length&&!0===this.singleExpanded&&(this.userExpanded=!1),e[t?"addClass":"removeClass"](this.expandCls),this.processCalendarPart(a,t),this.processSharedMailboxSubscribePart(a,t),this.fireEvent("contentchange",this))}},isRecordExpanded:function(t){var e=this.getNode(t),i=Ext.fly(e);return i&&i.down(".item-toggle-expanded")},toggleDetail:function(t,e){if(t){var i=this.getRecord(t.dom),n=SYNO.SDS.MailClient.Define.MessageStat;this.isNeedHideDetail(i)&&Ext.DomQuery.jsSelect(String.format("[syno-mc-data-message-id={0}] .item-detail",i.id),SYNO.SDS.MailClient.Control.Main.get("MessagePanel").el.dom)[0].classList.add("x-hide-display"),n.PREVIEW===i.get("message_status")&&this.fetchFullMessage(i,SYNO.SDS.MailClient.Settings.display_external_image),this.callParent(arguments)}},toggleDetailByRecord:function(t){var e=this.getNode(t),i=Ext.fly(e);this.toggleDetail(i,!1)},expandDetailByMsgIdxes:function(t){var e=this.getStore();t.forEach(function(t){var i=e.getAt(t);this.isRecordExpanded(i)||this.toggleDetailByRecord(i)},this)},expandLastMsg:function(){var t=this.getStore();t&&this.expandDetailByMsgIdxes([t.getCount()-1])},getLastMsg:function(){return this.getStore().getLastMsg()},getLastMsgNodeEl:function(){var t=this.getStore();return this.getNode(t.getCount()-1)},arm:Ext.emptyFn,disarm:function(){this.reset()},reset:function(){this.bindStore(),delete this.threadRec},resetFailedEncryptionInfo:function(){var t=SYNO.SDS.MailClient.Define.EncryptionStat,e=[t.INVALID_SIGN,t.DECRYPTED_INVALID,t.ERROR];if(this.store)return Promise.all(this.store.getRange().map(function(t){if(-1!==e.indexOf(t.data.pgp_encryption))return t.data.pgp_encryption=void 0,SYNO.SDS.MailClient.MessageHouseLib.Util.fillEncryptionInfo(t.data).then(function(){t.commit()}.bind(this))},this))},loadMessage:function(t,e){if(t&&e){var i,n,a,o=SYNO.SDS.MailClient.MessageHouseLib.Keeper,s=e.getCount(),l=[],r=this.getDefaultExpandIds(e),d=this._mapIdToIdx(e,r);for(this.threadRec=t,i=0;i<e.getCount();i++)a=e.getAt(i),a.get("id"),o.updateMsgRecordFromCache(a),a.data.tpl_more=!1,a.data.tpl_more_count=0,a.data.tpl_hide=!1,a.data.tpl_search_matched=!1,a.commit();var c,h;for(i=0;i<d.length;++i)c=d[i]-1,h=d[i]+1,c>=0&&-1===l.indexOf(c)&&l.push(c),h<s&&-1===l.indexOf(h)&&l.push(h);-1===d.indexOf(0)&&-1===l.indexOf(0)&&l.push(0);var u=0,S=l.concat(d).sort(function(t,e){return t-e});for(i=0;i<S.length;++i)if(i<S.length-1)for(u=S[i+1]-S[i]-1,n=S[i]+1;n<S[i+1];++n)a=e.getAt(n),u<3?(a.data.tpl_more=!1,a.data.tpl_more_count=0,a.data.tpl_hide=!1):n==S[i]+1?(a.data.tpl_more=!0,a.data.tpl_more_count=u,a.data.tpl_hide=!0):(a.data.tpl_more=!1,a.data.tpl_more_count=0,a.data.tpl_hide=!0),a.commit();this.bindStore(e),this.restoreUIState([],r),this._expandLastMatchedIds()}},_expandLastMatchedIds:function(){var t=this.getStore(),e=SYNO.SDS.MailClient.Switch.getRegister("lastMatchedIds"),i=[];Ext.isEmpty(e)||(this.triggerClickMore(),i=this._mapIdToIdx(t,e).filter(function(t){return t>=0}),i.sort(function(t,e){return t-e}),i.splice(1,i.length-2),this.expandDetailByMsgIdxes(i))},getDefaultExpandIds:function(t){return t.getDefaultExpandIds()},_mapIdToIdx:function(t,e){return e.map(function(e){return t.indexOfId(e)})},setImageErrorHandler:function(){var t=this.el.query(".attachment-item img");Ext.each(t,function(t){t.onerror=function(t){t.src=this.getFileIconUrl(t.getAttribute("ext"))}.bind(this,t)},this)},getFileIconUrl:function(t){var e=this.findAppWindow().appInstance.jsConfig.version;return SYNO.SDS.MailClient.MessageLib.UrlBuilder.getFileIconUrl(t)+"?v="+e},_processBody:function(t,e,i,n,a,o){var s=o?[]:this.highlightKeywords;return this._prepareCalendarData(),SYNO.SDS.MailClient.MessageLib.BodyProcessor.processBody(t,e,i,n,a,s)},_prepareCalendarData:function(){if(SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")){var t=this.getLastMsg(),e=t.data;SYNO.SDS.MailClient.SynoCalendarPlugin.setMessage({message_id:e.id,subject:e.subject,body:e.body,inline_image:e.inline_image||[],rfc_message_id:e.rfc_message_id})}},toggleBlockquote:function(t,e){t&&(e.dom.externalInBlockquote&&e.select(".show-external-ct").item(0).hasClass("x-hide-display")&&e.select(".show-external-ct").item(0).removeClass("x-hide-display"),t.toggleClass("blockquote-hidden"),this.fireEvent("contentchange",this))},getMessageIdWithUIInfo:function(t,e){var i,n;if("expand"==t){var a=this.toggledItemIds,o=this.store.getRange();for(n=[],i=0;i<o.length;++i)-1<a.indexOf(o[i].id)&&n.push(o[i].id)}else n=!1,void 0!==e?Ext.fly(this.all.elements[e]).select(".blockquote-content").each(function(t){if(!t.hasClass("blockquote-hidden"))return n=!0,!1},this):this.all.elements.forEach(function(t){var e=Ext.fly(t).select(".blockquote-content");for(i=0;i<e.getCount();++i)if(!e.item(i).hasClass("blockquote-hidden"))return n=!0,!1},this);return n},collapseAll:function(t){Ext.each(this.all.elements,function(e,i,n){var a=Ext.fly(e);if(a&&a.hasClass(this.expandCls)){if(i==n.length-1&&!t)return;this.toggleDetail(a,!1)}},this)},triggerClickMore:function(){this.el.query(".more").forEach(function(t){this.clickMore(Ext.fly(t))},this)},expandAll:function(){this.triggerClickMore(),Ext.each(this.all.elements,function(t,e,i){var n=Ext.fly(t);n&&!n.hasClass(this.expandCls)&&this.toggleDetail(n,!0)},this)},clickDetail:function(t,e){var i=this.store.getAt(t);i&&this.detailMenu.show(i.data,e)},clickMore:function(t){var e=t.prev(),i=this.indexOf(e),n=this.store.getAt(i);if(e&&n){t.remove();var a,o=n.data.tpl_more_count;for(n.data.tpl_more=!1,n.data.tpl_more_count=0,a=i;a<i+o;++a)this.store.getAt(a).data.tpl_hide=!1,this.store.getAt(a).commit()}},clickInlineImage:function(t){if(t){var e=t.dom.getAttribute("syno-mc-url")||t.dom.src;if(!t.parent("a")&&e){var i=-1==e.indexOf("?")?e.substr(e.lastIndexOf("/")+1):e.split("?")[0].substr(e.lastIndexOf("/")+1);SYNO.SDS.MailClient.Viewer.show({name:i,size:0,url:e},t)}}},fetchFullMessage:function(t,e,i){return SYNO.SDS.MailClient.MessageHouseLib.Keeper.fetchFullMsgIntoRecord(t,e,i).catch(function(t){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient.Error.getErrorString(t),[],!0)}.bind(this))},processCalendarPart:function(t,e){SYNO.SDS.MailClient.Message.ExtraPanelMgr.processCalendarPart(t,e)},loading:function(){var t=['<div class="item-wrap-loading"><div class="reset">','<div class="sending-hint"><div class="icon"></div><div class="text">',_T("common","loading"),"</div></div></div>"].join("");this.getTemplateTarget().update(t)},processSharedMailboxSubscribePart:function(t,e){SYNO.SDS.MailClient.Message.ExtraPanelMgr.processSharedMailboxSubscribePart(t,e)},isNeedHideDetail:function(t){var e=document.createElement("div");return e.innerHTML=SYNO.SDS.MailClient.MessageLib.BodyProcessor.getImageProcessedHtml(t.data.body.html,t.data.inline_image),0!==Ext.get(e).select('div[type="syno-sharedmailbox-notification-letter"]').getCount()},adjCalendarAndSubscribePanelSize:function(){SYNO.SDS.MailClient.Message.ExtraPanelMgr.adjCalendarPanelSize(),SYNO.SDS.MailClient.Message.ExtraPanelMgr.adjSubscribePanelSize()}}),Ext.define("SYNO.SDS.MailClient.ComboBox",{xtype:"syno_mc_combobox",extend:"SYNO.ux.ComboBox",initList:function(){this.callParent(arguments),this.list&&this.list.addClass("syno-mc-combo-list")}}),Ext.ns("SYNO.SDS.MailClient"),SYNO.SDS.MailClient.Tool=function(){return{openNewWindow:function(t,e,i){var n=window.open("about:blank",e);t.mode=i?"print":"message",t.cv=SYNO.SDS.MailClient.Settings.conversation_view?1:0,this.launchWindow("SYNO.SDS.MailClient.Application",t,n)},launchWindow:function(t,e,i){var n=SYNO.SDS.Config.FnMap[t];if(n){var a=n.config.url||SYNO.SDS.UrlTag[n.config.urlTag]||"",o=a.substr(0,a.indexOf(window.location.search)),s=Ext.urlDecode(a.substr(a.indexOf("?")+1));i.location=Ext.urlAppend(o,Ext.urlEncode(Ext.apply(s,{launchParam:Ext.urlEncode(e)})),!1)}},isMobileDevice:/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini|IEMobile|windows phone os 7|windows phone 8/i.test(navigator.userAgent),isMobileiOS:/iPhone|iPad|iPod/i.test(navigator.userAgent),imageFormat:["jpg","jpeg","jpe","bmp","gif","png"],isSupportImageFormat:function(t){var e;return!!Ext.isString(t)&&(e=t.split(".").pop(),!Ext.isEmpty(e)&&-1!==this.imageFormat.indexOf(e.toLowerCase()))},isEmptyObject:function(t){var e;for(e in t)if(t.hasOwnProperty(e))return!1;return!0},isEqualObject:function(t,e){return Ext.isPrimitive(t)&&Ext.isPrimitive(e)?t===e:Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(function(i){return e.hasOwnProperty(i)&&this.isEqualObject(t[i],e[i])}.bind(this))},isSupportPDFViewer:function(){if(Ext.isChrome){var t,e,i=window.navigator.plugins,n=["adobe acrobat","chrome pdf viewer","webKit built-in pdf"];for(t=0;t<i.length;++t)for(e=0;e<n.length;++e)if(new RegExp(n[e],"i").test(i[t].name))return!0}else if(Ext.isGecko||Ext.isSafari)return!0;return!1},isInMailbox:function(t,e){return e=e||SYNO.SDS.MailClient.Switch.inMailboxId,Ext.isArray(t)?-1<t.indexOf(e):e===t},isSameThreadCondition:function(t,e){if(!Ext.isDefined(t)&&!Ext.isDefined(e))return!0;if(Ext.isDefined(t)!==Ext.isDefined(e))return!1;if(!Ext.isArray(t)||!Ext.isArray(e))return!1;var i,n,a=0;for(i=0;i<t.length;++i)for(n=0;n<e.length;++n)if(t[i].name===e[n].name&&t[i].value===e[n].value){a++;break}return a===t.length&&t.length===e.length},base64Encode:function(t){var e,i,n,a,o,s,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(n=t.length,i=0,e="";i<n;){if(a=255&t.charCodeAt(i++),i==n){e+=l.charAt(a>>2),e+=l.charAt((3&a)<<4),e+="==";break}if(o=t.charCodeAt(i++),i==n){e+=l.charAt(a>>2),e+=l.charAt((3&a)<<4|(240&o)>>4),e+=l.charAt((15&o)<<2),e+="=";break}s=t.charCodeAt(i++),e+=l.charAt(a>>2),e+=l.charAt((3&a)<<4|(240&o)>>4),e+=l.charAt((15&o)<<2|(192&s)>>6),e+=l.charAt(63&s)}return e},base64Decode:function(t){
var e,i,n,a,o,s,l,r=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1];for(s=t.length,o=0,l="";o<s;){do{e=r[255&t.charCodeAt(o++)]}while(o<s&&-1==e);if(-1==e)break;do{i=r[255&t.charCodeAt(o++)]}while(o<s&&-1==i);if(-1==i)break;l+=String.fromCharCode(e<<2|(48&i)>>4);do{if(61==(n=255&t.charCodeAt(o++)))return l;n=r[n]}while(o<s&&-1==n);if(-1==n)break;l+=String.fromCharCode((15&i)<<4|(60&n)>>2);do{if(61==(a=255&t.charCodeAt(o++)))return l;a=r[a]}while(o<s&&-1==a);if(-1==a)break;l+=String.fromCharCode((3&n)<<6|a)}return l},encode_utf8:function(t){return window.unescape(encodeURIComponent(t))},decode_utf8:function(t){return decodeURIComponent(window.escape(t))},utf8_to_b64:function(t){return(Ext.isFunction(window.btoa)?window.btoa:SYNO.SDS.MailClient.Tool.base64Encode)(window.decodeURIComponent(window.encodeURIComponent(t)))},genUniqueImageRef:function(t,e){var i,n,a,o=new Date,s=[];if(n=Ext.get(t),Ext.isEmpty(n))return!1;a=n.query("img[ref]"),a.each(function(t){s.push(t.getAttribute("ref"))}),o=o.getTime();do{i=SYNO.SDS.MailClient.Tool.utf8_to_b64(o+e)}while(-1!==s.indexOf(i));return i},dataURItoBlob:function(t){var e=t.split(",")[0].split(":")[1].split(";")[0];window.atob||(window.atob=SYNO.SDS.MailClient.Tool.base64Decode);for(var i=window.atob(t.split(",")[1]),n=new ArrayBuffer(i.length),a=new Uint8Array(n),o=0;o<i.length;o++)a[o]=i.charCodeAt(o);return new Blob([n],{type:e})},hex2bin:function(t){for(var e=[],i=0;i<t.length-1;i+=2)e.push(parseInt(t.substr(i,2),16));return String.fromCharCode.apply(String,e)},calculateMD5:function(t){var e;e="0123456789abcdef".split("");var i=function(t,e){var i=t[0],n=t[1],r=t[2],d=t[3];i=a(i,n,r,d,e[0],7,-680876936),d=a(d,i,n,r,e[1],12,-389564586),r=a(r,d,i,n,e[2],17,606105819),n=a(n,r,d,i,e[3],22,-1044525330),i=a(i,n,r,d,e[4],7,-176418897),d=a(d,i,n,r,e[5],12,1200080426),r=a(r,d,i,n,e[6],17,-1473231341),n=a(n,r,d,i,e[7],22,-45705983),i=a(i,n,r,d,e[8],7,1770035416),d=a(d,i,n,r,e[9],12,-1958414417),r=a(r,d,i,n,e[10],17,-42063),n=a(n,r,d,i,e[11],22,-1990404162),i=a(i,n,r,d,e[12],7,1804603682),d=a(d,i,n,r,e[13],12,-40341101),r=a(r,d,i,n,e[14],17,-1502002290),n=a(n,r,d,i,e[15],22,1236535329),i=o(i,n,r,d,e[1],5,-165796510),d=o(d,i,n,r,e[6],9,-1069501632),r=o(r,d,i,n,e[11],14,643717713),n=o(n,r,d,i,e[0],20,-373897302),i=o(i,n,r,d,e[5],5,-701558691),d=o(d,i,n,r,e[10],9,38016083),r=o(r,d,i,n,e[15],14,-660478335),n=o(n,r,d,i,e[4],20,-405537848),i=o(i,n,r,d,e[9],5,568446438),d=o(d,i,n,r,e[14],9,-1019803690),r=o(r,d,i,n,e[3],14,-187363961),n=o(n,r,d,i,e[8],20,1163531501),i=o(i,n,r,d,e[13],5,-1444681467),d=o(d,i,n,r,e[2],9,-51403784),r=o(r,d,i,n,e[7],14,1735328473),n=o(n,r,d,i,e[12],20,-1926607734),i=s(i,n,r,d,e[5],4,-378558),d=s(d,i,n,r,e[8],11,-2022574463),r=s(r,d,i,n,e[11],16,1839030562),n=s(n,r,d,i,e[14],23,-35309556),i=s(i,n,r,d,e[1],4,-1530992060),d=s(d,i,n,r,e[4],11,1272893353),r=s(r,d,i,n,e[7],16,-155497632),n=s(n,r,d,i,e[10],23,-1094730640),i=s(i,n,r,d,e[13],4,681279174),d=s(d,i,n,r,e[0],11,-358537222),r=s(r,d,i,n,e[3],16,-722521979),n=s(n,r,d,i,e[6],23,76029189),i=s(i,n,r,d,e[9],4,-640364487),d=s(d,i,n,r,e[12],11,-421815835),r=s(r,d,i,n,e[15],16,530742520),n=s(n,r,d,i,e[2],23,-995338651),i=l(i,n,r,d,e[0],6,-198630844),d=l(d,i,n,r,e[7],10,1126891415),r=l(r,d,i,n,e[14],15,-1416354905),n=l(n,r,d,i,e[5],21,-57434055),i=l(i,n,r,d,e[12],6,1700485571),d=l(d,i,n,r,e[3],10,-1894986606),r=l(r,d,i,n,e[10],15,-1051523),n=l(n,r,d,i,e[1],21,-2054922799),i=l(i,n,r,d,e[8],6,1873313359),d=l(d,i,n,r,e[15],10,-30611744),r=l(r,d,i,n,e[6],15,-1560198380),n=l(n,r,d,i,e[13],21,1309151649),i=l(i,n,r,d,e[4],6,-145523070),d=l(d,i,n,r,e[11],10,-1120210379),r=l(r,d,i,n,e[2],15,718787259),n=l(n,r,d,i,e[9],21,-343485551),t[0]=S(i,t[0]),t[1]=S(n,t[1]),t[2]=S(r,t[2]),t[3]=S(d,t[3])},n=function(t,e,i,n,a,o){return e=S(S(e,t),S(n,o)),S(e<<a|e>>>32-a,i)},a=function(t,e,i,a,o,s,l){return n(e&i|~e&a,t,e,o,s,l)},o=function(t,e,i,a,o,s,l){return n(e&a|i&~a,t,e,o,s,l)},s=function(t,e,i,a,o,s,l){return n(e^i^a,t,e,o,s,l)},l=function(t,e,i,a,o,s,l){return n(i^(e|~a),t,e,o,s,l)},r=function(t){var e,n=t.length,a=[1732584193,-271733879,-1732584194,271733878];for(e=64;e<=t.length;e+=64)i(a,d(t.substring(e-64,e)));t=t.substring(e-64);var o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(e=0;e<t.length;e++)o[e>>2]|=t.charCodeAt(e)<<(e%4<<3);if(o[e>>2]|=128<<(e%4<<3),e>55)for(i(a,o),e=0;e<16;e++)o[e]=0;return o[14]=8*n,i(a,o),a},d=function(t){var e,i=[];for(e=0;e<64;e+=4)i[e>>2]=t.charCodeAt(e)+(t.charCodeAt(e+1)<<8)+(t.charCodeAt(e+2)<<16)+(t.charCodeAt(e+3)<<24);return i},c=function(t){var i,n;for(i="",n=0;n<4;n++)i+=e[t>>8*n+4&15]+e[t>>8*n&15];return i},h=function(t){var e;for(e=0;e<t.length;e++)t[e]=c(t[e]);return t.join("")},u=function(t){return h(r(t))},S=function(t,e){return t+e&4294967295};return"5d41402abc4b2a76b9719d911017c592"!==u("hello")&&(S=function(t,e){var i=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(i>>16)<<16|65535&i},"5d41402abc4b2a76b9719d911017c592"!==u("hello")&&SYNO.Debug("calculateMD5 self test failed")),u(t)},escapeRegExp:function(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}}}(),Ext.define("SYNO.SDS.MailClient.ZipUtil",{singleton:!0,requires:["SYNO.SDS.MailClient.Pako","SYNO.SDS.MailClient.Tool"],zipToBase64:function(t){var e;if(!t)return"";try{return e=SYNO.SDS.MailClient.Pako.deflate(t,{to:"string"}),SYNO.SDS.MailClient.Tool.base64Encode(e)}catch(t){return!1}},unzipFromBase64:function(t){var e;if(!t)return"";try{return e=SYNO.SDS.MailClient.Tool.base64Decode(t),SYNO.SDS.MailClient.Pako.inflate(e,{to:"string"})}catch(t){return!1}}}),Ext.ns("SYNO.SDS.MailClient"),SYNO.SDS.MailClient._T=function(t,e){try{return _TT("SYNO.SDS.MailClient.Application",t,e)||_T(t,e)}catch(i){return _T(t,e)}},Ext.define("SYNO.SDS.MailClient.Define",function(){var t,e={RemoveLabel:"remove_label",DeleteMail:"delete_mail",MoveTo:"move_to",Label:"label",Archive:"archive",Spam:"spam",NotSpam:"not_spam",AddToBlackList:"add_to_black_list",AddToWhiteList:"add_to_white_list",DeleteForever:"delete_forever",DiscardDraft:"discard_draft",ArchiveInLabel:"archive_in_label",MarkAllRead:"mark_all_read",MarkRead:"mark_read",MarkUnRead:"mark_unread",AddStar:"add_star",RemoveStar:"remove_star",AddToCalendar:"add_to_calendar",AddToTodoList:"add_to_todo_list",SearchField:"search_field",More:"more",Reload:"reload",Setting:"setting",View:"view"},i=Ext.urlDecode(Ext.urlDecode(window.location.search.substring(1)).launchParam),n=i.mode||"normal",a=["t","ui","pm","pd","print","cv","to","zip_to"];for(t=0;t<a.length;++t)i[a[t]]&&("t"===a[t]?i.t=parseInt(i.t,10):"zip_to"===a[t]?i.zip_to=Ext.decode(SYNO.SDS.MailClient.ZipUtil.unzipFromBase64(i.zip_to)):i[a[t]]=Ext.decode(i[a[t]]));return{singleton:!0,launchParam:i,MODE:n,isNormalMode:"normal"==n,isPrintMode:"print"==n,isMessageMode:"message"==n,isComposeMode:"compose"==n,SystemMailboxName:["priority","inbox","starred","drafts","sent","junk","trash"],inboxId:-1,draftsId:-3,sentId:-4,junkId:-5,trashId:-6,starredId:"starred",priorityId:"priority",allContactGroupId:"allgroup",allGroupId:"groups",MaxMailboxNameLength:200,IMAGE_PROPER_LENGTH:400,SingleAttachmentSizeLimit:104857600,PGPKeyFileSizeLimit:1048576,smallBatchOpLimit:2e3,spamRuleMaximumLimit:1e4,spamRulePageSize:100,textColors:["50555A","C73232","BF6000","997F00","567300","007326","007373","007399","0059B3","5536B3","B32483","A12A62","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF","FFFFFF"],bgColors:["DCE1E6","FFCCCC","FFD9B2","FFEC8C","DDF29D","C4F5D4","C2F2F2","C8EDFA","CCE6FF","E2D9FF","FFD9F2","FFC0D2","A0A5AA","FA8282","FA9C3E","F2CA00","94BF13","4DBF73","1DBFBF","24BFF2","499DF2","A18AE6","E67EC3","F56496","64696E","E04343","E67300","CCAA00","739900","009933","009999","008FBF","1470CC","7052CC","CC3D9C","C81466"],ConversationViewStringMap:{thread_delete:"message_delete",conversations_mark_read:"message_mark_read",conversations_mark_unread:"message_mark_unread",achived:"message_archived",thread_to_trash:"message_to_trash",spam:"message_spam",thread_move_to_mailbox:"message_move_to_mailbox"},getSystemMailboxPathById:function(t){switch(t){case this.inboxId:return"inbox";case this.draftsId:return"drafts";case this.sentId:return"sent";case this.junkId:return"junk";case this.trashId:return"trash";case this.starredId:return"starred";case this.priorityId:return"priority"}},getSystemMailboxIdByPath:function(t){switch(t.trim().toLowerCase()){case"inbox":return this.inboxId;case"drafts":return this.draftsId;case"sent":return this.sentId;case"junk":return this.junkId;case"trash":return this.trashId;case"starred":return this.starredId;case"priority":return this.priorityId}},getColorIndex:function(t,e){var i=SYNO.SDS.MailClient.Define.bgColors.indexOf(e);return SYNO.SDS.MailClient.Define.textColors[i]!=t?null:i},getUploadLimit:function(t){var e,i=this.getMaxMailSize(t),n=this.getUserAttachmentLimit(t);return e=i<0?n:n<0?i:Math.min(i,n),e>0?Math.min(this.SingleAttachmentSizeLimit,e):this.SingleAttachmentSizeLimit},getMaxMailSize:function(t){var e=this._getUsageLimits(t);return e?1024*e.max_mail_size*1024:-1},getUserAttachmentLimit:function(t){var e=this._getUsageLimits(t);return e?1024*e.attachment_size*1024:-1},_getUsageLimits:function(t){var e,i=SYNO.SDS.MailClient.Format,n=SYNO.SDS.MailClient.Info.usage_limits;if(n)return e=i.getMailByNameAddrOrAddr(t),n.find(function(t){return t.mail_from===e})},mainActionBarBtnItemId:e,mainActionBarBtnList:function(){var t=e;return{flex:[t.DeleteMail,t.DeleteForever,t.DiscardDraft,t.MoveTo,t.Label,t.Archive,t.Spam],mail:[t.More,t.RemoveLabel,t.DeleteMail,t.DeleteForever,t.DiscardDraft,t.MoveTo,t.Label,t.Archive,t.Spam,t.NotSpam,t.Reload,t.View,t.ArchiveInLabel,t.MarkAllRead,t.MarkRead,t.MarkUnRead,t.AddStar,t.RemoveStar,t.AddToTodoList,t.AddToCalendar],selectionchange:[t.RemoveLabel,t.DiscardDraft,t.DeleteForever,t.DeleteMail,t.MoveTo,t.Label,t.ArchiveInLabel,t.Archive,t.Spam,t.NotSpam,t.MarkAllRead,t.MarkRead,t.MarkUnRead]}}(),mailboxDisabled:function(t){var e=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,i=[e.DeleteForever,e.DiscardDraft,e.RemoveLabel,e.NotSpam],n={};return this.isSupportTodoPlugin()||i.push(e.AddToTodoList),n[this.inboxId]=i,n[SYNO.SDS.MailClient.Settings.archive_mailbox]=i.concat([e.Archive]),n[this.draftsId]=[e.DeleteMail,e.DeleteForever,e.MoveTo,e.Archive,e.Spam,e.NotSpam,e.RemoveLabel],n[this.sentId]=i,n[this.junkId]=[e.DeleteMail,e.DiscardDraft,e.Archive,e.Spam,e.RemoveLabel],n[this.trashId]=[e.DiscardDraft,e.DeleteMail,e.Archive,e.NotSpam,e.RemoveLabel],n[this.starredId]=i.concat([e.MoveTo]),n[t]||i},isVirtualMailbox:function(t){return"starred"===t.data.path||"priority"===t.data.path},isSystemMailbox:function(t){return this.isSystemMailboxName(t.data.path)},isSystemMailboxName:function(t){var e=t.trim().toLowerCase();return-1<SYNO.SDS.MailClient.Define.SystemMailboxName.indexOf(e)},getSystemMailboxNameString:function(t){return t=t.toLowerCase(),"drafts"===t?SYNO.SDS.MailClient._T("mailbox","draft"):SYNO.SDS.MailClient._T("mailbox",t)},getMailboxPermissionById:function(t){var e=SYNO.SDS.MailClient.Switch.getMailboxStore(),i=e.getById(t);return Ext.isDefined(i)?i.get("my_permission"):""},isReadOnlyMailbox:function(t){return this.getMailboxPermissionById(t)===this.MailboxPermission.READ_ONLY},isInReadOnlyMailbox:function(){var t=SYNO.SDS.MailClient.Switch.inMailboxId;return!(!t||0===t)&&SYNO.SDS.MailClient.Define.isReadOnlyMailbox(t)},isInVirtaulOrLabel:function(){var t=SYNO.SDS.MailClient.Switch.inMailboxId;return!t||0===t},isUserOrGroupNodeInMailboxList:function(t){return!(!Ext.isString(t.id)||this.isSystemMailboxName(t.id))},isMailboxAddable:function(t,e){var i=e.trim().toLowerCase(),n=[];return n=this.SystemMailboxName.filter(function(t){return"inbox"!==t}),(t===this.MailboxPermission.READ_WRITE||t===this.MailboxPermission.ADMIN)&&-1===n.indexOf(i)},isMailboxDeletable:function(t,e){return t===this.MailboxPermission.ADMIN&&!this.isSystemMailboxName(e)},isMailboxShareable:function(t){return t===this.MailboxPermission.ADMIN},isMailboxEditable:function(t,e){return t===this.MailboxPermission.ADMIN&&e&&!this.isReadOnlyMailbox(e)},isSupportTodoPlugin:function(){return SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")&&SYNO.SDS.Config.FnMap["SYNO.Cal.Application"].config.version>="2.0.0-0238"},isThreadRecordsReadOnly:function(t){return t.every(function(t){var e=t.get("message");return!!Ext.isDefined(e)&&e.every(function(t){return this.isReadOnlyMailbox(t.mailbox_id)}.bind(this))}.bind(this))},isDragDatasReadOnly:function(t){var e=this,i=t.data;return!i||e.isThreadRecordsReadOnly(i)},isMailboxAllowDropByDragData:function(t){var e=this,i=e.isInVirtaulOrLabel(),n=!i;return!(i&&e.isDragDatasReadOnly(t)||n&&e.isInReadOnlyMailbox())},badServerSMTPHint:SYNO.SDS.MailClient._T("composer","bad_server_smtp_hint"),DraftType:{NEW_THREAD:0,REPLY:1,FORWARD:2},MessageStat:{NOT_EXIST:0,PREVIEW:1,NO_EXTERNAL_IMAGE:2,FULL:3,FROM_DRAFT:4},EncryptionStat:{NONE:0,ENCRYPTED:1,SIGNED:2,VALID_SIGN:3,INVALID_SIGN:4,DECRYPTED:5,DECRYPTED_VALID:6,DECRYPTED_INVALID:7,ERROR:99},PGPStat:{CANCEL:1,NO_AVAILABLE_KEY:2},Source:{GOOGLE:"google",OUTLOOK:"outlook.com",YAHOO:"yahoo",CARDDAV:"carddav",LOCAL:"local",SHARE:"share",ALL:"all"},MailboxPermission:{READ_ONLY:"mailbox_read_only",READ_WRITE:"mailbox_read_write",ADMIN:"mailbox_admin"},SpamRuleType:{BLACK_LIST:0,WHITE_LIST:1},SpamRuleConditionType:{ADDRESS:0,DOMAIN:1},ContactsAddressbookType:{PUBLIC:0,NORMAL:1,SUGGESTED:2,DEFAULT:3,DEFAULT_PUBLIC:4,EXTERNAL:5},ContactsLabelType:{NORMAL:0,STARRED:1}}}),Ext.define("SYNO.SDS.MailClient.Error",{statics:{APIErrorStringMap:{120:_T("error","error_invalid"),400:_T("error","error_unknown_desc"),401:SYNO.SDS.MailClient._T("api_error","mailbox_not_exist"),402:_T("error","error_privilege_not_enough"),405:_T("common","error_no_enough_space"),406:SYNO.SDS.MailClient._T("api_error","invalid_account"),407:SYNO.SDS.MailClient._T("api_error","database_operation_failed"),408:SYNO.SDS.MailClient._T("error","error_privilege_not_enough"),409:SYNO.SDS.MailClient._T("error","version_mismatch"),410:SYNO.SDS.MailClient._T("api_error","database_is_upgrading"),411:SYNO.SDS.MailClient._T("api_error","file_operation_failed"),412:SYNO.SDS.MailClient._T("api_error","invalid_mailplus_path"),413:SYNO.SDS.MailClient._T("api_error","url_download_failed"),414:SYNO.SDS.MailClient._T("api_error","user_get_failed"),420:SYNO.SDS.MailClient._T("api_error","mailbox_name_too_long"),421:SYNO.SDS.MailClient._T("api_error","mailbox_name_duplicated"),422:SYNO.SDS.MailClient._T("api_error","mailbox_not_exist"),423:SYNO.SDS.MailClient._T("api_error","mailbox_not_exist"),424:SYNO.SDS.MailClient._T("api_error","mailbox_permission_too_many"),425:_T("pkgmgr","wait_pgsql"),426:SYNO.SDS.MailClient._T("api_error","mailbox_share_permission_failed"),440:SYNO.SDS.MailClient._T("api_error","label_name_too_long"),441:SYNO.SDS.MailClient._T("api_error","label_name_duplicated"),442:SYNO.SDS.MailClient._T("api_error","label_not_exist"),443:SYNO.SDS.MailClient._T("api_error","parent_not_exist"),450:SYNO.SDS.MailClient._T("filter","error_tests_deep_limit"),461:_T("error","error_unknown_desc"),462:SYNO.SDS.MailClient._T("api_error","sticker_not_exist"),480:SYNO.SDS.MailClient._T("api_error","draft_not_exist"),500:SYNO.SDS.MailClient._T("api_error","smtp_connection_failed"),501:SYNO.SDS.MailClient._T("api_error","smtp_authentication_failed"),503:SYNO.SDS.MailClient._T("api_error","contain_illegal_attachment"),505:SYNO.SDS.MailClient._T("api_error","recipient_not_available"),506:SYNO.SDS.MailClient._T("api_error","send_quota_reached"),507:SYNO.SDS.MailClient._T("api_error","no_recipient"),508:SYNO.SDS.MailClient._T("api_error","smtp_sender_email_duplicated"),510:SYNO.SDS.MailClient._T("api_error","daily_data_flow_exceed"),512:SYNO.SDS.MailClient._T("api_error","smtp_send_local_only"),600:SYNO.SDS.MailClient._T("error","auth_is_required"),601:_T("error","error_unknown_desc"),602:_T("error","error_unknown_desc"),603:_T("error","error_unknown_desc"),604:_T("error","error_unknown_desc"),700:SYNO.SDS.MailClient._T("api_error","pop_sender_email_duplicated"),702:SYNO.SDS.MailClient._T("api_error","pop_server_connection_error"),703:SYNO.SDS.MailClient._T("api_error","pop_auth_error"),704:SYNO.SDS.MailClient._T("api_error","pop_server_time_out"),705:SYNO.SDS.MailClient._T("api_error","pop_error"),1e3:SYNO.SDS.MailClient._T("api_error","import_format_error"),1100:SYNO.SDS.MailClient._T("api_error","group_name_duplicated"),1200:SYNO.SDS.MailClient._T("api_error","external_source_duplicated"),1201:_T("error","error_auth"),1202:SYNO.SDS.MailClient._T("api_error","connection_error"),2001:SYNO.SDS.MailClient._T("api_error","sharing_link_full"),5010:SYNO.SDS.MailClient._T("api_error","contacts_invalid_bound_domain")},apiErrorStringMapCall:function(t,e){var i=SYNO.SDS.MailClient.Define,n=SYNO.SDS.MailClient._T("api_error","smtp_send_err_default_message"),a=e.errors||{},o=((e||{}).senderInfo||{}).from,s=i.getUserAttachmentLimit(o),l=i.getMaxMailSize(o),r=[{code:504,string:SYNO.SDS.MailClient._T("api_error","sending_action_rejected")},{code:509,string:SYNO.SDS.MailClient._T("api_error","send_to_blacklist")},{code:513,string:SYNO.SDS.MailClient._T("api_error","recipient_over_quota")},{code:514,string:SYNO.SDS.MailClient._T("api_error","send_from_blacklist")}];switch(t){case 481:return Ext.isDefined(o)?SYNO.SDS.MailClient._T("api_error","send_draft_volume_quota"):SYNO.SDS.MailClient._T("api_error","draft_volume_quota");case 502:return l>0&&(l=Math.min(l,i.SingleAttachmentSizeLimit),n=SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(l,0)[0]),String.format(SYNO.SDS.MailClient._T("api_error","draft_send_exceed_max_size"),n);case 504:case 509:case 513:case 514:return a.invalid_recipient?(n=r.find(function(e){return e.code===t}).string,String.format("{0}<br>[{1}]",n,Ext.util.Format.htmlEncode(a.invalid_recipient))):String.format("{0}<br>[{1}]",SYNO.SDS.MailClient._T("api_error","sending_action_rejected_with_resp"),Ext.util.Format.htmlEncode(a.resp));case 511:return s>0&&(n=SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(s,0)[0]),String.format(SYNO.SDS.MailClient._T("api_error","attachment_upload_exceed_max_size"),n);case 460:case 463:return s=s>0?Math.min(s,i.SingleAttachmentSizeLimit):i.SingleAttachmentSizeLimit,n=SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(s,0)[0],String.format(SYNO.SDS.MailClient._T("api_error","attachment_upload_exceed_max_size"),n);default:return""}},updateAPIErrorStringMap:function(){Ext.apply(SYNO.SDS.MailClient.Error.APIErrorStringMap,{460:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,463:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,481:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,502:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,504:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,509:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,511:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,513:SYNO.SDS.MailClient.Error.apiErrorStringMapCall,514:SYNO.SDS.MailClient.Error.apiErrorStringMapCall})},isFatalErrorCode:function(t){return-1!==[105,405,406,407,408,410,412,414].indexOf(t)},isPrivilegeErrorCode:function(t){return-1!==[160,402].indexOf(t)},getErrorCode:function(t){if(Ext.isNumber(t.code))return t.code;var e=SYNO.API.Util.GetFirstError(t);return Ext.isObject(e)&&Ext.isNumber(e.code)?e.code:void 0},getErrorString:function(t,e){if(e=e||_T("common","error_system"),!Ext.isObject(t))return e+" [unknown]";var i=SYNO.SDS.MailClient.Error.getErrorCode(t),n=SYNO.SDS.MailClient.Error.APIErrorStringMap[i];if(Ext.isFunction(n)&&(n=n(i,t)||e),Ext.isString(n))return n;if(n=(SYNO.API.Errors||SYNO.API.Erros).common[i],Ext.isString(n))return n;if(i)return e+" ["+i+"]";var a="communication failure";return t.isTimeout?a="timeout":t.isAbort&&(a="transaction aborted"),SYNO.SDS.MailClient._T("api_error","connect_exception")+" ["+a+"]"}}}),Ext.define("SYNO.SDS.MailClient.BigSizeUploadWindow",{extend:"SYNO.SDS.MailClient.ModalWindow",constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("complete_one_task",this.onCompleteOneTask,this),this.on("failure_one_task",this.onFailureOneTask,this),this.on("show",function(){this.store.loadData(this.uploadQueue),this.prepareUpload()},this)},fillConfig:function(t){this.uploadQueue=t.big_size_files,this.attachmentLimit=t.attachment_limit,this.uploadIdx=-1;var e={title:SYNO.SDS.MailClient._T("sharing_link","send_with_shared_link"),width:520,height:320,layout:"fit",buttons:[{text:_T("common","cancel"),scope:this,handler:this.onCancel}],items:[this.getPanel()]};return Ext.apply(e,t)},getPanel:function(){return this.gridPanel=this.gridPanel||new SYNO.ux.GridPanel({autoExpandColumn:"name",region:"center",enableColumnMove:!1,hideHeaders:!0,sm:new Ext.grid.RowSelectionModel,cls:"syno-mc-big-attachment-uploading-panel",colModel:new Ext.grid.ColumnModel({defaults:{menuDisabled:!0},columns:[{id:"file_upload_status",width:24,renderer:function(t,e,i,n,a,o){return 0===i.data.file_upload_status?"<div class=file-upload-status><div>":1===i.data.file_upload_status?"<div class='file-upload-status syncing'><div>":2===i.data.file_upload_status?"<div class='file-upload-status success'><div>":"<div class='file-upload-status failed'><div>"}},{dataIndex:"name",width:260},{xtype:"actioncolumn",width:38,items:[{iconCls:"file-delete-button",scope:this,handler:function(t,e,i){this.uploadQueue.splice(e,1),t.getStore().removeAt(e),e>this.uploadIdx||(e===this.uploadIdx?(this.uploadIdx-=1,Ext.Ajax.abort(this.uploadRequest),this.fireEvent("complete_one_task")):this.uploadIdx-=1)}}]}]}),store:this.getStore()}),this.panel=this.panel||new SYNO.ux.FormPanel({autoFlexcroll:!1,hideHeaders:!0,layout:"border",items:[{xtype:"syno_displayfield",region:"north",value:String.format(SYNO.SDS.MailClient._T("sharing_link","sharing_link_desc"),Ext.util.Format.fileSize(this.attachmentLimit))},this.gridPanel]}),this.panel},getStore:function(){return this.store?this.store:(this.uploadQueue.forEach(function(t){if(this.isFromDS(t))return void Ext.apply(t,{file_upload_status:2});Ext.apply(t,{file_upload_status:0})},this),this.store=new Ext.data.Store({idIndex:0,reader:new Ext.data.JsonReader({fields:["name","file_upload_status"]})}),this.store)},onCancel:function(){Ext.Ajax.abort(this.uploadRequest),this.close()},onCompleteOneTask:function(){if(this.uploadQueue.length===this.uploadIdx+1)return Ext.isEmpty(this.uploadQueue)?void this.close():void this.createSharingLink();this.prepareUpload()},onFailureOneTask:function(t,e){this.store.getAt(this.uploadIdx).set("file_upload_status",-1),this.setStatusError({text:e})},prepareUpload:function(){this.uploadIdx+=1;var t=this.uploadQueue[this.uploadIdx];if(this.isFromDS(t))return Ext.apply(t,{file_path:t.source}),void this.fireEvent("complete_one_task");this.checkHomePrivilege(t)},checkHomePrivilege:function(t){var e=function(e,i,n){if(!e)return void this.fireEvent("failure_one_task",t,SYNO.SDS.MailClient._T("sharing","error_home_privilege"));this.uploadBigFile(t)};SYNO.API.Request({params:{path:"/home",filename:t.name,size:t.size,overwrite:!1},api:"SYNO.FileStation.CheckPermission",method:"write",version:3,callback:e,scope:this})},uploadBigFile:function(t){var e=function(e,i,n){if(!e)return void this.fireEvent("failure_one_task",t,SYNO.SDS.MailClient._T("sharing","error_home_privilege"));this.uploadQueue[this.uploadIdx]=Ext.apply(t,{file_path:i.file_path,file_upload_status:2}),this.store.getAt(this.uploadIdx).set("file_upload_status",2),this.fireEvent("complete_one_task")};this.uploadRequest=SYNO.SDS.MailClient.OP.html5UploadFile({file:t,name:t.name},e,function(t,e){-1!==this.uploadIdx&&1!==e.file_upload_status&&(e.file_upload_status=1,this.store.getAt(this.uploadIdx).set("file_upload_status",1))}.createDelegate(this,[t],!0),this,!0)},createSharingLink:function(){if(!Ext.isEmpty(this.uploadQueue)){var t=[];this.uploadQueue.forEach(function(e){t.push(e.file_path)});var e=function(t,e,i){if(!t)return void this.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(e));e.links.forEach(function(t,e,i){Ext.apply(this.uploadQueue[e],{url:t.url})},this),this.fireEvent("complete_create_sharing_link",this.uploadQueue),this.close()};SYNO.API.Request({params:{path:t},api:"SYNO.FileStation.Sharing",method:"create",version:3,callback:e,scope:this})}},isFromDS:function(t){return!Ext.isEmpty(t.format)&&"ds"===t.format}}),Ext.define("SYNO.SDS.MailClient.Editor.FileLabel",{extend:"Ext.util.Observable",constructor:function(t){this.addEvents("upload","remove","preview"),this.owner=t.owner,this.callParent([this.fillConfig(t||{})]),this.labelrendered=!1},fillConfig:function(t){var e=Ext.apply({width:"480px",labelHolderCls:"syno-ddupload-fileLabelHolder",labelCls:"syno-ddupload-fileLabel",labelHideCls:"syno-ddupload-fileLabel-hide",labelContainerCls:"syno-ddupload-fileLabelContainer",labelTextCls:"syno-ddupload-fileLabelText",labelOperCls:"syno-ddupload-fileOper",fileNameContainerCls:"syno-ddupload-fileNameContainer",fileNameCls:"syno-ddupload-fileName",fileSizeCls:"syno-ddupload-fileSize",delBtnCls:"syno-ddupload-fileDelButton",previewBtnCls:"syno-ddupload-filePreviewButton",normalColor:"rgb(228, 243, 253)",succColor:"#BFB",warnColor:"#FFC",errorColor:"#FDD"},t.settings),i=Ext.applyIf(t.file,{name:"EmptyFileName",size:"0"}),n={UPLOADING:1,UPLOADED:2,DELETING:3,DELETED:4,ABORTED:5,REMOTE:6,LOCAL:7,ERROROCCURED:9,CALCULATING:10},a=Ext.applyIf({owner:t.owner,stateEnum:n,state:Ext.isEmpty(t.file.id)?n.LOCAL:n.REMOTE,file:i,settings:e},t);return Ext.apply(this,a),a},onProgress:function(t){var e;return Ext.isEmpty(this.elms)?(this.state=this.stateEnum.LOCAL,100):"ds"===this.file.format||"sticker"===this.file.format?(this.elms.fileSize.innerHTML=String.format("({0})",SYNO.SDS.MailClient._T("common","msg_waiting")),this.state=this.stateEnum.UPLOADED,100):(e=Math.round(t/this.file.size*100),e>100&&(e=100),this.elms.fileSize.innerHTML=String.format("({0})",e.toFixed(2)+"%"),100===e?(this.elms.fileSize.innerHTML=String.format("({0})",SYNO.SDS.MailClient._T("common","msg_waiting")),this.state=this.stateEnum.UPLOADED):this.state=this.stateEnum.UPLOADING,e)},onFinish:function(){this.elms.fileSize.innerHTML="("+Ext.util.Format.fileSize(this.file.size)+")",this.labelrendered&&this.adjustTextWidth()},onError:function(t){this.elms.fileSize.innerHTML=String.format("({0})",t),this.state=this.stateEnum.LOCAL},addControl:function(t){!this.elms||!this.file.id&&Ext.isEmpty(this.file.temp_id)||(this.elms.fileNameContainer.innerHTML="",this.elms.fileName=Ext.DomHelper.createDom({tag:"div",cls:"link-font "+this.settings.fileNameCls,html:Ext.util.Format.htmlEncode(this.file.name)+" "},this.elms.fileNameContainer),this.elms.fileSize||(this.elms.fileSize=Ext.DomHelper.createDom({tag:"div",cls:"disable-font "+this.settings.fileSizeCls,html:"("+Ext.util.Format.fileSize(this.file.size)+")"},this.elms.labelText)),Ext.get(this.elms.fileName).on("click",this.click,this),this.elms.labelOper=Ext.DomHelper.createDom({tag:"div",cls:this.settings.labelOperCls},this.elms.container),this.elms.previewBtn=Ext.DomHelper.createDom({tag:"div",cls:this.settings.previewBtnCls},this.elms.labelOper),Ext.get(this.elms.previewBtn).on("click",function(t){this.fireEvent("preview",this,t)},this),this.elms.delBtn=Ext.DomHelper.createDom({tag:"div",cls:this.settings.delBtnCls},this.elms.labelOper),Ext.get(this.elms.delBtn).on("click",function(){this.fireEvent("remove",this)},this))},renderTo:function(t,e,i){if(this.elms&&Ext.isElement(this.elms.main))return void t.appendChild(this.elms.main);this.elms={},this.elms.main=Ext.DomHelper.createDom({tag:"div",cls:"clearfix "+this.settings.labelCls+(i?" "+this.settings.labelHideCls:""),style:{width:this.settings.width}}),this.elms.container=Ext.DomHelper.createDom({tag:"div",cls:this.settings.labelContainerCls},this.elms.main),this.elms.labelText=Ext.DomHelper.createDom({tag:"div",cls:this.settings.labelTextCls},this.elms.container),this.elms.fileNameContainer=Ext.DomHelper.createDom({tag:"div",cls:this.settings.fileNameContainerCls},this.elms.labelText),e?this.addControl():(this.elms.fileName=Ext.DomHelper.createDom({tag:"div",cls:"normal-font "+this.settings.fileNameCls,html:Ext.util.Format.htmlEncode(this.file.name)+" "},this.elms.fileNameContainer),this.elms.fileSize=Ext.DomHelper.createDom({tag:"div",cls:"disable-font "+this.settings.fileSizeCls,html:"("+SYNO.SDS.MailClient._T("common","msg_waiting")+")"},this.elms.labelText)),t.appendChild(this.elms.main),this.labelrendered=!0,this.adjustTextWidth.defer(100,this)},adjustTextWidth:function(){var t,e,i;this.elems&&(i=Ext.get(this.elms.fileSize).getWidth()+12,this.elms.labelOper&&(i+=Ext.get(this.elms.labelOper).getWidth()+10),e=Ext.get(this.elms.container),t=Ext.get(this.elms.fileName),t.getWidth()+i>e.getWidth()&&t.setWidth(e.getWidth()-i))},showContext:function(t,e){t.update("");var i=SYNO.SDS.MailClient.Format,n=Ext.get(this.elms.previewBtn);n.addClass("syno-ddupload-filePreviewButton-clicked"),t.previewClickBtn=n;var a=0,o=0;Ext.each(e,function(e){var n=Ext.DomHelper.createDom({tag:"div",cls:"syno-mc-editor-tinymce-preview-content",style:"font-size: 13px;line-height: 28px;"+String.format("font-family:{0};",i.getFontFamilyByLang()),html:e.text});Ext.get(n).on("click",function(){e.handler(),this.owner.deletePreviewBubbleElm()},this),t.appendChild(n);var s=Ext.util.TextMetrics.measure(n,e.text);s.width>a&&(a=s.width),o+=s.height},this),t.show();var s=this.editor.getContentAreaContainer();a+=56,a+n.getX()<=s.offsetWidth?t.setX(n.getX()):t.setX(n.getX()+n.getWidth()-a),o+=14,o+n.getY()+n.getHeight()<=s.offsetHeight?t.setY(n.getY()+n.getHeight()):t.setY(n.getY()-o)},click:function(){var t={};if(Ext.isEmpty(this.file.md5)){if(!Ext.isNumber(this.file.id))return;t.id=this.file.id}else t.md5=this.file.md5;this.appWindow.downloadWebAPI({webapi:{api:"SYNO.MailClient.Attachment",version:6,method:"download",params:t},filename:this.file.name})}}),Ext.define("SYNO.SDS.MailClient.Editor.DDUpload",{extend:"Ext.util.Observable",local_prefix:"tmp_file_",transparent_gif:"webman/3rdparty/MailClient/images/1x/_Common/icon_syncing.gif",constructor:function(t){this.adjust_size=SYNO.SDS.MailClient.Define.IMAGE_PROPER_LENGTH,this.addEvents("drop","refresh","filechange"),this.owner=t.owner,this.module=t.module,this.callParent([this.fillConfig(t||{})]),this.on("refresh",this.refresh,this,{buffer:100}),this.on("drop",function(t){var e,i,n=t.dataTransfer.files,a=this.owner.getEditor(),o=a.getDoc();if(!Ext.isEmpty(n)&&!_S("demo_mode")){o.caretRangeFromPoint?a.selection.setRng(o.caretRangeFromPoint(t.x,t.y)):(i=t.toElement?t.toElement:t.target?t.target:this.owner.getEditor().getBody().lastChild,i.parentNode===o?a.selection.setCursorLocation(this.owner.getEditor().getBody().lastChild):a.selection.setCursorLocation(i));var s=[],l=[];for(e=0;e<n.length;++e)Ext.isNumber(n[e].size)&&n[e].size>this.owner.getSenderUploadLimit()&&SYNO.SDS.StatusNotifier.isAppEnabled("SYNO.SDS.App.FileStation3.Instance")&&SYNO.SDS.MailClient.AdminSettings.SharingLink.enable&&!this.skip_check_big_size_file?l.push(n[e]):(n[e].inline=SYNO.SDS.MailClient.Tool.isSupportImageFormat(n[e].name),s.push(n[e]));this.skip_check_big_size_file||this.addBigSizeFiles(l),s.forEach(function(t,e,i){this.addFile(t)},this)}},this)},fillConfig:function(t){var e=Ext.applyIf({imageTypes:/^image/i,owner:t.owner,items:[]},t);return Ext.apply(this,e),e},isAlive:function(){return this.owner.isAlive()},getRandomString:function(t){
return(new Date*Math.random()).toString(36).replace(".","A").substr(0,t)},_getStickerStyle:function(t){var e=t.sticker_size.width,i=t.sticker_size.height;return String.format("width:{0}px; height:{1}px; max-width:{2}px;max-height:{3}px; min-width:{4}px; min-height:{5}px;",e,i,160,140,80,70)},_getEmojiStyle:function(t){var e=t.sticker_size.width,i=t.sticker_size.height;return String.format("width:{0}px; height:{1}px; max-width:{2}px;max-height:{3}px; min-width:{4}px; min-height:{5}px;vertical-align: baseline; margin: 0 2px",e,i,e,i,e,i)},_getStyle:function(t){return 5===t.sticker_category?this._getEmojiStyle(t):this._getStickerStyle(t)},_getEmojiTpl:function(t){return['<img class="syno-notestation-image-object syno-mc-sticker" ',' style="'+this._getStyle(t),'"',' src="',t.sticker_url,'"',' data-mce-src="',t.sticker_url,'" data-ref="{0}" data-temp />'].join("")},addImage:function(t,e){if(t.file.inline){var i,n,a,o=this.owner.getEditor();return i="sticker"===t.file.format&&t.file.sticker_url?this._getEmojiTpl(t.file):['<img class="syno-notestation-image-object" src="',this.transparent_gif,'" data-mce-src="',this.transparent_gif,'" data-ref="{0}" data-temp"/>'].join(""),a=Ext.id(void 0,this.getRandomString(3))+"_desktop_"+this.getRandomString(8),t.file.ref=a,Ext.isEmpty(e)?(n=String.format(i,a),this.correctRng(),o.insertContent(n)):e.setAttribute("data-ref",a),this.fireEvent("filechange"),a}},correctRng:function(){if(document.createRange){var t=this.owner.getEditor(),e=t.selection,i=e.getRng(),n=t.getBody(),a=n.getElementsByClassName("syno-mc-reply-content")[0],o=i.startContainer;if(!Ext.isGecko||a!==o)for(;o;){if(n===o)return;o=o.parentNode}var s=n.lastChild;s===a&&(s=s.previousSibling),i=t.getDoc().createRange(),i.setStart(s,s.childNodes.length),i.setEnd(s,s.childNodes.length),e.setRng(i)}},updateImage:function(t){Ext.get(this.owner.getEditor().getBody()).select(String.format('img[data-ref="{0}"]',t.ref)).on("load",function(e,i,n,a){this.onFinish(t),this.updateImageSize(t,i),this.fireEvent("refresh")},this,{single:!0}),this.onProgress(void 0,t)},updateImageSize:function(t,e){var i=this.owner.getEditor();if(i.getDoc()){var n=Ext.get(i.getBody()),a=n.select(String.format('img[data-ref="{0}"]',t.ref));if(a.getCount()&&"sticker"!=t.format){var o={};a.each(function(t){var i=Ext.apply({},o);e.width>=e.height&&e.width>600?(i.width=600,i.height=e.height*i.width/e.width):e.height>e.width&&e.height>600&&(i.height=600,i.width=e.width*i.height/e.height),a.set(i)})}}},removeLabel:function(t){var e=this.items.indexOf(t);if(-1===e)return void SYNO.Debug(t);this.items.splice(e,1),this.removeImage(t),this.fireEvent("filechange"),this.fireEvent("refresh")},addBigSizeFiles:function(t){if(!Ext.isEmpty(t)){new SYNO.SDS.MailClient.BigSizeUploadWindow({owner:this.owner.findWindow(),big_size_files:t,attachment_limit:this.owner.getSenderUploadLimit(),listeners:{scope:this,complete_create_sharing_link:function(t){this.owner.tinymce.getEditor().execCommand("syno_mc_attachment_sharinglink_insert",t)}}}).show()}},addFile:function(t,e,i,n){if("object"==typeof t){var a=this.addFileLabel(t);return a.renderTo(this.elm,t.id||t.temp_id,t.inline),(this.items.push(a),i&&(t.fromIncludeOrig=!0),e||i)?a:(t.inline&&this.addImage(a,n),Ext.isEmpty(t.id)&&(this.owner.ctrl?this.owner.ctrl.upload(t):this.owner.onImageUpload(t)),a)}},addFileLabel:function(t){return new SYNO.SDS.MailClient.Editor.FileLabel({file:t,owner:this,module:this.module,appWindow:this.owner.findAppWindow(),editor:this.owner.getEditor(),readonly:this.readonly,listeners:{remove:this.removeLabel,preview:this.preview,scope:this}})},preview:function(t,e){this.previewBubbleElm&&this.deletePreviewBubbleElm();var i=SYNO.SDS.MailClient.Viewer.show(t.file);if(i){var n=this.getPreviewContext();t.showContext(n,i),e.stopPropagation(),e.preventDefault()}},deletePreviewBubbleElm:function(){Ext.isEmpty(this.previewBubbleElm)||(this.previewBubbleElm.previewClickBtn&&this.previewBubbleElm.previewClickBtn.removeClass("syno-ddupload-filePreviewButton-clicked"),Ext.destroy(this.previewBubbleElm),delete this.previewBubbleElm)},getPreviewContext:function(){var t,e,i,n=this;return t=Ext.DomHelper.createDom({tag:"div",cls:"syno-mc-editor-tinymce-preview-bubble"}),e=this.owner.getEditor(),this.previewBubbleElm=Ext.get(t),this.previewBubbleElm.setVisibilityMode(Ext.Element.DISPLAY),i=e.getBody(),e.on("click blur",function(){Ext.isEmpty(n.previewBubbleElm)||n.previewBubbleElm.isVisible()&&n.deletePreviewBubbleElm()}),Ext.isEmpty(this.clickHandler)||Ext.getBody().un("click",this.clickHandler),this.clickHandler=function(t){Ext.isEmpty(n.previewBubbleElm)||!t.within(n.previewBubbleElm)&&n.previewBubbleElm.isVisible()&&n.deletePreviewBubbleElm()},Ext.getBody().on("click",this.clickHandler),this.previewBubbleElm.insertAfter(i),this.previewBubbleElm},removeImage:function(t){var e,i;t.state=t.stateEnum.DELETED,Ext.isEmpty(t.file.name)||(e=Ext.get(this.owner.getEditor().getBody()),i=e.select(String.format('img[data-ref="{0}"]',t.file.ref)),0!==i.getCount()&&i.first().remove())},renderTo:function(t){this.elm=Ext.DomHelper.createDom({tag:"div",cls:"clearfix syno-ddupload-fileLabelHolder",style:{position:"relative"}}),Ext.get(this.elm).insertAfter(t),this.refresh()},refresh:function(){if(!Ext.isDefined(this.elm))return void SYNO.Debug("elm is not defined");for(;this.elm.firstChild;)this.elm.removeChild(this.elm.firstChild);Ext.each(this.items,function(t){t.state!==t.stateEnum.DELETED&&t.renderTo(this.elm)},this);var t=this.owner.getEditor();t&&this.owner.isEmbedded&&t.execCommand("mceAutoResize")},detectAndUploadImage:function(){return this._handleBlobUrl().then(function(t){if(this.isAlive()){var e=this._handleUrlSrc();return t||e}}.bind(this))},_addDataUrlFile:function(t,e){e.dataset.synomcUploadingImg=!0;var i=Ext.id(void 0,"ns_attach_image_")+(new Date).getTime();2==t.length?i+="."+t[1]:i+=".jpg";var n=SYNO.SDS.MailClient.Tool.dataURItoBlob(e.src);Ext.isEmpty(n)||(n.name=i,n.inline=!0,this.addFile(n,void 0,void 0,e))},_addExternalUrlFile:function(t){t.dataset.synomcUploadingImg=!0,this.addFile({type:"image",format:"external",name:"tmep_image",inline:!0,url:t.getAttribute("data-synomc-external")},void 0,void 0,t)},_handleUrlSrc:function(){var t=!1;return Ext.get(this.owner.getEditor().getBody()).select("img:not([data-synomc-uploading-img])").each(function(e){var i=e.dom;if(SYNO.SDS.MailClient.Settings.enable_upload_external_image&&i.getAttribute("data-synomc-external"))return t=!0,void this._addExternalUrlFile(i);if(i.src){var n=i.src.match(/^data:image\/([a-zA-Z0-9]*);base64,/);return n?(t=!0,void this._addDataUrlFile(n,i)):void 0}},this),t},_handleBlobUrl:function(){var t=this.owner.getEditor(),e=[];return Ext.get(t.getBody()).select("img:not([data-synomc-uploading-img])").each(function(t){var i=t.dom;if(i.src){if(i.src.match(/^blob:([^\n]+)/)){i.dataset.synomcUploadingImg=!0;var n=window.blobUtil.imgSrcToBlob(i.src).then(function(t){if(this.isAlive()){var e=Ext.id(void 0,"ns_attach_image_")+(new Date).getTime()+".jpg";t.name=e,t.inline=!0,this.addFile(t,void 0,void 0,i)}}.bind(this));e.push(n)}}},this),Promise.all(e).then(function(){return e.length>0})},repairBody:function(t,e,i,n){t&&this.repairInlineImage(t,i,n);var a,o,s=new Array(this.items.length).fill(!1);for(a=0;a<e.length;++a)for(o=0;o<this.items.length;++o)if(this.isMatch(e[a],this.items[o].file)&&!this.items[o].file.fromIncludeOrig&&!s[o]){this.items[o].file=e[a],s[o]=!0;break}},isMatch:function(t,e){if(t.content_id){if(t.content_id===e.cid)return!0;if(t.content_id===e.content_id)return!0}else if(e.id&&t.name===e.name&&t.size===e.size)return!0;return!1},repairInlineImage:function(t,e,i){var n=(new DOMParser).parseFromString(t,"text/html"),a=Ext.get(this.owner.getEditor().getBody()),o={},s=[];Ext.each(this.items,function(t,e,i){t.file.inline&&(o[t.file.cid]=t)},this),n.querySelectorAll("img[syno-mc-cid]").forEach(function(t){var n,o,s=t.getAttribute("syno-mc-cid"),l=t.getAttribute("src");for(o=0;o<e.length;o++)if(s===e[o].cid){n=e[o].copied_id;break}var r;n?(Ext.each(this.owner.copiedAttachments,function(t,e,i){if(t.copied_id===n)return i.splice(e,1),!1}),r=a.select('img[syno-mc-copied-id="'+n+'"]')):r=a.select(String.format("img[syno-mc-cid={0}]",s)),i||r.each(function(t){var e=Ext.urlDecode(t.getAttribute("src"));!n&&Ext.isDefined(e.md5)||(t.set({"syno-mc-cid":s,src:Ext.urlAppend(l,"download_token="+SYNO.SDS.MailClient.Info.download_token)},!0),t.dom.removeAttribute("syno-mc-copied-id"))},this)},this),a.select("img[cid]").each(function(t){var e=t.getAttribute("cid"),i={"syno-mc-cid":e};s.push(e),null!==n.querySelector(String.format("img[syno-mc-cid={0}]",e))&&(t.set(i,!0),t.dom.removeAttribute("cid"),t.dom.removeAttribute("id"),t.dom.removeAttribute("data-mce-src"),t.dom.removeAttribute("data-temp-id"),o.hasOwnProperty(e)&&(this.items.remove(o[e]),delete o[e]))},this),Object.keys(o).forEach(function(t){-1===s.indexOf(t)&&this.items.remove(o[t])},this)},getAttachments:function(){var t=[];return this.items.forEach(function(e){var i=e.file;i.id&&t.push(i)},this),t},getTempAttachments:function(){var t,e=[];t=Ext.get(this.owner.getEditor().getBody()),t.select("img[data-temp-id]").each(function(t){e.push(parseInt(t.getAttribute("data-temp-id"),10))});var i=[];return this.items.forEach(function(t){var n=t.file;n.temp_id&&-1===e.indexOf(n.temp_id)&&i.push(n)},this),e.concat(i)},findFileLabel:function(t){var e;for(e=0;e<this.items.length;e++)if(this.items[e].file===t)return this.items[e]},onProgress:function(t,e){var i=this.findFileLabel(e);if(i){if(Ext.isEmpty(i.file.upload_offset)&&(i.file.upload_offset=0),!t)return void i.onProgress(e.size);var n=t.position||t.loaded;100<=i.onProgress(n-i.file.upload_offset)&&(i.file.upload_offset+=i.file.size)}},onFinish:function(t){var e=this.findFileLabel(t);e&&(e.addControl(),e.onFinish())},onFailed:function(t){var e=this.findFileLabel(t);e&&this.removeLabel(e)}}),Ext.define("SYNO.SDS.MailClient.Editor.FormUpload.Panel",{extend:"SYNO.SDS.Utils.FormPanel",requires:[],constructor:function(t){this.module=t.module,this.owner=t.owner,this.appWin=this.findAppWindow(),this.callParent([this.fillConfig(t||{})])},fillConfig:function(t){var e={fieldWidth:250,labelWidth:100,fileUpload:!0,layout:{type:"vbox",align:"stretch"},items:[{xtype:"hidden",name:"commit_msg",value:Ext.encode({device:"desktop"})},{xtype:"syno_editorgrid",itemId:"upload_file_grid",cls:"syno-ns-tinymce-fileupload-grid",flex:1,enableColumnMove:!1,colModel:new Ext.grid.ColumnModel({defaults:{menuDisabled:!0},columns:[{dataIndex:"filename",header:SYNO.SDS.MailClient._T("common","name")},{dataIndex:"filesize",header:SYNO.SDS.MailClient._T("common","size"),width:60,hidden:!SYNO.SDS.Utils.FileChooser.supportMultiSelect},{xtype:"actioncolumn",css:"syno-ns-actioncolumn",header:SYNO.SDS.MailClient._T("common","action"),items:[{iconCls:"syno-ns-tinymce-fileupload-delete-icon syno-mc-tinymce-fileupload-delete-icon",handler:function(t,e,i){var n=t.getStore().getAt(e).get("inputElm");t.getStore().removeAt(e),Ext.isObject(n)&&Ext.removeNode(Ext.getDom(n))}}],width:24,align:"center"}]}),store:this.getFileStore()}]};return Ext.apply(e,t)},getFileStore:function(){return this.fileStore?this.fileStore:(this.fileStore=new Ext.data.JsonStore({fields:["filename","filesize"]}),this.fileStore)}}),Ext.define("SYNO.SDS.MailClient.Editor.ListFile.GridPanel",{extend:"SYNO.ux.GridPanel",constructor:function(t){this.module=t.module,this.owner=t.owner,this.appWin=this.findAppWindow(),this.callParent([this.fillConfig(t||{})])},fillConfig:function(t){var e=new Ext.grid.ColumnModel({defaults:{menuDisabled:!0},columns:[{header:SYNO.SDS.MailClient._T("common","name"),width:280,dataIndex:"filename",id:"filename",renderer:function(t){return'<font class="syno-ns-filelist-filename">'+t+"</font>"},listeners:{click:function(t,e,i,n){e.getStore().getAt(i).get("filelabel").elms.fileName.click()}}},{header:SYNO.SDS.MailClient._T("common","size"),width:94,dataIndex:"filesize",id:"filesize"},{header:SYNO.SDS.MailClient._T("common","preview"),width:94,xtype:"actioncolumn",css:"syno-ns-actioncolumn",items:[{iconCls:"syno-mc-tinymce-fileupload-preview-icon",handler:function(t,e,i,n,a){var o=t.getStore().getAt(e).get("filelabel"),s=t.getEl().dom.getElementsByClassName("x-grid3-col-"+this.id)[e].firstChild;SYNO.SDS.MailClient.Viewer.show(o.file,Ext.get(s))}}],align:"center",id:Ext.id(void 0,"preview")},{header:SYNO.SDS.MailClient._T("common","delete"),width:94,xtype:"actioncolumn",css:"syno-ns-actioncolumn",items:[{iconCls:"syno-mc-tinymce-fileupload-delete-icon",handler:function(t,e,i){var n=t.getStore().getAt(e).get("filelabel");n.fireEvent("remove",n),t.getStore().removeAt(e)}}],align:"center"}]}),i={colModel:e,store:this.getAttachmentStore(),cls:"syno-ns-tinymce-filelist-grid",autoExpandColumn:"filename",enableColumnMove:!1,listeners:{viewready:function(t){t.getView().updateScroller()}}};return Ext.apply(t,i)},getAttachmentStore:function(){return this.attachmentStore?this.attachmentStore:(this.attachmentStore=new Ext.data.JsonStore({fields:["filename","filesize"]}),this.attachmentStore)}}),Ext.define("SYNO.SDS.MailClient.Editor.ListSharingLink.GridPanel",{extend:"SYNO.ux.GridPanel",constructor:function(t){this.module=t.module,this.owner=t.owner,this.appWin=this.findAppWindow(),this.callParent([this.fillConfig(t||{})])},fillConfig:function(t){var e=new Ext.grid.ColumnModel({defaults:{menuDisabled:!0},columns:[{header:SYNO.SDS.MailClient._T("common","name"),width:280,dataIndex:"filename",id:"filename",renderer:function(t){return'<font class="syno-ns-filelist-filename">'+t+"</font>"}},{header:SYNO.SDS.MailClient._T("common","size"),width:94,dataIndex:"filesize",id:"filesize"},{header:SYNO.SDS.MailClient._T("common","common_settings"),width:94,xtype:"actioncolumn",css:"syno-ns-actioncolumn",items:[{scope:this,iconCls:"syno-mc-tinymce-sharinglink-setting-icon",handler:function(t,e,i,n,a){var o=t.getStore().getAt(e).get("fileBlock"),s=[];if(this.sharing_link_dom_set.forEach(function(t){s.push(t.dataset.fileUrl)}),!Ext.isEmpty(s)){return new SYNO.SDS.MailClient.SharingLinkWindow({owner:this.findWindow(),file_url_set:s,clicked_file_block:o,listeners:{scope:this,apply:function(t){delete t.password,delete t.id,"true"===t.apply_to_all?this.sharing_link_dom_set.forEach(function(e){e.dataset.config=Ext.encode(t)}):o.dataset.config=Ext.encode(t)}}}).show()}}}],align:"center",id:Ext.id(void 0,"preview")},{header:SYNO.SDS.MailClient._T("common","delete"),width:94,xtype:"actioncolumn",css:"syno-ns-actioncolumn",items:[{scope:this,iconCls:"syno-mc-tinymce-fileupload-delete-icon",handler:function(t,e,i){var n=t.getStore().getAt(e).get("fileBlock");this.module.getEditor().execCommand("syno_mc_attachment_sharinglink_remove",n),t.getStore().removeAt(e)}}],align:"center"}]}),i={colModel:e,store:this.getAttachmentStore(),cls:"syno-ns-tinymce-filelist-grid",autoExpandColumn:"filename",enableColumnMove:!1,listeners:{viewready:function(t){t.getView().updateScroller()}}};return Ext.apply(t,i)},getAttachmentStore:function(){return this.attachmentStore?this.attachmentStore:(this.attachmentStore=new Ext.data.JsonStore({fields:["filename","filesize"]}),this.attachmentStore)}}),Ext.define("SYNO.SDS.MailClient.Editor.FormUpload.Window",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:[],constructor:function(t){this.module=t.module,this.owner=t.owner,this.appWin=this.findAppWindow(),this.callParent([this.fillConfig(t||{})]),this.createFileInputFromPC()},fillConfig:function(t){var e,i=!1;t.isInline?(e=this.getFileUploadFormPanel(),i=!0):e={xtype:"syno_tabpanel",items:[this.getFileUploadFormPanel(),this.getFileListGridPanel(),this.getSharingLinkListGridPanel()],activeTab:0};var n={title:i?SYNO.SDS.MailClient._T("tinymce","insert_image"):SYNO.SDS.MailClient._T("tinymce","attach_file"),width:600,height:500,cls:"syno-ns-add-file-win, syno-mc-add-file-window",items:e,layout:"fit",buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({xtype:"syno_button",btnStyle:"blue",text:_T("common","ok"),handler:this.onApply,scope:this},{xtype:"syno_button",text:_T("common","cancel"),scope:this,handler:this.onCancel}),listeners:{beforeshow:function(){if(!this.isInline){Ext.each(this.module.ddupload.items,function(t){if(!t.file.inline){var e=new Ext.data.Record({filename:t.file.name,filesize:Ext.util.Format.fileSize(t.file.size),filelabel:t});this.fileListGridPanel.getStore().add(e)}},this);var t=Ext.DomQuery.jsSelect("[data-file-url]",this.module.getEditor().getBody());this.sharingLinkListGridPanel.sharing_link_dom_set=t,Ext.each(t,function(t){var e=new Ext.data.Record({filename:t.dataset.fileName,filesize:Ext.util.Format.fileSize(t.dataset.fileSize),fileBlock:t});this.sharingLinkListGridPanel.getStore().add(e)},this)}}}};return Ext.apply(n,t)},createFileInputFromDS:function(){var t={owner:this,width:800,enumC2Share:!0,gotoPath:SYNO.SDS.UserSettings.getProperty("SYNO.SDS.MailClient.Application","lastFileChooserPath")||"",usage:{type:"open",multiple:!0},listeners:{choose:{fn:function(t,e,i){if(this.handleFileSelectFromDS(e),!Ext.isEmpty(e.records)){var n=e.records[0].get("path"),a=n.substring(0,n.lastIndexOf("/"));SYNO.SDS.UserSettings.setProperty("SYNO.SDS.MailClient.Application","lastFileChooserPath",a)}t.close()}},scope:this}};this.isInline&&(t.getFilterPattern=function(t){return"jpg,jpeg,jpe,bmp,gif,png"}),new SYNO.SDS.Utils.FileChooser.Chooser(t).show()},createFileInputFromPC:function(){var t,e=this.fileUploadFormPanel.getTopToolbar();this.fromPCBtn&&(this.mun(this.fromPCBtn.getEl(),"change"),t=Ext.get(this.fileUploadFormPanel.getForm().getEl().query("div")[0]),this.fromPCBtn.getEl().insertAfter(t),this.fromPCBtn.hide()),this.fromPCBtn=new SYNO.ux.FileButton({name:Ext.id(void 0,"file_"),buttonText:SYNO.SDS.MailClient._T("tinymce","from_pc"),buttonOnly:!0}),e.add(this.fromPCBtn),e.doLayout(),this.fromPCBtn.getEl().set({multiple:!0},!0),this.mon(this.fromPCBtn.getEl(),"change",this.handleFileSelectFromPC,this)},handleFileSelectFromDS:function(t){var e=this.fileUploadFormPanel.getComponent("upload_file_grid");if(Ext.isEmpty(t.records)){var i=t.path.substr(t.path.lastIndexOf("/")+1),n=new Ext.data.Record({name:i,filename:i,sharepath:t.path,selectfrom:"ds"});e.getStore().add(n)}else Ext.each(t.records,function(t){var i,n;t.get("isdir")||(i=SYNO.SDS.MailClient.Tool.isSupportImageFormat(t.get("type")),n=new Ext.data.Record({name:t.get("filename"),filename:t.get("filename"),filesize:Ext.util.Format.fileSize(t.get("filesize")),sharepath:t.get("path"),selectfrom:"ds",fileObj:{name:t.get("filename"),size:t.get("filesize"),type:i?"image":"binary",source:t.get("path"),format:"ds",inline:!1}}),e.getStore().add(n))})},handleFileSelectFromPC:function(t,e,i){var n,a=this.fileUploadFormPanel.getComponent("upload_file_grid"),o=0;if(SYNO.SDS.HTML5Utils.isSupportHTML5Upload())n=t.target.files,Ext.each(n,function(t){if(this.isInline&&!SYNO.SDS.MailClient.Tool.isSupportImageFormat(t.name))return void o++;var i=new Ext.data.Record({inputElm:e,name:Ext.id(void 0,"file_upload_"),filename:t.name,filesize:Ext.util.Format.fileSize(t.size),fileObj:t,selectfrom:"pc"});a.getStore().add(i)},this);else{var s,l=e.value,r=/fakepath\\(.+)$/.exec(l);if(s=null!==r?r[1]:l,Ext.isEmpty(s))return;var d=new Ext.data.Record({inputElm:e,name:e.getAttribute("name"),filename:s,filesize:"",fileObj:null,selectfrom:"pc"});a.getStore().add(d)}o&&this.getMsgBox().alert("",String.format(SYNO.SDS.MailClient._T("tinymce","unsupported_file_count"),o)),this.fromPCBtn.reset()},getFileListGridPanel:function(){return this.fileListGridPanel=new SYNO.SDS.MailClient.Editor.ListFile.GridPanel({owner:this.owner,module:this.module,title:SYNO.SDS.MailClient._T("tinymce","file_list")}),this.fileListGridPanel},getSharingLinkListGridPanel:function(){return this.sharingLinkListGridPanel=new SYNO.SDS.MailClient.Editor.ListSharingLink.GridPanel({owner:this.owner,module:this.module,title:SYNO.SDS.MailClient._T("tinymce","sharing_link_list")}),this.sharingLinkListGridPanel},getFileUploadFormPanel:function(){var t={xtype:"syno_button",text:SYNO.SDS.MailClient._T("tinymce","from_ds"),scope:this,handler:function(){this.createFileInputFromDS()}};return this.fileUploadFormPanel=new SYNO.SDS.MailClient.Editor.FormUpload.Panel({owner:this.owner,module:this.module,title:SYNO.SDS.MailClient._T("upload","upload_file"),tbar:[t]}),this.fileUploadFormPanel},getAttachment:function(){var t=[];return this.fileUploadFormPanel.getComponent("upload_file_grid").getStore().each(function(e){var i={action:"create",name:e.get("name"),format:"raw"};"ds"===e.get("selectfrom")&&Ext.apply(i,{format:"ds",source:e.get("sharepath")}),t.push(i)},this),t},onCancel:function(){this.close()},onApply:function(){this.uploadFile(),this.close()},uploadFile:function(){var t=this.fileUploadFormPanel.getComponent("upload_file_grid"),e=[],i=[];SYNO.SDS.HTML5Utils.isSupportHTML5Upload()&&(t.getStore().each(function(t){if(!Ext.isEmpty(t.get("fileObj"))){var n=t.get("fileObj");if(Ext.isNumber(n.size)&&n.size>this.module.getSenderUploadLimit()&&SYNO.SDS.StatusNotifier.isAppEnabled("SYNO.SDS.App.FileStation3.Instance")&&SYNO.SDS.MailClient.AdminSettings.SharingLink.enable&&!this.isSkipCheckBigSizeFile)return void i.push(n);n.inline=this.isInline,e.push(n)}},this),this.isSkipCheckBigSizeFile||this.module.addBigSizeFiles(i),e.forEach(function(t,e,i){this.module.addFile(t)},this))}}),Ext.define("SYNO.SDS.MailClient.Editor.Sticker.Panel",{extend:"SYNO.ux.Panel",xtype:"syno_mc_sticker_panel",constructor:function(t){this.category=t.category,this.callParent([this.fillConfig(t)]),5==this.category&&this.addClass("emoticon-panel"),this.addEvents("sticker_select"),this.store.load()},fillConfig:function(t){this.dataview=new SYNO.SDS.MailClient.Editor.Sticker.DataView({store:this.getStore(),listeners:{scope:this,click:this.onStickerSelected}});var e={cls:"syno-mc-sticker-panel",layout:"fit",store:this.getStore(),items:this.dataview};return Ext.apply(e,t)},onStickerSelected:function(t,e,i,n){var a=this.getStore().getAt(e);a&&this.fireEvent("sticker_select",a,this.keepOpenAfterClick)},getStore:function(){return this.store=this.store||new SYNO.API.Store({method:"POST",proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Sticker",method:"list",version:2,listeners:{scope:this,beforeload:function(t,e){var i=t.activeRequest.read;i&&Ext.Ajax.abort(i)}}}),baseParams:{category:this.category},reader:new Ext.data.JsonReader({root:"sticker",fields:["id","name","category","url","default_width","default_height"]}),listeners:{scope:this,load:function(t,e,i){var n,a=SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Sticker","get",2);for(n=0;n<e.length;++n)e[n].set("url",Ext.urlAppend(a,Ext.urlEncode({id:e[n].data.id})));this.preloadStickers()}}}),this.store},normalPreload:function(t){SYNO.SDS.MailClient.ImageLoader.preload(t)},preloadStickers:function(){var t=[];this.hasPreloadedStickers||(this.hasPreloadedStickers=!0,this.store.each(function(e){t.push(e.get("url"))},this),this.normalPreload(t))}}),Ext.define("SYNO.SDS.MailClient.Editor.Sticker.DataView",{extend:"SYNO.ux.FleXcroll.DataView",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={cls:"syno-mc-sticker-dataview",tpl:this.createTpl(),overClass:"item-over",itemSelector:"div.item-wrap"};return Ext.apply(e,t)},createTpl:function(){return new Ext.XTemplate('<tpl for=".">','<div class="item-wrap {[this.getBigImgClass(values)]}">','<div class="item-border">','<img src="{[this.getImageUrl(values)]}">',"</div>","</div>","</tpl>",'<div class="x-clear"></div>',{getImageUrl:function(t){var e=SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Sticker","get",2);return e=Ext.urlAppend(e,Ext.urlEncode({id:t.id}))},getBigImgClass:function(t){if(64!==t.default_width)return"";var e=["big-emoji"];return t.id%3==1&&e.push("endl"),t.name<="font_03.png"&&e.push("fl"),e.join(" ")}})}}),Ext.define("SYNO.SDS.MailClient.Editor.Sticker.Menu",{extend:"SYNO.ux.Menu",module:null,constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("hide",function(){Ext.defer(function(){this.module&&this.module.focusEditor()},300,this)},this)},fillConfig:function(t){var e={cls:"syno-mc-menu syno-mc-sticker-menu",items:this.getCardPanel()};return Ext.apply(e,t)},setModule:function(t){this.module=t},getCardPanel:function(){return this.cardPanel=this.cardPanel||new SYNO.ux.Panel({layout:"card",width:306,height:357,tbar:this.getTbarCfg(),activeItem:0,defaults:{xtype:"syno_mc_sticker_panel",keepOpenAfterClick:!1,listeners:{scope:this,sticker_select:this.onStickerSelected}},items:[{itemId:"emoticon",keepOpenAfterClick:!0,category:5},{itemId:"business-man",category:2},{itemId:"business-woman",category:3},{itemId:"shiba-inu",category:4},{itemId:"customize",category:0}]}),this.cardPanel},onStickerSelected:function(t,e){this.module.addFile({name:t.get("name"),type:"image",format:"sticker",sticker_id:t.get("id"),sticker_category:t.get("category"),sticker_url:t.get("url"),sticker_size:{width:t.get("default_width"),height:t.get("default_height")},inline:!0}),e?Ext.defer(function(){this.focus()},300,this):this.hide()},getTbarCfg:function(){return{cls:"syno-mc-tb",items:[{xtype:"syno_statebuttongroup",activeBtn:0,defaults:{width:60,height:32},buttons:[{itemId:"emoticon",iconCls:"sticker-emoticon-btn"},{itemId:"business-man",iconCls:"sticker-man-btn"},{itemId:"business-woman",iconCls:"sticker-woman-btn"},{itemId:"shiba-inu",iconCls:"sticker-inu-btn"}],listeners:{scope:this,activebuttonchange:function(t,e){Ext.isObject(this.cardPanel.layout.activeItem)&&e.itemId!=this.cardPanel.layout.activeItem.itemId&&this.cardPanel.layout.setActiveItem(e.itemId)}}},"->",{xtype:"syno_button",itemId:"add",iconCls:"sticker-add-btn",hidden:!0}]}}}),Ext.define("SYNO.SDS.MailClient.Editor.SelectContactWindow",{extend:"SYNO.SDS.MailClient.ModalWindow",expandGroupToContacts:!0,constructor:function(t){this.windowType=t.windowType,this.hideSortBtn=t.hideSortBtn,this.idProperty=t.idProperty,this.callParent([this.fillConfig(t)]),this.addEvents("selectdone"),this.mon(this.getContactStore(),"beforeload",function(){this.setStatusBusy()},this,{single:!0}),this.mon(this.getGroupStore(),"beforeload",function(){this.setStatusBusy()},this,{single:!0})},fillConfig:function(t){var e="syno-mc-editor-select-contact-window";"server"===this.windowType&&(e+=" syno-mc-editor-select-contact-window-server-mode"),this.groupId=SYNO.SDS.MailClient.Define.allContactGroupId,this.groupViewType="all",this.sort_by="full_name",this.sort_direction="asc",this.contactData=new Ext.util.MixedCollection,this.groupData=new Ext.util.MixedCollection;var i={width:"server"===this.windowType?480:680,height:520,title:SYNO.SDS.MailClient._T("composer","select_contact"),cls:e,tbar:{layout:"fit",items:[this.textfilter=new SYNO.ux.TextFilter({itemId:"text_filter",owner:this,filter:function(){var t=this.owner;t.getContactStore()===t.selectBar.getStore()?t.getContactStore().load({}):t.getGroupStore().doFilter(this.getValue().trim().split(" "))}})]},layout:"border",items:[this.getViewPanel(),this.getBottomBoxSelect()],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","choose"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})};return Ext.apply(i,t)},getContactViewPanel:function(){if(this.contactView)return this.contactView;var t={region:"center",store:this.getContactStore(),itemId:"contact_view",listeners:{scope:this,displayed:function(t,e,i){i?(this.contactData.add(e.id,e.data),this.bottomBoxSelect.addItem(e.data)):(this.contactData.removeKey(e.id),this.bottomBoxSelect.removeItem(e.id)),this.bottomBoxSelect.doLayout()},datachange:function(t){t.length?t.length==this.getContactStore().getCount()?this.viewPanel.getTopToolbar().checkAll():this.viewPanel.getTopToolbar().checkPartial():this.viewPanel.getTopToolbar().checkNone()},afterstoreload:function(t){Ext.each(this.getContactStore().getRange(),function(e){-1!==this.contactData.indexOfKey(e.id)&&t.checkById(e.id)},this)}}};return"server"===this.windowType?this.contactView=new SYNO.SDS.MailClient.SelectServersContactListView(t):this.contactView=new SYNO.SDS.MailClient.Editor.SelectContactListView(t),this.contactView},getGroupViewPanel:function(){if(this.groupView)return this.groupView;var t={region:"center",itemId:"group_view",store:this.getGroupStore(),listeners:{scope:this,displayed:function(t,e,i){i?(this.groupData.add(e.id,e.data),this.bottomBoxSelect.addGroupItem(e.data)):(this.groupData.removeKey(e.id),this.bottomBoxSelect.removeGroupItem(e.id)),this.bottomBoxSelect.doLayout()},datachange:function(t){t.length?t.length==this.getGroupStore().getCount()?this.viewPanel.getTopToolbar().checkAll():this.viewPanel.getTopToolbar().checkPartial():this.viewPanel.getTopToolbar().checkNone()},afterstoreload:function(t){Ext.each(this.getGroupStore().getRange(),function(e){-1!==this.groupData.indexOfKey(e.id)&&t.checkById(e.id)},this)}}};return"server"===this.windowType?this.groupView=new SYNO.SDS.MailClient.SelectServersGroupListView(t):this.groupView=new SYNO.SDS.MailClient.Editor.SelectGroupListView(t),this.groupView},getSelectBar:function(t){return this.selectBar=this.selectBar||new SYNO.SDS.MailClient.SelectContactToolbar({store:this.getContactStore(),hideSortBtn:t.hideSortBtn,windowType:this.windowType,listeners:{scope:this,selectall:function(){var t=this.selectBar.getStore(),e=t.getRange(),i=!1;Ext.each(e,function(e){i=!0,t===this.getContactStore()?(this.changeSelection(e.data,this.contactData,this.contactView,!0),this.bottomBoxSelect.addItem(e.data)):(this.changeSelection(e.data,this.groupData,this.groupView,!0),this.bottomBoxSelect.addGroupItem(e.data))},this),i&&this.bottomBoxSelect.doLayout()},selectnone:function(){var t=this.selectBar.getStore(),e=t.getRange(),i=!1;Ext.each(e,function(e){i=!0,t===this.getContactStore()?(this.changeSelection(e.data,this.contactData,this.contactView,!1),this.bottomBoxSelect.removeItem(e.id)):(this.changeSelection(e.data,this.groupData,this.groupView,!1),this.bottomBoxSelect.removeGroupItem(e.id))},this),i&&this.bottomBoxSelect.doLayout()},contactBtnClick:function(t){this.selectBar.bindStore(this.getContactStore()),this.groupId=t,this.getContactStore().load(),this.viewPanel.layout.setActiveItem("contact_view")},groupBtnClick:function(t){this.selectBar.bindStore(this.getGroupStore()),this.groupViewType=t,this.getGroupStore().load(),this.viewPanel.layout.setActiveItem("group_view")},sortItemClick:function(t){"sort_by"===t.group?this.sort_by=t.value:this.sort_direction=t.value,this.getContactStore()===this.selectBar.getStore()?this.selectBar.getStore().load():this.selectBar.getStore().sort("name",this.sort_direction)}}}),this.selectBar},getViewPanel:function(){return this.viewPanel?this.viewPanel:(this.viewPanel=new SYNO.ux.Panel({cls:"select-contact-list-view-panel",tbar:this.getSelectBar({hideSortBtn:this.hideSortBtn}),region:"center",margins:"0 20",activeItem:0,layout:"card",items:[this.getContactViewPanel(),this.getGroupViewPanel()]}),this.viewPanel)},changeSelection:function(t,e,i,n){var a="name"===this.idProperty?t.name:t.id;if(n){if(-1!==e.indexOfKey(a))return;e.add(a,t),i.checkById(a)}else{if(-1===e.indexOfKey(a))return;e.removeKey(a),i.uncheckById(a)}},getBottomBoxSelect:function(){if(this.bottomBoxSelect)return this.bottomBoxSelect;var t=function(t){var e=0<t.items.getCount();e===t.hidden&&(t[e?"show":"hide"](),this.doLayout())},e=this;return this.bottomBoxSelect=new Ext.Container({region:"south",cls:"bottom-box-select",autoFlexcroll:!0,hidden:!0,height:64,margins:SYNO.SDS.MailClient.Format.isDSM6()?"8 20 0 20":"8 20 8 20",addItem:function(t){var i="server"===e.windowType?t.name:t.full_name;this.add(new SYNO.SDS.MailClient.LabelItem({data:t,type:"contact",text:i,qtipText:i,listeners:{scope:this,delete:function(t,i){this.remove(t),e.changeSelection(i,e.contactData,e.contactView,!1)}}}))},addGroupItem:function(t){
this.add(new SYNO.SDS.MailClient.LabelItem({data:t,type:"group",text:t.name,qtipText:t.name,cls:"syno-mc-label-item bottom-box-group-select",listeners:{scope:this,delete:function(t,i){this.remove(t),e.changeSelection(i,e.groupData,e.groupView,!1)}}}))},removeItem:function(t){this.items.each(function(i){var n=i.data.id;if("name"===e.idProperty&&(n=i.data.name),"contact"===i.type&&n===t)return this.remove(i),!1},this)},removeGroupItem:function(t){this.items.each(function(i){var n=i.data.id;if("name"===e.idProperty&&(n=i.data.name),"group"===i.type&&n===t)return this.remove(i),!1},this)},listeners:{scope:this,add:t,remove:t}}),this.bottomBoxSelect},getContactStore:function(){return this.store?this.store:(this.store=new SYNO.API.Store({method:"POST",reader:new Ext.data.JsonReader({root:"contact",totalProperty:"total",fields:["id","addressbook_id","full_name","primary_mail","company","additional"]}),load:function(t){var e=t?t.params||{}:{};return Ext.applyIf(e,{offset:0,limit:100,additional:["extra_info"]}),this.groupId&&SYNO.SDS.MailClient.Define.allContactGroupId!==this.groupId&&(0===this.groupId.indexOf("addressbook_")?e.addressbook_id=parseInt(this.groupId.substring("addressbook_".length),10):0===this.groupId.indexOf("label_")?e.label_id=parseInt(this.groupId.substring("label_".length),10):0===this.groupId.indexOf("ou_")&&(e.group_id=parseInt(this.groupId.substring("ou_".length),10))),this.textfilter&&(e.keyword=this.textfilter.getValue().trim().split(" ")),this.sort_by&&(e.sort_by=this.sort_by),this.sort_direction&&(e.sort_direction=this.sort_direction),this.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listContact",e).then(function(t){this.store.loadData(t,{params:e})}.bind(this)).catch(function(t){this.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t,_T("error","error_io")),this.close,this)}.bind(this))}.bind(this),listeners:{scope:this,load:function(t,e,i){if(this.clearStatusBusy(),!t||0!==t.getCount()){var n=this.contactView.getNode(e[0]);n&&this.contactView.fleXcrollTo(n)}}}}),this.store)},getGroupStore:function(){return this.groupStore?this.groupStore:(this.groupStore=new SYNO.API.Store({method:"POST",reader:new Ext.data.JsonReader({root:"",fields:["id","name","member","member_count","type"]}),load:function(t){var e=this.groupViewType||"all";return this.setStatusBusy(),SYNO.SDS.MailClient.Control.Model.getGroupJson(e).then(function(e){this.groupStore.loadData(e),t&&t.callback&&t.callback({addressbook:e.filter(function(t){return"addressbook"===t.type}),label:e.filter(function(t){return"label"===t.type}),ou:e.filter(function(t){return"ou"===t.type})})}.bind(this)).catch(function(t){this.getMsgBox().alert("",_T("error","error_io"),this.close,this)}.bind(this))}.bind(this),doFilter:function(t){this.filterBy(function(e,i){return-1===t.findIndex(function(t){return-1===e.get("name").toLowerCase().indexOf(t.toLowerCase())})},this)},listeners:{scope:this,load:function(t,e,i){this.clearStatusBusy(),t&&0===t.getCount()||(t.sort("name",this.sort_direction),this.textfilter&&t.doFilter(this.textfilter.getValue().trim().split(" ")))}}}),this.groupStore)},show:function(){this.getContactStore().load(),this.getGroupStore().load({callback:function(t){t&&this.viewPanel.getTopToolbar().addGroupMenu(t)}.bind(this)}),this.callParent(arguments)},onApply:function(){return this.getContactStore().load({params:{limit:-1}}).then(function(){var t,e,i=[];this.groupData.each(function(t){"ou"===t.type&&(i=i.concat(t.member))}),Ext.each(this.getContactStore().getRange(),function(n){t="addressbook_"+n.data.addressbook_id,-1!==this.groupData.indexOfKey(t)&&this.contactData.add(n.id,n.data),Ext.each(n.data.additional.label,function(t){if(e="label_"+t.id,-1!==this.groupData.indexOfKey(e))return this.contactData.add(n.id,n.data),!1},this),-1!==i.indexOf(n.id)&&this.contactData.add(n.id,n.data)},this),this.fireEvent("selectdone",this.contactData,this.groupData),this.close()}.bind(this))},onCancel:function(){this.close()}}),Ext.define("SYNO.SDS.MailClient.Editor.SelectContactListView",{extend:"SYNO.SDS.MailClient.BasicListView",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={cls:"syno-mc-select-list-view",store:t.store,tpl:this.createTpl(),itemSelector:"div.item-wrap"};return Ext.apply(e,t)},createTpl:function(){return new Ext.XTemplate('<tpl for=".">','<div class="item-wrap select-contact-layout">','<div class="item-icon">','<div class="check-area">','<div class="align"></div>','<div class="syno-ux-checkbox-icon"></div>',"</div>","</div>",'<div class="summary">','<div class="from" ext:qtip="{values.full_name:htmlEncode}">{values.full_name:htmlEncode}</div>','<div class="from" ext:qtip="{values.company:htmlEncode}">{values.company:htmlEncode}</div>','<div class="subject" ext:qtip="{values.primary_mail:htmlEncode}">{values.primary_mail:htmlEncode}</div>',"</div>","</div>","</tpl>",'<div class="x-clear"></div>')},onClick:function(t,e,i){var n=Ext.fly(e);if(n){var a,o,s,l,r;a=n.hasClass(this.itemSelectorCls)?n:n.parent("."+this.itemSelectorCls),a&&(l=this.indexOf(a),r=this.store.getAt(l),s=a.child("."+this.checkIconCls),o=s.hasClass(this.checkedCls),s.toggleClass(this.checkedCls),o?(this.removeCheckedItemList(l),a.removeClass(this.selectedClass)):(this.addCheckedItemList(l),a.addClass(this.selectedClass)),this.onDisplayNode(r,o))}},onDisplayNode:function(t,e){this.fireEvent("displayed",this,t,!e)},checkById:function(t){var e=this.store.getById(t);if(e){var i=this.getNode(e),n=this.indexOf(i);this.addCheckedItemList(n),Ext.fly(i).addClass(this.selectedClass).child("."+this.checkIconCls).addClass(this.checkedCls)}},uncheckById:function(t){var e=this.store.getById(t);if(e){var i=this.getNode(e),n=this.indexOf(i);this.removeCheckedItemList(n),Ext.fly(i).removeClass(this.selectedClass).child("."+this.checkIconCls).removeClass(this.checkedCls)}}}),Ext.define("SYNO.SDS.MailClient.Editor.SelectGroupListView",{extend:"SYNO.SDS.MailClient.Editor.SelectContactListView",createTpl:function(){return new Ext.XTemplate('<tpl for=".">','<div class="item-wrap select-contact-layout">','<div class="item-icon">','<div class="check-area">','<div class="align"></div>','<div class="syno-ux-checkbox-icon"></div>',"</div>","</div>",'<div class="summary">','<div class="group-from from" ext:qtip="{[Ext.util.Format.htmlEncode(values.name)]}">{[Ext.util.Format.htmlEncode(values.name)]}</div>','<div class="subject" ext:qtip="{[String.format(SYNO.SDS.MailClient._T("contact_group", "member_count"), values.member_count)]}">{[String.format(SYNO.SDS.MailClient._T("contact_group", "member_count"), values.member_count)]}</div>',"</div>","</div>","</tpl>",'<div class="x-clear"></div>')}}),Ext.define("SYNO.SDS.MailClient.SelectContactToolbar",{extend:"Ext.PagingToolbar",hideSortBtn:!1,windowType:"normal",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("contactBtnClick","sortItemClick"),this.firstGroupLoad=!0},fillConfig:function(t){var e={pageSize:100,jumpOffset:1,displayButtons:!1,showRefreshBtn:!1,cls:"select-contact-tollber"};return Ext.apply(e,t)},onLoad:function(t,e,i){var n=i.add||i;if(!this.rendered)return void(this.dsLoaded=[t,e,n]);var a=this.getParams();if(a){this.cursor=n.params&&n.params[a.start]?n.params[a.start]:0;var o=this.getPageData(),s=o.activePage,l=o.pages;this.prev.setDisabled(1==s),this.next.setDisabled(s==l),this.fireEvent("change",this,o)}},initComponent:function(){var t=[this.checkBtn=new SYNO.ux.Button({cls:"check-btn",scope:this,handler:function(t,e){t.toggle(),t.pressed?(t.removeClass("select-partial").addClass("select-all"),this.fireEvent("selectall",{})):(t.removeClass("select-partial").removeClass("select-all"),this.fireEvent("selectnone",{}))}}),this.groupBtn=new SYNO.ux.Button({cls:"group-btn",text:SYNO.SDS.MailClient._T("contact_group","all_contact"),menu:{cls:"syno-ux-groupcheck-menu syno-mc-menu",items:[{xtype:"menucheckitem",text:SYNO.SDS.MailClient._T("contact_group","all_contact"),value:SYNO.SDS.MailClient.Define.allContactGroupId,group:"contact_group",checked:!0,handler:this._clickContactHandler,scope:this}]}}),"->",this.prev=new SYNO.ux.Button({cls:"prev-btn",handler:this.jumpPageHandler,scope:this}),this.next=new SYNO.ux.Button({cls:"next-btn",handler:this.jumpPageHandler,scope:this}),this.pageSortSep=new Ext.BoxComponent({hidden:this.hideSortBtn,cls:"sep"}),this.sortBtn=new SYNO.ux.Button({cls:"sort-btn",hidden:this.hideSortBtn,menu:{cls:"syno-ux-groupcheck-menu syno-mc-menu",items:[{xtype:"menucheckitem",itemId:"name",group:"sort_by",value:"full_name",checked:!0,text:String.format(SYNO.SDS.MailClient._T("sort","sort_by"),SYNO.SDS.MailClient._T("contact_detail","name"))},{xtype:"menucheckitem",itemId:"company",group:"sort_by",value:"company",text:String.format(SYNO.SDS.MailClient._T("sort","sort_by"),SYNO.SDS.MailClient._T("contact_detail","company"))},{xtype:"menucheckitem",itemId:"primary_mail",group:"sort_by",value:"email",text:String.format(SYNO.SDS.MailClient._T("sort","sort_by"),SYNO.SDS.MailClient._T("pop","email_address"))},{xtype:"menuseparator",itemId:"sep"},{xtype:"menucheckitem",itemId:"order_asc",group:"sort_order",checked:!0,value:"asc",text:SYNO.SDS.MailClient._T("sort","order_asc")},{xtype:"menucheckitem",itemId:"order_desc",group:"sort_order",value:"desc",text:SYNO.SDS.MailClient._T("sort","order_desc")}],listeners:{scope:this,itemclick:function(t){this.fireEvent("sortItemClick",t)}}}})];this.items=t,Ext.PagingToolbar.superclass.initComponent.call(this),this.addEvents("change","beforechange"),this.cursor=0,this.bindStore(this.store,!0)},_clickContactHandler:function(t){"server"!==this.windowType&&(this.prev.show(),this.next.show(),this.pageSortSep.show()),this.groupBtn.setText(t.text),this.sortBtn.menu.getComponent("name").show(),this.sortBtn.menu.getComponent("company").show(),this.sortBtn.menu.getComponent("primary_mail").show(),this.sortBtn.menu.getComponent("sep").show(),this.fireEvent("contactBtnClick",t.value)},_clickGroupHandler:function(t){"server"!==this.windowType&&(this.prev.hide(),this.next.hide(),this.pageSortSep.hide()),this.groupBtn.setText(t.text),this.sortBtn.menu.getComponent("name").hide(),this.sortBtn.menu.getComponent("company").hide(),this.sortBtn.menu.getComponent("primary_mail").hide(),this.sortBtn.menu.getComponent("sep").hide(),this.fireEvent("groupBtnClick",t.value)},bindStore:function(t,e){if(this.callParent(arguments),t&&t.lastOptions&&t.lastOptions.params){this.cursor=t.lastOptions.params.offset;var i=this.getPageData(),n=i.activePage,a=i.pages;this.prev.setDisabled(1==n),this.next.setDisabled(n==a)}},jumpPageByOffset:function(t){var e=this.getPageData().activePage,i=this.getPageData().pages;e+t<=1?this.moveFirst():e+t>=i?this.moveLast():this.doLoad(this.cursor+t*this.pageSize)},jumpPageHandler:function(t,e){var i=0;i=t===this.prev?-1*this.jumpOffset:t===this.next?this.jumpOffset:t.getText()-this.getPageData().activePage,this.jumpPageByOffset(i)},checkAll:function(){this.checkBtn.toggle(!0),this.checkBtn.removeClass("select-partial").addClass("select-all")},checkPartial:function(){this.checkBtn.toggle(!0),this.checkBtn.removeClass("select-all").addClass("select-partial")},checkNone:function(){this.checkBtn.toggle(!1),this.checkBtn.removeClass("select-all").removeClass("select-partial")},addGroupMenu:function(t){"server"===this.windowType?this._addGroupMenuForServerWindowType(t):this._addGroupMenuForNormalWindowType(t)},_addGroupMenuForNormalWindowType:function(t){if(this.firstGroupLoad&&(this.firstGroupLoad=!1,t)){var e=this.groupBtn.menu;0!==t.addressbook.length&&e.addItem({xtype:"menucheckitem",text:SYNO.SDS.MailClient._T("contact_group","all_addressbook"),value:"addressbook",group:"contact_group",checked:!0,handler:this._clickGroupHandler,scope:this}),0!==t.label.length&&e.addItem({xtype:"menucheckitem",text:SYNO.SDS.MailClient._T("search","all_labels"),value:"label",group:"contact_group",checked:!0,handler:this._clickGroupHandler,scope:this}),0!==t.ou.length&&e.addItem({xtype:"menucheckitem",text:SYNO.SDS.MailClient._T("contact_group","all_ou"),value:"ou",group:"contact_group",checked:!0,handler:this._clickGroupHandler,scope:this}),this._addMenuItems(e,t.addressbook),this._addMenuItems(e,t.label),this._addMenuItems(e,t.ou)}},_addMenuItems:function(t,e){0!==e.length&&(e.sort(function(t,e){return t.name>e.name?1:-1}),t.addItem(new Ext.menu.Separator),e.forEach(function(e){t.addItem({xtype:"menucheckitem",text:Ext.util.Format.htmlEncode(e.name),value:e.id,type:e.type,group:"contact_group",checked:!1,handler:this._clickContactHandler,scope:this})},this))},_addGroupMenuForServerWindowType:function(t){if(this.firstGroupLoad&&(this.firstGroupLoad=!1,t&&0!==t.length)){var e=this.groupBtn.menu;e.addItem({xtype:"menucheckitem",text:SYNO.SDS.MailClient._T("contact_group","all_group"),value:SYNO.SDS.MailClient.Define.allGroupId,group:"contact_group",checked:!0,handler:function(t){this.groupBtn.setText(t.text),this.fireEvent("groupBtnClick",t.value)},scope:this}),e.addItem(new Ext.menu.Separator),Ext.each(t,function(t){e.addItem({xtype:"menucheckitem",text:Ext.util.Format.htmlEncode(t.get("name")),value:t.id,group:"contact_group",checked:!1,handler:function(t){this.groupBtn.setText(t.text),this.fireEvent("contactBtnClick",t.value)},scope:this})},this)}},getStore:function(){return this.store},onLoadError:function(){this.rendered&&this.refresh&&this.refresh.enable&&this.refresh.enable()}}),Ext.define("SYNO.SDS.MailClient.Editor.Link.Window",{extend:"SYNO.SDS.MailClient.ModalWindow",constructor:function(t){this.module=t.module,this.owner=t.owner,this.callParent([this.fillConfig(t||{})])},fillConfig:function(t){var e={resizable:!1,title:SYNO.SDS.MailClient._T("tinymce","insert_edit_link"),height:200,width:540,layout:"fit",items:this.getFormPanel(t),buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({xtype:"syno_button",btnStyle:"blue",text:_T("common","ok"),handler:this.onApply,scope:this},{xtype:"syno_button",text:_T("common","cancel"),scope:this,handler:this.onCancel}),listeners:{scope:this,single:!0,beforeshow:function(){this.pluginVar.onlyText&&!Ext.isEmpty(this.pluginVar.initialText)&&this.linkPanel.onUrlCheck()},show:function(){this.linkPanel.linkUrl.focus(!0,300)}}};return Ext.apply(e,t)},getFormPanel:function(t){return Ext.isEmpty(this.linkPanel)&&(this.linkPanel=new SYNO.SDS.MailClient.Editor.Link.Panel({owner:this,data:t.data,pluginVar:t.pluginVar})),this.linkPanel},onApply:function(t){this.handleInsertLink(t),this.close()},handleInsertLink:function(t){var e=this.linkPanel.getForm(),i={data:{href:e.findField("link_url").getValue(),text:e.findField("link_text").getValue()}};this.onSubmitLink(i)}}),Ext.define("SYNO.SDS.MailClient.Editor.Link.Panel",{extend:"SYNO.ux.FormPanel",url:"",constructor:function(t){this.callParent([this.fillConfig(t||{})]),this.linkUrl.addEvents("afterpaste")},fillConfig:function(t){var e=t.data,i=t.pluginVar.onlyText;this.linkUrl=new SYNO.ux.TextField({xtype:"syno_textfield",cls:"syno-mc-insert-link-url-textfield",fieldLabel:SYNO.SDS.MailClient._T("composer","url"),name:"link_url",allowBlank:!1,enableKeyEvents:!0,value:Ext.isEmpty(e.href)?void 0:e.href,maxlength:8192,selectOnFocus:!0,listeners:{scope:this,keyup:this.onUrlCheck}});var n={labelWidth:150,fieldWidth:300,items:[this.linkUrl,{xtype:"syno_textfield",hidden:!i,cls:"syno-mc-insert-link-display-textfield",fieldLabel:SYNO.SDS.MailClient._T("composer","text_to_display"),value:Ext.isEmpty(e.text)?void 0:e.text,name:"link_text",allowBlank:!1,isDirty:!1,enableKeyEvents:!0,maxlength:8192,listeners:{scope:this,keyup:this.onTextKeyup}}],listeners:{scope:this,afterlayout:{fn:function(){this.linkUrl.getEl().dom.onpaste=this.onPaste.createDelegate(this),this.linkUrl.on("afterpaste",this.onUrlCheck.createDelegate(this))},single:!0}}};return Ext.apply(n,t)},onPaste:function(){Ext.defer(function(){this.linkUrl.fireEvent("afterpaste")},100,this)},onUrlCheck:function(t){var e=this.pluginVar.initialText,i=this.data,n=this.pluginVar.onlyText,a=this.getForm(),o=a.findField("link_url");this.url=o.getValue(),e||0!==i.text.length||!n||a.findField("link_text").isDirty||a.findField("link_text").setValue(this.url)},onTextKeyup:function(t){t.isDirty=!0}}),Ext.define("SYNO.SDS.MailClient.Editor.Table.Window",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.Editor.Table.Panel"],constructor:function(t){this.module=t.module,this.owner=t.owner,this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={resizable:!1,title:SYNO.SDS.MailClient._T("tinymce","adjust_table_size"),height:200,width:310,layout:"fit",items:this.getFormPanel(t),buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({xtype:"syno_button",btnStyle:"blue",text:_T("common","ok"),handler:this.onApply,scope:this},{xtype:"syno_button",text:_T("common","cancel"),handler:this.onCancel,scope:this}),listeners:{afterlayout:this.fillDefaultValue,scope:this}};return Ext.apply(e,t)},getFormPanel:function(t){return Ext.isEmpty(this.tablePanel)&&(this.tablePanel=new SYNO.SDS.MailClient.Editor.Table.Panel({owner:this})),this.tablePanel},fillDefaultValue:function(){var t=this.getFormPanel().getForm(),e=this.editor.dom.getStyle(this.tableElm,"width"),i=this.editor.dom.getStyle(this.tableElm,"height");t.findField("row_width").setValue(e),t.findField("col_height").setValue(i)},adjustTable:function(t){var e=this.getFormPanel().getForm(),i=e.findField("row_width").getValue(),n=e.findField("col_height").getValue();e.isValid()&&(Ext.isNumber(i)&&this.editor.dom.setStyle(this.tableElm,"width",i+"px"),Ext.isNumber(n)&&this.editor.dom.setStyle(this.tableElm,"height",n+"px"),this.editor.nodeChanged())},onApply:function(){this.adjustTable(),this.close()}}),Ext.define("SYNO.SDS.MailClient.Editor.Table.Panel",{extend:"SYNO.ux.FormPanel",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={labelWidth:120,fieldWidth:100,items:[{xtype:"syno_numberfield",width:100,fieldLabel:SYNO.SDS.MailClient._T("tinymce","row_width"),name:"row_width",allowBlank:!1,allowDecimals:!0,maxlength:6},{xtype:"syno_numberfield",width:100,fieldLabel:SYNO.SDS.MailClient._T("tinymce","column_height"),name:"col_height",allowBlank:!1,allowDecimals:!0,maxlength:6}]};return Ext.apply(e,t)}}),Ext.define("SYNO.SDS.MailClient.Editor.SuperBoxSelect",{extend:"SYNO.ux.SuperBoxSelect",extraDelimiterKey:[",",";"],statics:{toAddressDisplay:function(t,e){return e=!!e||void 0===e,'<div ext:qtip="'+Ext.util.Format.htmlEncode(t)+'" class="syno-ux-superboxselect-item-inner'+(e?"":" invalid")+'">'+t+"</div>"}},constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("newitem",this.onNewItem,this),this.mon(SYNO.SDS.MailClient.Switch,"editorcontentmousedown",function(t){!this.isDestroyed&&this.isExpanded()&&this.collapse()},this),this.highlights=[],this.fakeValue="",this.on("afterrender",function(t){t.dragZone=new SYNO.SDS.MailClient.Editor.SuperBoxSelectDragZone(t,{ddGroup:"superboxDDgroup",dropNotAllowed:"syno-mc-superbox-no-drop",dropAllowed:"syno-mc-superbox-drop"}),t.dropZone=new SYNO.SDS.MailClient.Editor.SuperBoxSelectDropZone(t,{ddGroup:"superboxDDgroup",dropNotAllowed:"syno-mc-superbox-no-drop",dropAllowed:"syno-mc-superbox-drop"})}),this.firefoxWatcher=new SYNO.SDS.MailClient.Editor.SuperBoxSelectFirefoxWatcher(this),this.firefoxWatcher.startTask()},destroy:function(){return this.firefoxWatcher.stopTask(),this.dragZone&&this.dragZone.destroy(),this.callParent(arguments)},fillConfig:function(t){var e={htmlEncode:!1,hidden:!0,emptyText:SYNO.SDS.MailClient._T("composer","receiver_empty_text"),maskRe:/[^,;]/,store:this.createStore(),minChars:1,mode:"local",queryParam:"keyword",displayField:"address_display",valueField:"address_value",searchField:"search_field",tpl:new Ext.XTemplate('<tpl for=".">','<div class="x-combo-list-item" ext:qtip="{combobox_display_encode:htmlEncode}">{combobox_display:htmlEncode}','<tpl if="values.members">','<tpl for="values.members">',"<span> {[Ext.util.Format.htmlEncode(SYNO.SDS.MailClient.Format.composeNameAddr(values.full_name, values.primary_mail))]},</span>","</tpl>","</tpl>","</div>","</tpl>",{}),triggerAction:"all",renderFieldBtns:!1,allowAddNewData:!0,addNewDataOnBlur:!0,navigateItemsWithTab:!1,listClass:"syno-ux-combobox-list syno-mc-editor-superbox-list",listWidth:500};return Ext.apply(e,t)},createStore:function(){return new Ext.data.JsonStore({autoDestroy:!0,root:"contact",idProperty:"id",totalProperty:"total",remoteSort:!0,fields:["id","full_name","primary_mail","mail","search_field","name_with_nickname","combobox_display","combobox_display_encode","address_value","address_encode","address_display","members","mail_for_search","type"],proxy:SYNO.SDS.MailClient.Switch.getAutoCompleteMemProxy()})},onRender:function(t,e){this.callParent(arguments),this.cursor=t.createChild({tag:"div",style:"position: absolute; width: 2px; height: 24px; z-index: 1; background: black;"},t.first()),this.cursor.hide(),this.el.on("paste",this.onPaste,this),this.fakeInput=t.createChild({tag:"input",style:"position: absolute; left: -99999px;",tabIndex:-1},t.first()),this.fakeInput.on("blur",this.onFakeInputBlur,this),this.fakeInput.on("keydown",this.onFakeInputKeyDown,this),this.fakeInput.on("cut",this.onFakeInputCut,this),this.fakeInput.keyMap=new Ext.KeyMap(this.fakeInput,[{key:[Ext.EventObject.BACKSPACE,Ext.EventObject.DELETE],fn:this.destroyHighlights,scope:this},{key:[Ext.EventObject.RIGHT,Ext.EventObject.DOWN],fn:this.moveHighlight.createDelegate(this,[1])},{key:[Ext.EventObject.LEFT,Ext.EventObject.UP],fn:this.moveHighlight.createDelegate(this,[-1])},{key:[Ext.EventObject.HOME],fn:this.setFirstHightlight,scope:this},{key:[Ext.EventObject.END],fn:this.setLastHighlight,scope:this},{key:[Ext.EventObject.TAB],fn:function(){this.el.focus()},scope:this}]),this.fakeInput.keyMap.stopEvent=!0;var i=this.findWindow();i!==this.findAppWindow()&&this.mon(i,"show",this.resizeItems,this,{single:!0})},onPaste:function(t){var e=window.clipboardData;if(e||(e=t.browserEvent.clipboardData)&&-1!==e.types.indexOf("text/plain")){t.preventDefault();var i=(this.el.dom.value+e.getData("text").trim()).split(/[,;\n]/);if(i.length){var n;for(n=0;n<i.length-1;n++)i[n]&&this.fireNewItemEvent(i[n]);var a=i[i.length-1];a&&(SYNO.SDS.MailClient.Format.isValidEmail(a)?(this.fireNewItemEvent(a),this.el.dom.value=""):this.el.dom.value=a)}}},setVisible:function(t){var e=this.callParent(arguments);return this.resizeItems(),e},onResize:function(t,e,i,n){var a=Ext.isIE6?4:Ext.isIE7?1:Ext.isIE8?1:0;this.wrapEl&&(t-=this.itemCt.getPadding("lr"),this._width=t,this.outerWrapEl.setWidth(t-a),this.renderFieldBtns&&(a+=this.buttonWrap.getWidth()+20,this.wrapEl.setWidth(t-a)),this.resizeItems()),SYNO.ux.SuperBoxSelect.superclass.onResize.call(this,t,e,i,n),this.autoSize()},resizeItems:function(){this.isVisible()&&(this.itemMaxWidth=this.wrapEl.getWidth()-38,this.items.each(function(t){t.el.setStyle("max-width",this.itemMaxWidth+"px")},this))},fireNewItemEvent:function(t){this.view&&this.view.clearSelections(),this.collapse(),this.setRawValue(""),this.queryFilterRe&&!(t=t.replace(this.queryFilterRe,""))||this.fireEvent("newitem",this,t,this.filteredQueryData)},onKeyUp:function(t){this.isDelimiterKeyEvent(t)||this.callParent(arguments)},onKeyDownHandler:function(t,e){t.stopPropagation();var i,n=this.el.dom.value,a=t.ctrlKey;if(this.isDelimiterKeyEvent(t)){if(t.stopEvent(),""!==n)a||!this.isExpanded()?this.fireNewItemEvent(n):(this.trimmedValue=n.trim(),this.onViewClick(),delete this.trimmedValue,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}return t.getKey()===t.HOME?!!this.el.dom.value||(t.stopEvent(),this.items.getCount()>0&&(this.collapse(),this.addHighlightByIdx(0)),!0):t.getKey()===t.LEFT||t.getKey()===t.UP&&!this.isExpanded()?!!this.el.dom.value||(t.stopEvent(),this.collapse(),this.items.getCount()>0&&this.addHighlightByIdx(this.items.getCount()-1),!0):t.getKey()===t.RIGHT?(this.el.dom.value||t.stopEvent(),!0):t.getKey()===t.BACKSPACE?!!this.el.dom.value||(t.stopEvent(),this.collapse(),i=this.items.get(this.items.getCount()-1),i&&!0!==i.disabled&&i.preDestroy(!0),!0):void this.callParent(arguments)},isDelimiterKeyEvent:function(t){var e=t.browserEvent.key;return-1!==this.extraDelimiterKey.indexOf(e)},onViewClick:function(t){var e,i=-1,n=this.store;if(this.trimmedValue){for(e=0;e<n.getCount();e++)if(this.trimmedValue===SYNO.SDS.MailClient.Format.toEmail(n.getAt(e).get(this.valueField))){i=e;break}}else i=this.view.getSelectedIndexes()[0];var a=n.getAt(i);if(a)if("contact"!==a.get("type")){this.store.clearFilter();var o=SYNO.SDS.MailClient.Switch.getContactByGroupData(a.get("id"));Ext.each(o,function(t){if(t.primary_mail){var e=SYNO.SDS.MailClient.Format.composeNameAddr(t.full_name,t.primary_mail);this.fireNewItemEvent(e)}},this),this.collapse()}else this.onSelect(a,i);else this.collapse();!1!==t&&this.el.focus()},doQuery:function(t,e,i,n){if(t=Ext.isEmpty(t)?"":t,Ext.isEmpty(t))return void this.collapse();var a={query:t,forceAll:e,combo:this,cancel:!1};if(!1===this.fireEvent("beforequery",a)||a.cancel)return!1;if(t=a.query,!0===(e=a.forceAll)||t.length>=this.minChars||i&&!Ext.isEmpty(t))if(n||this.forceSameValueQuery||this.shouldQuery(t))if(this.selectedIndex=-1,e)this.store.clearFilter(),this.onLoad();else{var o,s=this.searchField,l=this.usedRecords.keys,r=this.valueField,d=this.store.data.createValueMatcher(t,!0);o=t.indexOf("@")<0?function(t){return d.test(t.data[s])&&-1==l.indexOf(t.data[r])}:function(e){return d.test(e.data.name_with_nickname)||e.data.mail_for_search&&e.data.mail_for_search.startsWith(t)&&-1==l.indexOf(e.data[r])},this.store.load({params:{start:0,limit:100,filterFn:o}})}else this.selectedIndex=-1,this.onLoad()},expand:function(){this.callParent(arguments),this.list.setZIndex(this.getZIndex())},addItem:function(t,e){var i=t[this.valueField];if(this.disabled)return!1;if(!this.preventDuplicates||!this.hasValue(i)){var n=this.findRecord(this.valueField,i);if(n)return void this.addRecord(n);if(this.allowAddNewData){if(!e&&"remote"===this.mode)return this.remoteLookup.push(t),void this.doQuery(i,!1,!1,e);var a=this.createRecord(t);return a.isNew=!0,this.addRecord(a),!0}}},addRecord:function(t){var e=t.data[this.displayField],i=this.getCaption(t),n=t.data[this.valueField],a=this.classField?t.data[this.classField]:"",o=this.styleField?t.data[this.styleField]:"";this.removeValuesFromStore&&!t.isNew&&this.usedRecords.add(n,t),this.addItemBox(n,e,i,a,o),this.fireEvent("additem",this,n,t),this.fireEvent.defer(250,this,["valuechanged",this]),this.resizeItems()},markInvalidTip:function(t){Ext.each([this.el.dom,this.wrapEl.dom,this.outerWrapEl.dom],function(e){Ext.apply(e,{itip:t,iclass:"x-form-invalid-tip"})}),SYNO.ux.InvalidQuickTips&&SYNO.ux.InvalidQuickTips.enable()},convertAddrToUnicode:function(t){var e,i=SYNO.SDS.MailClient.Format,n=SYNO.SDS.MailPlusServer.Punycode.Converter;if(i.isNameAddr(t)){if(e=i.matchNameAddr(t))return i.composeNameAddr(e[1],n.toUnicode(e[2]))}else if(i.isAddrSpec(t))return n.toUnicode(t);return t},onNewItem:function(t,e){var i=this.convertAddrToUnicode(e.trim());if(i){var n=SYNO.SDS.MailClient.Format.isNameAddr(i),a=SYNO.SDS.MailClient.Format.isAddrSpec(i),o=!!n||!!a,s=Ext.util.Format.htmlEncode(i),l={name:n?n[0]:a?a[0]:i,primary_mail:i,mail:[o?SYNO.SDS.MailClient.Format.toEmail(i):i],additional:"",address_value:i,address_encode:s,address_display:SYNO.SDS.MailClient.Editor.SuperBoxSelect.toAddressDisplay(s,o)};t.addItem(l)}},addItemBox:function(t,e,i,n,a){var o,s=Ext.id(null,"sbx-item"),l=new SYNO.SDS.MailClient.Editor.SuperBoxSelectItem({owner:this,disabled:this.disabled,renderTo:this.wrapEl,cls:this.extraItemCls+" "+n,style:function(t){var e="";switch(typeof t){case"function":e=t.call();break;case"object":for(var i in t)t.hasOwnProperty(i)&&(e+=i+":"+t[i]+";");break;case"string":e=t+";"}return e}(this.extraItemStyle)+" "+a,caption:i,display:e,value:t,key:s,"aria-label":e,listeners:{remove:function(t){if(!1===this.fireEvent("beforeremoveitem",this,t.value))return!1;this.items.removeKey(t.key),this.removeValuesFromStore&&this.usedRecords.containsKey(t.value)&&(this.usedRecords.removeKey(t.value),this.sortStore(),this.view&&this.view.render()),this.preventMultipleRemoveEvents||(this.fireEvent.defer(250,this,["removeitem",this,t.value,this.findInStore(t.value)]),this.fireEvent.defer(250,this,["valuechanged",this]),this.fireEvent("valuechange",this))},destroy:function(){this.collapse(),this.autoSize().manageClearBtn(),this.validate()},scope:this}});l.render(),o={tag:"input",type:"text",name:this.hiddenName||this.name,style:"display:none","non-serialize":!0},this.disabled&&Ext.apply(o,{disabled:"disabled"}),SYNO.SDS.MailClient.Format.isDSM6()?(l.hidden=this.el.insertSibling(o,"before"),l.hidden.dom.value=t):(l.hiddenEl=this.el.insertSibling(o,"before"),l.hiddenEl.dom.value=t),this.items.add(s,l),this.applyEmptyText().autoSize().manageClearBtn(),this.validate()},addHighlight:function(t,e,i){var n,a,o=this.items.indexOf(t);if(-1!==o){var s=this.lastHighlight&&e;s?(a=this.items.indexOf(this.lastHighlight))>o&&(n=a,a=o,o=n):a=o;var l,r=-1===this.highlights.indexOf(t)||e;for(n=a;n<=o;n++)l=this.items.get(n),r&&-1===this.highlights.indexOf(l)?(this.highlights.push(l),l.onLnkFocus()):r||-1===this.highlights.indexOf(l)||(this.highlights.remove(l),l.onLnkBlur());s||(this.lastHighlight=t),this.updateFakeInput(i)}},removeHighlight:function(t){this.highlights.remove(t),t.onLnkBlur(),this.updateFakeInput()},clearHighlight:function(){var t;for(t=0;t<this.highlights.length;t++)this.highlights[t].onLnkBlur();this.highlights=[],this.fakeValue="",this.fakeInput.dom.value=""},moveHighlight:function(t){var e,i,n;if(1===t){for(n=-1,e=0;e<this.highlights.length;e++)(i=this.items.indexOf(this.highlights[e]))>n&&(n=i);n++}else{for(n=this.items.length,e=0;e<this.highlights.length;e++)(i=this.items.indexOf(this.highlights[e]))<n&&(n=i);if(0===n)return;n--}this.addHighlightByIdx(n)},setFirstHightlight:function(){this.addHighlightByIdx(0)},setLastHighlight:function(){var t=this.items.length-1;-1!==this.highlights.indexOf(this.items.get(t))&&t++,this.addHighlightByIdx(t)},addHighlightByIdx:function(t){this.clearHighlight(),this.items.get(t)?this.addHighlight(this.items.get(t)):this.el.focus()},destroyHighlights:function(t){var e;for(e=0;e<this.highlights.length;e++)this.highlights[e].preDestroy(!0);this.highlights=[],t||this.el.focus()},updateFakeInput:function(t){this.fireEvent("beforefocusfakeinput");var e,i=[];for(e=0;e<this.highlights.length;e++)i.push(this.highlights[e].value);this.fakeValue=i.join();var n=this.fakeInput.dom;n.value=this.fakeValue,t||(n.setSelectionRange(0,n.value.length),this.fakeInput.focus()),this.fireEvent("focusfakeinput")},onFakeInputBlur:function(){delete this.lastHighlight,this.clearHighlight()},onFakeInputKeyDown:function(t){var e=this.fakeInput.dom;-1===[Ext.EventObject.BACKSPACE,Ext.EventObject.DELETE,Ext.EventObject.RIGHT,Ext.EventObject.DOWN,Ext.EventObject.LEFT,Ext.EventObject.UP,Ext.EventObject.HOME,Ext.EventObject.END,Ext.EventObject.TAB].indexOf(t.getKey())&&function(){e.value=this.fakeValue,e.setSelectionRange(0,e.value.length)}.defer(10,this)},autoSize:function(){if(!this.rendered)return this;var t=this.el,e=t.dom.value,i=document.createElement("div");""===e&&this.emptyText&&this.items.getCount()<1&&(e=this.emptyText),i.appendChild(document.createTextNode(e)),e=i.innerHTML,i=null,e+="0";var n=Math.max(Ext.util.TextMetrics.measure(this.el,e,"auto",!1).width+4,4);return void 0!==this._width&&(n=Math.min(this._width,n)),Ext.isGecko&&(n+=16),this.el.setWidth(n),Ext.isIE&&(this.el.dom.style.top="0"),this.fireEvent("autosize",this,n),this},onFakeInputCut:function(){this.destroyHighlights.defer(50,this)}}),
Ext.define("SYNO.SDS.MailClient.Editor.SuperBoxSelectItem",{extend:"SYNO.ux.SuperBoxSelectItem",onRender:function(){this.callParent(arguments),this.el.on("mousedown",function(t){t.preventDefault()})},onElClick:function(t){var e=this.owner;e.clearCurrentFocus().collapse(),t.ctrlKey||t.shiftKey||e.clearHighlight(),e.addHighlight(this,t.shiftKey)},onLnkClick:function(t){this.owner.removeHighlight(this),this.callParent(arguments)},enableLnkListeners:function(){this.initialized&&this.disableAllListeners(),this.lnk.on("click",this.onLnkClick,this),this.initialized=!0},disableAllListeners:function(){this.el.removeAllListeners(),this.lnk.un("click",this.onLnkClick,this)},setupKeyMap:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.Editor.SuperBoxSelectDragZone",{extend:"Ext.dd.DragZone",constructor:function(t,e){this.cmp=t,this.callParent([t.container,e]),this.proxy.el.disableShadow()},getDragData:function(t){var e=t.getTarget("li");if(!e)return!1;delete this.draggedItem;var i;for(i=0;i<this.cmp.items.length;i++)if(this.cmp.items.get(i).el.dom===e){this.draggedItem=this.cmp.items.get(i);break}if(!this.draggedItem)return!1;var n=[],a=document.createElement("ul");if(-1===this.cmp.highlights.indexOf(this.draggedItem))this.clearHighlight=!0,n.push(this.draggedItem.value),a.appendChild(this.draggedItem.el.addClass("syno-ux-superboxselect-item-focus").dom.cloneNode(!0));else for(this.clearHighlight=!1,i=0;i<this.cmp.items.length;i++)-1!==this.cmp.highlights.indexOf(this.cmp.items.get(i))&&(n.push(this.cmp.items.get(i).value),a.appendChild(this.cmp.items.get(i).el.addClass("syno-ux-superboxselect-item-focus").dom.cloneNode(!0)));return{ddel:a,target:e,sourceCmp:this.cmp,data:n}},onInitDrag:function(t,e){return this.proxy.dropNotAllowed="syno-mc-superbox-no-drop",this.callParent(arguments)},startDrag:function(t,e){this.callParent(arguments),this.clearHighlight&&(this.cmp.clearHighlight(),this.cmp.addHighlight(this.draggedItem,!1,!0));var i,n;for(i=0;i<this.cmp.highlights.length;i++)n=this.cmp.highlights[i],n.dragged=!0,n.el.applyStyles("visibility: hidden;")},endDrag:function(t){this.callParent(arguments);var e,i;for(e=0;e<this.cmp.items.length;e++)i=this.cmp.items.get(e),i.dragged&&(i.dragged=!1,i.el.applyStyles("visibility: visible;"))},beforeDragOut:function(t,e,i){return!this.validateTarget(t,e,i)},getRepairXY:function(){return Ext.Element.fly(this.dragData.target).getXY()}}),Ext.define("SYNO.SDS.MailClient.Editor.SuperBoxSelectDropZone",{extend:"Ext.dd.DropZone",constructor:function(t,e){this.cmp=t,this.callParent([t.wrapEl,e])},getTargetFromEvent:function(t){return t.getTarget("ul")},onNodeEnter:function(t,e,i,n){this.nodeData=[];var a,o;for(a=0;a<this.cmp.items.length;a++)o=this.cmp.items.get(a).el,this.nodeData.push({left:o.getLeft(),top:o.getTop()-1,bottom:o.getBottom()+1,width:o.getWidth()+4});this.cmp.cursor.show()},onNodeOver:function(t,e,i,n){var a=i.getXY(),o=this.getOverItemIdx(a[0],a[1]);return this.overIdx!==o&&(this.overIdx=o,-1===o?this.cmp.cursor.alignTo(this.cmp.wrapEl,"tr-tl",[-1,0]):this.cmp.cursor.alignTo(this.cmp.items.get(o).el,"l-r",[1,0])),this.dropAllowed},onNodeOut:function(t,e,i,n){this.cmp.cursor.hide(),delete this.overIdx,this.clean()},onNodeDrop:function(t,e,i,n){var a=i.getXY(),o=this.getOverItemIdx(a[0],a[1],!0);n.sourceCmp.destroyHighlights(!0),this.cmp.clearHighlight();var s,l=[];for(s=o+1;s<this.cmp.items.length;s++)l.push(this.cmp.items.get(s));var r=[];for(s=0;s<l.length;s++)r.push(l[s].value),l[s].preDestroy(!0);var d=this.cmp.items.length;for(s=0;s<n.data.length;s++)this.cmp.fireNewItemEvent(n.data[s]);var c=this.cmp.items.length;for(s=0;s<r.length;s++)this.cmp.fireNewItemEvent(r[s]);for(s=d;s<c;s++)this.cmp.addHighlight(this.cmp.items.get(s));return this.clean(),!0},notifyEnter:function(t,e,i){return this.dropAllowed},notifyDrop:function(t,e,i){this.lastOverNode&&(this.skipClean=!0,this.onNodeOut(this.lastOverNode,t,e,i),this.skipClean=!1,this.lastOverNode=null);var n=this.getTargetFromEvent(e);return n?this.onNodeDrop(n,t,e,i):this.onContainerDrop(t,e,i)},getOverItemIdx:function(t,e,i){var n,a=-1;for(n=this.cmp.items.length-1;n>=0;n--)if(!this.cmp.items.get(n).dragged&&(e>this.nodeData[n].bottom||e>=this.nodeData[n].top&&t>this.nodeData[n].left+this.nodeData[n].width/2)){a=n;break}var o=0;if(i){for(n=0;n<=a;n++)this.cmp.items.get(n).dragged&&o++;a-=o}return a},clean:function(){this.skipClean||delete this.nodeData}}),Ext.define("SYNO.SDS.MailClient.Editor.SuperBoxSelectFirefoxWatcher",{extend:"Ext.util.TaskRunner",constructor:function(t){this.callParent(arguments),this._lastQueryVal="",this._owner=t,this._task={interval:200,run:function(){this._owner.autoSize();var t=this._owner.getRawValue();t!==this._lastQueryVal&&t&&this._owner.doQuery(t),this._lastQueryVal=t}.bind(this)}},startTask:function(){this._isEnable()&&this.start(this._task)},stopTask:function(){this._isEnable()&&this.stop(this._task)},_isEnable:function(){return Ext.isGecko}}),Ext.define("SYNO.SDS.MailClient.Editor.ComboBox",{extend:"SYNO.SDS.MailClient.ComboBox",autoFitText:!1,constructor:function(t){this.callParent([t]),this.mon(SYNO.SDS.MailClient.Switch,"editorcontentmousedown",function(t){!this.isDestroyed&&this.isExpanded()&&this.collapse()},this),this.on("show",function(){this.setWidthFitText(this.getValue())},this)},setValue:function(t){this.callParent(arguments),this.setWidthFitText(t)},setWidthFitText:function(t){if(this.el&&this.autoFitText){var e=Ext.util.TextMetrics.measure(this.el,Ext.util.Format.htmlEncode(t));this.setWidth(e.width+32)}}}),Ext.define("SYNO.SDS.MailClient.Editor.SelectContactPlugin",{extend:"Object",constructor:function(t){this.callParent(arguments),this.owner=t.owner,this.key=t.key},init:function(t){t.on("afterrender",function(){var e=t.label,i=Ext.get(document.createElement("span"));i.update(e.dom.textContent),e.update(""),i.on("click",this.openSelectWindow.createDelegate(this.owner.mailCmp[this.key])),e.appendChild(i)},this)},openSelectWindow:function(){new SYNO.SDS.MailClient.Editor.SelectContactWindow({owner:this.findWindow(),listeners:{scope:this,selectdone:function(t){t.each(function(t){if(Ext.isEmpty(t.primary_mail))return!0;t.address_value=SYNO.SDS.MailClient.Format.composeNameAddr(t.full_name,t.primary_mail),t.address_encode=Ext.util.Format.htmlEncode(t.address_value),t.address_display=SYNO.SDS.MailClient.Editor.SuperBoxSelect.toAddressDisplay(t.address_encode),this.addItem(t,!0)},this)}}}).open()}}),Ext.define("SYNO.SDS.MailClient.Editor.LevelEnum",{singleton:!0,NONE:0,MAIN_WIN_EMBEDDED:1,MAIN_WIN_POPOUT:2,NEW_WIN:3}),Ext.define("SYNO.SDS.MailClient.Editor.EditorPanel",{extend:"SYNO.ux.Panel",focusTarget:null,constructor:function(t){this.LevelEnum=SYNO.SDS.MailClient.Editor.LevelEnum,this.callParent([this.fillConfig(t)]),this.isWaked=!1,this.addEvents("initialize","contentchange"),window.e=this,window.to=this.mailCmp.to,window.cc=this.mailCmp.cc,window.bcc=this.mailCmp.bcc,this.changeTask=new Ext.util.DelayedTask(this.onDataChange,this),this.toCcBccValueChangeTask=new Ext.util.DelayedTask(this.adjTopHeightForToCcBccValueChange,this),[this.mailCmp.to,this.mailCmp.cc,this.mailCmp.bcc].forEach(function(t){this.relayEvents(t,["beforefocusfakeinput","focusfakeinput"])},this)},fillConfig:function(t){var e="SYNO.SDS.MailClient.Application",i=e+SYNO.SDS.Config.FnMap[e].config.version;this.isEmbedded=t.level===this.LevelEnum.MAIN_WIN_EMBEDDED,this.mailCmp={},this.copiedAttachments=[];var n=["syno_mc_fontselect","syno_fontsizeselect","textcolor","hr","syno_mc_lists","syno_mc_formupload","syno_mc_ddupload","syno_mc_sticker","syno_mc_collapse_reply","syno_mc_link","syno_mc_autolink","syno_mc_image","syno_mc_pastelink","syno_mc_tab","syno_mc_indent_outdent","syno_mc_blockquote","syno_mc_attachment_sharinglink","syno_mc_table"];this.isEmbedded&&n.push("syno_mc_autoresize"),this.ddupload=new SYNO.SDS.MailClient.Editor.DDUpload({owner:this,listeners:{scope:this,upload:function(t){this.ctrl.upload(t)},refresh:this.adjTinyMCESize,filechange:function(){this.changeTask.delay(0,null,null,["ddupload filechange"])}}}),this.tinymce=new SYNO.ux.TinyMCE({owner:this,mceConfig:{automatic_uploads:!1,images_dataimg_filter:Ext.emptyFn,paste_data_images:!0,plugins:n,synoPostfix:i,external_plugins:{syno_paste:"plugins/syno_mc_paste/plugin.min.js"},content_css:"webman/3rdparty/MailClient/js/tinymce_plugins/content_patch.css",toolbar:["syno_mc_fontselect syno_fontsizeselect forecolor backcolor bold italic underline strikethrough removeformat | ","alignleft aligncenter alignright alignjustify numlist bullist syno_mc_outdent syno_mc_indent hr | ","syno_mc_table syno_mc_link xxxtable syno_mc_image syno_mc_sticker syno_mc_formupload syno_mc_blockquote"].join(""),statusbar:!1,menubar:!1,browser_spellcheck:!0,convert_urls:!1,table_toolbar:!1,forced_root_block:"div",forced_root_block_attrs:SYNO.SDS.MailClient.Format.getTinyMCEDefaultStyle(!0),extended_valid_elements:["img[class|style|src|srcset|border=0|alt|title|width|height|align|onmouseover|onmouseout|cid|syno-mc-cid|syno-mc-copied-id|syno-mc-url|syno-mc-block-src|syno-mc-block-srcset|data-synomc-external|data-synomc-display]","a[href|target=_blank]","td[style|border|colspan|rowspan|headers|abbr|axis|scope|align|char|charoff|valign|nowrap|bgcolor|width|height]","source[id|accesskey|class|dir|lang|style|tabindex|title|src|srcset|type|media|sizes|syno-mc-block-src|syno-mc-block-srcset]","input[id|accesskey|class|dir|lang|style|tabindex|title|accept|altautocomplete|checked|dirname|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|list|max|maxlength|min|multiple|name|pattern|readonly|required|size|src|step|type|value|width|syno-mc-block-src]"].join(","),visual:!1,syno_mc_ddupload:{instance:this.ddupload},autoresize_min_height:t.mceConfig&&t.mceConfig.autoresize_min_height,autoresize_bottom_margin:0,syno_paste_format:!0,paste_retain_style_properties:"border border-collapse border-spacing border-top border-left border-bottom border-right width vertical-align padding",paste_webkit_styles:"all",syno_word_keep_all_format:!0,syno_paste_hide_external_img:SYNO.SDS.MailClient.Settings.enable_upload_external_image,owner:this,module:this},listeners:{scope:this,initialize:this.onTinyMCEInit,afterrender:function(){this.onMask(),this.isEmbedded&&this.mon(this.ownerCt.ownerCt.el,"mousewheel",this.onMessagePanelScroll,this)}}});var a={cls:"syno-mc-editor"+(this.isEmbedded?" embedded":""),layout:"form",tbar:this.createTbar(),items:[{itemId:"scrollWrap",xtype:"container",layout:"form",items:[this.createTopPanel(t),this.mailCmp.cc=this.createSuperBoxSelectConfig("cc"),this.mailCmp.bcc=this.createSuperBoxSelectConfig("bcc"),this.mailCmp.from=new SYNO.SDS.MailClient.Editor.ComboBox({itemId:"from",cls:"from-combo",tabindex:-1,fieldLabel:SYNO.SDS.MailClient._T("mail","sender"),hidden:!0,autoFitText:!0,store:new Ext.data.JsonStore({fields:["address","encode","id"],data:SYNO.SDS.MailClient.ComposerLib.Config.getSMTPData()}),value:SYNO.SDS.MailClient.ComposerLib.Draft.getFromAddr(t.refMsg),displayField:"address",valueField:"address",tpl:'<tpl for="."><div class="x-combo-list-item" ext:qtip="{encode:htmlEncode}">{address:htmlEncode}</div></tpl>',listeners:{scope:this,select:this.smtpChange}})]},this.mailCmp.subject=new SYNO.ux.TextField({itemId:"subject",ctCls:"subject-ct",itemCls:"subject-form-item",hidden:this.isEmbedded,hideLabel:!0,emptyText:SYNO.SDS.MailClient._T("composer","subject_empty_text"),enableKeyEvents:!0,listeners:{scope:this,keydown:function(t,e){e.stopPropagation()},blur:this.checkSubjectChange}}),this.tinymce],listeners:{afterlayout:function(t){t.fireEvent("contentchange")},afterrender:function(t){t.getEditor()&&t.ddupload&&t.ddupload.renderTo(t.getEditor().getBody())}}};return(this.isEmbedded||t.level===this.LevelEnum.NEW_WIN)&&(a.buttonAlign="left",a.buttons=[{xtype:"syno_button",itemId:"send_button",cls:"syno-mc-send",btnStyle:"blue",text:SYNO.SDS.MailClient._T("composer","send"),handler:this.clickSend.createDelegate(this,[])},{itemId:"includeAttachment",xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("composer","include_original_attachments"),hidden:!0,listeners:{scope:this,check:this.checkIncludeAttachment}},"->",this.syncStatus=new SYNO.ux.DisplayField({cls:"sync-status"}),"-",{xtype:"syno_button",cls:"syno-mc-discard",iconCls:"syno-mc-print-icon",tooltip:SYNO.SDS.MailClient._T("composer","discard"),handler:this.clickDiscard.createDelegate(this,[])}]),Ext.apply(a,t)},createTbar:function(){return new Ext.Toolbar({hidden:!0,items:[{xtype:"label",text:SYNO.SDS.MailClient._T("composer","draft_poped_out")},{xtype:"tbspacer"},{xtype:"label",cls:"popin-click",text:SYNO.SDS.MailClient._T("composer","draft_continue_edit_here"),listeners:{scope:this,afterrender:function(t){t.el.on("click",function(){this.ctrl.wakeEditor(this)},this)}}}]})},createTopPanel:function(t){return{itemId:"top",xtype:"syno_panel",layout:"border",cls:"top",items:[{itemId:"center",region:"center",xtype:"container",layout:"form",items:[this.mailCmp.toCcBcc=new Ext.form.DisplayField({cls:"toccbcc empty",value:SYNO.SDS.MailClient._T("composer","receiver_empty_text"),plugins:new SYNO.SDS.MailClient.Editor.SelectContactPlugin({owner:this,key:"to"}),fieldLabel:SYNO.SDS.MailClient._T("mail","receiver"),listeners:{scope:this,afterrender:function(t){t.label.addClass("syno-ux-item-label"),t.container.on("click",function(){this.switchFieldVisible("to",!0),this.mailCmp.cc.getValue()&&this.switchFieldVisible("cc",!0,!0),this.mailCmp.bcc.getValue()&&this.switchFieldVisible("bcc",!0,!0)}.createDelegate(this))}}}),this.mailCmp.to=this.createSuperBoxSelectConfig("to")]},{itemId:"east",region:"east",xtype:"container",items:[{xtype:"syno_button",cls:"cc-btn",tabIndex:-1,text:SYNO.SDS.MailClient._T("mail","copy"),scope:this,handler:function(){this.switchFieldVisible("to",!0,!0),this.switchFieldVisible("cc",!0)}},{xtype:"syno_button",cls:"bcc-btn",tabIndex:-1,text:SYNO.SDS.MailClient._T("mail","blind_copy"),scope:this,handler:function(){this.switchFieldVisible("to",!0,!0),this.switchFieldVisible("bcc",!0)}},{xtype:"displayfield",cls:"separator",hidden:!SYNO.SDS.MailClient.PGPSettings.enable_pgp},this.mailCmp.encrypt=Ext.create({xtype:"syno_button",cls:"pgp-btn pgp-encrypt",tabIndex:-1,enableToggle:!0,hidden:!SYNO.SDS.MailClient.PGPSettings.enable_pgp,tooltip:SYNO.SDS.MailClient._T("pgp","encrypt"),scope:this,handler:function(t){this.draftObj.willEncrypt=t.pressed}}),this.mailCmp.sign=Ext.create({xtype:"syno_button",cls:"pgp-btn pgp-sign",tabIndex:-1,enableToggle:!0,hidden:!SYNO.SDS.MailClient.PGPSettings.enable_pgp,tooltip:SYNO.SDS.MailClient._T("pgp","sign"),scope:this,handler:function(t,e){this.draftObj.willSign=t.pressed}}),{xtype:"displayfield",cls:"separator",hidden:!this.isEmbedded},{xtype:"syno_button",cls:"more-btn",tabIndex:-1,hidden:!this.isEmbedded,htmlEncode:!1,menu:{cls:"syno-mc-menu",items:[{text:SYNO.SDS.MailClient._T("composer","edit_subject"),handler:this.popOut.createDelegate(this,["subject"])},{text:SYNO.SDS.MailClient._T("composer","pop_out"),hidden:SYNO.SDS.MailClient.Define.isMessageMode,handler:this.popOut.createDelegate(this,[])}]}}],listeners:{scope:this,afterrender:this.adjTopEastWidth}}]}},popOut:function(t){SYNO.SDS.MailClient.Window.popOutWinManager.openComposer(this.draftRec,this.draftObj,t),this.subjectChanged&&this.ctrl.close()},createSuperBoxSelectConfig:function(t){var e={to:"receiver",cc:"copy",bcc:"blind_copy"},i=new SYNO.SDS.MailClient.Editor.SuperBoxSelect({plugins:new SYNO.SDS.MailClient.Editor.SelectContactPlugin({owner:this,key:t}),fieldLabel:SYNO.SDS.MailClient._T("mail",e[t])});return i.on({scope:this,valuechanged:this.onToCcBccValueChange}),i},beforeDestroy:function(){this.sendDataChange("before destroy in destroying"),this.callParent(arguments);var t=this.getEditor();Ext.isEmpty(t)||(Ext.EventManager.un(t.getDoc(),"mousemove",this.ddMouseMoveHandler),Ext.EventManager.un(t.getDoc(),"mouseup",this.ddMouseUpHandler)),this.dropTarget&&(this.dropTarget.unreg(),delete this.dropTarget),this.animateTask&&this.animateTask.cancel()},onResize:function(){this.callParent(arguments),this.adjTopHeight()},detectAndUploadImage:function(){return this.ddupload.detectAndUploadImage().then(function(t){return t&&this.onTinyMCEChange(),t}.bind(this))},onEditorChange:function(){return this.detectAndUploadImage().then(function(t){this.onTinyMCEChange()}.bind(this))},onTinyMCEInit:function(t,e){window.editor=this.getEditor();var i,n,a=e.schema.elements;for(i in a)a.hasOwnProperty(i)&&a[i].hasOwnProperty("attributes")&&(a[i].attributes["syno-mc-class"]={});this.mon(SYNO.SDS.MailClient.Switch,"settingchange",function(){this.getEditor().settings.forced_root_block_attrs=SYNO.SDS.MailClient.Format.getTinyMCEDefaultStyle(!0)},this),e.on("keyup",this.onTinyMCEChange.createDelegate(this)),e.on("change",this.onEditorChange.createDelegate(this)),e.on("focus",this.onTinyMCEFocus.createDelegate(this)),e.on("mousedown",this.onTinyMCEMouseDown.createDelegate(this));var o=e.getDoc();Ext.EventManager.on(o,"mousemove",this.ddMouseMoveHandler,this),Ext.EventManager.on(o,"mouseup",this.ddMouseUpHandler,this),this.addCustomMouseEvent(),this.draftRec.get("from")||this.draftRec.set("from",this.mailCmp.from.getValue());var s=this.draftRec.get("body"),l="";void 0===s&&(this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("error","ui")),s={}),Ext.isString(s)?l=s:Ext.isDefined(s.html)?l=s.html:Ext.isDefined(s.plain)&&(l=s.plain),this.isNew&&(l=SYNO.SDS.MailClient.ComposerLib.Draft.initNewDraftContent(l,this.isMailtoLink,this.mailCmp.from.getValue()),this.draftRec.set("subject",this.draftRec.get("subject").trim())),this.getEditor().setContent(l),this.draftRec.set("body",this.getEditor().getContent()),this.onUnmask(),SYNO.SDS.MailClient.Window.draftManager.open(this,this.draftRec.get("id"),this.draftObj),this.isWaked&&(this.focusTarget?this.switchFieldFocus(this.focusTarget):this.doScroll?"forward"===this.draftObj.replyType?(this.switchFieldVisible("subject",!0,!0),this.switchFieldVisible("to",!0)):(this.getEditor().iframeElement.focus(),this.getEditor().selection.setCursorLocation(this.getEditor().getBody())):this.isEmbedded||(this.switchFieldVisible("subject",!0,!0),this.switchFieldVisible("to",!0),this.mailCmp.cc.getValueEx().length&&this.switchFieldVisible("cc",!0,!0),this.mailCmp.bcc.getValueEx().length&&this.switchFieldVisible("bcc",!0,!0)),this.adjTopHeight()),this.draftRec.get("id")||(n=this.getEditor().getBody().querySelectorAll("img"),n.length>0&&this.draftObj.forceSave()),this.fireEvent("initialize")},addCustomMouseEvent:function(){if(this.isEmbedded){var t,e,i;if(Ext.isGecko)t="DOMMouseScroll",e="MouseEvents",i="initMouseEvent";else{if(!(Ext.isIE||Ext.isIE10||Ext.isIE11))return;t="mousewheel",e="MouseWheelEvent",i="initMouseWheelEvent"}var n=this,a=this.getEditor().getDoc();a.addEventListener(t,function(o){var s=[t,!0,!0,window,o.detail,0,0,0,0];s=Ext.isGecko?s.concat([o.ctrlKey,o.altKey,o.shiftKey,0,0,null]):s.concat([0,null,"",o.wheelDelta]);var l=document.createEvent(e);l[i].apply(l,s);var r=o.detail||-o.wheelDelta/120,d=a.documentElement;n.getEditor().settings.syno_mc_scroll?r>0&&d.scrollTop==d.scrollHeight-d.clientHeight?n.el.dom.dispatchEvent(l):r<0&&0===d.scrollTop&&n.el.dom.dispatchEvent(l):n.el.dom.dispatchEvent(l)})}},smtpChange:function(t,e,i,n){function a(t,e){if(t.hasClass(e))return!0;var i=t.getAttribute("syno-mc-class");return-1!==(Ext.isString(i)?i.split(" "):[]).indexOf(e)}if(!SYNO.SDS.MailClient.Settings.enable_signature)return void this.changeTask.delay(0,null,null,["smtpChange !enable_signature"]);var o,s,l,r=Ext.get(this.getEditor().getBody());for(o=0;o<r.dom.children.length&&(l=Ext.fly(r.dom.children[o]),!a(l,"syno-mc-forward-content"));++o)if(a(l,"syno-mc-signature")){s=r.dom.children[o];break}s&&(s.innerHTML=SYNO.SDS.MailClient.ComposerLib.Draft.getSignature(e.get("address"))),this.changeTask.delay(0,null,null,["smtpChange enable_signature"])},setDDPos:function(t){var e=this.getEditor(),i=e.getDoc(),n=e.getContentAreaContainer(),a=Ext.get(n.getElementsByTagName("iframe")[0]),o=i.documentElement.scrollTop||i.body.scrollTop,s=i.documentElement.scrollLeft||i.body.scrollLeft;t.xy=[a.getXY()[0]+t.xy[0]+s,a.getXY()[1]+t.xy[1]-o]},ddMouseMoveHandler:function(t){Ext.isEmpty(Ext.dd.DragDropMgr.dragCurrent)||(t.preventDefault(),this.setDDPos(t),Ext.dd.DragDropMgr.handleMouseMove(t))},ddMouseUpHandler:function(t){if(Ext.isEmpty(Ext.dd.DragDropMgr.dragCurrent))return!0;this.setDDPos(t),Ext.dd.DragDropMgr.handleMouseUp(t)},onTinyMCEFocus:function(){this.switchFieldVisible("to",!1),this.switchFieldVisible("cc",!1),this.switchFieldVisible("bcc",!1)},onTinyMCEMouseDown:function(){SYNO.SDS.MailClient.Switch.editorContentMouseDown(this),Ext.menu.MenuMgr.hideAll()},extractCopiedAttachment:function(t){var e=this.getEditor().getDoc(),i=document.location.origin,n="syno-mc-copied-id",a=0,o=[];Ext.each(e.querySelectorAll('img[syno-mc-cid][src^="'+i+'"]'),function(i){if(-1===Array.prototype.indexOf.call(t,i)){var s=i.src,l=s.substr(s.indexOf("?")+1,s.length-s.indexOf("?")),r=Ext.urlDecode(l),d={};if("SYNO.MailClient.Attachment"===r.api&&"download"===r.method&&r.content_id&&(r.id||r.md5)){var c,h=(new Date).getTime();do{c=h+"-"+a++}while(e.querySelectorAll("img["+n+'="'+c+'"]').length);i.setAttribute(n,c),i.removeAttribute("data-mce-src"),i.removeAttribute("data-mce-style"),d.cid=r.content_id.replace(/(^"|"$)/g,""),d.copied_id=c,r.id&&(d.id=parseInt(r.id,10)),r.md5&&(d.md5=r.md5.replace(/(^"|"$)/g,"")),o.push(d)}}},this),o.length&&(this.copiedAttachments=this.copiedAttachments.concat(o),this.changeTask.delay(0,null,null,["copy inline change"]))},getSubject:function(){return this.mailCmp.subject.getValue().trim()},checkSubjectChange:function(t){SYNO.SDS.MailClient.ComposerLib.Draft.isSameSubject(t.getValue(),this.draftRec.get("subject"))||(this.ctrl.handleSubjectChange(this),this.changeTask.delay(0,null,null,["checkSubjectChange"]),this.subjectChanged=!0)},onMessagePanelScroll:function(){if(this.getEditor()){var t=this.getEditor().theme.panel.find("menubutton"),e=this.getEditor().theme.panel.find("colorbutton");t.each(function(t){t.hideMenu()}),e.each(function(t){t.hidePanel()}),SYNO.SDS.MailClient.Window.stickerMenu&&SYNO.SDS.MailClient.Window.stickerMenu.hide()}},isAlive:function(){return!this.destroying&&!this.isDestroyed},canFireChange:function(){return this.isWaked&&this.isAlive()},onTinyMCEChange:function(){this.canFireChange()&&this.changeTask.delay(500,null,null,["tinymce change"])},sendDataChange:function(t){this.changeTask.cancel(),this.onDataChange(t)},onDataChange:function(t){this.canFireChange()&&this.fireEvent("datachange",this,t)},setValue:function(){var t,e=this.mailCmp.from,i=this.draftRec.get("from");Ext.isDefined(i)&&e.setValue(i);var n=this.mailCmp.subject,a=this.draftRec.get("subject");Ext.isDefined(a)&&n.setValue(a);var o,s,l,r,d,c,h,u,S,m,f,p=["to","cc","bcc"];for(o=0;o<p.length;o++){for(l=p[o],r=this.mailCmp[l],d=this.draftRec.get(l),c=[],s=0;s<d.length;s++)h=d[s],m=!0,u=S=h,SYNO.SDS.MailClient.Format.isNameAddr(h)?(u=h.substr(0,h.indexOf("<")).trim(),S=SYNO.SDS.MailClient.Format.toEmail(h)):SYNO.SDS.MailClient.Format.isAddrSpec(h)?u=h.substr(0,h.indexOf("@")):m=!1,f=Ext.util.Format.htmlEncode(h),c.push({name:u,mail:[S],primary_mail:S,additional:"",address_value:h,address_encode:f,address_display:SYNO.SDS.MailClient.Editor.SuperBoxSelect.toAddressDisplay(f,m)});r.setValueEx(c)}this.setTinyMCEContent(this.draftRec.get("body"));var g=this.draftRec.get("attachment");for(o=0;o<g.length;++o)this.addFile(g[o],!0);var b=this.draftRec.get("temp_attachment");for(o=0;o<b.length;++o)this.addFile(b[o],!0);for(t=this.draftObj.getUploadQueue(),o=0;o<t.length;o++)this.addFile(t[o],!0);this.mailCmp.encrypt.toggle(this.draftObj.willEncrypt),this.mailCmp.sign.toggle(this.draftObj.willSign)},setTinyMCEContent:function(t){var e=this.getEditor(),i="";Ext.isString(t)?i=t:Ext.isDefined(t.html)?i=t.html:Ext.isDefined(t.plain)&&(i=t.plain);var n=document.createElement("div");n.innerHTML=i,Ext.each(n.childNodes,function(t){"DIV"===t.tagName&&1===t.childNodes.length&&3===t.childNodes[0].nodeType&&String.fromCharCode(160)===t.childNodes[0].textContent&&(t.innerHTML="<br>")}),i=n.innerHTML,e.setContent(i),this.getEditor().undoManager.clear(),this.restoreTinyMCEBody()},restoreTinyMCEBody:function(){var t=this.getEditor().getBody(),e=t.parentNode;e.childNodes[1]!==t&&e.insertBefore(t,e.childNodes[1])},getData:function(){var t={};t.subject=this.mailCmp.subject.getValue(),t.from=this.mailCmp.from.getValue();var e,i,n,a,o=["to","cc","bcc"];for(e=0;e<o.length;e++)for(n=o[e],t[n]=[],a=this.mailCmp[n].getValueEx(),i=0;i<a.length;i++)Ext.isEmpty(a[i])||t[n].push(a[i].address_value);return t.body=this.getEditor().getContent(),t.attachment=this.getAttachments(),t.temp_attachment=this.getTempAttachments(),t.copied_attachment=SYNO.Util.copy(this.copiedAttachments),t},getSenderUploadLimit:function(){return this.draftObj.getSenderUploadLimit()},changeDraftId:function(t){var e,i,n=Ext.applyIf({id:t},this.draftRec.data),a=this.ownerCt.store;i=a?new this.ownerCt.store.recordType(n,n.id):new Ext.data.Record(n),e=this.draftRec,this.draftRec=i,a&&Ext.isFunction(this.ownerCt.replaceRec)&&this.ownerCt.replaceRec(e,i)},adjTopHeightForToCcBccValueChange:function(){this.adjTopHeight(),this.doLayout()},onToCcBccValueChange:function(){var t,e,i,n,a,o=["to","cc","bcc"],s=SYNO.SDS.MailClient.Format,l={},r=[];for(t=0;t<o.length;t++)for(i=this.mailCmp[o[t]].getValueEx(),e=0;e<i.length;e++)n=s.matchNameAddr(i[e].address_value)||s.isAddrSpec(i[e].address_value,!0),n?(a=n[1],l[a]=l[a]||0,l[a]++,r.push({name:a,full:i[e].address_value})):r.push({full:i[e].address_value});var d,c=[];for(t=0;t<r.length;t++)d=r[t],d.name?l[d.name]>1?c.push(Ext.util.Format.htmlEncode(d.full)):c.push(Ext.util.Format.htmlEncode(d.name)):c.push('<span class="invalid">'+Ext.util.Format.htmlEncode(d.full)+"</span>");c.length?this.mailCmp.toCcBcc.removeClass("empty"):(c.push(SYNO.SDS.MailClient._T("composer","receiver_empty_text")),this.mailCmp.toCcBcc.el.addClass("empty")),this.mailCmp.toCcBcc.setValue(c.join()),this.toCcBccValueChangeTask.delay(125),this.changeTask.delay(0,null,null,["onToCcBccValueChange"])},onEditorSync:function(t,e){var i=this.ownerCt.syncStatus?this.ownerCt:this;this.updateSyncStatus.apply(i,arguments)},updateSyncStatus:function(t,e){this.syncStatus["syncing"===t?"addClass":"removeClass"]("syncing2"),this.syncStatus["syncsuccess"===t?"addClass":"removeClass"]("success"),this.syncStatus["syncfailed"===t?"addClass":"removeClass"]("failed"),this.animateTask||(this.animateTask=new Ext.util.DelayedTask(function(){this.syncStatus.addClass("animate"),this.syncStatus.addClass("fade-out")},this)),this.syncStatus.el.dom.qtip="syncfailed"===t?e:"","syncsuccess"===t?this.animateTask.delay(2e3):(this.animateTask.cancel(),this.syncStatus.removeClass("animate"),this.syncStatus.removeClass("fade-out"))},clickSend:function(){var t=this.draftObj.getPublicKeyInfo(),e=t.unsatisfiedAddresses,i=function(){return this.draftObj.willEncrypt?0===t.publicKeys.length?new Promise(function(t,e){this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("pgp","empty_public_key"),function(t){e("empty publicKeys")},this)}.bind(this)):e.length>0?new Promise(function(t,i){this.findWindow().getMsgBox().confirm("",String.format(SYNO.SDS.MailClient._T("pgp","no_key_confirm"),e.join(", ")),function(e){"yes"===e?t():i("missing publicKeys")},this)}.bind(this)):Promise.resolve():Promise.resolve()}.bind(this),n=function(){return!this.draftObj.willSign||this.draftObj.isSenderHasPrivateKey()?Promise.resolve():new Promise(function(t,e){this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("pgp","empty_private_key"),function(t){e("missing privateKeys")},this)}.bind(this))}.bind(this),a=function(){return""!==this.mailCmp.subject.getValue()?Promise.resolve():new Promise(function(t,e){this.findWindow().getMsgBox().confirm("",SYNO.SDS.MailClient._T("composer","empty_subject_confirm"),function(i){"yes"===i?(this.sendDataChange("check subject"),t()):e("empty subject")},this)}.bind(this))}.bind(this);return Promise.resolve().then(i).then(n).then(a).then(function(t){this.sendDataChange("click send"),this.draftObj.send()}.bind(this)).catch(function(t){})},clickDiscard:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("composer","discard_confirm"),function(t){"yes"===t&&this.draftObj.discard()},this)},switchFieldVisible:function(t,e,i){var n=this.mailCmp[t].isVisible();if(Ext.isBoolean(e)&&e===n)return void(n&&-1!==["to","cc","bcc"].indexOf(t)&&!i&&this.switchFieldFocus(t));var a=!n;"to"===t||"from"===t?(this.mailCmp.to.setVisible(a),this.mailCmp.from.setVisible(a),this.mailCmp.toCcBcc.setVisible(!a)):this.mailCmp[t].setVisible(a),a&&-1!==["to","cc","bcc"].indexOf(t)&&!i&&this.switchFieldFocus(t),this.adjTopHeight(),this.doLayout()},switchFieldFocus:function(t){var e,i,n,a=this.getComponent("scrollWrap").el,o=a.dom,s=this.mailCmp[t].el.dom,l=s.currentStyle||window.getComputedStyle(s);!this.isEmbedded&&o.fleXdata&&o.fleXdata.scrollPosition[1][1]&&(e=o.fleXdata.scrollPosition[1][0],i=this.mailCmp[t].el.getOffsetsTo(a)[1]-parseInt(l.marginTop,10),n=o.offsetHeight-i-s.offsetHeight-parseInt(l.marginBottom,10),i<0?o.fleXcroll.setScrollPos(!1,e+i):n<0&&o.fleXcroll.setScrollPos(!1,e-n)),this.mailCmp[t].focus(!0,200)},adjTopEastWidth:function(){var t=0,e=this.getComponent("scrollWrap").getComponent("top"),i=e.getComponent("east");i.items.each(function(e){if(e.el&&e.el.dom){var i=e.el.dom,n=i.currentStyle||window.getComputedStyle(i);e.initialConfig.hidden||(t+=e.getWidth(),t+=parseInt(n.marginLeft,10)||0,t+=parseInt(n.marginRight,10)||0)}}),i.boxMinWidth=t+2,i.setWidth(i.boxMinWidth),this.adjTopWidth(),e.doLayout()},adjTopHeight:function(){var t=this.mailCmp.to.getHeight()||this.mailCmp.toCcBcc.getHeight();t+=4,this.getComponent("scrollWrap").getComponent("top").setHeight(t),this.adjTinyMCESize()},adjTopWidth:function(t){var e=t||this.getWidth()-this.el.getPadding("r"),i=this.getComponent("scrollWrap"),n=i.getComponent("top");i.setWidth(e),n.setWidth(e),this.mailCmp.toCcBcc.setWidth(e-i.getComponent("top").getComponent("east").getWidth()-105-12-24)},adjTinyMCESize:function(){if(!this.isEmbedded){var t,e,i=0,n=this.getComponent("scrollWrap"),a=n.items,o=this.tinymce.getEditor();for(e=0;e<a.length;e++)a.itemAt(e).itemCt?i+=a.itemAt(e).itemCt.getHeight():i+=a.itemAt(e).getHeight();var s=Math.round(this.getHeight()/2,0)-32-31;i=i>s?s:i,n.setHeight(i).updateScroller(),i=this.getHeight(),Ext.each(this.body.dom.childNodes,function(t){Ext.fly(t).hasClass("mce-tinymce")||(i-=t.offsetHeight)}),o&&o.initialized&&(t=Ext.get(o.getContainer()),i-=t.getMargins("tb")+t.getBorderWidth("tb")),this.tinymce.adjustEditorSize(this.tinymce,this.getWidth(),i)}},getEditor:function(){return this.tinymce.editor},focusEditor:function(){this.getEditor().focus()},addFile:function(t,e,i){this.ddupload.addFile(t,e,i)},addBigSizeFiles:function(t){this.ddupload.addBigSizeFiles(t)},getAttachments:function(){return this.ddupload.getAttachments()},getTempAttachments:function(){return this.ddupload.getTempAttachments()},checkIncludeAttachment:function(t,e){if(this.draftObj.canIncludeAttachment&&this.draftObj.refMsg&&Ext.isArray(this.draftObj.refMsg.attachment)&&"forward"!==this.draftObj.replyType){var i;for(i=0;i<this.draftObj.refMsg.attachment.length;i++)this.addFile(this.draftObj.refMsg.attachment[i],!1,!0);this.draftObj.canIncludeAttachment=void 0,(this.footer?this.fbar:this.ownerCt.fbar).getComponent("includeAttachment").hide(),this.changeTask.delay(0,null,null,["checkIncludeAttachment"])}},sleep:function(){for(this.sendDataChange("go to sleep"),this.isWaked=!1;this.ddupload.items[0];)this.ddupload.removeLabel(this.ddupload.items[0]);this.getTopToolbar().show(),this.body.setVisibilityMode(Ext.Element.DISPLAY).hide(),
this.footer&&this.footer.setVisibilityMode(Ext.Element.DISPLAY).hide(),Ext.fly(this.getEditor().getContainer()).setVisibilityMode(Ext.Element.DISPLAY).hide(),this.fireEvent("contentchange")},wake:function(){this.isWaked=!0;var t=this.draftRec.get("id");this.draftRec.data=SYNO.Util.copy(this.draftObj.newData),t&&this.draftRec.set("id",t),this.setValue(),this.ddupload.fireEvent("refresh"),this.getTopToolbar().hide(),this.body.show(),this.footer&&this.footer.show();var e=this.footer?this.fbar:this.ownerCt.fbar,i=e.getComponent("includeAttachment");i&&(this.draftObj.canIncludeAttachment&&this.draftObj.refMsg&&this.draftObj.refMsg.attachment.length&&"forward"!==this.draftObj.replyType?i.show():i.hide()),Ext.fly(this.getEditor().getContainer()).show(),this.adjTopEastWidth(),this.getEditor().execCommand("mceAutoResize"),this.restoreTinyMCEBody(),this.fireEvent("contentchange")},getMaskEl:function(){return this.isEmbedded||this.level===this.LevelEnum.NEW_WIN?this.el:this.findWindow().el},onMask:function(t,e){var i=this.getMaskEl();i.maskMsg=t||i.maskMsg,i.maskCls=e||i.maskCls,i.maskMsg||i.maskCls?i.mask(i.maskMsg||_T("common","loading"),i.maskCls||"x-mask-loading"):i.mask()},onUnmask:function(){var t=this.getMaskEl();this.draftObj&&this.draftObj.masked||this.el.masked||!this.tinymce.getEditor()||!this.tinymce.getEditor().initialized||(t.unmask(),delete t.maskMsg,delete t.maskCls)},onComposerMask:function(){this.getMaskEl().masked=!0,this.onMask()},onComposerUnmask:function(){this.getMaskEl().masked=!1,this.onUnmask()},onDraftMask:function(t,e){this.onMask(t||_T("common","loading"),e||"x-mask-loading")},onDraftUnmask:function(){this.onUnmask()},showInvalidDraftMsg:function(t){var e;for(e in t.invalid)if(t.invalid.hasOwnProperty(e)){if(!this.mailCmp[e].markInvalidTip)return;"empty"===t.invalid[e]?this.mailCmp[e].markInvalidTip(SYNO.SDS.MailClient._T("composer","bad_draft_field_empty")):"format"===t.invalid[e]&&this.mailCmp[e].markInvalidTip(_T("common","error_bademail")),this.switchFieldVisible(e,!0)}var i;i="empty"===t.invalidStr?SYNO.SDS.MailClient._T("composer","bad_draft_field_empty"):"format"===t.invalidStr?SYNO.SDS.MailClient._T("composer","bad_draft_format"):SYNO.SDS.MailClient._T("common","error_unknown"),this.findWindow().getMsgBox().alert("",i)},repairBody:function(t,e,i,n){this.ddupload.repairBody(t,e,i,n),this.changeTask.delay(0,null,null,["onDraftRepairBody"])},updateImage:function(t){this.ddupload.updateImage(t)},refreshInlineImage:function(){Ext.get(this.getEditor().getBody()).select("img[syno-mc-cid]").each(function(t){var e=t.getAttribute("src").split("?"),i=Ext.urlDecode(1==e.length?"":e[1]);i.download_token=SYNO.SDS.MailClient.Info.download_token,t.set({src:Ext.urlAppend(e[0],Ext.urlEncode(i))},!0)},this)}}),Ext.define("SYNO.SDS.MailClient.MessageComposer",{extend:"SYNO.ux.Panel",constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("scrollto","contentchange"),this.editors=[],this.on("added",function(){this.mon(this.ownerCt,"flexcrollinitdone",function(){this.ownerFlexcrollinitdone=!0,this.init()},this)},this),window.mc?window.mc2=this:window.mc=this},fillConfig:function(t){this.store=new Ext.data.JsonStore({autoDestroy:!0,fields:["id","from","subject","body_preview","attachment","arrival_time","star","read"]});var e={cls:"syno-mc-message-composer",items:[{itemId:"refwdButtons",xtype:"container",layout:"hbox",cls:"refwd-buttons",items:[this.createReFwdConfig("re","reply","reply"),{xtype:"displayfield",cls:"spacer",width:9},{xtype:"displayfield",width:8},this.createReFwdConfig("re-all","reply_all","reply_all"),{xtype:"displayfield",cls:"spacer",width:9},{xtype:"displayfield",width:1},this.createReFwdConfig("fwd","forward","forward")],listeners:{scope:this,resize:{buffer:110,fn:function(){this.getInnerWidth()>0&&this.getComponent("refwdButtons").setWidth(this.getInnerWidth())}}}}]};return Ext.apply(e,t)},createReFwdConfig:function(t,e,i){return{xtype:"container",cls:t,flex:1,html:'<div class="icon"></div><br>'+SYNO.SDS.MailClient._T("mail",e),listeners:{scope:this,afterrender:function(t){SYNO.SDS.MailClient.SMTP.smtp.length||(t.el.dom.qtip=SYNO.SDS.MailClient.Define.noMailServerSMTPHint),t.el.on("click",this.refwdLastMessage.createDelegate(this,[i]))}}}},arm:function(){this.hide()},disarm:function(){this.reset(),this.hide()},reset:function(){this.storeready=!1,this.removeAllEditors()},storeUpdate:Ext.emptyFn,loadMessage:function(t,e,i){t&&(this.show(),i?(this.store.add(i.getRange()),this.storeready=!0,this.init()):t.get("draft").length?this.setReFwdButtonsVisibility(!1):this.setReFwdButtonsVisibility(!0))},init:function(){if(this.ownerFlexcrollinitdone&&this.storeready){var t,e;for(t=0;t<this.store.getCount();t++)e=this.store.getAt(t),this.renderEditor(e);this.doLayout(),this.fireEvent("contentchange")}},resumeEditor:function(t,e,i){Ext.apply(t,{thread_id:i,id:e});var n=new this.store.recordType(t,e);this.store.add(n),this.renderEditor(n),this.setReFwdButtonsVisibility(),this.doLayout()},renderEditor:function(t,e,i,n){var a=new SYNO.SDS.MailClient.Editor.EditorPanel({composerPanel:this,level:SYNO.SDS.MailClient.Editor.LevelEnum.MAIN_WIN_EMBEDDED,border:!0,isNew:!t.get("id"),draftRec:t,replyType:e,refMsg:i,canIncludeAttachment:!0,doScroll:!!n,mceConfig:{autoresize_min_height:156}});return n&&this.mon(a,"initialize",function(){this.fireEvent("scrollto",a.id)},this),this.mon(a,"initialize",function(){this.setEditorMaxHeight(this.ownerCt.getHeight())},this),this.mon(a,"contentchange",this.onEditorContentChange,this),this.relayEvents(a,["beforefocusfakeinput","focusfakeinput"]),this.editors.push(a),this.add(a),a},onSwitchDeleteDrafts:function(t){var e,i;for(e=0;e<this.editors.length;e++)i=this.editors[e],-1===t.indexOf(i.draftRec.get("id"))||i.preventDelete||this.removeEditor(i)},onEditorContentChange:function(){this.fireEvent("contentchange")},replaceRec:function(t,e){var i,n,a=[this.store,this.ownerCt.draftStore];for(i=0;i<a.length;i++)-1!==(n=a[i].indexOf(t))&&(a[i].remove(t),a[i].insert(n,e))},removeEditor:function(t){var e=this.editors.indexOf(t);-1!==e&&(this.store.remove(t.draftRec),this.remove(t,!0),this.editors.splice(e,1),this.setReFwdButtonsVisibility(),this.doLayout(),this.fireEvent("contentchange"))},removeAllEditors:function(){this.store.removeAll();var t;for(t=0;t<this.editors.length;t++)this.remove(this.editors[t],!0);this.editors=[],this.doLayout(),this.fireEvent("contentchange")},refwdLastMessage:function(t){var e,i=this.ownerCt.getComponent("messageList").store;if(!i||0===i.getCount())return void SYNO.SDS.MailClient.Window.getMsgBox().alert({code:400},_T("error","error_error_system"));e=i.getAt(i.getCount()-1),this.refwdMessage(t,e)},refwdMessage:function(t,e){SYNO.SDS.MailClient.DraftLib.DraftManager.canOpenDraft()&&e&&e.get("message_status")!==SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT&&(e.get("body").truncated?(this.findAppWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.getMessage({id:[e.get("id")],additional:["blockquote"]}).then(function(e){if(this.findAppWindow().clearStatusBusy(),0===e.message.length)return void SYNO.Debug.warn("resp.message.length === 0");e.message[0]=SYNO.SDS.MailClient.Format.formatAddrsOfMsgToNormal(e.message[0]),this.createDraft(t,e.message[0])}.bind(this)).catch(function(t){SYNO.Debug.warn("getMessage failed"),this.findAppWindow().clearStatusBusy()}.bind(this))):this.createDraft(t,e.data))},createDraft:function(t,e){var i=this.getDataFromRefMessage(t,e),n=new Ext.data.Record(i);this.store.add(n),this.renderEditor(n,t,e,!0),this.setReFwdButtonsVisibility(),this.doLayout(),this.fireEvent("contentchange")},setReFwdButtonsVisibility:function(t){var e=Ext.isDefined(t)?t:!this.store.getCount(),i=this.ownerCt.msgStore,n=e&&i.getAt(i.getCount()-1).get("message_status")===SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT;this.getComponent("refwdButtons").setVisible(e),this.getComponent("refwdButtons")[e&&n?"addClass":"removeClass"]("disable")},getDataFromRefMessage:function(t,e){function i(t){return SYNO.SDS.MailClient.Format.toEmail(t).toLowerCase()}var n,a=SYNO.SDS.MailClient.ComposerLib.Draft.removePrefix(e.subject);"reply"===t||"reply_all"===t?n="Re: ":"forward"===t&&(n="Fwd: "),a=n+a.trim();var o,s=SYNO.SDS.MailClient.ComposerLib.Config.getSMTPData(),l={},r=SYNO.SDS.MailClient.ComposerLib.Draft.getFromAddr(e),d=[],c=[];s.forEach(function(t){l[i(t.address)]=!0}),"reply"!==t&&"reply_all"!==t||(!function(t){return l.hasOwnProperty(i(t))}(e.from)?(e.rfc_reply_to?d=d.concat(e.rfc_reply_to):d.push(e.from),o=e.to.concat(e.cc)):(1===e.to.length?d.push(e.to[0]):d=d.concat(e.to.filter(function(t){return SYNO.SDS.MailClient.Format.isValidEmail(t)&&i(t)!==i(r)})),o=e.cc)),"reply_all"===t&&(c=c.concat(o.filter(function(t){return SYNO.SDS.MailClient.Format.isValidEmail(t)&&i(t)!==i(r)})));var h=this.processBody(t,e),u=[];return"forward"===t&&(u=SYNO.Util.copy(e.attachment)),{subject:a,to:d,cc:c,bcc:[],body:h,attachment:u}},plain2html:function(t){var e=Ext.util.Format.htmlEncode(t);return"<pre>"+(e=Ext.util.Format.nl2br(e))+"</pre>"},processBody:function(t,e){var i,n,a,o,s,l=e.body.html;return Ext.isEmpty(l)&&(l=this.plain2html(e.pgp_decrypted||e.body.plain)),o=Ext.util.Format.date(new Date(1e3*e.arrival_time),"Y-m-d H:i"),i=document.createElement("div"),"reply"===t||"reply_all"===t?(s=document.createElement("div"),s.className="syno-mc-reply-content",a=document.createElement("div"),a.innerHTML=Ext.util.Format.htmlEncode(String.format(SYNO.SDS.MailClient._T("composer","template_reply"),o,e.from)),s.appendChild(a),n=document.createElement("blockquote"),n.innerHTML=l,n.setAttribute("style","padding-left: 5px; margin-left: 5px; border-left: #c8d2dc 2px solid"),n.setAttribute("class","syno-mc-blockquote"),s.appendChild(n),i.appendChild(s)):"forward"===t&&(i.innerHTML=l,a=document.createElement("div"),a.className="syno-mc-forward-content",a.innerHTML=SYNO.SDS.MailClient._T("composer","template_forward")+"<br>"+this.formatForwardField("mail","sender",e.from)+"<br>"+this.formatForwardField("mail","date",o)+"<br>"+this.formatForwardField("mail","subject",e.subject)+"<br>"+this.formatForwardField("mail","receiver",e.to.join(", "))+(e.cc.length?"<br>"+this.formatForwardField("mail","copy",e.cc.join(", ")):""),i.childNodes.length&&i.insertBefore(document.createElement("div"),i.childNodes[0]),i.insertBefore(a,i.childNodes[0])),Ext.get(i).select("blockquote[syno-mc-blockquote]").each(function(t){var i=t.getAttribute("syno-mc-blockquote");if(!Ext.isEmpty(i)){var n=document.createElement("div"),a=Ext.fly(n);n.innerHTML=e.body.blockquote[parseInt(i,10)],t.replaceWith(a)}},this),{html:i.innerHTML,plain:i.textContent}},formatForwardField:function(t,e,i){return Ext.util.Format.htmlEncode(SYNO.SDS.MailClient._T(t,e)+_T("common","colon")+" "+i)},setEditorMaxHeight:function(t){var e,i,n=t-165-100;for(e=0;e<this.editors.length;e++)(i=this.editors[e].getEditor())&&(i.settings.autoresize_max_height=n,i.execCommand("mceAutoResize",void 0,void 0,{skip_focus:!0}))},adjComponentSize:function(t,e){var i;for(this.setEditorMaxHeight(e),i=0;i<this.editors.length;i++)this.editors[i].adjTopWidth(),this.editors[i].adjTopHeight()},onShortCutReFwd:function(t){if(this.getComponent("refwdButtons").isVisible())return this.refwdLastMessage(t),!0}}),Ext.define("SYNO.SDS.MailClient.MessageSelection",{extend:"Ext.Container",maxButtonWidth:160,constructor:function(t){var e,i,n=SYNO.SDS.MailClient.Settings.conversation_view;SYNO.SDS.MailClient.Define.isMessageMode?(e=SYNO.SDS.MailClient._T("mail","conversation_no_longer_exist"),i=SYNO.SDS.MailClient._T("common","close_tab")):(e=SYNO.SDS.MailClient._T("mail",n?"no_conversation_selected":"no_message_selected"),i=SYNO.SDS.MailClient._T("common","clear_selected_conversation")),this.noSelectedString=t.noSelectionString||e,t.actionButton?this.actionButton=t.actionButton:this.actionButton=[],Ext.each(this.actionButton,function(t){t.on("afterrender",function(t){var e=Ext.util.TextMetrics.measure(t.el.child("button"),t.text),i=e.width+30;i>this.maxButtonWidth&&(this.maxButtonWidth=i)},this)},this);var a={cls:"syno-mc-message-selection",buttonLayout:2,forceLayout:!0,items:[{xtype:"container",cls:"syno-mc-message-selection-inner",itemId:"inner",items:[{xtype:"container",itemId:"emptyIcon",cls:"syno-mc-empty-icon",items:{xtype:"container",cls:"selection-text",itemId:"selectionText",hidden:!0,html:"0"}},{xtype:"box",cls:"no-selection-text",itemId:"noSelectionText",html:this.noSelectedString},{xtype:"box",cls:"clear-selection-text",itemId:"clearSelectionText",hidden:!0,html:i,listeners:{scope:this,afterrender:function(t){t.el.on("click",function(){this.fireEvent("clickclearselection")},this)}}},{xtype:"container",itemId:"actionCt",cls:"action-ct",hidden:!0,hideMode:"visibility",forceLayout:!0,items:this.actionButton}]}]};this.callParent([Ext.apply(a,t)]),this.addEvents("clickclearselection"),this.on("resize",this.resize,this)},arm:Ext.emptyFn,disarm:function(){this.updateSelectionText(0),this.setVisible(!0)},resize:function(t,e,i,n,a,o){var s,l=this.getComponent("inner"),r=l.getComponent("actionCt");e<this.maxButtonWidth*this.buttonLayout+20?r.setWidth(this.maxButtonWidth+8*this.buttonLayout):r.setWidth((this.maxButtonWidth+8+2)*this.buttonLayout),s=.3*(i-l.getHeight()),l.el.setTop(s)},setAllButtonWidth:function(t){Ext.each(this.actionButton,function(e){e.setWidth(t)},this)},checkButtonWidth:function(){Ext.each(this.actionButton,function(t){var e=t.getWidth();e>this.maxButtonWidth&&(this.maxButtonWidth=e,this.setAllButtonWidth(this.maxButtonWidth))},this)},updateSelectionText:function(t,e){var i=this.getComponent("inner").getComponent("emptyIcon").getComponent("selectionText"),n=this.getComponent("inner").getComponent("actionCt"),a=this.getComponent("inner").getComponent("clearSelectionText"),o=this.getComponent("inner").getComponent("noSelectionText");if(i.rendered){if(!SYNO.SDS.MailClient.Define.isNormalMode)return void a.setVisible(!t);this.setAllButtonWidth(this.maxButtonWidth),i.update(t.toString()),o.update(e||this.noSelectedString),i.setVisible(t),o.setVisible(!t),a.setVisible(t),n.setVisible(t)}}}),Ext.define("SYNO.SDS.MailClient.MessageNotify",{extend:"Ext.Container",constructor:function(t){this.callParent([this.fillConfig(t)]),window.mn?window.mn2=this:window.mn=this},fillConfig:function(t){var e={keep:!1,keepTime:2e3,cls:"link-font notify",hidden:!0,listeners:{scope:this,afterrender:{single:!0,fn:function(){this.mon(this.renderCmp,"resize",function(){this.isVisible()&&this.align()},this,{buffer:250}),Ext.isFunction(t.handler)&&this.el.on("click",t.handler,t.scope||this)}},hide:function(t){t.el.applyStyles("opacity: 0; filter: Alpha(opacity=0);")}}};return Ext.apply(e,t)},align:function(){var t=this.alignOffset||[0,0],e=this.renderCmp.body;this.el.alignTo(e,"t-t",t)},animShow:function(){this.show(),this.align(),this.el.animate({opacity:{to:1}},.5,void 0,"easeOut","run")},animHide:function(){this.el.animate({opacity:{to:0}},.5,function(){this.taskIsExpired()&&this.hide()}.createDelegate(this),"easeOut","run")},taskRefresh:function(){this.taskRefreshTime=(new Date).getTime()},taskIsExpired:function(){return!this.keep&&this.keepTime<(new Date).getTime()-this.taskRefreshTime},taskStart:function(){this.taskRunner=this.taskRunner||new Ext.util.TaskRunner,this.taskStop(),this.taskRunner.start({scope:this,interval:200,run:function(){this.taskIsExpired()&&(this.taskStop(),this.hideNotify())}})},taskStop:function(){this.taskRunner&&this.taskRunner.stopAll()},showNotify:function(t,e){this.rendered||this.render(this.renderCmp.el),(this.keep=!!e)?this.taskStop():(this.taskRefresh(),this.taskStart()),this.el.dom.innerHTML=t,this.animShow()},showNotifyText:function(t,e){this.showNotify(Ext.util.Format.htmlEncode(t),e)},hideNotify:function(t){if(this.keep=!1,this.rendered)return t?(this.taskStop(),void this.hide()):void this.animHide()}}),Ext.define("SYNO.SDS.MailClient.Model.BaseThreadProvider",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition"],constructor:function(t){var e={};this.callParent([Ext.apply(e,t)]),this.initThreadProvider()},initThreadProvider:function(){},getThreadLists:function(t){var e,i=SYNO.SDS.MailClient.Switch,n=SYNO.SDS.MailClient.Define,a=SYNO.SDS.MailClient.WebAPI;return e=t.map(function(t){return{apiType:"listThread",params:{condition:t.condition.toWebAPIParams(),offset:t.offset,limit:t.limit,additional:i.inMailboxId===n.sentId?["with_recipient"]:[]},callback:t.callback}}.bind(this)),0===e.length?Promise.resolve([]):a.send(e,{mode:"parallel"}).then(function(t){var e,i=t.parsedResp,n=[];for(e=0;e<i.length;++e)i[e].resp.thread=SYNO.SDS.MailClient.Format.formatAddrsOfThreadsToNormal(i[e].resp.thread),n.push(i[e]);return n})},getThreadList:function(t,e,i){var n=SYNO.SDS.MailClient.Switch,a=SYNO.SDS.MailClient.Define;return SYNO.SDS.MailClient.WebAPI.send("listThread",{condition:t.toWebAPIParams(),offset:e,limit:i,additional:n.inMailboxId===a.sentId?["with_recipient"]:[]})}}),Ext.define("SYNO.SDS.MailClient.Model.ThreadProvider",{extend:"SYNO.SDS.MailClient.Model.BaseThreadProvider",singleton:!0,constructor:function(t){var e={};this.callParent([Ext.apply(e,t)]),this.initThreadProvider()},initThreadProvider:function(){}}),Ext.define("SYNO.SDS.MailClient.UtilLib.Deferred",{extend:"Ext.util.Observable",requires:[],constructor:function(t){this.callParent(arguments),this.promise=new Promise(function(t,e){this._resolve=t,this._reject=e}.bind(this)),this.status="pending"},isPending:function(){return"pending"===this.status},isResolved:function(){return"resolved"===this.status},isRejected:function(){return"rejected"===this.status},resolve:function(t){this.status="resolved",this.value=t,this._resolve.call(this.promise,t)},reject:function(t){this.status="rejected",this.value=t,this._reject.call(this.promise,t)},then:function(t,e){return this.promise.then(t,e)},catch:function(t){return this.promise.catch(t)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Fetcher",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Model.ThreadProvider","SYNO.SDS.MailClient.UtilLib.Deferred"],singleton:!0,constructor:function(t){this.callParent(arguments),this.Provider=SYNO.SDS.MailClient.Model.ThreadProvider,this.aggregateInterval=0,this.waitingQueue=[],this.runningQueue=[],this.runTask=new Ext.util.DelayedTask(this._run.bind(this))},get:function(t,e,i){var n;return n=e?this._push([],t,i):this._push(t,[],i),this.runTask.delay(this.aggregateInterval),n},_get:function(t,e,i){var n=SYNO.SDS.MailClient.WebAPI,a=[];return i=i||[],t.length>0&&a.push({apiType:"getMessageWithoutExtImg",params:t}),e.length>0&&a.push({apiType:"getMessageWithExtImg",params:e}),i.length>0&&a.push({apiType:"getDraft",params:{id:i}}),n.send(a).then(this._handleWebAPIResp.bind(this)).catch(this._handleWebAPIError.bind(this))},_handleWebAPIResp:function(t){var e=t.parsedResp,i=this.runningQueue,n=[],a=[],o=[];e.getMessageWithoutExtImg&&e.getMessageWithoutExtImg.succ&&(n=SYNO.SDS.MailClient.Format.formatAddrsOfMsgsToNormal(e.getMessageWithoutExtImg.resp.message)),e.getMessageWithExtImg&&e.getMessageWithExtImg.succ&&(a=SYNO.SDS.MailClient.Format.formatAddrsOfMsgsToNormal(e.getMessageWithExtImg.resp.message)),e.getDraft&&e.getDraft.succ&&(o=SYNO.SDS.MailClient.Format.formatAddrsOfMsgsToNormal(e.getDraft.resp.draft)),i.forEach(function(t){var e=n.filter(function(e){return-1!==t.msgIds.indexOf(e.id)}),i=a.filter(function(e){return-1!==t.msgWithExtImgIds.indexOf(e.id)}),s=o.filter(function(e){return-1!==t.draftIds.indexOf(e.id)});t.deferred.resolve([e,i,s])},this)},_handleWebAPIError:function(t){this.runningQueue.forEach(function(e){e.deferred.reject(t)},this)},_run:function(){var t,e,i,n;return this.runningQueue.length>0?void this.runTask.delay(100):(this.runningQueue=this.waitingQueue,this.waitingQueue=[],t=this.runningQueue,e=this._queueToIds(t,"msgIds"),n=this._queueToIds(t,"msgWithExtImgIds"),i=this._queueToIds(t,"draftIds"),this._get(e,n,i).then(function(t){return this.runningQueue=[],t}.bind(this)).catch(function(t){SYNO.Debug.error("Fetcher webapi failed",t),this.runningQueue=[]}.bind(this)))},_queueToIds:function(t,e){var i,n;return i=t.map(function(t){return t[e]}),n=[].concat.apply([],i),n=Ext.unique(n)},_push:function(t,e,i){var n=new SYNO.SDS.MailClient.UtilLib.Deferred;return this.waitingQueue.push({msgIds:t,msgWithExtImgIds:e,draftIds:i,deferred:n}),n},_delay:function(t,e){return t.then(function(t){return new Promise(function(i,n){window.setTimeout(function(){i(t)},e)})})}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.CacheCollection",{extend:"Ext.util.MixedCollection",requires:[],constructor:function(t){this.callParent(arguments)},item:function(t){var e=this.map[t],i=e;return"function"!=typeof i||this.allowFunctions?i:null},get:function(t){return this.item(t)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.LRUCacheCollection",{extend:"SYNO.SDS.MailClient.MessageHouseLib.CacheCollection",requires:[],constructor:function(t){this.callParent(arguments),this.accessTimeTable={},this.usedSize=0,this.GCCountThreshhold=t.GCCountThreshhold||500,this.GCSizeThreshhold=t.GCSizeThreshhold||104857600,this.GCCount=t.GCCount||200},get:function(t){return this.updateAccessTable(t),this.callParent(arguments)},replace:function(t,e){var i=this.item(t);this.callParent(arguments),this.updateAccessTable(t),this.updateUsedSize(i,e),this.isNeedGC()&&this.GC()},removeKey:function(t){var e=this.callParent(arguments);this.removeAccessTable(t),this.updateUsedSize(e)},updateUsedSize:function(t,e){t&&(this.usedSize-=Ext.encode(t).length),e&&(this.usedSize+=Ext.encode(e).length)},updateAccessTable:function(t){this.accessTimeTable[t]=+new Date},removeAccessTable:function(t){delete this.accessTimeTable[t]},isNeedGC:function(){return this.getCount()>this.GCCountThreshhold||this.usedSize>this.GCSizeThreshhold},GC:function(){var t,e,i,n=this.accessTimeTable;t=Object.keys(n).map(function(t){return[t,n[t]]}),t.sort(function(t,e){return t[1]-e[1]}),e=t.slice(0,this.GCCount),i=e.map(function(t){return parseInt(t[0],10)}),i.forEach(function(t){this.removeKey(t),delete n[t]},this)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.CachePreprocessor",{extend:"Ext.util.Observable",singleton:!0,requires:[],constructor:function(t){this.callParent(arguments)},processMessageCalendarInfo:function(t){function e(t){return"text/calendar"===t.mimetype&&Ext.isEmpty(t.name)}function i(t){return"application/ics"===t.mimetype||"text/calendar"===t.mimetype&&!Ext.isEmpty(t.name)}function n(t){return e(t)||i(t)}t.calendar_attachment=t.attachment.filter(n),t.attachment=t.attachment.filter(function(t){return!e(t)})},processMessage:function(t){this.processMessageCalendarInfo(t)},processMessageResp:function(t,e,i,n){t&&e.message.forEach(this.processMessage,this)},getHighlightKeywords:function(){var t,e=SYNO.SDS.MailClient.Switch.getRegister("lastSplitKeyword"),i=SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition"),n=[],a=/((?=[\x00-\x7F])\W)+/;return Ext.isEmpty(e)?i&&Ext.isArray(i.conditions)&&(i.conditions.forEach(function(e){"keyword"===e.name&&(t=e.value)}),Ext.isEmpty(t)||(n=t.match(/([\w]+|[^\x00-\x7F]+)/g)||[])):n=e.split(" "),n=n.filter(function(t){return""!==t&&!a.test(t)}),n=n.sort(function(t,e){return e.length-t.length})}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Cache",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.Fetcher","SYNO.SDS.MailClient.MessageHouseLib.LRUCacheCollection","SYNO.SDS.MailClient.MessageHouseLib.CachePreprocessor","SYNO.SDS.MailClient.MessageHouseLib.Util"],constructor:function(t){this.callParent(arguments),this.cache=new SYNO.SDS.MailClient.MessageHouseLib.LRUCacheCollection({}),this.Fetcher=SYNO.SDS.MailClient.MessageHouseLib.Fetcher},get:function(t,e,i){return i=i||[],this._prepareCache(t,e,i).then(function(n){var a,o;return a=SYNO.SDS.MailClient.Array.deepCopy(this._buildRespFromCache(t,e)),i.length>0&&(o={draft:n[2]}),[a,o]}.bind(this))},_prepareCache:function(t,e,i){var n;return i=i||[],n=t.filter(function(t){return!this.getCachedMsgById(t,e)},this),0===n.length&&0===i.length?Promise.resolve([]):this.Fetcher.get(n,e,i).then(function(t){var e=SYNO.SDS.MailClient.MessageHouseLib.Util,i=t[0],n=t[1];return Promise.all([e.fillEncryptionInfoForMsgs(i),e.fillEncryptionInfoForMsgs(n),Promise.resolve(t[2])])}).then(function(t){var e=t[0],i=t[1];return this._addMsgsToCache(e,!1),this._addMsgsToCache(i,!0),t}.bind(this))},getFromCache:function(t){return this.cache.get(t)},_buildRespFromCache:function(t,e){var i=t.map(function(t){return this.getCachedMsgById(t,e)},this);return i=i.filter(function(t){return!!t}),{message:i}},has:function(t){return this.cache.containsKey(t)},getCachedMsgById:function(t,e){var i=SYNO.SDS.MailClient.Define.MessageStat,n=this.cache.get(t),a=e?i.FULL:i.NO_EXTERNAL_IMAGE;if(n&&(n.message_status===a||n.message_status===i.FULL))return n},_addMsgsToCache:function(t,e){var i,n=SYNO.SDS.MailClient.Define.MessageStat,a=e?n.FULL:n.NO_EXTERNAL_IMAGE;i={message:t},SYNO.SDS.MailClient.MessageHouseLib.CachePreprocessor.processMessageResp(!0,i),i.message.forEach(function(t){t.has_fail||(t.message_status=a,this.update(t))},this)},update:function(t){var e;t.has_fail||(e=SYNO.SDS.MailClient.Array.deepCopy(t,["inline_image","tpl_body"]),this.cache.replace(e.id,e))},checkAndUpdate:function(t,e){this._checkIfDataMatchedRecord(t,e)?this.update(e.data):this.removeCache(e.data)},_checkIfDataMatchedRecord:function(t,e){var i=!0;return e.data.rfc_message_id&&e.data.rfc_message_id!==t.rfc_message_id&&(i=!1,SYNO.Debug.warn("rfc_message_id not matched",e.data.rfc_message_id,t.rfc_message_id)),e.data.thread_id&&e.data.thread_id!==t.thread_id&&(i=!1,SYNO.Debug.warn("thread_id not matched",e.data.thread_id,t.thread_id)),i},removeCache:function(t){this.removeCacheById(t.id)},removeCacheById:function(t){this.cache.removeKey(t)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.LRUCacheCollection"],constructor:function(t){this.callParent(arguments),this.inlineImageCache=new SYNO.SDS.MailClient.MessageHouseLib.LRUCacheCollection({GCCount:40})},get:function(t){if(null===t)return Promise.resolve([]);var e=this.inlineImageCache.get(t),i=SYNO.SDS.MailClient.Settings.enlarge_image_cache_threshold?512:128;return e?Promise.resolve(SYNO.SDS.MailClient.Array.deepCopy(e)):SYNO.SDS.MailClient.WebAPI.downloadInline({id:t,size_limit:i}).then(function(e){return this.inlineImageCache.replace(t,e),SYNO.SDS.MailClient.Array.deepCopy(e)}.bind(this))},getFromCache:function(t){return this.inlineImageCache.get(t)},removeCacheById:function(t){this.inlineImageCache.removeKey(t)},has:function(t){return this.inlineImageCache.containsKey(t)}}),Ext.define("SYNO.SDS.MailClient.MessageLib.BodyProcessor",{extend:"Ext.util.Observable",singleton:!0,requires:[],processBody:function(t,e,i,n,a,o){var s,l=t.html,r=t.blockquote||[];return Ext.isEmpty(l)&&(l="<pre>"+Ext.util.Format.htmlEncode(t.plain)+"</pre>"),l=this.getImageProcessedHtml(l,e),r=r.map(function(t){return this.getImageProcessedHtml(t,e)},this),s=document.createElement("div"),s.innerHTML=l,this.findBlockquoteAndReplace(s,r,i),this.findUrlTextAndReplace(s),this.findKeywordAndHighlight(s,o),this.findDateAndHighlight(s,n),this.appendStyleTag(s,t.style,a),l=s.outerHTML},extractImgSrcsFromHtml:function(t){var e=t.match(/<img([^>]+)syno-mc-cid=([^>]+)>/g)||[],i=[];return e.forEach(function(t){var e,n=t.match(/src=\"(webapi[^\"]+)\"|src=\'(webapi[^']+)\'/);n&&(e=Ext.util.Format.htmlDecode(n[1]?n[1]:n[2]),e=Ext.urlAppend(e,"download_token="+SYNO.SDS.MailClient.Info.download_token),i.push(e))}),i},_addExternalImageTip:function(t){if(!DOMParser)return t;var e=(new DOMParser).parseFromString(t,"text/html");return[].slice.call(e.images).forEach(function(t){var e=t.getAttribute("src")||t.getAttribute("syno-mc-block-src");e&&!t.getAttribute("syno-mc-cid")&&t.setAttribute("ext:qtip",Ext.util.Format.ellipsis(e,50))}),e.body.innerHTML},getImageProcessedHtml:function(t,e){if(!Ext.isString(t))return t;t=this._addExternalImageTip(t);return this.getInlineImageTagMatches(t).forEach(function(i){var n,a,o,s,l,r,d,c,h=i.match(/src=\"(webapi[^\"]+)\"|src=\'(webapi[^']+)\'/);if(h){if(n=h[1]?h[1]:h[2],a=Ext.util.Format.htmlDecode(n),o=Ext.urlAppend(a,"download_token="+SYNO.SDS.MailClient.Info.download_token),s=Ext.urlDecode(a.substr(a.indexOf("?")+1)),l=parseInt(s.id,10),r=s.content_id.replace(/(^"|"$)/g,""),l&&r&&e&&(d=e.find(function(t){return t.id===l&&t.content_id===r})))return c=i.replace(n,d.content),c=c.replace(">",' syno-mc-url="'+Ext.util.Format.htmlEncode(o)+'" >'),void(t=t.replace(i,c));c=i.replace(n,Ext.util.Format.htmlEncode(o)),t=t.replace(i,c)}}),t},getInlineImageTagMatches:function(t){return t.match(/<img([^>]+)syno-mc-cid=([^>]+)>/g)||[]},findBlockquoteAndReplace:function(t,e,i){var n=Ext.get(t).select("blockquote[syno-mc-blockquote]");0===n.getCount()&&(e=this._replaceBlockquoteNodeByEmptyTag(t),n=Ext.get(t).select("blockquote[syno-mc-blockquote]")),n.each(function(t){var n=t.getAttribute("syno-mc-blockquote");Ext.isEmpty(n)||this._buildBlockquoteNode(t,e[n],i)},this)},_replaceBlockquoteNodeByEmptyTag:function(t){for(var e,i,n,a=[];;){if(e=Ext.get(t).select("blockquote.syno-mc-blockquote, blockquote[syno-mc-class*=syno-mc-blockquote]"),0===e.getCount())break;n=e.first().dom,a.push(n.outerHTML),i=String.format("<blockquote syno-mc-blockquote={0}></blockquote>",a.length-1),this._buildBlockquoteNode(Ext.get(n),i,!1)}return a},_buildBlockquoteNode:function(t,e,i){var n=document.createElement("div");n.innerHTML=e,t.replaceWith(n),t.addClass("blockquote-content"),i||t.addClass("blockquote-hidden"),t.insertSibling({tag:"div",cls:"blockquote-toggle syno-ux-button-default x-clear"},"before")},findUrlTextAndReplace:function(t){if(document.createTreeWalker)for(var e,i,n,a,o,s,l,r,d,c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null,!1),h=0;e=c.nextNode();)if(n=e.nodeValue.match(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim)){for(i=!1,a=e.parentNode;a&&a!=t;){if("A"===a.tagName.toUpperCase()){i=!0;break}a=a.parentNode}if(!i){for(a=e.parentNode,r=e.nodeValue,h=0,d=null,s=0;s<n.length;++s)l=r.indexOf(n[s],h),a.insertBefore(document.createTextNode(r.substring(h,l)),e),o=document.createElement("A"),o.appendChild(document.createTextNode(n[s])),o.href=n[s],o.target="_blank",a.insertBefore(o,e),h=l+n[s].length;a.insertBefore(d=document.createTextNode(r.substring(h)),e),a.removeChild(e),c.currentNode=d}}},findKeywordAndHighlight:function(t,e){e&&e.forEach(function(e){SYNO.SDS.MailClient.TextHighlighter.highlight(e,t)},this)},findDateAndHighlight:function(t,e){if(SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")){var i=SYNO.SDS.MailClient.SynoCalendarPlugin.preRenderMessage(t.innerHTML);SYNO.SDS.MailClient.SynoCalendarPlugin.parseDateAndReplace(i,1e3*e,t)}},appendStyleTag:function(t,e,i){var n;Ext.isEmpty(e)||Ext.isEmpty(i)||(t.setAttribute("syno-mc-class","syno-mc-"+i),n=document.createElement("style"),n.innerHTML=e,/syno-mc-block-[\S]+[\s]*:/.test(e)&&n.setAttribute("syno-mc-block-style",""),t.appendChild(n))}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.Cache","SYNO.SDS.MailClient.MessageLib.BodyProcessor"],mergeMsgsIntoRecord:function(t,e,i,n,a){var o=SYNO.SDS.MailClient.Define.MessageStat,s=this._buildFinalMsg(t,i);return t.length?Ext.apply(e.data,s,{message_status:n?o.FULL:o.NO_EXTERNAL_IMAGE,show_blockquote:a}):e.data.message_status=o.NOT_EXIST,e.commit(),s},update:function(t,e,i){var n,a=t.getById(e);return a||(a=t.getAt(t.findExact("rfc_message_id",i.rfc_message_id))),a?(n=SYNO.SDS.MailClient.Array.deepCopy(i),delete n.star,delete n.read,delete n.id,delete n.body,delete n.bcc,delete n.mailbox_id,this._mergeDataBodyIntoRecord(i,a),
Ext.isArray(i.bcc)&&i.bcc.length>a.data.bcc.length&&(a.data.bcc=[].concat(i.bcc)),Ext.apply(a.data,n),this._fixUndefinedBody(a),a):null},_buildFinalMsg:function(t,e){var i,n,a;return t.forEach(function(t){t.mailbox_id===e&&(i=SYNO.SDS.MailClient.Array.deepCopy(t)),n=n||t.body.html,a=a||t.body.plain},this),i||(i=SYNO.SDS.MailClient.Array.deepCopy(t[0])),i.body.html=n,i.body.plain=a,i},_mergeDataBodyIntoRecord:function(t,e){e.data.body?(e.data.body.html||(e.data.body.html=t.body.html,e.data.body.truncated=t.body.truncated,Ext.isArray(t.body.blockquote)&&(e.data.body.blockquote=t.body.blockquote)),e.data.body.plain||(e.data.body.plain=t.body.plain)):e.data.body=t.body},_fixUndefinedBody:function(t){Ext.isObject(t.data.body)||(t.data.body={html:"",plain:""})}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.ImagePreloadTask",{extend:"Ext.util.Observable",requires:[],constructor:function(t,e){this.callParent(arguments),this._count=0,this.concurrency=5,this._queue=[],this._deferred=new SYNO.SDS.MailClient.UtilLib.Deferred,this._resolvedValue=e,t.forEach(function(t){this._add(t)}.bind(this)),this._check()},then:function(t,e){return this._deferred.then(t,e)},_check:function(){if(0===this._count&&0===this._queue.length)return void this._allDone();for(;this._queue.length>0&&this._count<this.concurrency;)this._preload()},_add:function(t){this._queue.push(t),this._check()},_preload:function(){var t,e;++this._count,t=this._queue.shift(),e=Ext.DomHelper.createDom({tag:"img",src:t});var i=function(){--this._count,this._check()}.bind(this);e.onload=i,e.onerror=i},_allDone:function(){this._deferred.resolve(this._resolvedValue)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Throttle",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.ImagePreloadTask"],constructor:function(){this.callParent(arguments),this._count=0,this.concurrency=2,this._queue=[]},guard:function(t){return function(e){var i=new SYNO.SDS.MailClient.UtilLib.Deferred;return i._preSavedValue=e,i._preSavedSrcs=t(e),this._queue.push(i),this._check(),i}.bind(this)},_check:function(){for(;this._queue.length>0&&this._count<this.concurrency;)this._run(this._pop())},_pop:function(){return this._queue.shift()},_run:function(t){var e=new SYNO.SDS.MailClient.MessageHouseLib.ImagePreloadTask(t._preSavedSrcs,t._preSavedValue);++this._count;var i=function(){--this._count,t.resolve(t._preSavedValue),this._check()}.bind(this);return e.then(i).catch(i)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.Cache","SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache","SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator","SYNO.SDS.MailClient.MessageHouseLib.Throttle","SYNO.SDS.MailClient.MessageLib.BodyProcessor"],updateMsg:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.Cache,n=SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator,a=n.update(t,e.id,e);a.commit(),i.checkAndUpdate(e,a)},fetchFullMsgIntoRecord:function(t,e,i){var n=SYNO.SDS.MailClient.MessageHouseLib.Cache,a=SYNO.SDS.MailClient.MessageHouseLib.Throttle,o=SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator,s=function(a){if(a.length){var s=SYNO.SDS.MailClient.Control.Main.getInMailboxId(),l=o.mergeMsgsIntoRecord(a,t,s,e,i);n.checkAndUpdate(l,t)}}.bind(this);return this._fetchMsgWithCompoundInlineImage(t,e).then(a.guard(this._extractPreloadImgSrcs)).then(function(t){s(t)}.bind(this))},prefetchImageInFullMsgRecord:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.Throttle;return this._fetchMsgWithCompoundInlineImage(t,e).then(i.guard(this._extractPreloadImgSrcs))},_fetchMsgWithCompoundInlineImage:function(t,e){var i,n=SYNO.SDS.MailClient.MessageHouseLib.Cache,a=SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache;return n.get(t.get("operation_ids"),e).then(function(e){return i=e,this._isMsgHasInlineImage(i[0].message[0].body)?a.get(t.get("id")):a.get(null)}.bind(this)).then(function(e){return i[0].message.forEach(function(i){i.id===t.get("id")&&(i.inline_image=e)}),i[0].message})},_isMsgHasInlineImage:function(t){var e=SYNO.SDS.MailClient.MessageLib.BodyProcessor,i=t.html,n=t.blockquote||[];return e.getInlineImageTagMatches(i).length>0||n.some(function(t){return e.getInlineImageTagMatches(t).length>0})},_extractPreloadImgSrcs:function(t){var e=t[0].body,i=e.html||"",n=e.blockquote?e.blockquote.join(" "):"",a=i+" "+n,o=SYNO.SDS.MailClient.MessageLib.BodyProcessor.extractImgSrcsFromHtml(a),s={},l=[];return t[0].inline_image&&t[0].inline_image.forEach(function(t){s[t.id]=t.content_id}),o.forEach(function(t){var e=Ext.urlDecode(t.substr(t.indexOf("?")+1)),i=parseInt(e.id,10),n=e.content_id.replace(/(^"|"$)/g,"");s.hasOwnProperty(i)&&s[i]===n||l.push(t)}),l},addNewMsg:function(t,e,i){var n=i.message,a=[];return n.forEach(function(i){var n,o=Ext.apply(e[i.id]||{},i);o.message_status=SYNO.SDS.MailClient.Define.MessageStat.FULL,n=this._addNewMsgAndUpdateCache(t,o),a.push(n)},this),a},_addNewMsgAndUpdateCache:function(t,e,i){var n,a=SYNO.SDS.MailClient.MessageHouseLib.Cache,o=new t.recordType(e,e.id);return t.updateOperationIdForStoreAndRecord(o),e.message_status===SYNO.SDS.MailClient.Define.MessageStat.PREVIEW&&a.has(e.id)&&(n=a.getFromCache(o.get("id")),Ext.copyTo(o.data,n,"body,to,cc,bcc,operation_ids,message_status"),n.mailbox_id=e.mailbox_id),Ext.isDefined(i)?t.insert(i,o):t.add(o),o},purgeInvalidCache:function(t){var e=SYNO.SDS.MailClient.MessageHouseLib.Cache,i=SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache;t.forEach(function(t){var n=t.id,a=e.getFromCache(n);a&&(a.rfc_message_id&&t.rfc_message_id&&a.rfc_message_id!==t.rfc_message_id&&(SYNO.Debug.warn(a.rfc_message_id,t.rfc_message_id,"rfc_msg_id is not matched","purge",n),e.removeCacheById(n),i.removeCacheById(n)),a.thread_id&&t.thread_id&&a.thread_id!==t.thread_id&&(SYNO.Debug.warn(a.thread_id,t.thread_id,"thread_id is not matched","purge",n),e.removeCacheById(n),i.removeCacheById(n)))},this)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Modifier",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper","SYNO.SDS.MailClient.MessageHouseLib.Util"],appendSendingDraft:function(t,e,i,n,a){var o=SYNO.SDS.MailClient.Format.draftDataToFakeMessage(e,i,n,!1,n.isCopyBeforeSend,a),s=new t.recordType(o,o.id);return t.add(s),SYNO.SDS.MailClient.Control.View.expandLastMsg(),s},updateSendingDraftToSent:function(t,e,i){var n=SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper,a=t.getById(i.id);if(a&&a.get("message_status")===SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT){delete a.data.tpl_body,delete a.data.body;var o=Ext.apply(SYNO.SDS.MailClient.Format.fullMessageToPreviewMessage(i),i);o.operation_ids=a.get("operation_ids"),o.message_status=SYNO.SDS.MailClient.Define.MessageStat.FULL,n.updateMsg(t,o)}}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Updater",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper","SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator","SYNO.SDS.MailClient.MessageHouseLib.Util"],updateByGetMsgResp:function(t,e,i){var n=e.message,a=SYNO.SDS.MailClient.Define.MessageStat,o=SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator,s=SYNO.SDS.MailClient.Settings.display_external_image,l=s?a.FULL:a.NO_EXTERNAL_IMAGE,r=[],d=[];n.forEach(function(e){delete e.star,delete e.read,delete e.replied,delete e.forwarded,e.message_status=l,o.update(t,e.id,e)},this),r=n.map(function(t){return t.operation_ids?t.operation_ids:[t.id]}),r=[].concat.apply([],r),d=i.filter(function(t){return-1===r.indexOf(t)}),d.forEach(function(e){o.update(t,e,{message_status:a.NOT_EXIST})},this)},identifyNewMsgsByGetThreadResp:function(t,e){if(e.thread.length<=0)return[];var i=SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper,n=SYNO.SDS.MailClient.MessageHouseLib.Util,a=t.getNormalizedMsgData(e.thread[0].message),o=[],s={};return a=a.filter(function(t){return n.shouldShowMsg(t)}),a.forEach(function(e){var n,a,l=t.findExact("rfc_message_id",e.rfc_message_id);-1!==l?(n=t.getAt(l),a=Ext.unique(n.data.operation_ids.concat(e.operation_ids)),n.data.operation_ids=a):n?i.updateMsg(t,e.id,e):(o.push(e.id),s[e.id]=e)},this),[o,s]},updateByThreadMsgs:function(t,e){function i(t,e){var i=!1;t.data.star!==e.star&&(t.data.star=e.star,i=!0),t.data.read!==e.read&&(t.data.read=e.read,i=!0),t.data.replied!==e.replied&&(t.data.replied=e.replied,i=!0),t.data.forwarded!==e.forwarded&&(t.data.forwarded=e.forwarded,i=!0),t.data.mailbox_id!==e.mailbox_id&&(t.data.mailbox_id=e.mailbox_id,i=!0),i&&t.commit()}var n,a=SYNO.SDS.MailClient.MessageHouseLib.Util,o=t.getNormalizedMsgData(e),s=e.map(a.msgToId);o.forEach(function(e){var n=t.getById(e.id),a=t.getByRfcMsgId(e.rfc_message_id);n?(i(n,e),t.updateOperationIdForStoreAndRecord(n)):a&&-1===a.data.operation_ids.indexOf(e.id)&&a.data.operation_ids.push(e.id)},this),n=t.getRange().filter(function(t){return-1===s.indexOf(t.id)&&t.data.message_status!==SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT}),t.remove(n)},updateMailboxByMap:function(t,e){var i;Ext.iterate(e,function(e,n){n.forEach(function(n){(i=t.getById(n))&&this._modifyMailbox(i,e,0,!1)},this)},this)},updateMailbox:function(t,e,i){t.each(function(t){this._modifyMailbox(t,e,i,!0)},this)},_modifyMailbox:function(t,e,i,n){SYNO.SDS.MailClient.MessageHouseLib.Util.isMsgMovable(t.data,e,i,n)&&(t.data.mailbox_id=e,t.commit())},examineByGetMsgResp:function(t,e,i){var n=SYNO.SDS.MailClient.Lib.Logger;e.message.forEach(function(e){var i,a=t.getById(e.id);if(!a&&!(a=t.getAt(t.findExact("rfc_message_id",e.rfc_message_id))))return void n.error("rfc_message_id",e.rfc_message_id,"not found");i=a.data,i.rfc_message_id&&e.rfc_message_id&&i.rfc_message_id!==e.rfc_message_id&&function(t){n.error(t),n.error("thread ===>",i.id,i.thread_id,i.rfc_message_id),n.error("msg ===>",e.id,e.thread_id,e.rfc_message_id)}("[BAD RFC_MSG_ID]")},this)}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.NewMsgChecker",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper","SYNO.SDS.MailClient.MessageHouseLib.Updater"],checkNewMsg:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.Cache,n=SYNO.SDS.MailClient.MessageHouseLib.Updater,a=SYNO.SDS.MailClient.Settings.display_external_image;return SYNO.SDS.MailClient.WebAPI.send("getThread",{id:[e]}).then(function(o){var s=n.identifyNewMsgsByGetThreadResp(t,o),l=s[0].length>0,r=s[0],d=s[1],c=SYNO.SDS.MailClient.Format.formatAddrsOfMsgsToNormal(o.thread[0].message);return l?(SYNO.SDS.MailClient.Control.Thread.modifyThread("edit",[{id:e,prop:{message:c}}]),i.get(r).then(function(t){return[t[0],a,d]})):Promise.resolve()}.bind(this)).catch(function(t){throw SYNO.Debug.error(t),t}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Prefetcher",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.MessageHouseLib.Cache"],singleton:!0,constructor:function(t){this.callParent(arguments),this.Cache=SYNO.SDS.MailClient.MessageHouseLib.Cache,this.idsToPrefetch=[],this.checkPrefetchListTask=new Ext.util.DelayedTask(this.checkPrefetchList,this),this.fetchSizeAtSameTime=10},monStore:function(t){t&&(t=Ext.StoreMgr.lookup(t),t.on({scope:this,datachanged:function(t){this.checkPrefetchListTask.delay(100,null,null,[t])}}))},checkPrefetchList:function(){var t=this._getPrefetchIds();this._processPrefetch(t)},_processPrefetch:function(t){this.idsToPrefetch=this.idsToPrefetch.concat(t),this.isPrefetching||this._doProcessPrefetch()},_doProcessPrefetch:function(){var t=[].concat(this.idsToPrefetch).splice(0,this.fetchSizeAtSameTime),e=SYNO.SDS.MailClient.Settings.display_external_image;if(0===t.length)return void(this.isPrefetching=!1);this.isPrefetching=!0;var i=function(){this._doProcessPrefetch.defer(0,this)}.bind(this);this.Cache.get(t,e).then(function(e){t.forEach(function(t){this.idsToPrefetch.remove(t)},this),i()}.bind(this)).catch(function(t){})},_getPrefetchIds:function(){var t=this._getThreadsNeedToCheck(),e=this._getMsgsFromThreads(t);return e=e.filter(function(t){var e=this.Cache.has(t.id),i=-1!==this.idsToPrefetch.indexOf(t.id),n=!t.read||t.star;return!e&&!i&&n},this),e.map(function(t){return t.id})},_getThreadsNeedToCheck:function(){var t=SYNO.SDS.MailClient.Lib.Thread.getAllUnreadOrStarredRecords();return SYNO.SDS.MailClient.Switch.inPriority?t:t.slice(0,30)},_getMsgsFromThreads:function(t){var e=[];return t.forEach(function(t){t.data.message.forEach(function(t){e.push(t)},this)},this),e}}),Ext.define("SYNO.SDS.MailClient.MessageHouseLib.Keeper",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageHouseLib.Cache","SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper","SYNO.SDS.MailClient.MessageHouseLib.CachePreprocessor","SYNO.SDS.MailClient.MessageHouseLib.Fetcher","SYNO.SDS.MailClient.MessageHouseLib.Modifier","SYNO.SDS.MailClient.MessageHouseLib.MsgUpdateOperator","SYNO.SDS.MailClient.MessageHouseLib.NewMsgChecker","SYNO.SDS.MailClient.MessageHouseLib.Normalizer","SYNO.SDS.MailClient.MessageHouseLib.Prefetcher","SYNO.SDS.MailClient.MessageHouseLib.Updater","SYNO.SDS.MailClient.MessageLib.BodyProcessor"],bind:function(t){this.store=t},updateMsgRecordFromCache:function(t){var e,i=SYNO.SDS.MailClient.MessageHouseLib.Cache,n=SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache,a=t.id;i.has(a)&&n.has(a)&&(e=SYNO.SDS.MailClient.Array.deepCopy(i.getFromCache(a)),e.inline_image=n.getFromCache(a),delete e.mailbox_id,delete e.read,delete e.star,delete e.message_status,delete e.replied,delete e.forwarded,Ext.apply(t.data,e))},getMsgs:function(t,e,i){return SYNO.SDS.MailClient.MessageHouseLib.Cache.get(t,e,i)},checkNewMsg:function(t){var e=SYNO.SDS.MailClient.MessageHouseLib.NewMsgChecker,i=this.store;return e.checkNewMsg(i,t)},examineAndUpdateByGetMsgResp:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.Updater,n=this.store;i.examineByGetMsgResp(n,t,e),i.updateByGetMsgResp(n,t,e)},updateByThreadMsgs:function(t){var e=SYNO.SDS.MailClient.MessageHouseLib.Updater,i=this.store;e.updateByThreadMsgs(i,t)},updateMailbox:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.Updater,n=this.store;i.updateMailbox(n,t,e)},updateMailboxByMap:function(t){var e=SYNO.SDS.MailClient.MessageHouseLib.Updater,i=this.store;e.updateMailboxByMap(i,t)},addNewMsg:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper,n=this.store;return i.addNewMsg(n,t,e)},fetchFullMsgIntoRecord:function(t,e,i){return SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper.fetchFullMsgIntoRecord(t,e,i)},prefetchImageInFullMsgRecord:function(t,e){return SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper.prefetchImageInFullMsgRecord(t,e)},purgeInvalidCache:function(t){return SYNO.SDS.MailClient.MessageHouseLib.CacheKeeper.purgeInvalidCache(t)},appendSendingDraft:function(t,e,i,n){var a=SYNO.SDS.MailClient.MessageHouseLib.Modifier,o=this.store;return a.appendSendingDraft(o,t,e,i,n)},updateSendingDraftToSent:function(t,e){var i=SYNO.SDS.MailClient.MessageHouseLib.Modifier,n=this.store;return i.updateSendingDraftToSent(n,t,e)}}),Ext.define("SYNO.SDS.MailClient.MessageLib.Attachment",{extend:"Ext.util.Observable",singleton:!0,requires:[],saveToDS:function(t,e,i){return this.openFileChooser(t,e).then(function(t){var e={id:i,dest:t};return SYNO.SDS.MailClient.WebAPI.downloadDSM(e)}).then(function(){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("mail","attachment_save_ds_success"))}).catch(function(t){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient.Error.getErrorString(t),[],!0)})},saveAllToDS:function(t,e,i){return this.openFileChooser(t,e).then(function(t){var e={id:i,dest:t};return SYNO.SDS.MailClient.WebAPI.downloadDSMAll(e)}).then(function(){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("mail","attachment_save_ds_success"))}).catch(function(t){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient.Error.getErrorString(t),[],!0)})},openFileChooser:function(t,e){return new Promise(function(i,n){var a={owner:t,width:800,enumC2Share:!0,gotoPath:SYNO.SDS.UserSettings.getProperty("SYNO.SDS.MailClient.Application","lastFileChooserPath")||"",usage:{type:"save",oldFilename:e,multiple:!1},listeners:{choose:{fn:function(t,e,n){i(e.path);var a=e.path.substring(0,e.path.lastIndexOf("/"));SYNO.SDS.UserSettings.setProperty("SYNO.SDS.MailClient.Application","lastFileChooserPath",a),t.close()}}}};new SYNO.SDS.Utils.FileChooser.Chooser(a).show()})}}),Ext.define("SYNO.SDS.MailClient.Message.ListTpl",{extend:"Ext.util.Observable",singleton:!0,requires:[],createTpl:function(){return new Ext.XTemplate(this.getTpl(),this.getTplFn())},getTpl:function(){return this.tpl=this.tpl||['<tpl for=".">','<div class="item-wrap <tpl if="this.isSearchMatched(values.id)">search-matched</tpl> <tpl if="values.tpl_hide">hide</tpl>" syno-mc-data-message-id="{values.id}">','<div class="item-summary item-toggle">','<div class="star<tpl if="values.star"> syno-ux-cb-checked</tpl><tpl if="this.isFromDraft(values)"> disable</tpl>"></div>','<tpl if="!SYNO.SDS.MailClient.Settings.conversation_view && (values.replied || values.forwarded)">','<div class="<tpl if="values.replied">replied</tpl> <tpl if="values.forwarded">forwarded</tpl>"></div>',"</tpl>",'<div class="item-title">','<div class="from-error-image <tpl if="!this.isDisplayNameMalicious(values.from)">x-hide-display</tpl>" ext:qtip="{[SYNO.SDS.MailClient._T("mail", "malicious_addr")]}"></div>','<div class="from">{[SYNO.SDS.MailClient.Format.toEmailSpanShowSelf(values.from)]}</div>',"<tpl if=\"this.getFrom(values.from) !== ''\">",'<div class="from-addr">{[this.getFrom(values.from)]}</div>',"</tpl>",'<div class="split-body-preview"> - </div>','<div class="body-preview">{body_preview:htmlEncode}</div>','<div class="split-to">',SYNO.SDS.MailClient._T("mail","sender_receiver_separator"),"</div>",'<div class="flex">','<div class="to-ct">','<div class="to">',"{[this.getToCC(values.to, values.cc)]}","</div>","</div>",'<div class="info-ct">','<span class="info x-btn syno-ux-button syno-ux-button-default x-btn-icon">','<button class="info-btn-icon x-btn-text"></button>',"</span>","</div>","</div>","</div>","{[SYNO.SDS.MailClient.Format.templateNotShareIcon(values)]}","{[SYNO.SDS.MailClient.Format.templateAttachment([values], [])]}",'<tpl if="!SYNO.SDS.MailClient.Settings.disable_show_mailbox">','<div class="mailbox-label<tpl if="this.isFromDraft(values)"> disable</tpl>" ext:qtip="{[String.format(SYNO.SDS.MailClient._T("mailbox", "mailbox_tooltip"), this.getMailboxText(values.mailbox_id))]}">',"{[this.getMailboxText(values.mailbox_id)]}","</div>","</tpl>",'<div class="time" title="{[SYNO.SDS.MailClient.Format.toFullTimeString(values.arrival_time)]}">',"{[SYNO.SDS.MailClient.Format.toTimeString(values.arrival_time, true)]}","</div>",'<div class="spacer"></div>','<div class="action">','<div class="reply<tpl if="this.isFromDraft(values)"> disable</tpl>" ext:qtip="{[SYNO.SDS.MailClient._T("mail", "reply")]}"></div>','<div class="reply-all<tpl if="this.isFromDraft(values)"> disable</tpl>" ext:qtip="{[SYNO.SDS.MailClient._T("mail", "reply_all")]}"></div>','<div class="forward<tpl if="this.isFromDraft(values)"> disable</tpl>" ext:qtip="{[SYNO.SDS.MailClient._T("mail", "forward")]}"></div>','<div class="more-action<tpl if="this.isFromDraft(values)"> disable</tpl>" ext:qtip="{[SYNO.SDS.MailClient._T("common", "more")]}"></div>',"</div>","</div>",'<div class="suspicious-ct <tpl if="values.pass_security !== false">x-hide-display</tpl>">','<div class="mail-suspicious-image"></div>','<div class="mail-suspicious-text">{[String.format(SYNO.SDS.MailClient._T("mail", "suspicious_mail"), this.getAddrHostname(values.from))]}</div> ',"</div>",'<div class="calendar-panel x-hide-display"></div>','<div class="sharedmailbox-subscribe-panel x-hide-display"></div>','<div class="item-detail<tpl if="this.isFromDraft(values)"> disable</tpl>" style="display:none">','<div class="show-external-ct x-hide-display">','<div class="info-image"></div>','<div class="info-text">{[SYNO.SDS.MailClient._T("mail", "image_blocked")]}</div> ','<div class="show-external-text">{[SYNO.SDS.MailClient._T("mail", "show_external_image")]}</div>',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.ENCRYPTED">x-hide-display</tpl>">','<div class="encrypt-image"></div>','<div class="info-text">{[SYNO.SDS.MailClient._T("pgp", "encrypted_mail")]}</div> ','<div class="pgp-text">{[SYNO.SDS.MailClient._T("pgp", "decrypt_mail")]}</div>',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.DECRYPTED">x-hide-display</tpl>">','<div class="decrypt-image"></div>','<div class="info-text">{[SYNO.SDS.MailClient._T("pgp", "decrypted_mail")]}</div> ',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.DECRYPTED_VALID">x-hide-display</tpl>">','<div class="decrypt-image"></div>','<div class="info-text">{[SYNO.SDS.MailClient._T("pgp", "decrypted_mail")]}</div>','<div class="seperator"></div>','<div class="sign-image"></div>','<div class="info-text">{[this.getPGPDecryptVerifyMsg(values)]}</div> ',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.DECRYPTED_INVALID">x-hide-display</tpl>">','<div class="decrypt-image"></div>','<div class="info-text">{[SYNO.SDS.MailClient._T("pgp", "decrypted_mail")]}</div>','<div class="seperator"></div>','<div class="sign-fail-image"></div>','<div class="error-text" ext:qtip="{[this.getPGPSignQtip(values)]}">{[this.getPGPDecryptVerifyMsg(values)]}</div> ',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.VALID_SIGN">x-hide-display</tpl>">','<div class="sign-image"></div>','<div class="info-text">{[this.getPGPSignMsg(values)]}</div> ',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.INVALID_SIGN">x-hide-display</tpl>">','<div class="sign-fail-image"></div>','<div class="error-text" ext:qtip="{[this.getPGPSignQtip(values)]}">{[this.getPGPSignMsg(values)]}</div> ',"</div>",'<div class="pgp-ct <tpl if="values.pgp_encryption !== SYNO.SDS.MailClient.Define.EncryptionStat.ERROR">x-hide-display</tpl>">','<div class="decrypt-fail-image"></div>','<div class="error-text" ext:qtip="{[this.getPGPErrorQTip(values)]}">{[this.getPGPErrorMsg(values)]}</div> ',"</div>",'<div class="show-no-message-hint <tpl if="SYNO.SDS.MailClient.Define.MessageStat.NOT_EXIST !== values.message_status">x-hide-display</tpl>">','<div class="error-image"></div>','<div class="info-text">{[SYNO.SDS.MailClient._T("mail", "message_not_exist")]}</div>',"</div>",'<div class="body reset">',"{[this.getBodyContent(values.tpl_body)]}",'<tpl if="values.body && values.body.truncated">','<div class="truncated-hint">',"<br>","---<br>",'[{[SYNO.SDS.MailClient._T("mail", "message_clipped")]}] <span class="message-clipped-hint">{[SYNO.SDS.MailClient._T("mail", "view_all_message")]}</span>',"</div>","</tpl>",'<div class="x-clear"></div>',"</div>",'<tpl if="values.attachment.length">','<div class="attachment-display">','<div class="attachment-action">','<div class="count">{[String.format(SYNO.SDS.MailClient._T("mail", "attachments_count"), values.attachment.length)]}</div>','<div class="spacer"></div>','<div class="attachment-action-download">{[SYNO.SDS.MailClient._T("mail", "attachment_download_all")]}</div>','<div class="spacer"></div>','<div class="attachment-action-saveds">{[SYNO.SDS.MailClient._T("mail", "attachment_save_ds_all")]}</div>',"</div>",'<div class="attachment-list">','<tpl for="values.attachment">','<div class="attachment-item {[this.getAttachmentItemPreviewClass(values)]}">','<div class="attachment-item-mask" ext:qtip="{[this.getAttachmentName(values)]}"></div>',"<img {[this.getAttachmentImageURL(values, parent)]} />",'<div class="attachment-item-filename" title="{[this.getAttachmentName(values)]}">{[this.getAttachmentName(values)]}</div>','<div class="attachment-item-filesize">{[SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(values.size, 0)[0]]}</div>','<div class="attachment-item-download" ext:qtip="{[SYNO.SDS.MailClient._T("mail", "attachment_download")]}"></div>','<div class="attachment-item-saveds" ext:qtip="{[SYNO.SDS.MailClient._T("mail", "attachment_save_ds")]}"></div>',"</div>","</tpl>","</div>","</div>","</tpl>","</div>","</div>",'<tpl if="values.tpl_more">','<div class="more">',"<div>",'<span>{[String.format(SYNO.SDS.MailClient._T("mail", "collapse_mail_count"), values.tpl_more_count)]}</span>',"</div>","</div>","</tpl>","</tpl>",'<div class="x-clear"></div>'].join(""),this.tpl},getTplFn:function(){return this.tplFn=this.tplFn||{getBodyContent:function(t){return Ext.isString(t)?t:""},getAttachmentItemPreviewClass:function(t){return Ext.isObject(t)||"[object File]"===Object.prototype.toString.call(t)?t.mimetype&&0!==t.mimetype.indexOf("image/")?"non-preview":t.type&&0!==t.type.indexOf("image/")?"non-preview":"":""},getAttachmentName:function(t){return Ext.util.Format.htmlEncode(SYNO.SDS.MailClient.Format.toAttachmentName(t))},getFrom:function(t){var e=SYNO.SDS.MailClient.Format.getFromInfo(t);return e.isInContact?"":Ext.util.Format.htmlEncode(e.email)},getAddrHostname:function(t){var e=SYNO.SDS.MailClient.Format.getMailByNameAddrOrAddr(t)||"",i=e.indexOf("@")>-1?e.split("@")[1]:e;return Ext.util.Format.htmlEncode(i)},isFromDraft:function(t){return t.message_status===SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT},isDisplayNameMalicious:function(t){var e=SYNO.SDS.MailClient.Format.getFromInfo(t);return!e.isInContact&&SYNO.SDS.MailClient.Format.isDisplayNameMalicious(e.displayName,e.innerEmail)},isSearchMatched:function(t){return SYNO.SDS.MailClient.Switch.getRegister("lastMatchedIds").indexOf(t)>-1},getToCC:function(t,e){t=t||[],e=e||[];var i,n=t.concat(e),a="";for(i=0;i<n.length;++i)a+=SYNO.SDS.MailClient.Format.toEmailSpanShowSelf(n[i])+(i===n.length-1?"":", ");return a},getMailboxText:function(t){var e=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t);return e?SYNO.SDS.MailClient.Format.getMailboxText(e.data):""},getAttachmentImageURL:function(t,e){var i=this.isFromDraft(e);return SYNO.SDS.MailClient.MessageLib.UrlBuilder.getAttachmentImageURL(t,i)},getPGPErrorMsg:function(t){var e=SYNO.SDS.MailClient._T("pgp","decrypt_fail");return t.pgp_error&&t.pgp_error.code===SYNO.SDS.MailClient.Define.PGPStat.NO_AVAILABLE_KEY&&(e+=SYNO.SDS.MailClient._T("pgp","no_key")),e},getPGPErrorQTip:function(t){return t.pgp_error&&t.pgp_error.code===SYNO.SDS.MailClient.Define.PGPStat.NO_AVAILABLE_KEY?String.format(SYNO.SDS.MailClient._T("pgp","need_key"),t.pgp_error.info.join(",")):""},getPGPSignMsgCore:function(t){var e,i=t.pgp_verify_info;return i?i.verifiedInfo?(e=Ext.util.Format.htmlEncode(i.verifiedInfo.userId),String.format(SYNO.SDS.MailClient._T("pgp","valid_signature"),e)):i.verifyInfos.length>0?(e=Ext.util.Format.htmlEncode(i.verifyInfos[0].userId),String.format(SYNO.SDS.MailClient._T("pgp","invalid_signature"),e)):String.format(SYNO.SDS.MailClient._T("pgp","unknown_signature")):""},getPGPSignQtip:function(t){var e,i=t.pgp_verify_info;return i?(e=!i.verifiedInfo&&0===i.verifyInfos.length,e&&i.keyId?String.format(SYNO.SDS.MailClient._T("pgp","need_key"),i.keyId):""):""},getPGPSignMsg:function(t){var e=SYNO.SDS.MailClient.Define.EncryptionStat,i=t.pgp_encryption;return-1===[e.VALID_SIGN,e.INVALID_SIGN].indexOf(i)?"":this.getPGPSignMsgCore(t)},getPGPDecryptVerifyMsg:function(t){var e=SYNO.SDS.MailClient.Define.EncryptionStat,i=t.pgp_encryption;return-1===[e.DECRYPTED_VALID,e.DECRYPTED_INVALID].indexOf(i)?"":this.getPGPSignMsgCore(t)}},this.tplFn}}),Ext.define("SYNO.SDS.MailClient.Model.DraftStore",{extend:"Ext.data.JsonStore",requires:[],constructor:function(t){var e={autoDestroy:!0,fields:["id","arrival_time","attachment","bcc","body","body_preview","cc","email","from","last_modified","mailbox_id","read","star","subject","thread_id","to","rfc_message_id","operation_ids"]};this.callParent([Ext.apply(e,t)]),this.initStore()},initStore:function(){},getByFn:function(t){var e=[];return this.each(function(i){t(i)&&e.push(i)}),e},getAll:function(){return this.getByFn(function(t){return!0})},loadDraft:function(t){this.removeAll(),t.forEach(function(t){this.add(new this.recordType(t,t.id))},this)},updateByGetDraftResp:function(t,e){if(t){var i=e.draft;i.length,this.getCount(),i.forEach(function(t){var e=this.getById(t.id);e&&Ext.apply(e.data,t)},this)}}}),Ext.define("SYNO.SDS.MailClient.MessageLib.MsgStore",{extend:"Ext.data.JsonStore",requires:["SYNO.SDS.MessageLib.MsgProcessor"],constructor:function(t){var e={fields:["id","arrival_time","attachment",{name:"bcc",defaultValue:[]},"body","body_preview","cc","email","from","last_modified","mailbox_id","read","star","replied","forwarded","subject","thread_id","to","rfc_message_id","operation_ids","message_status"]};this.callParent([Ext.apply(e,t)]),this.initStore()},initStore:function(){},getDefaultExpandIds:function(t){var e,i=this.getLastMsg(),n=this.getStarIds(),a=this.getUnreadIds();return n.splice(1,n.length-2),a.splice(1,a.length-2),e=[].concat(n,a),t&&this.IsMsgIdInDraftManager(i.get("id"))||e.push(i.get("id")),Ext.isArray(SYNO.SDS.MailClient.Define.launchParam.ui)&&(e=e.concat(SYNO.SDS.MailClient.Define.launchParam.ui)),Ext.unique(e)},IsMsgIdInDraftManager:function(t){return SYNO.SDS.MailClient.Window.draftManager.draftHash.hasOwnProperty(t)},getFakeMsgs:function(){return this.getByFn(function(t){return t.get("message_status")===SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT})},getStarIds:function(){return this.getIdsByFn(function(t){return!!t.get("star")})},getUnreadIds:function(){return this.getIdsByFn(function(t){return!t.get("read")})},getLastMsg:function(){return this.getAt(this.getCount()-1)},getByRfcMsgId:function(t){var e=this.findExact("rfc_message_id",t);return-1!==e?this.getAt(e):null},parseNewMsgData:function(t){return t.message.filter(function(t){var e=-1!==this.findExact("rfc_message_id",t.rfc_message_id),i=this.getById(t.id);return!e&&!i},this)},getByFn:function(t){var e=[];return this.each(function(i){t(i)&&e.push(i)}),e},getIdsByFn:function(t){var e=[];return this.each(function(i){t(i)&&e.push(i.get("id"))}),e},loadMsg:function(t){var e;e=this.getNormalizedMsgData(t),this.loadData(e)},getNormalizedMsgData:function(t){return SYNO.SDS.MailClient.MessageHouseLib.Normalizer.normalizeMsgs(t)},updateOperationIdForStoreAndRecord:function(t){var e,i=t.data.id,n=this.getByRfcMsgId(t.data.rfc_message_id);n?(e=n.data.operation_ids,-1===e.indexOf(i)&&e.push(i),t.data.operation_ids=[].concat(e)):t.data.operation_ids=[i]},removeFakeSentMsg:function(t){var e=this.getById(t);e&&e.get("message_status")===SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT&&this.remove(e)},processCalendarPart:function(t){SYNO.SDS.MailClient.MessageList.prototype.processCalendarPart(t)}}),Ext.define("SYNO.SDS.MailClient.MessageLib.MsgProvider",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.MessageHouseLib.Keeper"],constructor:function(t){this.callParent(arguments)},bind:function(t,e,i){this.msgStore=t,this.draftStore=e,this.guarder=i},IsMsgIdInDraftManager:function(t){return SYNO.SDS.MailClient.Window.draftManager.draftHash.hasOwnProperty(t)},prepareMsg:function(){var t=SYNO.SDS.MailClient.MessageHouseLib.Keeper,e=this._getMsgPreloadIds(),i=this._getDraftPreloadIds(),n=SYNO.SDS.MailClient.Settings.display_external_image;return t.getMsgs(e,n,i).then(this._guardPromise()).then(function(i){var n=i[0],a=i[1];t.examineAndUpdateByGetMsgResp(n,e),a&&this.draftStore.updateByGetDraftResp(!0,a)}.bind(this))},_getMsgPreloadIds:function(){var t,e=this.msgStore.getDefaultExpandIds(!0);return t=e.filter(function(t){return void 0!==this.msgStore.getById(t)},this).map(function(t){
return this.msgStore.getById(t).get("operation_ids")},this),[].concat.apply([],t)},_getDraftPreloadIds:function(){return this.draftStore.getAll().map(function(t){return t.get("id")})},_guard:function(t,e){return this.guarder.guard(t,e||this)},_guardPromise:function(t){return this.guarder.guardPromise(t)}}),Ext.define("SYNO.SDS.MailClient.MessageLib.NoteStation",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageLib.NoteStation.UrlBuilder"],checkNoteStationVersion:function(){var t,e="SYNO.SDS.NoteStation.Application";return!!SYNO.SDS.StatusNotifier.isAppEnabled(e)&&!!((t=SYNO.SDS.Config.FnMap[e])&&t.config&&t.config.version&&t.config.version>"1.1-0174")},prepareParamsForNoteSataion:function(t,e,i){var n,a,o=[];return a=this.processInlineImageForNoteStation(e),Ext.each(a.images,function(t){o.push({rotate:!1,action:"create",format:"url",name:"inline_image",source:t.src,ref:t.ref})},this),Ext.each(i,function(t){o.push({rotate:!1,action:"create",format:"url",name:t.name,source:SYNO.SDS.MailClient.MessageLib.UrlBuilder.getAttachmentDownloadUrlWithFileHash(t)})},this),n={title:t,parent_id:"preset",content:a.html,commit_msg:{first_version:!1}},o.length>0&&(n.attachment=o),n},processInlineImageForNoteStation:function(t){var e,i,n,a=[];return e=document.createElement("div"),e.innerHTML=t,i=Ext.get(e).select("img[syno-mc-cid]"),i.each(function(t){var e,i;e=t.getAttribute("syno-mc-cid"),i=t.getAttribute("src"),t.set({ref:e,adjust:"true"}),t.addClass("syno-notestation-image-object"),a.push({src:i,ref:e})},this),n=e.innerHTML,{html:n,images:a}}}),Ext.define("SYNO.SDS.MailClient.MessageLib.ThreadMonitor",{extend:"Ext.util.Observable",requires:[],constructor:function(t){this.callParent(arguments),this.addEvents("threadchange","emptymsg"),this.initMonitor()},initMonitor:function(){},bind:function(t,e){this.bindRecord(t),this.bindStore(e)},unbind:function(){this.bindRecord(null),this.bindStore(null)},bindRecord:function(t){this.threadRecord=t},bindStore:function(t){this.threadStore!==t&&(this.threadStore&&this.munStore(this.threadStore),this.threadStore=t,this.threadStore&&this.monStore(this.threadStore))},monStore:function(t){t.on({update:this.onStoreUpdate,datachanged:this.onStoreDataChanged,scope:this})},munStore:function(t){t.un("update",this.onStoreUpdate,this),t.un("datachanged",this.onStoreDataChanged,this)},refresh:function(){this.fireEvent("threadchange",this.threadRecord)},checkAndUpdateThreadRecord:function(t){this.threadRecord.data=t.data,this.fireEvent("threadchange",this.threadRecord)},onStoreUpdate:function(t,e,i){this.threadRecord&&this.threadRecord.id===e.id&&this.checkAndUpdateThreadRecord(e)},onStoreDataChanged:function(t){if(this.threadRecord){var e=t.getById(this.threadRecord.get("id"));e?this.checkAndUpdateThreadRecord(e):this.fireEvent("emptymsg")}}}),Ext.define("SYNO.SDS.MailClient.MessageLib.FileIconType",{extend:"Ext.util.Observable",singleton:!0,requires:[],data:{pptx:"ppt",ppt:"ppt",docx:"doc",doc:"doc",docm:"doc",dot:"doc",dotm:"doc",odt:"doc",xps:"doc",xlsx:"xls",xls:"xls",xlsm:"xls",xlt:"xls",xltm:"xls",xltx:"xls",xlw:"xls",mobi:"txt",azw3:"txt",prc:"txt",pdb:"txt",c:"txt",cc:"txt",cpp:"txt",hpp:"txt",h:"txt",asp:"txt",aspx:"txt",php:"txt",cgi:"txt",php4:"txt",php5:"txt",jsp:"txt",jspx:"txt",txt:"txt",js:"code",htm:"htm",html:"htm",xml:"htm",xhtm:"htm",xhtml:"htm",rhtml:"htm",shtml:"htm",html5:"htm",avi:"video",rmvb:"video",mpg:"video",mpeg:"video",m4v:"video",mp4:"video",mkv:"video",flv:"video",wmv:"video",yuv:"video",vob:"video",asf:"video","3gp":"video",ani:"image",bmp:"image",cal:"image",fax:"image",img:"image",jpg:"image",jpe:"image",jpeg:"image",gif:"image",mac:"image",pbm:"image",pcd:"image",pcx:"image",pct:"image",pgm:"image",png:"image",ppm:"image",ras:"image",tga:"image",tiff:"image",wmf:"image",heic:"image",aac:"audio",ac3:"audio",aif:"audio",aiff:"audio",ape:"audio",cue:"audio",dff:"audio",dsf:"audio",flac:"audio",m3u:"audio",m4a:"audio",m4b:"audio",m4p:"audio",mp1:"audio",mp2:"audio",mp3:"audio",mpa:"audio",ogg:"audio",pcm:"audio",pls:"audio",ra:"audio",ram:"audio",wav:"audio",wma:"audio",wpl:"audio",pdf:"pdf",psd:"psd",exe:"exe",ai:"ai",iso:"iso",zip:"zip",rar:"zip","7z":"zip",indd:"idn",indt:"idn",swf:"swf",fla:"fla",acc:"acc",bkpi:"bkpi",ttf:"ttf"},getType:function(t){return this.data[t]}}),Ext.define("SYNO.SDS.MailClient.MessageLib.UrlBuilder",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.MessageLib.FileIconType"],getAttachmentImageURL:function(t,e){var i,n,a,o="";return"[object File]"===Object.prototype.toString.call(t)?0===t.type.indexOf("image/")?'src="'+URL.createObjectURL(t)+'"':(o=t.name.split(".").pop(),'src="'+this.getFileIconUrl(o)+'"'):Ext.isObject(t)&&void 0!==t.name?(n=SYNO.SDS.MailClient.Format.toAttachmentName(t).split("."),n.length>1&&(o=n.pop().toLowerCase()),t.mimetype&&this._isThumbConvertType(t.mimetype,o)?(a=SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Attachment","download",6))?(i={id:t.id,type:"thumb"},e&&(i.dc=(+new Date).toString()),'src="'+(a=Ext.urlAppend(a,Ext.urlEncode(i)))+'" ext="'+o+'"'):"":'src="'+this.getFileIconUrl(o)+'"'):""},getAttachmentDownloadUrl:function(t){return String.format("{0}/{1}",this.getLocalUrlPrefix(),SYNO.SDS.MailClient.Format.getAttachmentDownloadUrl(t,!0))},getAttachmentDownloadUrlWithFileHash:function(t){return String.format("{0}/{1}",this.getLocalUrlPrefix(),SYNO.SDS.MailClient.Format.getAttachmentDownloadUrlWithFileHash(t,!0))},getOriginalMessageUrl:function(t){return String.format("{0}&{1}",SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Message","get_original",8,!0),Ext.urlEncode({id:t.get("id")}))},getOriginalMessageDownloadUrl:function(t){return String.format("{0}&{1}",SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Message","download_original",8,!0),Ext.urlEncode({id:t.get("id")}))},getFileIconUrl:function(t){var e=SYNO.SDS.MailClient.Window.appInstance.jsConfig.version;return this._getFileIconUrl(t)+"?v="+e},_getFileIconUrl:function(t){return"webman/3rdparty/MailClient/images/"+(SYNO.SDS.UIFeatures.test("isRetina")?"2x":"1x")+"/_FileType/"+(this._getFileIconType(t)||"xxx")+".png"},_getFileIconType:function(t){return SYNO.SDS.MailClient.MessageLib.FileIconType.getType(t)},getLocalUrlPrefix:function(){var t=/(^\/([^\\\/])*?)\//.exec(window.location.pathname),e=t?t[1]:"";return String.format("{0}//{1}{2}",location.protocol,location.host,e)},_isThumbConvertType:function(t,e){var i=["image/jpeg","image/png","image/tiff","image/bmp","image/heic","image/heic-sequence","image/heif","image/heif-sequence"];return-1!==["jpg","jpeg","jpe","png","tif","tiff","bmp","heic","heif","gif","psd"].indexOf(e)||-1!==i.indexOf(t)}}),Ext.define("SYNO.SDS.MailClient.UtilLib.CallbackGuarder",{extend:"Ext.util.Observable",requires:[],constructor:function(t){this.callParent(arguments),this.revokeCount=0},guard:function(t,e){var i=this.revokeCount;return function(){this.revokeCount>i||t.apply(e||window,arguments)}.bind(this)},guardPromise:function(){var t=this.revokeCount;return function(e){return this.revokeCount>t?new Promise(function(){}):Promise.resolve(e)}.bind(this)},revoke:function(){++this.revokeCount}}),Ext.define("SYNO.SDS.MailClient.MessageLib.MsgVault",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.MessageHouseLib.Keeper","SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache","SYNO.SDS.MailClient.MessageLib.Attachment","SYNO.SDS.MailClient.MessageLib.BodyProcessor","SYNO.SDS.MailClient.Message.ExtraPanelMgr","SYNO.SDS.MailClient.Message.ListTpl","SYNO.SDS.MailClient.Model.DraftStore","SYNO.SDS.MailClient.MessageLib.MsgCache","SYNO.SDS.MailClient.MessageLib.MsgStore","SYNO.SDS.MailClient.MessageLib.MsgProvider","SYNO.SDS.MailClient.MessageLib.NoteStation","SYNO.SDS.MailClient.MessageLib.ThreadMonitor","SYNO.SDS.MailClient.MessageLib.UrlBuilder","SYNO.SDS.MailClient.UtilLib.CallbackGuarder"],constructor:function(t){this.callParent(arguments),this.addEvents("newmsg"),this.initVault()},initVault:function(){this.draftStore=new SYNO.SDS.MailClient.Model.DraftStore,this.msgStore=new SYNO.SDS.MailClient.MessageLib.MsgStore,this.msgProvider=new SYNO.SDS.MailClient.MessageLib.MsgProvider,this.threadMonitor=this.createThreadMonitor(),this.guarder=new SYNO.SDS.MailClient.UtilLib.CallbackGuarder,SYNO.SDS.MailClient.MessageHouseLib.Keeper.bind(this.msgStore)},prepareMsg:function(){return this.msgProvider.prepareMsg()},guard:function(t,e){return this.guarder.guard(t,e||this)},guardPromise:function(t){return this.guarder.guardPromise(t)},createThreadMonitor:function(){var t=new SYNO.SDS.MailClient.MessageLib.ThreadMonitor;return t.on({threadchange:this.onThreadMonitorThreadChange,emptymsg:this.onThreadMonitorEmptyMsg,scope:this}),t},setThreadRecord:function(t){var e=SYNO.SDS.MailClient.MessageHouseLib.Keeper;this.threadRecord=t,e.updateByThreadMsgs(this.threadRecord.get("message"))},checkNewMsg:function(t){if(!this.threadRecord)return Promise.resolve();var e=SYNO.SDS.MailClient.MessageHouseLib.Keeper,i=this.threadRecord.id;return-1===t.indexOf(i)?Promise.resolve():e.checkNewMsg(i).then(this.guardPromise()).then(function(t){if(!t)return Promise.resolve();var e,i=t[0].message,n=t[1]?["blockquote"]:["blockquote","block_external_image"],a=t[2];e={message:i,additional:n},this.fireEvent("newmsg",e,a)}.bind(this))},onThreadMonitorThreadChange:function(t){this.setThreadRecord(t),this.fireEvent("threadchange",t)},onThreadMonitorEmptyMsg:function(){this.fireEvent("emptymsg")},unbind:function(){this.unbindThreadMonitor(),this.guarder.revoke(),this.msgStore.removeAll(),this.draftStore.removeAll()},bind:function(t,e){this.threadRecord=t,this.threadStore=e,this.bindThreadMonitor(),this.bindMsgProvider(),this.msgStore.cached=SYNO.SDS.MailClient.MessageHouseLib.Cache,this.msgStore.cachedInlineImage=SYNO.SDS.MailClient.MessageHouseLib.InlineImageCache,this.load()},bindThreadMonitor:function(){this.threadMonitor.bind(this.threadRecord,this.threadStore)},bindMsgProvider:function(){this.msgProvider.bind(this.msgStore,this.draftStore,this.guarder)},unbindThreadMonitor:function(){this.threadMonitor.unbind()},load:function(){var t,e,i=this.threadRecord;this.threadRecord&&(t=i.get("message"),e=i.get("draft"),this.msgStore.loadMsg(t),this.draftStore.loadDraft(e))},refresh:function(){var t=SYNO.SDS.MailClient.MessageHouseLib.Keeper,e=this.threadRecord,i=e.get("message");t.updateByThreadMsgs(i)},purgeInvalidCache:function(){var t=SYNO.SDS.MailClient.MessageHouseLib.Keeper,e=this.threadRecord,i=e.get("message");t.purgeInvalidCache(i)}}),Ext.define("SYNO.SDS.MailClient.Lib.MsgVault",{extend:"SYNO.SDS.MailClient.MessageLib.MsgVault",singleton:!0}),Ext.define("SYNO.SDS.MailClient.MessagePanel",{extend:"SYNO.SDS.MailClient.BasePanel",xtype:"mc_MessagePanel",refreshMessageViewInterval:6e4,constructor:function(t){window.mp=this,this.callParent([this.fillConfig(t)]),this.delayedContentChangeTask=new Ext.util.DelayedTask(this.updateScroller,this),this.refreshMessageViewTask=new Ext.util.DelayedTask(function(){this.getComponent("messageList").updateArrivalTime(),this.refreshMessageViewTask&&this.refreshMessageViewTask.delay(this.refreshMessageViewInterval)},this),this.guarder=new SYNO.SDS.MailClient.UtilLib.CallbackGuarder,this.addEvents("clickclearselection","emptymessage"),this.on({scope:this,resize:function(t,e,i,n,a,o){this.getComponent("messageSelection").setSize(e-12,i-(this.toolbarHeight||44)),this.getComponent("messageComposer").adjComponentSize(e-this.el.getPadding("lr"),i-this.el.getPadding("tb")),this.getComponent("messageList").adjCalendarAndSubscribePanelSize()},afterrender:function(t){this.notify=new SYNO.SDS.MailClient.MessageNotify({renderCmp:this,alignOffset:[0,36],scope:this,handler:function(){this.appendNewMsg(),this.jumpToNewMsg(),this.switchNewMsgHintVisible()}}),SYNO.SDS.MailClient.Define.isNormalMode&&this.initKeyNav()},flexcrollinitdone:function(){this.getContentTarget().dom.fleXdata&&(this.getContentTarget().dom.fleXdata.fixIEDispBug=Ext.emptyFn,this.getContentTarget().dom.fleXdata.keyAct["_"+Ext.EventObject.SPACE]=[0,"1p"])}}),this.clearNewMsgs(),this.noSelection=!0,this.layout.renderItem=function(t,e,i){t&&(t.rendered?this.isValidParent(t,i)||(Ext.isNumber(e)&&(e=i.dom.childNodes[e]),t.getPositionEl().dom!==e&&i.dom.insertBefore(t.getPositionEl().dom,e||null),t.container=i,this.configureItem(t)):(t.render(i,e),this.configureItem(t)))};var e=SYNO.SDS.MailClient.KeyNavigator.ShortCut;SYNO.SDS.MailClient.Window.regShortCut(this,[e.REPLY,e.REPLY_ALL,e.FORWARD,e.BACK_TO_THREAD]),t.handleShortCutThread&&SYNO.SDS.MailClient.Window.regShortCut(this,[e.UP_THREAD,e.DOWN_THREAD]),SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")&&SYNO.SDS.JSLoad("SYNO.Cal.Create.Popup.Container")},guard:function(t,e){return this.guarder.guard(t,e||this)},getThread:function(){return this.threadRec},getThreadSubject:function(){if(!this.threadRec)return null;var t=this.threadRec.get("message");return t&&t[0]?t[0].subject:null},fillConfig:function(t){this.threadAction=SYNO.SDS.MailClient.Lib.ThreadAction;var e=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,i={border:!1,cls:"syno-mc-message-panel",bodyCssClass:"syno-mc-message-panel-body",autoFlexcroll:!1,flexcrollPosFix:!1,updateFormForScrollbar:!0,boxMinWidth:100,boxMinHeight:100,tbar:this.toolbar=new SYNO.SDS.MailClient.MessageToolbar({hidden:!0,hideBack:t.hideBack,hidePrevNext:t.hidePrevNext,displayInfo:t.displayInfo,hideOpen:t.hideOpen,listeners:{scope:this,backclick:this.backToThread.createDelegate(this,[!0]),printclick:this.clickPrint,openclick:this.openNewWindow,collapseclick:function(){this.getComponent("messageList").collapseAll()},expandclick:function(){this.getComponent("messageList").expandAll()}}}),items:[new SYNO.SDS.MailClient.MessageSubject({itemId:"messageSubject",threadAction:this.threadAction,hidden:!t.hideOpen,enableDrop:!0,ddGroup:"threadDDGroup",dropSource:["label"],drop:this.onLabelDrop.bind(this),listeners:{scope:this,contentchange:function(){this.delayedContentChangeTask.delay(150)},afterrender:function(t){SYNO.SDS.MailClient.SynoCalendarPlugin.bind(this.getComponent("messageSubject").el),t.dropZone||!t.enableDrop&&!t.enableDD||(t.dropZone=new SYNO.SDS.MailClient.BasicListViewDropZone(t,{ddGroup:t.ddGroup,dropSource:t.dropSource}))}}}),new SYNO.SDS.MailClient.MessageList({itemId:"messageList",hidden:!t.hideOpen,enableDrop:!0,ddGroup:"threadDDGroup",dropSource:["label"],drop:this.onLabelDrop.bind(this),listeners:{scope:this,contentchange:this.updateScroller,printclick:this.clickPrint,showallmessageclick:this.clickShowAllMessage,singledelete:this.clickSingleDelete,singleaddtoblacklist:this.clickSingleAddToBlackList,singleaddtowhitelist:this.clickSingleAddToWhiteList,afterrender:function(t){SYNO.SDS.MailClient.SynoCalendarPlugin.bind(this.getComponent("messageList").el),t.dropZone||!t.enableDrop&&!t.enableDD||(t.dropZone=new SYNO.SDS.MailClient.BasicListViewDropZone(t,{ddGroup:t.ddGroup,dropSource:t.dropSource}))},toggled:function(t,e){e.length==this.msgStore.getCount()?this.toolbar.setExpandCollapseVisible(!1,!0):this.toolbar.setExpandCollapseVisible(!0,!1)}}}),new SYNO.SDS.MailClient.MessageComposer({messagePanel:this,itemId:"messageComposer",hidden:!t.hideOpen,listeners:{scope:this,contentchange:this.updateScroller,scrollto:function(t){this.nativeScrollTo(t)},beforefocusfakeinput:function(){this.originalScrollTop=this.el.query(".syno-mc-message-panel-body")[0].scrollTop},focusfakeinput:function(){this.el.query(".syno-mc-message-panel-body")[0].scrollTop=this.originalScrollTop}}}),new SYNO.SDS.MailClient.MessageSelection({itemId:"messageSelection",hidden:t.hideOpen,actionButton:SYNO.SDS.MailClient.Lib.Factory.createActionButtonsByInfo([{type:"GhostButton",actionId:e.RemoveLabel},{type:"GhostButton",actionId:e.Archive},{type:"GhostButton",actionId:e.DeleteMail},{type:"GhostButton",actionId:e.DeleteForever},{type:"GhostButton",actionId:e.DiscardDraft},{type:"GhostButton",actionId:e.ArchiveInLabel},{type:"GhostButton",actionId:e.MoveTo},{type:"GhostSplitButton",actionId:e.Spam},{type:"GhostSplitButton",actionId:e.NotSpam},{type:"GhostButton",actionId:e.Label},{type:"GhostButton",actionId:e.More}]),listeners:{scope:this,clickclearselection:function(){this.fireEvent("clickclearselection")}}})],listeners:{scope:this,emptymessage:function(){},clickclearselection:function(){SYNO.SDS.MailClient.Define.isMessageMode&&window.close()}}};return Ext.apply(i,t)},clickPrint:function(t,e){if(this.threadRec){var i,n,a=[],o=[];if(void 0!==t)a.push(this.msgStore.getAt(t).id),n=this.msgStore.getAt(t).get("subject");else{if(this.msgStore.getCount())for(n=this.msgStore.getAt(0).get("subject"),i=0;i<this.msgStore.getCount();++i)a.push(this.msgStore.getAt(i).id);if(this.draftStore.getCount())for(n=n||this.draftStore.getAt(0).get("subject"),i=0;i<this.draftStore.getCount();++i)o.push(this.draftStore.getAt(i).id)}var s=!!e||this.getComponent("messageList").getMessageIdWithUIInfo("blockquote",t),l={pm:Ext.encode(a),ui:Ext.encode(s),print:Ext.encode(!e)};o.length&&(l.pd=Ext.encode(o)),SYNO.SDS.MailClient.Tool.openNewWindow(l,n,!0)}},clickShowAllMessage:function(t){this.clickPrint(t,!0)},clickSingleDelete:function(t){var e=[],i=this.msgStore.getAt(t);this.threadRec&&i&&(e=i.get("operation_ids"),e.length&&this.threadAction.messageToTrash(e,[this.threadRec.data]))},clickSingleAddToBlackList:function(t){var e=[],i=this.msgStore.getAt(t);this.threadRec&&i&&(e=i.get("operation_ids"),e.length&&this.threadAction.messageAddToSpamRule(e,[this.threadRec.data],!0))},clickSingleAddToWhiteList:function(t){var e=[],i=this.msgStore.getAt(t);this.threadRec&&i&&(e=i.get("operation_ids"),e.length&&this.threadAction.messageAddToSpamRule(e,[this.threadRec.data],!1))},openNewWindow:function(){if(this.threadRec){var t=this.getComponent("messageList").getMessageIdWithUIInfo("expand"),e={t:this.threadRec.id,ui:Ext.encode(t)};SYNO.SDS.MailClient.Tool.openNewWindow(e,this.threadRec.get("subject"),!1)}},getHighlightKeywords:function(){return SYNO.SDS.MailClient.MessageHouseLib.CachePreprocessor.getHighlightKeywords()},showEmptyPanel:function(){var t=SYNO.SDS.MailClient.Settings.conversation_view;this.showSelection(!0,0,SYNO.SDS.MailClient._T("mail",t?"no_conversation_selected":"no_message_selected")),this.fireClearCheckThread()},fireCheckThisThread:function(){SYNO.SDS.MailClient.Control.Selection.selectThread([this.threadRec])},fireClearCheckThread:function(){SYNO.SDS.MailClient.Control.Selection.selectThread([])},getVaultEventList:function(){return{threadchange:this.onVaultThreadChange,emptymsg:this.onVaultEmptyMsg,newmsg:this.onVaultNewMsg,scope:this}},monVault:function(){SYNO.SDS.MailClient.Lib.MsgVault.on(this.getVaultEventList())},munVault:function(){var t=SYNO.SDS.MailClient.Lib.MsgVault,e=this.getVaultEventList();Ext.iterate(e,function(e,i){"scope"!==e&&t.un(e,i,this)},this)},onVaultThreadChange:function(t){this.threadRec&&this.threadRec.get("id")==t.get("id")&&(this.getComponent("messageSubject").storeUpdate(),this.getComponent("messageComposer").storeUpdate(),this.autoSelectThread())},onVaultEmptyMsg:function(){this.showEmptyPanel(),this.backToThread(!0),this.fireEvent("emptymsg")},onVaultNewMsg:function(t,e){this.newMsgs=t,this.newMsgPreview=e,this.switchNewMsgHintVisible()},loadMessage:function(t){var e=SYNO.SDS.MailClient.Lib.MsgVault;this.reset(),this.resetThreadStore();var i=this.threadStore.getById(t);return i?(SYNO.SDS.MailClient.Lib.MsgVault.bind(i,this.threadStore),this.msgStore=e.msgStore,this.draftStore=e.draftStore,this.threadRec=i,this.showSelection(!1),this.fireCheckThisThread(),this.messageLoading=!0,this.getComponent("messageSubject").loadMessage(this.threadRec,e.msgStore,e.draftStore),this.getComponent("messageSubject").highlightKeywords=this.getHighlightKeywords(),this.getComponent("messageList").loading(),this.getComponent("messageList").highlightKeywords=this.getHighlightKeywords(),this.getComponent("messageComposer").loadMessage(this.threadRec),this.mask(),SYNO.SDS.MailClient.Lib.MsgVault.purgeInvalidCache(),SYNO.SDS.MailClient.Lib.MsgVault.prepareMsg().then(this.prefetchForInitialExpandedMsgs.bind(this,this.msgStore,this.getDefaultExpandIds(this.msgStore))).then(function(){this.unMask(),this.messageIsReady(),this.messageLoading=!1}.bind(this)).catch(function(){this.unMask(),this.messageLoading=!1}.bind(this))):void this.showEmptyPanel()},prefetchForInitialExpandedMsgs:function(t,e){var i,n,a=SYNO.SDS.MailClient.Settings.display_external_image;return i=e.filter(function(e){return void 0!==t.getById(e)},this).map(function(e){return t.getById(e)},this),n=i.map(function(t){return SYNO.SDS.MailClient.MessageHouseLib.Keeper.prefetchImageInFullMsgRecord(t,a)}),Promise.all(n).catch(function(t){}.bind(this))},getDefaultExpandIds:function(t){return this.getComponent("messageList").getDefaultExpandIds(t)},refresh:function(){this.getComponent("messageList").refresh()},refreshInlineImage:function(){var t=function(t,e){var i,n=t.getAttribute(e).split("?");2===n.length&&(i=Ext.urlDecode(n[1]),i.download_token=SYNO.SDS.MailClient.Info.download_token,t.dom.setAttribute(e,Ext.urlAppend(n[0],Ext.urlEncode(i))))}.bind(this);this.el.select("img[src][syno-mc-cid]:not([syno-mc-url])").each(function(e){t(e,"src")},this),this.el.select("img[syno-mc-url][syno-mc-cid]").each(function(e){t(e,"syno-mc-url")},this)},resetThreadStore:function(){var t=SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore();this.threadStore&&this.threadStore!=t&&(this.getTopToolbar().bindStore(null),this.threadStore=t,this.threadStore&&this.getTopToolbar().bindStore(this.threadStore))},arm:function(){this.monVault(),this.toolbar.arm(),this.getComponent("messageSubject").arm(),this.getComponent("messageList").arm(),this.getComponent("messageComposer").arm(),this.getComponent("messageSelection").arm(),this.threadStore=SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore(),this.threadStore&&this.getTopToolbar().bindStore(this.threadStore)},disarm:function(){this.munVault(),this.reset(),this.toolbar.disarm(),this.getComponent("messageSubject").disarm(),this.getComponent("messageList").disarm(),this.getComponent("messageComposer").disarm(),this.getComponent("messageSelection").disarm(),this.threadStore&&this.getTopToolbar().bindStore(null)},reset:function(){delete this.threadRec,delete this.reloadMask,this.clearNewMsgs(),this.switchNewMsgHintVisible(),SYNO.SDS.MailClient.Lib.MsgVault.unbind(),this.refreshMessageViewTask&&this.refreshMessageViewTask.cancel(),this.setReadDelay&&(this.setReadDelay.cancel(),delete this.setReadDelay),this.getComponent("messageSubject").reset(),this.getComponent("messageList").reset(),this.getComponent("messageComposer").reset(),this.toolbar.reset(),this.unMask()},autoSelectThread:function(){this.noSelection&&this.fireCheckThisThread()},checkListView:function(t){var e;this.noSelection=!t.length,0===t.length&&this.threadRec&&this.threadStore.getById(this.threadRec.get("id"))?(this.showSelection(!1),this.switchNewMsgHintVisible(),this.fireCheckThisThread()):(e=t.length,"allthread"===t&&(e=this.threadStore.getTotalCount()),this.showSelection(!0,e),this.switchNewMsgHintVisible(!0),SYNO.SDS.MailClient.Control.Selection.selectThread(t)),this.updateScroller()},updateScroller:function(){if(!this.autoFlexcroll)return void(this.fakeInitFlexcrollDone||(this.fireEvent("flexcrollinitdone"),this.fakeInitFlexcrollDone=!0));this.callParent(arguments)},nativeScrollTo:function(t){var e=Ext.fly(t);e&&e.dom&&e.dom.scrollIntoView()},getCheckedItemRecords:function(){return this.threadRec?[this.threadRec]:[]},messageIsReady:function(){this.getComponent("messageList").loadMessage(this.threadRec,this.msgStore,this.draftStore),this.getComponent("messageSubject").loadMessage(this.threadRec,this.msgStore,this.draftStore),this.getComponent("messageComposer").loadMessage(this.threadRec,this.msgStore,this.draftStore),this.updateToolbar(),this.threadRec.get("unread")&&this.setReadThread(),this.refreshMessageViewTask.delay(this.refreshMessageViewInterval)},setReadThread:function(){var t=[this.threadRec.get("id")];this.setReadDelay=new Ext.util.DelayedTask(this._setReadThread.bind(this,t,!0)),this.setReadDelay.delay(1e3*SYNO.SDS.MailClient.Settings.mark_as_read_time)},_setReadThread:function(t,e){return SYNO.SDS.MailClient.Lib.ThreadAction.doMarkRead(t,e)},isThreadId:function(t){return this.threadRec&&this.threadRec.get("id")===t},appendSendingDraft:function(t,e,i){var n=SYNO.SDS.MailClient.MessageHouseLib.Keeper,a=n.appendSendingDraft(this.threadRec.get("id"),t,e,i);this.getComponent("messageComposer").setReFwdButtonsVisibility(),this.getComponent("messageList").clickRecords(a)},updateSentDraft:function(t){if(this.threadRec){var e=SYNO.SDS.MailClient.MessageHouseLib.Keeper,i=this.threadRec.get("id");e.updateSendingDraftToSent(i,t),this.getComponent("messageComposer").setReFwdButtonsVisibility(),this.updateToolbar()}},resumeEditor:function(t,e,i){this.msgStore.removeFakeSentMsg(e),this.getComponent("messageComposer").resumeEditor(t,e,i)},onSwitchDraftChange:function(t,e){if(this.threadRec){var i,n,a=SYNO.SDS.MailClient.Define.draftsId===SYNO.SDS.MailClient.Switch.inMailboxId;for(i=0;i<e.length;i++)if(e[i].id===this.threadRec.get("id")||a&&Ext.isArray(e[i].data)&&e[i].data.indexOf(this.threadRec.get("id"))>-1){n=e[i].data;break}if(n){if("add"===t)this.draftStore.add(new this.draftStore.recordType(n,n.id));else if("edit"===t);else if("delete"===t){for(i=0;i<n.length;i++)this.draftStore.remove(this.draftStore.getById(n[i]));this.getComponent("messageComposer").onSwitchDeleteDrafts(n)}if(SYNO.SDS.MailClient.Define.isMessageMode){var o=["messageSubject","messageList","messageComposer","messageSelection"];if(!this.draftStore.getCount()&&!this.msgStore.getCount()){for(i=0;i<o.length;++i)this.getComponent(o[i]).setVisible("messageSelection"==o[i]);this.disarm()}}else a&&!this.draftStore.getCount()&&(SYNO.SDS.MailClient.Control.Mail.clearMessage(),SYNO.SDS.MailClient.Control.Mail.backToThreadAndKeepUrl())}}},switchNewMsgHintVisible:function(t){var e=SYNO.SDS.MailClient.Settings,i=-1===this.newMsgs.additional.indexOf("block_external_image");(i&&!e.display_external_image||!i&&e.display_external_image)&&(this.newMsgs={message:[],additional:[]},this.newMsgPreview={}),!0===t||this.getComponent("messageSelection").isVisible()||!this.newMsgs.message.length?this.notify.hideNotify(!0):this.notify.showNotifyText(String.format(SYNO.SDS.MailClient._T("mail","new_message_count"),this.newMsgs.message.length),!0)},clearNewMsgs:function(){this.newMsgs={message:[],additional:[]},this.newMsgPreview={}},appendNewMsg:function(){var t,e=SYNO.SDS.MailClient.MessageHouseLib.Keeper,i=e.addNewMsg(this.newMsgPreview,this.newMsgs),n=this.getComponent("messageList");t=i.some(function(t){return!t.get("read")}),i.forEach(function(t){n.clickRecords(t)}),this.clearNewMsgs(),t&&(this.setReadDelay?this.setReadDelay.delay(1e3*SYNO.SDS.MailClient.Settings.mark_as_read_time):this.setReadThread()),this.updateToolbar()},jumpToNewMsg:function(){var t,e=this.getComponent("messageSubject").getHeight(),i=this.getComponent("messageList").getNodes();for(t=0;t<i.length-1;++t)e+=i[t].offsetHeight;this.body.scrollTo("top",e)},showSelection:function(t,e,i){var n,a=["messageSubject","messageList","messageComposer"];if(!0!==this.messageLoading){for(this.getComponent("messageSelection").setVisible(t).updateSelectionText(e||"",i),n=0;n<a.length;++n)this.getComponent(a[n]).setVisible(!t);return this.toolbar.setVisible(!t),this}},updateToolbar:function(){this.threadRec&&this.getComponent("messageList").store&&(this.toolbar.loadMessage(this.threadRec,this.msgStore,this.draftStore),this.getComponent("messageList").getToggledItemIds().length==this.msgStore.getCount()&&this.msgStore.getCount()>1&&this.toolbar.setExpandCollapseVisible(!1,!0))},mask:function(){this.el.mask().addClass("syno-mc-transparent")},unMask:function(){this.el.unmask()},backToThread:function(t){SYNO.SDS.MailClient.Control.Mail.backToThread(),this.fireEvent("navigate","left",{clearSelections:t})},initKeyNav:function(){this.body.set({tabIndex:0}),this.keyNav=new Ext.KeyNav(this.el,{scope:this,backspace:this.onKeyLeft,left:this.onKeyLeft}),!Ext.isWindows&&Ext.isGecko||(this.keyNav.keyToHandler[8]="backspace")},onKeyLeft:function(t){return this.backToThread(),!0},onNavigateOut:function(){this.getComponent("messageList").clearSelections()},onNavigateIn:function(t){if(this.ownerCt.isVisible()&&this.isVisible())return"right"===t?(this.body.focus(),!0):void 0},onShortCut:function(t){var e,i=SYNO.SDS.MailClient.KeyNavigator.ShortCut;if(this.activated&&this.threadRec&&!this.getComponent("messageSelection").isVisible()){if(-1!==[i.REPLY,i.REPLY_ALL,i.FORWARD].indexOf(t))return this.getComponent("messageComposer").onShortCutReFwd(t);if(i.BACK_TO_THREAD===t)return this.backToThread(),!0;if(i.UP_THREAD===t?e=-1:i.DOWN_THREAD===t&&(e=1),e&&!this.el.isMasked())return SYNO.SDS.MailClient.Switch.loadMessageByIdxDiff(this.threadRec.id,e),!0}},hasEditor:function(){return this.getComponent("messageComposer").editors.length>0},onLabelDrop:function(t,e){if("label"===e.source){var i=e.data,n=this.threadRec.data;SYNO.SDS.MailClient.Lib.ThreadAction.threadChangeLabel([n],[i],[])}}}),Ext.define("SYNO.SDS.MailClient.ThreadMessagePanel",{extend:"SYNO.SDS.MailClient.BasePanel",requires:["SYNO.SDS.MailClient.MessagePanel","SYNO.SDS.MailClient.ThreadPanel"],xtype:"mc_ThreadMessagePanel",constructor:function(t){this.callParent([this.fillConfig(t)]),window.tmp?window.tmp2=this:window.tmp=this,SYNO.SDS.MailClient.Window.addPanel("SYNO.SDS.MailClient.ThreadMessagePanel",this)},fillConfig:function(t){this.threadCardPanel=new SYNO.SDS.MailClient.ThreadCardPanel({itemId:"threadCardPanel",cls:"mc-thread",displayInfo:!0,handleShortCutThread:!0,region:"west",split:!0,smallLayout:!0,width:SYNO.SDS.MailClient.UserSettingProperty.getThreadWidth(),minWidth:340,keepScroll:function(){var t=!1;return this.view.el&&this.view.el.dom&&this.view.el.dom.fleXdata?((this.view.displayedNodeId||this.view.getCheckedItemRecords().length||0!==this.view.el.dom.fleXdata.scrollPosition[1][0])&&(t=!0),t):t},listeners:{resize:function(t,e,i,n,a,o){SYNO.SDS.MailClient.UserSettingProperty.setThreadWidth(e)}}}),this.messagePanel=new SYNO.SDS.MailClient.MessagePanel({itemId:"messagePanel",region:"center",minWidth:100,displayInfo:!1,hideBack:!0,hidePrevNext:!0,listeners:{scope:this,clickclearselection:function(){this.threadCardPanel.clearSelections()},emptymsg:function(){this.threadCardPanel.clickNext()}}});var e={border:!1,layout:"border",cls:"syno-mc-thread-message-panel",bodyCssClass:"syno-mc-thread-message-panel-body",items:[this.threadCardPanel,this.messagePanel],listeners:{activate:function(){SYNO.SDS.MailClient.Switch.inPriority?this.threadCardPanel.switchToPriorityMailbox():this.threadCardPanel.switchToNormalMailbox()}}};return Ext.apply(e,t)},arm:function(){this.threadCardPanel.activated=this.messagePanel.activated=this.activated,this.threadCardPanel.arm(),this.messagePanel.arm()},disarm:function(){this.threadCardPanel.activated=this.messagePanel.activated=this.activated,this.threadCardPanel.disarm(),this.messagePanel.disarm()},layoutChange:function(t){t&&this.threadCardPanel.layoutChange(t)}}),Ext.define("SYNO.SDS.MailClient.CardPanel",{extend:"SYNO.ux.Panel",xtype:"mc_CardPanel",constructor:function(t){t=t||{},this.callParent([this.fillConfig(t)]),SYNO.SDS.MailClient.Window.addPanel("SYNO.SDS.MailClient.CardPanel",this),this.on("resize",SYNO.SDS.MailClient.Switch.cardWidthChange,SYNO.SDS.MailClient.Switch)},fillConfig:function(t){var e=[];SYNO.SDS.MailClient.Define.isNormalMode?(this.threadCardPanel=new SYNO.SDS.MailClient.ThreadCardPanel({itemId:"threadCardPanel",displayInfo:!0}),this.messagePanel=new SYNO.SDS.MailClient.MessagePanel({itemId:"messagePanel",displayInfo:!0,hidePrevNext:!1,handleShortCutThread:!0}),this.threadMessagePanel=new SYNO.SDS.MailClient.ThreadMessagePanel({cls:"syno-mc-thread-message-panel",
itemId:"threadMessagePanel"}),e=[this.threadCardPanel,this.messagePanel,this.threadMessagePanel]):(this.messagePanel=new SYNO.SDS.MailClient.MessagePanel({itemId:"messagePanel",displayInfo:!1,hideBack:!0,hidePrevNext:!0,hideOpen:!0}),e=[this.messagePanel]);var i="syno-mc-card ";t&&t.cls&&(i+=t.cls,delete t.cls);var n={layout:"card",border:!1,region:"center",cls:i,activeItem:0,bodyCssClass:"syno-mc-card-body",items:e};return Ext.apply(n,t)},mcMask:function(){this.el.mask().addClass("syno-mc-transparent")},unMask:function(){this.el.unmask()},getActiveItem:function(){return this.layout.activeItem},switchToTwoColumn:function(){this.layout.setActiveItem("threadCardPanel")},switchToThreeColumn:function(){this.layout.setActiveItem("threadMessagePanel")},getActiveThread:function(){var t=this.getActiveItem();return"messagePanel"===t.itemId?t.threadRec:null}}),Ext.define("SYNO.SDS.MailClient.AddEditWindow",{extend:"SYNO.SDS.MailClient.ModalWindow",mode:"",targetInfo:{},apiType:null,constructor:function(t){if(t.mode&&(this.mode=t.mode),!Ext.isString(this.apiType))throw"apiType is not a string";var e=Ext.apply({title:"add"==this.mode?_T("common","create"):_T("common","alt_edit"),items:this.getFormPanel(),resizable:!1,width:500,height:200,buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):"",handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})},t);this.callParent([e]),this.on("show",function(){this.setFocus()},this)},setFocus:Ext.emptyFn,getFormPanel:Ext.emptyFn,getParams:Ext.emptyFn,onApplyDone:Ext.emptyFn,onApply:function(){if(this.getFormPanel().getForm().isValid()){var t=this.getParams();t&&(this.setStatusBusy({text:_T("common","loading")}),SYNO.SDS.MailClient.WebAPI.send(this.apiType,t).then(function(e){this.clearStatusBusy(),this.onApplyDone(),this.fireEvent("apply",e,t),this.close()}.bind(this)).catch(function(t){this.clearStatusBusy(),this.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(t)})}.bind(this)))}},onCancel:function(){if("edit"!=this.mode||!this.isDirty())return void this.close();var t=function(t){"yes"===t&&this.close()};this.owner.getMsgBox().confirm(this.title,_T("common","confirm_lostchange"),t,this)},isDirty:Ext.emptyFn,mailboxNameValidator:function(t){if(!(t=t.trim()))return SYNO.SDS.MailClient._T("common","name_field_not_blank");var e=this.getFormPanel().getComponent("mailboxBtn"),i=0;return e&&(i=e.getMailboxId()),-1<t.indexOf(".")||-1<t.indexOf("/")?String.format(SYNO.SDS.MailClient._T("common","name_field_contain_invalid_character"),"'.', '/'"):t.startsWith("~")?SYNO.SDS.MailClient._T("common","name_field_start_with_tilde"):0!==i||!SYNO.SDS.MailClient.Define.isSystemMailboxName(t)||SYNO.SDS.MailClient._T("common","name_field_conflict_system_name")},labelNameValidator:function(t){return t=t.trim(),t?-1===t.indexOf("/")||String.format(SYNO.SDS.MailClient._T("common","name_field_contain_invalid_character"),"'/'"):SYNO.SDS.MailClient._T("common","name_field_not_blank")}}),Ext.define("SYNO.SDS.MailClient.AddMailbox",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="addMailbox";var e=t.targetInfo;this.mailboxId=e.id,this.name=e.name,delete t.targetInfo,this.createName=t.createName,this.callParent([t])},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define;return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_mc_mailbox_button",itemId:"mailboxBtn",fieldLabel:SYNO.SDS.MailClient._T("mailbox","create_in"),text:Ext.util.Format.htmlEncode(this.name),currentMailboxId:this.mailboxId,menuCfg:{width:250,hideCreate:!0,hideManageBtn:!0,hideInbox:!0,rootVisible:!SYNO.SDS.MailClient.Switch.getMailboxStore().isSubscribedSharedMailbox(),showSharedByOthers:!0,hideReadOnlyMailbox:!0,mailboxEnable:!0,currentNodeId:this.mailboxId,hideMailbox:[t.draftsId,t.sentId,t.junkId,t.trashId,t.starredId]}},{xtype:"syno_textfield",fieldLabel:_T("common","name"),itemId:"name",name:"name",validator:this.mailboxNameValidator.createDelegate(this),value:this.createName?this.createName:void 0}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm(),e={},i=t.getFieldValues(),n=i.name.trim(),a=this.getFormPanel().getComponent("mailboxBtn");return n&&(e.name=n),a&&(e.parent_id=a.getMailboxId()),e.name?-1<e.name.indexOf(".")?(t.markInvalid({name:SYNO.SDS.MailClient._T("common","name_field_contain_invalid_character")}),!1):(0!==e.parent_id||!SYNO.SDS.MailClient.Define.isSystemMailboxName(n))&&e:(t.markInvalid({name:SYNO.SDS.MailClient._T("common","name_field_not_blank")}),!1)},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.EditMailbox",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setMailbox";var e=t.targetInfo;if(!e)throw"no target";this.mailboxId=e.id,this.name=e.name,this.parent_id=e.parent_id||0,this.parent_name=this.getParentName(e.path),this.subscribed=e.subscribed,delete t.targetInfo,this.callParent([t])},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define;return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_mc_mailbox_button",itemId:"mailboxBtn",fieldLabel:SYNO.SDS.MailClient._T("filter","move_to"),text:Ext.util.Format.htmlEncode(this.parent_name),currentMailboxId:this.parent_id,menuCfg:{width:250,hideCreate:!0,hideManageBtn:!0,hideInbox:!0,disableChild:!0,rootVisible:!0,currentNodeId:this.mailboxId,hideMailbox:[t.draftsId,t.sentId,t.junkId,t.trashId,t.starredId]}},{xtype:"syno_textfield",fieldLabel:_T("common","name"),itemId:"name",value:this.name,allowBlank:!1,name:"name",disabled:0===this.parent_id&&SYNO.SDS.MailClient.Define.isSystemMailboxName(this.name),validator:this.mailboxNameValidator.createDelegate(this)},{xtype:"syno_checkbox",fieldLabel:SYNO.SDS.MailClient._T("mailbox","subscribed"),hideLabel:!1,hidden:!0,checked:this.subscribed,name:"subscribed"}]}),this.formPanel},getParams:function(){var t,e=this.getFormPanel().getForm(),i={},n=e.getFieldValues(),a=this.getFormPanel().getComponent("mailboxBtn");return i.id=this.mailboxId,n.name&&(t=n.name.trim())&&t!=this.name&&(i.name=t),n.subscribed!=this.subscribed&&(i.subscribed=!!n.subscribed),a&&a.getMailboxId()!==this.parent_id&&(i.parent_id=a.getMailboxId()),Ext.isEmpty(i.name)&&Ext.isEmpty(i.subscribed)&&Ext.isEmpty(i.parent_id)?void this.onCancel():!(!this.mailboxId||0===i.parent_id&&i.name&&SYNO.SDS.MailClient.Define.isSystemMailboxName(i.name))&&i},getParentName:function(t){var e=t.lastIndexOf("."),i=-1;return e<0?SYNO.SDS.MailClient._T("common","mailbox"):(i=t.lastIndexOf(".",e-1),-1==i?t.substr(0,e):t.substr(i+1,e-i-1))},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.EditShareMailbox",{extend:"SYNO.SDS.MailClient.EditMailbox",constructor:function(t){this.callParent([t])},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",fieldLabel:_T("common","name"),itemId:"name",value:this.name,allowBlank:!1,name:"name",disabled:0===this.parent_id&&SYNO.SDS.MailClient.Define.isSystemMailboxName(this.name),validator:this.mailboxNameValidator.createDelegate(this)},{xtype:"syno_checkbox",fieldLabel:SYNO.SDS.MailClient._T("mailbox","subscribed"),hideLabel:!1,hidden:!0,checked:this.subscribed,name:"subscribed"}]}),this.formPanel}}),Ext.define("SYNO.SDS.MailClient.AddLabel",{extend:"SYNO.SDS.MailClient.AddEditWindow",requires:["SYNO.SDS.MailClient.LabelButton"],mode:"add",apiType:"addLabel",constructor:function(t){var e=t.targetInfo||{id:0,name:SYNO.SDS.MailClient._T("common","label")};this.createName=t.createName,this.labelId=e.id,this.name=e.name,delete t.targetInfo,this.callParent([Ext.apply({width:528,height:276},t)])},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form add-label",border:!1,autoHeight:!0,items:[{itemCls:"label-parent",xtype:"syno_mc_label_button",itemId:"parent",width:250,fieldLabel:SYNO.SDS.MailClient._T("label","create_in"),text:Ext.util.Format.htmlEncode(this.name),currentLabelId:this.labelId,menuCfg:{width:250,hideCreate:!0,rootVisible:!0,currentNodeId:this.labelId}},{itemCls:"label-name",xtype:"syno_textfield",fieldLabel:_T("common","name"),name:"name",itemId:"name",width:250,validator:this.labelNameValidator,value:this.createName?this.createName:void 0},{itemCls:"label-color",xtype:"syno_mc_colorpalette",fieldLabel:SYNO.SDS.MailClient._T("label","color"),labelStyle:"width:147px;",itemId:"color",defaultColor:0,width:336}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm(),e=t.getFieldValues().name.trim(),i=this.getFormPanel().getComponent("parent"),n=this.formPanel.getComponent("color").getSelectedNode(),a={};return e&&(a.name=e),i&&(a.parent_id=i.getLabelId()),n&&(a.text_color=n.textColor,a.background_color=n.bgColor),a},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.EditLabel",{extend:"SYNO.SDS.MailClient.AddEditWindow",requires:["SYNO.SDS.MailClient.LabelButton"],mode:"edit",apiType:"setLabel",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e,i=t.targetInfo;if(!i)throw"no target";return this.labelId=i.id,this.parentId=i.parent_id,this.parentLabel=SYNO.SDS.MailClient.Switch.getLabelStore().getById(this.parentId),this.name=i.name,this.textColor=i.text_color,this.bgColor=i.background_color,delete t.targetInfo,e={width:528,height:276},Ext.apply(e,t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form edit-label",autoHeight:!0,border:!1,items:[{itemCls:"label-parent",xtype:"syno_mc_label_button",itemId:"parent",width:250,fieldLabel:SYNO.SDS.MailClient._T("filter","move_to"),text:Ext.isEmpty(this.parentLabel)?SYNO.SDS.MailClient._T("common","label"):Ext.util.Format.htmlEncode(this.parentLabel.get("name")),currentLabelId:this.parentId,menuCfg:{width:250,hideCreate:!0,rootVisible:!0,disableChild:!0,currentNodeId:this.labelId}},{itemCls:"label-name",xtype:"syno_textfield",fieldLabel:_T("common","name"),name:"name",itemId:"name",value:this.name,width:250,validator:this.labelNameValidator},{itemCls:"label-color",xtype:"syno_mc_colorpalette",fieldLabel:SYNO.SDS.MailClient._T("label","color"),labelStyle:"width:147px;",itemId:"color",defaultColor:SYNO.SDS.MailClient.Define.getColorIndex(this.textColor,this.bgColor),width:336}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm(),e=t.getFieldValues().name.trim(),i=this.getFormPanel().getComponent("parent"),n=this.formPanel.getComponent("color").getSelectedNode(),a={};return!!this.labelId&&(this.parentId===i.getLabelId()&&this.name===e&&this.textColor===n.textColor&&this.bgColor===n.bgColor?void this.onCancel():(a.id=this.labelId,i.getLabelId()!==this.parentId&&(a.parent_id=i.getLabelId()),e!==this.name&&(a.name=e),n&&n.bgColor!==this.bgColor&&(a.text_color=n.textColor,a.background_color=n.bgColor),a))},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.SharingLinkWindow",{extend:"SYNO.SDS.MailClient.ModalWindow",params:null,fakePwd:"1234567890",constructor:function(t){this.file_url_set=t.file_url_set,this.clicked_file_block=t.clicked_file_block,this.callParent([this.fillConfig(t)]),this.addEvents("apply"),this.on("show",this.setValues,this)},fillConfig:function(t){this.params={},this.clicked_file_block.dataset&&this.clicked_file_block.dataset.config&&(this.params=Ext.decode(this.clicked_file_block.dataset.config)),this.formPanel=this.createFormPanel(t);var e={width:480,height:340,title:_T("sharing","sharing_links"),resizable:!1,collapsible:!1,layout:"fit",buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),items:[this.formPanel]};return Ext.apply(e,t)},createFormPanel:function(t){return new SYNO.ux.FormPanel({defaults:{anchor:"100%"},updateFormForScrollbar:!0,items:[{xtype:"syno_checkbox",name:"expire_at_enable",boxLabel:_T("sharing","enable_expire_at"),listeners:{scope:this,check:function(t,e){var i=this.formPanel.getComponent("expire_at_date"),n=this.formPanel.getComponent("expire_at_time");e?(i.enable(),n.enable()):(i.disable(),n.disable())}}},{xtype:SYNO.SDS.MailClient.Format.isDSM6()?"syno_datefield":"syno_datetimefield",name:"expire_at_date",itemId:"expire_at_date",editable:!1,disabled:!0,minValue:new Date,isAllDay:!0,dateFormat:"Y-m-d",format:"Y-m-d",indent:1,allowBlank:!1,fieldLabel:_T("sharing","expire_at_date")},{xtype:"syno_timefield",name:"expire_at_time",itemId:"expire_at_time",editable:!1,disabled:!0,format:"H:i:s",indent:1,fieldLabel:_T("sharing","expire_at_time")},{xtype:"syno_checkbox",name:"protect_type_enable",boxLabel:_T("sharing","restrict_sharing"),tabIndex:-1,listeners:{scope:this,check:function(t,e){e?this.formPanel.getForm().findField("protect_password").enable():this.formPanel.getForm().findField("protect_password").disable()}}},{xtype:"syno_textfield",name:"protect_password",itemId:"protect_password",tabIndex:-1,indent:1,disabled:!0,allowBlank:!1,style:{marginBottom:"16px"},textType:"password",fieldLabel:_T("sharing","enter_password"),listeners:{scope:this,focus:this.onProtectPasswordFocus}},{xtype:"syno_checkbox",name:"apply_to_all",boxLabel:SYNO.SDS.MailClient._T("sharing","apply_to_all"),tabIndex:-1,checked:!0}]})},onCancel:function(){this.close()},onProtectPasswordFocus:function(t){t.setValue(null),this.isProtectPasswordEdited=!0},isValid:function(){return this.formPanel.getForm().isValid()},setValues:function(){if(!SYNO.ux.Utils.checkObjectConsistency(this.params,{})){var t=this.params;"password"===t.protect_type&&(t.protect_password=this.fakePwd),this.isProtectPasswordEdited=!1,this.formPanel.getForm().setValues(t)}},getValues:function(){var t,e=this.formPanel.getForm().getValues();return"true"===e.expire_at_enable?(t=e.expire_at_date,e.expire_at_time?t+=" "+e.expire_at_time:t+=" 23:59:59",e.expire_at=t):e.expire_at="","true"===e.protect_type_enable?e.protect_type="password":e.protect_type="none",e.protect_password&&(this.fakePwd!==e.protect_password||this.isProtectPasswordEdited)||delete e.protect_password,e},onApply:function(){if(!this.isValid())return void this.getMsgBox().alert("",_T("common","forminvalid"));var t=this.onPrepareParam();this.setStatusBusy(),this.sendWebAPI({api:"SYNO.FileStation.Sharing",method:"edit",version:3,params:t,scope:this,callback:function(e,i){this.clearStatusBusy(),e?(this.fireEvent("apply",t),this.close()):this.onShowError(_T("error","error_error_system"))}})},onPrepareParam:function(){this.linkIDs=[];var t=this.getValues();if("true"===t.apply_to_all)this.file_url_set.forEach(function(t){this.linkIDs.push(t.substr(t.lastIndexOf("/")+1))},this);else{var e=this.clicked_file_block.dataset.fileUrl;this.linkIDs.push(e.substr(e.lastIndexOf("/")+1))}return t.id=this.linkIDs,Ext.isEmpty(t.protect_password)||(t.password=t.protect_password,delete t.protect_password),Ext.isEmpty(t.expire_at)||(t.date_expired=t.expire_at,delete t.expire_at),t}}),Ext.define("SYNO.SDS.MailClient.Export",{singleton:!0,openMailPlusByMsgId:function(t){return SYNO.SDS.MailClient.Control.Sidebar.openMsgId(t)}}),Ext.ns("SYNO.SDS.MailClient.SearchLib"),SYNO.SDS.MailClient.SearchLib.PegjsParser=function(){"use strict";function t(e,i,n,a){this.message=e,this.expected=i,this.found=n,this.location=a,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}function e(e,i){function n(){return e.substring(Nn,On)}function a(t,e){return{type:"literal",text:t,ignoreCase:e}}function o(t,e,i){return{type:"class",parts:t,inverted:e,ignoreCase:i}}function s(t){return{type:"other",description:t}}function l(t){var i,n=En[t];if(n)return n;for(i=t-1;!En[i];)i--;for(n=En[i],n={line:n.line,column:n.column};i<t;)10===e.charCodeAt(i)?(n.line++,n.column=1):n.column++,i++;return En[t]=n,n}function r(t,e){var i=l(t),n=l(e);return{start:{offset:t,line:i.line,column:i.column},end:{offset:e,line:n.line,column:n.column}}}function d(t){On<wn||(On>wn&&(wn=On,Yn=[]),Yn.push(t))}function c(e,i,n){return new t(t.buildMessage(e,i),e,i,n)}function h(){var t,e,i,n;return t=On,e=ft(),e!==Ot?(i=Mt(),i!==Ot?(n=ft(),n!==Ot?(Nn=t,e=wt(i),t=e):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot),t}function u(){var t;return e.length>On?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Yt)),t}function S(){var t;return Tn++,9===e.charCodeAt(On)?(t=It,On++):(t=Ot,0===Tn&&d(Pt)),t===Ot&&(11===e.charCodeAt(On)?(t=At,On++):(t=Ot,0===Tn&&d(kt)),t===Ot&&(12===e.charCodeAt(On)?(t=Ft,On++):(t=Ot,0===Tn&&d(Lt)),t===Ot&&(32===e.charCodeAt(On)?(t=Bt,On++):(t=Ot,0===Tn&&d(Rt)),t===Ot&&(160===e.charCodeAt(On)?(t=Vt,On++):(t=Ot,0===Tn&&d(Wt)),t===Ot&&(65279===e.charCodeAt(On)?(t=Ut,On++):(t=Ot,0===Tn&&d(jt)),t===Ot&&(t=et())))))),Tn--,t===Ot&&(Ot,0===Tn&&d(Tt)),t}function m(){var t;return Ht.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Gt)),t}function f(){var t;return Tn++,10===e.charCodeAt(On)?(t=zt,On++):(t=Ot,0===Tn&&d(Kt)),t===Ot&&(e.substr(On,2)===Jt?(t=Jt,On+=2):(t=Ot,0===Tn&&d(Xt)),t===Ot&&(13===e.charCodeAt(On)?(t=Qt,On++):(t=Ot,0===Tn&&d(Zt)),t===Ot&&(8232===e.charCodeAt(On)?(t=$t,On++):(t=Ot,0===Tn&&d(te)),t===Ot&&(8233===e.charCodeAt(On)?(t=ee,On++):(t=Ot,0===Tn&&d(ie)))))),Tn--,t===Ot&&(Ot,0===Tn&&d(qt)),t}function p(){var t;return t=it(),t===Ot&&(t=nt())===Ot&&(t=at())===Ot&&(t=ot())===Ot&&(t=st())===Ot&&(t=lt())===Ot&&(t=rt())===Ot&&(t=dt())===Ot&&(t=ut())===Ot&&(t=St())===Ot&&(t=ct())===Ot&&(t=ht())===Ot&&(t=mt()),t}function g(){var t,i,n,a;return t=On,e.substr(On,3)===ne?(i=ne,On+=3):(i=Ot,0===Tn&&d(ae)),i!==Ot?(n=ft(),n!==Ot?(e.substr(On,6)===oe?(a=oe,On+=6):(a=Ot,0===Tn&&d(se)),a!==Ot?(Nn=t,i=le(),t=i):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot),t}function b(){var t,i,n,a;return t=On,e.substr(On,3)===ne?(i=ne,On+=3):(i=Ot,0===Tn&&d(ae)),i!==Ot?(n=ft(),n!==Ot?(e.substr(On,7)===re?(a=re,On+=7):(a=Ot,0===Tn&&d(de)),a!==Ot?(Nn=t,i=ce(),t=i):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot),t}function C(){var t,i,n,a;return t=On,e.substr(On,4)===he?(i=he,On+=4):(i=Ot,0===Tn&&d(ue)),i!==Ot?(n=ft(),n!==Ot?(e.substr(On,10)===Se?(a=Se,On+=10):(a=Ot,0===Tn&&d(me)),a!==Ot?(Nn=t,i=fe(),t=i):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot),t}function y(){var t,e,i;return t=On,e=On,Tn++,i=p(),Tn--,i===Ot?e=void 0:(On=e,e=Ot),e!==Ot?(i=x(),i!==Ot?(Nn=t,e=pe(i),t=e):(On=t,t=Ot)):(On=t,t=Ot),t}function x(){var t,e,i,n;if(Tn++,(t=b())===Ot&&(t=C())===Ot&&(t=g())===Ot)if(t=On,(e=M())!==Ot){for(i=[],n=M();n!==Ot;)i.push(n),n=M();i!==Ot?(Nn=t,e=be(e,i),t=e):(On=t,t=Ot)}else On=t,t=Ot;return Tn--,t===Ot&&(e=Ot,0===Tn&&d(ge)),t}function _(){var t;return t=D(),t===Ot&&(36===e.charCodeAt(On)?(t=Ce,On++):(t=Ot,0===Tn&&d(ye)),t===Ot&&(95===e.charCodeAt(On)?(t=xe,On++):(t=Ot,0===Tn&&d(_e)))),t}function M(){var t;return t=_(),t===Ot&&(t=v())===Ot&&(t=Z())===Ot&&(t=tt())===Ot&&(8204===e.charCodeAt(On)?(t=Me,On++):(t=Ot,0===Tn&&d(De)),t===Ot&&(8205===e.charCodeAt(On)?(t=ve,On++):(t=Ot,0===Tn&&d(Oe)))),t}function D(){var t;return t=J(),t===Ot&&(t=G())===Ot&&(t=K())===Ot&&(t=q())===Ot&&(t=z())===Ot&&(t=$()),t}function v(){var t;return t=Q(),t===Ot&&(t=X()),t}function O(){var t;return t=E(),t===Ot&&(t=F()),t}function N(){var t;return t=y(),t===Ot&&(t=O()),t}function E(){var t,e,i,n;return Tn++,t=On,e=w(),e!==Ot?(i=On,Tn++,n=_(),n===Ot&&(n=T()),Tn--,n===Ot?i=void 0:(On=i,i=Ot),i!==Ot?(Nn=t,e=Ee(e),t=e):(On=t,t=Ot)):(On=t,t=Ot),Tn--,t===Ot&&(e=Ot,0===Tn&&d(Ne)),t}function w(){var t,i,n,a,o;if(t=On,(i=Y())!==Ot)if(46===e.charCodeAt(On)?(n=we,On++):(n=Ot,0===Tn&&d(Ye)),n!==Ot){for(a=[],o=T();o!==Ot;)a.push(o),o=T();a!==Ot?(o=P(),o===Ot&&(o=null),o!==Ot?(Nn=t,i=Te(),t=i):(On=t,t=Ot)):(On=t,t=Ot)}else On=t,t=Ot;else On=t,t=Ot;if(t===Ot){if(t=On,46===e.charCodeAt(On)?(i=we,On++):(i=Ot,0===Tn&&d(Ye)),i!==Ot){if(n=[],(a=T())!==Ot)for(;a!==Ot;)n.push(a),a=T();else n=Ot;n!==Ot?(a=P(),a===Ot&&(a=null),a!==Ot?(Nn=t,i=Te(),t=i):(On=t,t=Ot)):(On=t,t=Ot)}else On=t,t=Ot;t===Ot&&(t=On,i=Y(),i!==Ot?(n=P(),n===Ot&&(n=null),n!==Ot?(Nn=t,i=Te(),t=i):(On=t,t=Ot)):(On=t,t=Ot),t===Ot&&(t=On,i=k(),i!==Ot&&(Nn=t,i=Ie()),t=i))}return t}function Y(){var t,i,n,a;if(48===e.charCodeAt(On)?(t=Pe,On++):(t=Ot,0===Tn&&d(Ae)),t===Ot)if(t=On,(i=I())!==Ot){for(n=[],a=T();a!==Ot;)n.push(a),a=T();n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)}else On=t,t=Ot;return t}function T(){var t;return ke.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Fe)),t}function I(){var t;return Le.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Be)),t}function P(){var t,e,i;return t=On,e=A(),e!==Ot?(i=k(),i!==Ot?(e=[e,i],t=e):(On=t,t=Ot)):(On=t,t=Ot),t}function A(){var t;return e.substr(On,1).toLowerCase()===Re?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Ve)),t}function k(){var t,i,n,a;if(t=On,We.test(e.charAt(On))?(i=e.charAt(On),On++):(i=Ot,0===Tn&&d(Ue)),i===Ot&&(i=null),i!==Ot){if(n=[],(a=T())!==Ot)for(;a!==Ot;)n.push(a),a=T();else n=Ot;n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)}else On=t,t=Ot;return t}function F(){var t,i,n,a;if(Tn++,t=On,34===e.charCodeAt(On)?(i=He,On++):(i=Ot,0===Tn&&d(Ge)),i!==Ot){for(n=[],a=L();a!==Ot;)n.push(a),a=L();n!==Ot?(34===e.charCodeAt(On)?(a=He,On++):(a=Ot,0===Tn&&d(Ge)),a!==Ot?(Nn=t,i=qe(n),t=i):(On=t,t=Ot)):(On=t,t=Ot)}else On=t,t=Ot;if(t===Ot)if(t=On,39===e.charCodeAt(On)?(i=ze,On++):(i=Ot,0===Tn&&d(Ke)),i!==Ot){for(n=[],a=B();a!==Ot;)n.push(a),a=B();n!==Ot?(39===e.charCodeAt(On)?(a=ze,On++):(a=Ot,0===Tn&&d(Ke)),a!==Ot?(Nn=t,i=qe(n),t=i):(On=t,t=Ot)):(On=t,t=Ot)}else On=t,t=Ot;return Tn--,t===Ot&&(i=Ot,0===Tn&&d(je)),t}function L(){var t,i,n;return t=On,i=On,Tn++,34===e.charCodeAt(On)?(n=He,On++):(n=Ot,0===Tn&&d(Ge)),n===Ot&&(92===e.charCodeAt(On)?(n=Je,On++):(n=Ot,0===Tn&&d(Xe)),n===Ot&&(n=m())),Tn--,n===Ot?i=void 0:(On=i,i=Ot),i!==Ot?(n=u(),n!==Ot?(Nn=t,i=Qe(),t=i):(On=t,t=Ot)):(On=t,t=Ot),t===Ot&&(t=On,92===e.charCodeAt(On)?(i=Je,On++):(i=Ot,0===Tn&&d(Xe)),i!==Ot?(n=V(),n!==Ot?(Nn=t,i=Ze(n),t=i):(On=t,t=Ot)):(On=t,t=Ot),t===Ot&&(t=R())),t}function B(){var t,i,n;return t=On,i=On,Tn++,39===e.charCodeAt(On)?(n=ze,On++):(n=Ot,0===Tn&&d(Ke)),n===Ot&&(92===e.charCodeAt(On)?(n=Je,On++):(n=Ot,0===Tn&&d(Xe)),n===Ot&&(n=m())),Tn--,n===Ot?i=void 0:(On=i,i=Ot),i!==Ot?(n=u(),n!==Ot?(Nn=t,i=Qe(),t=i):(On=t,t=Ot)):(On=t,t=Ot),t===Ot&&(t=On,92===e.charCodeAt(On)?(i=Je,On++):(i=Ot,0===Tn&&d(Xe)),i!==Ot?(n=V(),n!==Ot?(Nn=t,i=Ze(n),t=i):(On=t,t=Ot)):(On=t,t=Ot),t===Ot&&(t=R())),t}function R(){var t,i,n;return t=On,92===e.charCodeAt(On)?(i=Je,On++):(i=Ot,0===Tn&&d(Xe)),i!==Ot?(n=f(),n!==Ot?(Nn=t,i=$e(),t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function V(){var t,i,n,a;return t=W(),t===Ot&&(t=On,48===e.charCodeAt(On)?(i=Pe,On++):(i=Ot,0===Tn&&d(Ae)),i!==Ot?(n=On,Tn++,a=T(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(Nn=t,i=ti(),t=i):(On=t,t=Ot)):(On=t,t=Ot)),t}function W(){var t;return t=U(),t===Ot&&(t=j()),t}function U(){var t,i;return 39===e.charCodeAt(On)?(t=ze,On++):(t=Ot,0===Tn&&d(Ke)),t===Ot&&(34===e.charCodeAt(On)?(t=He,On++):(t=Ot,0===Tn&&d(Ge)),t===Ot&&(92===e.charCodeAt(On)?(t=Je,On++):(t=Ot,0===Tn&&d(Xe)),t===Ot&&(t=On,98===e.charCodeAt(On)?(i=ei,On++):(i=Ot,0===Tn&&d(ii)),i!==Ot&&(Nn=t,i=ni()),(t=i)===Ot&&(t=On,102===e.charCodeAt(On)?(i=ai,On++):(i=Ot,0===Tn&&d(oi)),i!==Ot&&(Nn=t,i=si()),(t=i)===Ot&&(t=On,110===e.charCodeAt(On)?(i=li,On++):(i=Ot,0===Tn&&d(ri)),i!==Ot&&(Nn=t,i=di()),(t=i)===Ot&&(t=On,114===e.charCodeAt(On)?(i=ci,On++):(i=Ot,0===Tn&&d(hi)),i!==Ot&&(Nn=t,i=ui()),(t=i)===Ot&&(t=On,116===e.charCodeAt(On)?(i=Si,On++):(i=Ot,0===Tn&&d(mi)),i!==Ot&&(Nn=t,i=fi()),(t=i)===Ot&&(t=On,118===e.charCodeAt(On)?(i=pi,On++):(i=Ot,0===Tn&&d(gi)),i!==Ot&&(Nn=t,i=bi()),t=i)))))))),t}function j(){var t,e,i;return t=On,e=On,Tn++,i=H(),i===Ot&&(i=m()),Tn--,i===Ot?e=void 0:(On=e,e=Ot),e!==Ot?(i=u(),i!==Ot?(Nn=t,e=Qe(),t=e):(On=t,t=Ot)):(On=t,t=Ot),t}function H(){var t;return t=U(),t===Ot&&(t=T())===Ot&&(120===e.charCodeAt(On)?(t=Ci,On++):(t=Ot,0===Tn&&d(yi)),t===Ot&&(117===e.charCodeAt(On)?(t=xi,On++):(t=Ot,0===Tn&&d(_i)))),t}function G(){var t;return Mi.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Di)),t}function q(){var t;return vi.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Oi)),t}function z(){var t;return Ni.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Ei)),t}function K(){var t;return wi.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Yi)),t}function J(){var t;return Ti.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Ii)),t}function X(){var t;return Pi.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Ai)),t}function Q(){var t;return ki.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Fi)),t}function Z(){var t;return Li.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Bi)),t}function $(){var t;return Ri.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Vi)),t}function tt(){var t;return Wi.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Ui)),t}function et(){var t;return ji.test(e.charAt(On))?(t=e.charAt(On),On++):(t=Ot,0===Tn&&d(Hi)),t}function it(){var t,i,n,a;return t=On,e.substr(On,3)===Gi?(i=Gi,On+=3):(i=Ot,0===Tn&&d(qi)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function nt(){var t,i,n,a;return t=On,e.substr(On,2)===zi?(i=zi,On+=2):(i=Ot,0===Tn&&d(Ki)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function at(){var t,i,n,a;return t=On,e.substr(On,3)===Ji?(i=Ji,On+=3):(i=Ot,0===Tn&&d(Xi)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function ot(){var t,i,n,a;return t=On,e.substr(On,5)===Qi?(i=Qi,On+=5):(i=Ot,0===Tn&&d(Zi)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function st(){var t,i,n,a;return t=On,e.substr(On,3)===$i?(i=$i,On+=3):(i=Ot,0===Tn&&d(tn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function lt(){var t,i,n,a;return t=On,e.substr(On,8)===en?(i=en,On+=8):(i=Ot,0===Tn&&d(nn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function rt(){var t,i,n,a;return t=On,e.substr(On,3)===an?(i=an,On+=3):(i=Ot,0===Tn&&d(on)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function dt(){var t,i,n,a;return t=On,e.substr(On,6)===sn?(i=sn,On+=6):(i=Ot,0===Tn&&d(ln)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function ct(){var t,i,n,a;return t=On,e.substr(On,7)===rn?(i=rn,On+=7):(i=Ot,0===Tn&&d(dn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function ht(){var t,i,n,a;return t=On,e.substr(On,8)===cn?(i=cn,On+=8):(i=Ot,0===Tn&&d(hn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function ut(){var t,i,n,a;return t=On,e.substr(On,7)===un?(i=un,On+=7):(i=Ot,0===Tn&&d(Sn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function St(){var t,i,n,a;return t=On,e.substr(On,6)===mn?(i=mn,On+=6):(i=Ot,0===Tn&&d(fn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function mt(){var t,i,n,a;return t=On,e.substr(On,9)===pn?(i=pn,On+=9):(i=Ot,0===Tn&&d(gn)),i!==Ot?(n=On,Tn++,a=M(),Tn--,a===Ot?n=void 0:(On=n,n=Ot),n!==Ot?(i=[i,n],t=i):(On=t,t=Ot)):(On=t,t=Ot),t}function ft(){var t,e;for(t=[],e=S(),e===Ot&&(e=f());e!==Ot;)t.push(e),(e=S())===Ot&&(e=f());return t}function pt(){var t,i,n,a,o,s;return t=On,40===e.charCodeAt(On)?(i=bn,On++):(i=Ot,0===Tn&&d(Cn)),i!==Ot?(n=ft(),n!==Ot?(a=xt(),a!==Ot?(o=ft(),o!==Ot?(41===e.charCodeAt(On)?(s=yn,On++):(s=Ot,0===Tn&&d(xn)),s!==Ot?(Nn=t,i=_n(a),t=i):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot),t===Ot&&(t=N()),t}function gt(){var t,e,i,n;return t=pt(),t===Ot&&(t=On,e=bt(),e!==Ot?(i=ft(),i!==Ot?(n=gt(),n!==Ot?(Nn=t,e=Mn(e,n),t=e):(On=t,t=Ot)):(On=t,t=Ot)):(On=t,t=Ot)),t}function bt(){var t;return e.substr(On,3)===Gi?(t=Gi,On+=3):(t=Ot,0===Tn&&d(qi)),t===Ot&&(e.substr(On,3)===an?(t=an,On+=3):(t=Ot,0===Tn&&d(on)),t===Ot&&(e.substr(On,6)===sn?(t=sn,On+=6):(t=Ot,0===Tn&&d(ln)),t===Ot&&(e.substr(On,5)===Qi?(t=Qi,On+=5):(t=Ot,0===Tn&&d(Zi)),t===Ot&&(e.substr(On,3)===$i?(t=$i,On+=3):(t=Ot,0===Tn&&d(tn)),t===Ot&&(e.substr(On,8)===en?(t=en,On+=8):(t=Ot,0===Tn&&d(nn)),t===Ot&&(e.substr(On,6)===mn?(t=mn,On+=6):(t=Ot,0===Tn&&d(fn)),t===Ot&&(e.substr(On,7)===un?(t=un,On+=7):(t=Ot,0===Tn&&d(Sn)),t===Ot&&(e.substr(On,8)===cn?(t=cn,On+=8):(t=Ot,0===Tn&&d(hn)),t===Ot&&(e.substr(On,7)===rn?(t=rn,On+=7):(t=Ot,0===Tn&&d(dn)),t===Ot&&(e.substr(On,9)===pn?(t=pn,On+=9):(t=Ot,0===Tn&&d(gn)))))))))))),t}function Ct(){var t,e,i,n,a,o,s,l;if(t=On,(e=gt())!==Ot){for(i=[],n=On,a=ft(),a!==Ot?(o=yt(),o===Ot&&(o=null),o!==Ot?(s=ft(),s!==Ot?(l=gt(),l!==Ot?(a=[a,o,s,l],n=a):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot);n!==Ot;)i.push(n),n=On,a=ft(),a!==Ot?(o=yt(),o===Ot&&(o=null),o!==Ot?(s=ft(),s!==Ot?(l=gt(),l!==Ot?(a=[a,o,s,l],n=a):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot);i!==Ot?(Nn=t,e=Dn(e,i),t=e):(On=t,t=Ot)}else On=t,t=Ot;return t}function yt(){var t;return e.substr(On,3)===Ji?(t=Ji,On+=3):(t=Ot,0===Tn&&d(Xi)),t}function xt(){var t,e,i,n,a,o,s,l;if(t=On,(e=Ct())!==Ot){for(i=[],n=On,a=ft(),a!==Ot?(o=_t(),o!==Ot?(s=ft(),s!==Ot?(l=Ct(),l!==Ot?(a=[a,o,s,l],n=a):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot);n!==Ot;)i.push(n),n=On,a=ft(),a!==Ot?(o=_t(),o!==Ot?(s=ft(),s!==Ot?(l=Ct(),l!==Ot?(a=[a,o,s,l],n=a):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot)):(On=n,n=Ot);i!==Ot?(Nn=t,e=Dn(e,i),t=e):(On=t,t=Ot)}else On=t,t=Ot;return t}function _t(){var t;return e.substr(On,2)===zi?(t=zi,On+=2):(t=Ot,0===Tn&&d(Ki)),t}function Mt(){var t,e;return t=On,e=xt(),e!==Ot&&(Nn=t,e=vn(e)),t=e}function Dt(t,e){return e.reduce(function(t,e){return{type:"BinaryExpression",operator:e[1]?e[1]:"AND",left:t,right:e[3]}},t)}i=void 0!==i?i:{};var vt,Ot={},Nt={Start:h},Et=h,wt=function(t){return t},Yt=function(){return{type:"any"}}(),Tt=s("whitespace"),It="\t",Pt=a("\t",!1),At="\v",kt=a("\v",!1),Ft="\f",Lt=a("\f",!1),Bt=" ",Rt=a(" ",!1),Vt=" ",Wt=a(" ",!1),Ut="\ufeff",jt=a("\ufeff",!1),Ht=/^[\n\r\u2028\u2029]/,Gt=o(["\n","\r","\u2028","\u2029"],!1,!1),qt=s("end of line"),zt="\n",Kt=a("\n",!1),Jt="\r\n",Xt=a("\r\n",!1),Qt="\r",Zt=a("\r",!1),$t="\u2028",te=a("\u2028",!1),ee="\u2029",ie=a("\u2029",!1),ne="is:",ae=a("is:",!1),oe="unread",se=a("unread",!1),le=function(){return{type:"Identifier",value:"is:unread"}},re="starred",de=a("starred",!1),ce=function(){return{type:"Identifier",value:"is:starred"}},he="has:",ue=a("has:",!1),Se="attachment",me=a("attachment",!1),fe=function(){return{type:"Identifier",value:"has:attachment"}},pe=function(t){return t},ge=s("identifier"),be=function(t,e){return{type:"Identifier",value:t+e.join("")}},Ce="$",ye=a("$",!1),xe="_",_e=a("_",!1),Me="",De=a("",!1),ve="",Oe=a("",!1),Ne=s("number"),Ee=function(t){return t},we=".",Ye=a(".",!1),Te=function(){return{type:"Literal",
value:parseFloat(n())}},Ie=function(){return{type:"Literal",value:parseFloat(n())}},Pe="0",Ae=a("0",!1),ke=/^[0-9]/,Fe=o([["0","9"]],!1,!1),Le=/^[1-9]/,Be=o([["1","9"]],!1,!1),Re="e",Ve=a("e",!0),We=/^[+\-]/,Ue=o(["+","-"],!1,!1),je=s("string"),He='"',Ge=a('"',!1),qe=function(t){return{type:"Literal",value:t.join("")}},ze="'",Ke=a("'",!1),Je="\\",Xe=a("\\",!1),Qe=function(){return n()},Ze=function(t){return t},$e=function(){return""},ti=function(){return"\0"},ei="b",ii=a("b",!1),ni=function(){return"\b"},ai="f",oi=a("f",!1),si=function(){return"\f"},li="n",ri=a("n",!1),di=function(){return"\n"},ci="r",hi=a("r",!1),ui=function(){return"\r"},Si="t",mi=a("t",!1),fi=function(){return"\t"},pi="v",gi=a("v",!1),bi=function(){return"\v"},Ci="x",yi=a("x",!1),xi="u",_i=a("u",!1),Mi=/^[a-z\xB5\xDF-\xF6\xF8-\xFF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137-\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148-\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C-\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA-\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9-\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC-\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF-\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F-\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0-\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB-\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE-\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0529\u052B\u052D\u052F\u0561-\u0587\u13F8-\u13FD\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6-\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FC7\u1FD0-\u1FD3\u1FD6-\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6-\u1FF7\u210A\u210E-\u210F\u2113\u212F\u2134\u2139\u213C-\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65-\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73-\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3-\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA699\uA69B\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793-\uA795\uA797\uA799\uA79B\uA79D\uA79F\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7B5\uA7B7\uA7FA\uAB30-\uAB5A\uAB60-\uAB65\uAB70-\uABBF\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A]/,Di=o([["a","z"],"µ",["ß","ö"],["ø","ÿ"],"ā","ă","ą","ć","ĉ","ċ","č","ď","đ","ē","ĕ","ė","ę","ě","ĝ","ğ","ġ","ģ","ĥ","ħ","ĩ","ī","ĭ","į","ı","ij","ĵ",["ķ","ĸ"],"ĺ","ļ","ľ","ŀ","ł","ń","ņ",["ň","ʼn"],"ŋ","ō","ŏ","ő","œ","ŕ","ŗ","ř","ś","ŝ","ş","š","ţ","ť","ŧ","ũ","ū","ŭ","ů","ű","ų","ŵ","ŷ","ź","ż",["ž","ƀ"],"ƃ","ƅ","ƈ",["ƌ","ƍ"],"ƒ","ƕ",["ƙ","ƛ"],"ƞ","ơ","ƣ","ƥ","ƨ",["ƪ","ƫ"],"ƭ","ư","ƴ","ƶ",["ƹ","ƺ"],["ƽ","ƿ"],"dž","lj","nj","ǎ","ǐ","ǒ","ǔ","ǖ","ǘ","ǚ",["ǜ","ǝ"],"ǟ","ǡ","ǣ","ǥ","ǧ","ǩ","ǫ","ǭ",["ǯ","ǰ"],"dz","ǵ","ǹ","ǻ","ǽ","ǿ","ȁ","ȃ","ȅ","ȇ","ȉ","ȋ","ȍ","ȏ","ȑ","ȓ","ȕ","ȗ","ș","ț","ȝ","ȟ","ȡ","ȣ","ȥ","ȧ","ȩ","ȫ","ȭ","ȯ","ȱ",["ȳ","ȹ"],"ȼ",["ȿ","ɀ"],"ɂ","ɇ","ɉ","ɋ","ɍ",["ɏ","ʓ"],["ʕ","ʯ"],"ͱ","ͳ","ͷ",["ͻ","ͽ"],"ΐ",["ά","ώ"],["ϐ","ϑ"],["ϕ","ϗ"],"ϙ","ϛ","ϝ","ϟ","ϡ","ϣ","ϥ","ϧ","ϩ","ϫ","ϭ",["ϯ","ϳ"],"ϵ","ϸ",["ϻ","ϼ"],["а","џ"],"ѡ","ѣ","ѥ","ѧ","ѩ","ѫ","ѭ","ѯ","ѱ","ѳ","ѵ","ѷ","ѹ","ѻ","ѽ","ѿ","ҁ","ҋ","ҍ","ҏ","ґ","ғ","ҕ","җ","ҙ","қ","ҝ","ҟ","ҡ","ң","ҥ","ҧ","ҩ","ҫ","ҭ","ү","ұ","ҳ","ҵ","ҷ","ҹ","һ","ҽ","ҿ","ӂ","ӄ","ӆ","ӈ","ӊ","ӌ",["ӎ","ӏ"],"ӑ","ӓ","ӕ","ӗ","ә","ӛ","ӝ","ӟ","ӡ","ӣ","ӥ","ӧ","ө","ӫ","ӭ","ӯ","ӱ","ӳ","ӵ","ӷ","ӹ","ӻ","ӽ","ӿ","ԁ","ԃ","ԅ","ԇ","ԉ","ԋ","ԍ","ԏ","ԑ","ԓ","ԕ","ԗ","ԙ","ԛ","ԝ","ԟ","ԡ","ԣ","ԥ","ԧ","ԩ","ԫ","ԭ","ԯ",["ա","և"],["ᏸ","ᏽ"],["ᴀ","ᴫ"],["ᵫ","ᵷ"],["ᵹ","ᶚ"],"ḁ","ḃ","ḅ","ḇ","ḉ","ḋ","ḍ","ḏ","ḑ","ḓ","ḕ","ḗ","ḙ","ḛ","ḝ","ḟ","ḡ","ḣ","ḥ","ḧ","ḩ","ḫ","ḭ","ḯ","ḱ","ḳ","ḵ","ḷ","ḹ","ḻ","ḽ","ḿ","ṁ","ṃ","ṅ","ṇ","ṉ","ṋ","ṍ","ṏ","ṑ","ṓ","ṕ","ṗ","ṙ","ṛ","ṝ","ṟ","ṡ","ṣ","ṥ","ṧ","ṩ","ṫ","ṭ","ṯ","ṱ","ṳ","ṵ","ṷ","ṹ","ṻ","ṽ","ṿ","ẁ","ẃ","ẅ","ẇ","ẉ","ẋ","ẍ","ẏ","ẑ","ẓ",["ẕ","ẝ"],"ẟ","ạ","ả","ấ","ầ","ẩ","ẫ","ậ","ắ","ằ","ẳ","ẵ","ặ","ẹ","ẻ","ẽ","ế","ề","ể","ễ","ệ","ỉ","ị","ọ","ỏ","ố","ồ","ổ","ỗ","ộ","ớ","ờ","ở","ỡ","ợ","ụ","ủ","ứ","ừ","ử","ữ","ự","ỳ","ỵ","ỷ","ỹ","ỻ","ỽ",["ỿ","ἇ"],["ἐ","ἕ"],["ἠ","ἧ"],["ἰ","ἷ"],["ὀ","ὅ"],["ὐ","ὗ"],["ὠ","ὧ"],["ὰ","ώ"],["ᾀ","ᾇ"],["ᾐ","ᾗ"],["ᾠ","ᾧ"],["ᾰ","ᾴ"],["ᾶ","ᾷ"],"ι",["ῂ","ῄ"],["ῆ","ῇ"],["ῐ","ΐ"],["ῖ","ῗ"],["ῠ","ῧ"],["ῲ","ῴ"],["ῶ","ῷ"],"ℊ",["ℎ","ℏ"],"ℓ","ℯ","ℴ","ℹ",["ℼ","ℽ"],["ⅆ","ⅉ"],"ⅎ","ↄ",["ⰰ","ⱞ"],"ⱡ",["ⱥ","ⱦ"],"ⱨ","ⱪ","ⱬ","ⱱ",["ⱳ","ⱴ"],["ⱶ","ⱻ"],"ⲁ","ⲃ","ⲅ","ⲇ","ⲉ","ⲋ","ⲍ","ⲏ","ⲑ","ⲓ","ⲕ","ⲗ","ⲙ","ⲛ","ⲝ","ⲟ","ⲡ","ⲣ","ⲥ","ⲧ","ⲩ","ⲫ","ⲭ","ⲯ","ⲱ","ⲳ","ⲵ","ⲷ","ⲹ","ⲻ","ⲽ","ⲿ","ⳁ","ⳃ","ⳅ","ⳇ","ⳉ","ⳋ","ⳍ","ⳏ","ⳑ","ⳓ","ⳕ","ⳗ","ⳙ","ⳛ","ⳝ","ⳟ","ⳡ",["ⳣ","ⳤ"],"ⳬ","ⳮ","ⳳ",["ⴀ","ⴥ"],"ⴧ","ⴭ","ꙁ","ꙃ","ꙅ","ꙇ","ꙉ","ꙋ","ꙍ","ꙏ","ꙑ","ꙓ","ꙕ","ꙗ","ꙙ","ꙛ","ꙝ","ꙟ","ꙡ","ꙣ","ꙥ","ꙧ","ꙩ","ꙫ","ꙭ","ꚁ","ꚃ","ꚅ","ꚇ","ꚉ","ꚋ","ꚍ","ꚏ","ꚑ","ꚓ","ꚕ","ꚗ","ꚙ","ꚛ","ꜣ","ꜥ","ꜧ","ꜩ","ꜫ","ꜭ",["ꜯ","ꜱ"],"ꜳ","ꜵ","ꜷ","ꜹ","ꜻ","ꜽ","ꜿ","ꝁ","ꝃ","ꝅ","ꝇ","ꝉ","ꝋ","ꝍ","ꝏ","ꝑ","ꝓ","ꝕ","ꝗ","ꝙ","ꝛ","ꝝ","ꝟ","ꝡ","ꝣ","ꝥ","ꝧ","ꝩ","ꝫ","ꝭ","ꝯ",["ꝱ","ꝸ"],"ꝺ","ꝼ","ꝿ","ꞁ","ꞃ","ꞅ","ꞇ","ꞌ","ꞎ","ꞑ",["ꞓ","ꞕ"],"ꞗ","ꞙ","ꞛ","ꞝ","ꞟ","ꞡ","ꞣ","ꞥ","ꞧ","ꞩ","ꞵ","ꞷ","ꟺ",["ꬰ","ꭚ"],["ꭠ","ꭥ"],["ꭰ","ꮿ"],["ff","st"],["ﬓ","ﬗ"],["a","z"]],!1,!1),vi=/^[\u02B0-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0374\u037A\u0559\u0640\u06E5-\u06E6\u07F4-\u07F5\u07FA\u081A\u0824\u0828\u0971\u0E46\u0EC6\u10FC\u17D7\u1843\u1AA7\u1C78-\u1C7D\u1D2C-\u1D6A\u1D78\u1D9B-\u1DBF\u2071\u207F\u2090-\u209C\u2C7C-\u2C7D\u2D6F\u2E2F\u3005\u3031-\u3035\u303B\u309D-\u309E\u30FC-\u30FE\uA015\uA4F8-\uA4FD\uA60C\uA67F\uA69C-\uA69D\uA717-\uA71F\uA770\uA788\uA7F8-\uA7F9\uA9CF\uA9E6\uAA70\uAADD\uAAF3-\uAAF4\uAB5C-\uAB5F\uFF70\uFF9E-\uFF9F]/,Oi=o([["ʰ","ˁ"],["ˆ","ˑ"],["ˠ","ˤ"],"ˬ","ˮ","ʹ","ͺ","ՙ","ـ",["ۥ","ۦ"],["ߴ","ߵ"],"ߺ","ࠚ","ࠤ","ࠨ","ॱ","ๆ","ໆ","ჼ","ៗ","ᡃ","ᪧ",["ᱸ","ᱽ"],["ᴬ","ᵪ"],"ᵸ",["ᶛ","ᶿ"],"ⁱ","ⁿ",["ₐ","ₜ"],["ⱼ","ⱽ"],"ⵯ","ⸯ","々",["〱","〵"],"〻",["ゝ","ゞ"],["ー","ヾ"],"ꀕ",["ꓸ","ꓽ"],"ꘌ","ꙿ",["ꚜ","ꚝ"],["ꜗ","ꜟ"],"ꝰ","ꞈ",["ꟸ","ꟹ"],"ꧏ","ꧦ","ꩰ","ꫝ",["ꫳ","ꫴ"],["ꭜ","ꭟ"],"ー",["゙","゚"]],!1,!1),Ni=/^[\xAA\xBA\u01BB\u01C0-\u01C3\u0294\u05D0-\u05EA\u05F0-\u05F2\u0620-\u063F\u0641-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u0800-\u0815\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0972-\u0980\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0CF1-\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10D0-\u10FA\u10FD-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17DC\u1820-\u1842\u1844-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C77\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5-\u1CF6\u2135-\u2138\u2D30-\u2D67\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3006\u303C\u3041-\u3096\u309F\u30A1-\u30FA\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA014\uA016-\uA48C\uA4D0-\uA4F7\uA500-\uA60B\uA610-\uA61F\uA62A-\uA62B\uA66E\uA6A0-\uA6E5\uA78F\uA7F7\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9E0-\uA9E4\uA9E7-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA6F\uAA71-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAAE0-\uAAEA\uAAF2\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF66-\uFF6F\uFF71-\uFF9D\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,Ei=o(["ª","º","ƻ",["ǀ","ǃ"],"ʔ",["א","ת"],["װ","ײ"],["ؠ","ؿ"],["ف","ي"],["ٮ","ٯ"],["ٱ","ۓ"],"ە",["ۮ","ۯ"],["ۺ","ۼ"],"ۿ","ܐ",["ܒ","ܯ"],["ݍ","ޥ"],"ޱ",["ߊ","ߪ"],["ࠀ","ࠕ"],["ࡀ","ࡘ"],["ࢠ","ࢴ"],["ऄ","ह"],"ऽ","ॐ",["क़","ॡ"],["ॲ","ঀ"],["অ","ঌ"],["এ","ঐ"],["ও","ন"],["প","র"],"ল",["শ","হ"],"ঽ","ৎ",["ড়","ঢ়"],["য়","ৡ"],["ৰ","ৱ"],["ਅ","ਊ"],["ਏ","ਐ"],["ਓ","ਨ"],["ਪ","ਰ"],["ਲ","ਲ਼"],["ਵ","ਸ਼"],["ਸ","ਹ"],["ਖ਼","ੜ"],"ਫ਼",["ੲ","ੴ"],["અ","ઍ"],["એ","ઑ"],["ઓ","ન"],["પ","ર"],["લ","ળ"],["વ","હ"],"ઽ","ૐ",["ૠ","ૡ"],"ૹ",["ଅ","ଌ"],["ଏ","ଐ"],["ଓ","ନ"],["ପ","ର"],["ଲ","ଳ"],["ଵ","ହ"],"ଽ",["ଡ଼","ଢ଼"],["ୟ","ୡ"],"ୱ","ஃ",["அ","ஊ"],["எ","ஐ"],["ஒ","க"],["ங","ச"],"ஜ",["ஞ","ட"],["ண","த"],["ந","ப"],["ம","ஹ"],"ௐ",["అ","ఌ"],["ఎ","ఐ"],["ఒ","న"],["ప","హ"],"ఽ",["ౘ","ౚ"],["ౠ","ౡ"],["ಅ","ಌ"],["ಎ","ಐ"],["ಒ","ನ"],["ಪ","ಳ"],["ವ","ಹ"],"ಽ","ೞ",["ೠ","ೡ"],["ೱ","ೲ"],["അ","ഌ"],["എ","ഐ"],["ഒ","ഺ"],"ഽ","ൎ",["ൟ","ൡ"],["ൺ","ൿ"],["අ","ඖ"],["ක","න"],["ඳ","ර"],"ල",["ව","ෆ"],["ก","ะ"],["า","ำ"],["เ","ๅ"],["ກ","ຂ"],"ຄ",["ງ","ຈ"],"ຊ","ຍ",["ດ","ທ"],["ນ","ຟ"],["ມ","ຣ"],"ລ","ວ",["ສ","ຫ"],["ອ","ະ"],["າ","ຳ"],"ຽ",["ເ","ໄ"],["ໜ","ໟ"],"ༀ",["ཀ","ཇ"],["ཉ","ཬ"],["ྈ","ྌ"],["က","ဪ"],"ဿ",["ၐ","ၕ"],["ၚ","ၝ"],"ၡ",["ၥ","ၦ"],["ၮ","ၰ"],["ၵ","ႁ"],"ႎ",["ა","ჺ"],["ჽ","ቈ"],["ቊ","ቍ"],["ቐ","ቖ"],"ቘ",["ቚ","ቝ"],["በ","ኈ"],["ኊ","ኍ"],["ነ","ኰ"],["ኲ","ኵ"],["ኸ","ኾ"],"ዀ",["ዂ","ዅ"],["ወ","ዖ"],["ዘ","ጐ"],["ጒ","ጕ"],["ጘ","ፚ"],["ᎀ","ᎏ"],["ᐁ","ᙬ"],["ᙯ","ᙿ"],["ᚁ","ᚚ"],["ᚠ","ᛪ"],["ᛱ","ᛸ"],["ᜀ","ᜌ"],["ᜎ","ᜑ"],["ᜠ","ᜱ"],["ᝀ","ᝑ"],["ᝠ","ᝬ"],["ᝮ","ᝰ"],["ក","ឳ"],"ៜ",["ᠠ","ᡂ"],["ᡄ","ᡷ"],["ᢀ","ᢨ"],"ᢪ",["ᢰ","ᣵ"],["ᤀ","ᤞ"],["ᥐ","ᥭ"],["ᥰ","ᥴ"],["ᦀ","ᦫ"],["ᦰ","ᧉ"],["ᨀ","ᨖ"],["ᨠ","ᩔ"],["ᬅ","ᬳ"],["ᭅ","ᭋ"],["ᮃ","ᮠ"],["ᮮ","ᮯ"],["ᮺ","ᯥ"],["ᰀ","ᰣ"],["ᱍ","ᱏ"],["ᱚ","ᱷ"],["ᳩ","ᳬ"],["ᳮ","ᳱ"],["ᳵ","ᳶ"],["ℵ","ℸ"],["ⴰ","ⵧ"],["ⶀ","ⶖ"],["ⶠ","ⶦ"],["ⶨ","ⶮ"],["ⶰ","ⶶ"],["ⶸ","ⶾ"],["ⷀ","ⷆ"],["ⷈ","ⷎ"],["ⷐ","ⷖ"],["ⷘ","ⷞ"],"〆","〼",["ぁ","ゖ"],"ゟ",["ァ","ヺ"],"ヿ",["ㄅ","ㄭ"],["ㄱ","ㆎ"],["ㆠ","ㆺ"],["ㇰ","ㇿ"],["㐀","䶵"],["一","鿕"],["ꀀ","ꀔ"],["ꀖ","ꒌ"],["ꓐ","ꓷ"],["ꔀ","ꘋ"],["ꘐ","ꘟ"],["ꘪ","ꘫ"],"ꙮ",["ꚠ","ꛥ"],"ꞏ","ꟷ",["ꟻ","ꠁ"],["ꠃ","ꠅ"],["ꠇ","ꠊ"],["ꠌ","ꠢ"],["ꡀ","ꡳ"],["ꢂ","ꢳ"],["ꣲ","ꣷ"],"ꣻ","ꣽ",["ꤊ","ꤥ"],["ꤰ","ꥆ"],["ꥠ","ꥼ"],["ꦄ","ꦲ"],["ꧠ","ꧤ"],["ꧧ","ꧯ"],["ꧺ","ꧾ"],["ꨀ","ꨨ"],["ꩀ","ꩂ"],["ꩄ","ꩋ"],["ꩠ","ꩯ"],["ꩱ","ꩶ"],"ꩺ",["ꩾ","ꪯ"],"ꪱ",["ꪵ","ꪶ"],["ꪹ","ꪽ"],"ꫀ","ꫂ",["ꫛ","ꫜ"],["ꫠ","ꫪ"],"ꫲ",["ꬁ","ꬆ"],["ꬉ","ꬎ"],["ꬑ","ꬖ"],["ꬠ","ꬦ"],["ꬨ","ꬮ"],["ꯀ","ꯢ"],["가","힣"],["ힰ","ퟆ"],["ퟋ","ퟻ"],["豈","舘"],["並","龎"],"יִ",["ײַ","ﬨ"],["שׁ","זּ"],["טּ","לּ"],"מּ",["נּ","סּ"],["ףּ","פּ"],["צּ","ﮱ"],["ﯓ","ﴽ"],["ﵐ","ﶏ"],["ﶒ","ﷇ"],["ﷰ","ﷻ"],["ﹰ","ﹴ"],["ﹶ","ﻼ"],["ヲ","ッ"],["ア","ン"],["ᅠ","ᄒ"],["ᅡ","ᅦ"],["ᅧ","ᅬ"],["ᅭ","ᅲ"],["ᅳ","ᅵ"]],!1,!1),wi=/^[\u01C5\u01C8\u01CB\u01F2\u1F88-\u1F8F\u1F98-\u1F9F\u1FA8-\u1FAF\u1FBC\u1FCC\u1FFC]/,Yi=o(["Dž","Lj","Nj","Dz",["ᾈ","ᾏ"],["ᾘ","ᾟ"],["ᾨ","ᾯ"],"ᾼ","ῌ","ῼ"],!1,!1),Ti=/^[A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178-\u0179\u017B\u017D\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018B\u018E-\u0191\u0193-\u0194\u0196-\u0198\u019C-\u019D\u019F-\u01A0\u01A2\u01A4\u01A6-\u01A7\u01A9\u01AC\u01AE-\u01AF\u01B1-\u01B3\u01B5\u01B7-\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A-\u023B\u023D-\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u037F\u0386\u0388-\u038A\u038C\u038E-\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9-\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0-\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0528\u052A\u052C\u052E\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u13A0-\u13F5\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E-\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA698\uA69A\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D-\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA796\uA798\uA79A\uA79C\uA79E\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA-\uA7AD\uA7B0-\uA7B4\uA7B6\uFF21-\uFF3A]/,Ii=o([["A","Z"],["À","Ö"],["Ø","Þ"],"Ā","Ă","Ą","Ć","Ĉ","Ċ","Č","Ď","Đ","Ē","Ĕ","Ė","Ę","Ě","Ĝ","Ğ","Ġ","Ģ","Ĥ","Ħ","Ĩ","Ī","Ĭ","Į","İ","IJ","Ĵ","Ķ","Ĺ","Ļ","Ľ","Ŀ","Ł","Ń","Ņ","Ň","Ŋ","Ō","Ŏ","Ő","Œ","Ŕ","Ŗ","Ř","Ś","Ŝ","Ş","Š","Ţ","Ť","Ŧ","Ũ","Ū","Ŭ","Ů","Ű","Ų","Ŵ","Ŷ",["Ÿ","Ź"],"Ż","Ž",["Ɓ","Ƃ"],"Ƅ",["Ɔ","Ƈ"],["Ɖ","Ƌ"],["Ǝ","Ƒ"],["Ɠ","Ɣ"],["Ɩ","Ƙ"],["Ɯ","Ɲ"],["Ɵ","Ơ"],"Ƣ","Ƥ",["Ʀ","Ƨ"],"Ʃ","Ƭ",["Ʈ","Ư"],["Ʊ","Ƴ"],"Ƶ",["Ʒ","Ƹ"],"Ƽ","DŽ","LJ","NJ","Ǎ","Ǐ","Ǒ","Ǔ","Ǖ","Ǘ","Ǚ","Ǜ","Ǟ","Ǡ","Ǣ","Ǥ","Ǧ","Ǩ","Ǫ","Ǭ","Ǯ","DZ","Ǵ",["Ƕ","Ǹ"],"Ǻ","Ǽ","Ǿ","Ȁ","Ȃ","Ȅ","Ȇ","Ȉ","Ȋ","Ȍ","Ȏ","Ȑ","Ȓ","Ȕ","Ȗ","Ș","Ț","Ȝ","Ȟ","Ƞ","Ȣ","Ȥ","Ȧ","Ȩ","Ȫ","Ȭ","Ȯ","Ȱ","Ȳ",["Ⱥ","Ȼ"],["Ƚ","Ⱦ"],"Ɂ",["Ƀ","Ɇ"],"Ɉ","Ɋ","Ɍ","Ɏ","Ͱ","Ͳ","Ͷ","Ϳ","Ά",["Έ","Ί"],"Ό",["Ύ","Ώ"],["Α","Ρ"],["Σ","Ϋ"],"Ϗ",["ϒ","ϔ"],"Ϙ","Ϛ","Ϝ","Ϟ","Ϡ","Ϣ","Ϥ","Ϧ","Ϩ","Ϫ","Ϭ","Ϯ","ϴ","Ϸ",["Ϲ","Ϻ"],["Ͻ","Я"],"Ѡ","Ѣ","Ѥ","Ѧ","Ѩ","Ѫ","Ѭ","Ѯ","Ѱ","Ѳ","Ѵ","Ѷ","Ѹ","Ѻ","Ѽ","Ѿ","Ҁ","Ҋ","Ҍ","Ҏ","Ґ","Ғ","Ҕ","Җ","Ҙ","Қ","Ҝ","Ҟ","Ҡ","Ң","Ҥ","Ҧ","Ҩ","Ҫ","Ҭ","Ү","Ұ","Ҳ","Ҵ","Ҷ","Ҹ","Һ","Ҽ","Ҿ",["Ӏ","Ӂ"],"Ӄ","Ӆ","Ӈ","Ӊ","Ӌ","Ӎ","Ӑ","Ӓ","Ӕ","Ӗ","Ә","Ӛ","Ӝ","Ӟ","Ӡ","Ӣ","Ӥ","Ӧ","Ө","Ӫ","Ӭ","Ӯ","Ӱ","Ӳ","Ӵ","Ӷ","Ӹ","Ӻ","Ӽ","Ӿ","Ԁ","Ԃ","Ԅ","Ԇ","Ԉ","Ԋ","Ԍ","Ԏ","Ԑ","Ԓ","Ԕ","Ԗ","Ԙ","Ԛ","Ԝ","Ԟ","Ԡ","Ԣ","Ԥ","Ԧ","Ԩ","Ԫ","Ԭ","Ԯ",["Ա","Ֆ"],["Ⴀ","Ⴥ"],"Ⴧ","Ⴭ",["Ꭰ","Ᏽ"],"Ḁ","Ḃ","Ḅ","Ḇ","Ḉ","Ḋ","Ḍ","Ḏ","Ḑ","Ḓ","Ḕ","Ḗ","Ḙ","Ḛ","Ḝ","Ḟ","Ḡ","Ḣ","Ḥ","Ḧ","Ḩ","Ḫ","Ḭ","Ḯ","Ḱ","Ḳ","Ḵ","Ḷ","Ḹ","Ḻ","Ḽ","Ḿ","Ṁ","Ṃ","Ṅ","Ṇ","Ṉ","Ṋ","Ṍ","Ṏ","Ṑ","Ṓ","Ṕ","Ṗ","Ṙ","Ṛ","Ṝ","Ṟ","Ṡ","Ṣ","Ṥ","Ṧ","Ṩ","Ṫ","Ṭ","Ṯ","Ṱ","Ṳ","Ṵ","Ṷ","Ṹ","Ṻ","Ṽ","Ṿ","Ẁ","Ẃ","Ẅ","Ẇ","Ẉ","Ẋ","Ẍ","Ẏ","Ẑ","Ẓ","Ẕ","ẞ","Ạ","Ả","Ấ","Ầ","Ẩ","Ẫ","Ậ","Ắ","Ằ","Ẳ","Ẵ","Ặ","Ẹ","Ẻ","Ẽ","Ế","Ề","Ể","Ễ","Ệ","Ỉ","Ị","Ọ","Ỏ","Ố","Ồ","Ổ","Ỗ","Ộ","Ớ","Ờ","Ở","Ỡ","Ợ","Ụ","Ủ","Ứ","Ừ","Ử","Ữ","Ự","Ỳ","Ỵ","Ỷ","Ỹ","Ỻ","Ỽ","Ỿ",["Ἀ","Ἇ"],["Ἐ","Ἕ"],["Ἠ","Ἧ"],["Ἰ","Ἷ"],["Ὀ","Ὅ"],"Ὑ","Ὓ","Ὕ","Ὗ",["Ὠ","Ὧ"],["Ᾰ","Ά"],["Ὲ","Ή"],["Ῐ","Ί"],["Ῠ","Ῥ"],["Ὸ","Ώ"],"ℂ","ℇ",["ℋ","ℍ"],["ℐ","ℒ"],"ℕ",["ℙ","ℝ"],"ℤ","Ω","ℨ",["K","ℭ"],["ℰ","ℳ"],["ℾ","ℿ"],"ⅅ","Ↄ",["Ⰰ","Ⱞ"],"Ⱡ",["Ɫ","Ɽ"],"Ⱨ","Ⱪ","Ⱬ",["Ɑ","Ɒ"],"Ⱳ","Ⱶ",["Ȿ","Ⲁ"],"Ⲃ","Ⲅ","Ⲇ","Ⲉ","Ⲋ","Ⲍ","Ⲏ","Ⲑ","Ⲓ","Ⲕ","Ⲗ","Ⲙ","Ⲛ","Ⲝ","Ⲟ","Ⲡ","Ⲣ","Ⲥ","Ⲧ","Ⲩ","Ⲫ","Ⲭ","Ⲯ","Ⲱ","Ⲳ","Ⲵ","Ⲷ","Ⲹ","Ⲻ","Ⲽ","Ⲿ","Ⳁ","Ⳃ","Ⳅ","Ⳇ","Ⳉ","Ⳋ","Ⳍ","Ⳏ","Ⳑ","Ⳓ","Ⳕ","Ⳗ","Ⳙ","Ⳛ","Ⳝ","Ⳟ","Ⳡ","Ⳣ","Ⳬ","Ⳮ","Ⳳ","Ꙁ","Ꙃ","Ꙅ","Ꙇ","Ꙉ","Ꙋ","Ꙍ","Ꙏ","Ꙑ","Ꙓ","Ꙕ","Ꙗ","Ꙙ","Ꙛ","Ꙝ","Ꙟ","Ꙡ","Ꙣ","Ꙥ","Ꙧ","Ꙩ","Ꙫ","Ꙭ","Ꚁ","Ꚃ","Ꚅ","Ꚇ","Ꚉ","Ꚋ","Ꚍ","Ꚏ","Ꚑ","Ꚓ","Ꚕ","Ꚗ","Ꚙ","Ꚛ","Ꜣ","Ꜥ","Ꜧ","Ꜩ","Ꜫ","Ꜭ","Ꜯ","Ꜳ","Ꜵ","Ꜷ","Ꜹ","Ꜻ","Ꜽ","Ꜿ","Ꝁ","Ꝃ","Ꝅ","Ꝇ","Ꝉ","Ꝋ","Ꝍ","Ꝏ","Ꝑ","Ꝓ","Ꝕ","Ꝗ","Ꝙ","Ꝛ","Ꝝ","Ꝟ","Ꝡ","Ꝣ","Ꝥ","Ꝧ","Ꝩ","Ꝫ","Ꝭ","Ꝯ","Ꝺ","Ꝼ",["Ᵹ","Ꝿ"],"Ꞁ","Ꞃ","Ꞅ","Ꞇ","Ꞌ","Ɥ","Ꞑ","Ꞓ","Ꞗ","Ꞙ","Ꞛ","Ꞝ","Ꞟ","Ꞡ","Ꞣ","Ꞥ","Ꞧ","Ꞩ",["Ɦ","Ɬ"],["Ʞ","Ꞵ"],"Ꞷ",["A","Z"]],!1,!1),Pi=/^[\u0903\u093B\u093E-\u0940\u0949-\u094C\u094E-\u094F\u0982-\u0983\u09BE-\u09C0\u09C7-\u09C8\u09CB-\u09CC\u09D7\u0A03\u0A3E-\u0A40\u0A83\u0ABE-\u0AC0\u0AC9\u0ACB-\u0ACC\u0B02-\u0B03\u0B3E\u0B40\u0B47-\u0B48\u0B4B-\u0B4C\u0B57\u0BBE-\u0BBF\u0BC1-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD7\u0C01-\u0C03\u0C41-\u0C44\u0C82-\u0C83\u0CBE\u0CC0-\u0CC4\u0CC7-\u0CC8\u0CCA-\u0CCB\u0CD5-\u0CD6\u0D02-\u0D03\u0D3E-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D57\u0D82-\u0D83\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DF2-\u0DF3\u0F3E-\u0F3F\u0F7F\u102B-\u102C\u1031\u1038\u103B-\u103C\u1056-\u1057\u1062-\u1064\u1067-\u106D\u1083-\u1084\u1087-\u108C\u108F\u109A-\u109C\u17B6\u17BE-\u17C5\u17C7-\u17C8\u1923-\u1926\u1929-\u192B\u1930-\u1931\u1933-\u1938\u1A19-\u1A1A\u1A55\u1A57\u1A61\u1A63-\u1A64\u1A6D-\u1A72\u1B04\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B44\u1B82\u1BA1\u1BA6-\u1BA7\u1BAA\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2-\u1BF3\u1C24-\u1C2B\u1C34-\u1C35\u1CE1\u1CF2-\u1CF3\u302E-\u302F\uA823-\uA824\uA827\uA880-\uA881\uA8B4-\uA8C3\uA952-\uA953\uA983\uA9B4-\uA9B5\uA9BA-\uA9BB\uA9BD-\uA9C0\uAA2F-\uAA30\uAA33-\uAA34\uAA4D\uAA7B\uAA7D\uAAEB\uAAEE-\uAAEF\uAAF5\uABE3-\uABE4\uABE6-\uABE7\uABE9-\uABEA\uABEC]/,Ai=o(["ः","ऻ",["ा","ी"],["ॉ","ौ"],["ॎ","ॏ"],["ং","ঃ"],["া","ী"],["ে","ৈ"],["ো","ৌ"],"ৗ","ਃ",["ਾ","ੀ"],"ઃ",["ા","ી"],"ૉ",["ો","ૌ"],["ଂ","ଃ"],"ା","ୀ",["େ","ୈ"],["ୋ","ୌ"],"ୗ",["ா","ி"],["ு","ூ"],["ெ","ை"],["ொ","ௌ"],"ௗ",["ఁ","ః"],["ు","ౄ"],["ಂ","ಃ"],"ಾ",["ೀ","ೄ"],["ೇ","ೈ"],["ೊ","ೋ"],["ೕ","ೖ"],["ം","ഃ"],["ാ","ീ"],["െ","ൈ"],["ൊ","ൌ"],"ൗ",["ං","ඃ"],["ා","ෑ"],["ෘ","ෟ"],["ෲ","ෳ"],["༾","༿"],"ཿ",["ါ","ာ"],"ေ","း",["ျ","ြ"],["ၖ","ၗ"],["ၢ","ၤ"],["ၧ","ၭ"],["ႃ","ႄ"],["ႇ","ႌ"],"ႏ",["ႚ","ႜ"],"ា",["ើ","ៅ"],["ះ","ៈ"],["ᤣ","ᤦ"],["ᤩ","ᤫ"],["ᤰ","ᤱ"],["ᤳ","ᤸ"],["ᨙ","ᨚ"],"ᩕ","ᩗ","ᩡ",["ᩣ","ᩤ"],["ᩭ","ᩲ"],"ᬄ","ᬵ","ᬻ",["ᬽ","ᭁ"],["ᭃ","᭄"],"ᮂ","ᮡ",["ᮦ","ᮧ"],"᮪","ᯧ",["ᯪ","ᯬ"],"ᯮ",["᯲","᯳"],["ᰤ","ᰫ"],["ᰴ","ᰵ"],"᳡",["ᳲ","ᳳ"],["〮","〯"],["ꠣ","ꠤ"],"ꠧ",["ꢀ","ꢁ"],["ꢴ","ꣃ"],["ꥒ","꥓"],"ꦃ",["ꦴ","ꦵ"],["ꦺ","ꦻ"],["ꦽ","꧀"],["ꨯ","ꨰ"],["ꨳ","ꨴ"],"ꩍ","ꩻ","ꩽ","ꫫ",["ꫮ","ꫯ"],"ꫵ",["ꯣ","ꯤ"],["ꯦ","ꯧ"],["ꯩ","ꯪ"],"꯬"],!1,!1),ki=/^[\u0300-\u036F\u0483-\u0487\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962-\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2-\u09E3\u0A01-\u0A02\u0A3C\u0A41-\u0A42\u0A47-\u0A48\u0A4B-\u0A4D\u0A51\u0A70-\u0A71\u0A75\u0A81-\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7-\u0AC8\u0ACD\u0AE2-\u0AE3\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62-\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55-\u0C56\u0C62-\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC-\u0CCD\u0CE2-\u0CE3\u0D01\u0D41-\u0D44\u0D4D\u0D62-\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB-\u0EBC\u0EC8-\u0ECD\u0F18-\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86-\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039-\u103A\u103D-\u103E\u1058-\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17B4-\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193B\u1A17-\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABD\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80-\u1B81\u1BA2-\u1BA5\u1BA8-\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8-\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8-\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099-\u309A\uA66F\uA674-\uA67D\uA69E-\uA69F\uA6F0-\uA6F1\uA802\uA806\uA80B\uA825-\uA826\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31-\uAA32\uAA35-\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7-\uAAB8\uAABE-\uAABF\uAAC1\uAAEC-\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/,Fi=o([["̀","ͯ"],["҃","҇"],["֑","ֽ"],"ֿ",["ׁ","ׂ"],["ׄ","ׅ"],"ׇ",["ؐ","ؚ"],["ً","ٟ"],"ٰ",["ۖ","ۜ"],["۟","ۤ"],["ۧ","ۨ"],["۪","ۭ"],"ܑ",["ܰ","݊"],["ަ","ް"],["߫","߳"],["ࠖ","࠙"],["ࠛ","ࠣ"],["ࠥ","ࠧ"],["ࠩ","࠭"],["࡙","࡛"],["ࣣ","ं"],"ऺ","़",["ु","ै"],"्",["॑","ॗ"],["ॢ","ॣ"],"ঁ","়",["ু","ৄ"],"্",["ৢ","ৣ"],["ਁ","ਂ"],"਼",["ੁ","ੂ"],["ੇ","ੈ"],["ੋ","੍"],"ੑ",["ੰ","ੱ"],"ੵ",["ઁ","ં"],"઼",["ુ","ૅ"],["ે","ૈ"],"્",["ૢ","ૣ"],"ଁ","଼","ି",["ୁ","ୄ"],"୍","ୖ",["ୢ","ୣ"],"ஂ","ீ","்","ఀ",["ా","ీ"],["ె","ై"],["ొ","్"],["ౕ","ౖ"],["ౢ","ౣ"],"ಁ","಼","ಿ","ೆ",["ೌ","್"],["ೢ","ೣ"],"ഁ",["ു","ൄ"],"്",["ൢ","ൣ"],"්",["ි","ු"],"ූ","ั",["ิ","ฺ"],["็","๎"],"ັ",["ິ","ູ"],["ົ","ຼ"],["່","ໍ"],["༘","༙"],"༵","༷","༹",["ཱ","ཾ"],["ྀ","྄"],["྆","྇"],["ྍ","ྗ"],["ྙ","ྼ"],"࿆",["ိ","ူ"],["ဲ","့"],["္","်"],["ွ","ှ"],["ၘ","ၙ"],["ၞ","ၠ"],["ၱ","ၴ"],"ႂ",["ႅ","ႆ"],"ႍ","ႝ",["፝","፟"],["ᜒ","᜔"],["ᜲ","᜴"],["ᝒ","ᝓ"],["ᝲ","ᝳ"],["឴","឵"],["ិ","ួ"],"ំ",["៉","៓"],"៝",["᠋","᠍"],"ᢩ",["ᤠ","ᤢ"],["ᤧ","ᤨ"],"ᤲ",["᤹","᤻"],["ᨗ","ᨘ"],"ᨛ","ᩖ",["ᩘ","ᩞ"],"᩠","ᩢ",["ᩥ","ᩬ"],["ᩳ","᩼"],"᩿",["᪰","᪽"],["ᬀ","ᬃ"],"᬴",["ᬶ","ᬺ"],"ᬼ","ᭂ",["᭫","᭳"],["ᮀ","ᮁ"],["ᮢ","ᮥ"],["ᮨ","ᮩ"],["᮫","ᮭ"],"᯦",["ᯨ","ᯩ"],"ᯭ",["ᯯ","ᯱ"],["ᰬ","ᰳ"],["ᰶ","᰷"],["᳐","᳒"],["᳔","᳠"],["᳢","᳨"],"᳭","᳴",["᳸","᳹"],["᷀","᷵"],["᷼","᷿"],["⃐","⃜"],"⃡",["⃥","⃰"],["⳯","⳱"],"⵿",["ⷠ","ⷿ"],["〪","〭"],["゙","゚"],"꙯",["ꙴ","꙽"],["ꚞ","ꚟ"],["꛰","꛱"],"ꠂ","꠆","ꠋ",["ꠥ","ꠦ"],"꣄",["꣠","꣱"],["ꤦ","꤭"],["ꥇ","ꥑ"],["ꦀ","ꦂ"],"꦳",["ꦶ","ꦹ"],"ꦼ","ꧥ",["ꨩ","ꨮ"],["ꨱ","ꨲ"],["ꨵ","ꨶ"],"ꩃ","ꩌ","ꩼ","ꪰ",["ꪲ","ꪴ"],["ꪷ","ꪸ"],["ꪾ","꪿"],"꫁",["ꫬ","ꫭ"],"꫶","ꯥ","ꯨ","꯭","ﬞ",["︀","️"],["︠","︯"]],!1,!1),Li=/^[0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]/,Bi=o([["0","9"],["٠","٩"],["۰","۹"],["߀","߉"],["०","९"],["০","৯"],["੦","੯"],["૦","૯"],["୦","୯"],["௦","௯"],["౦","౯"],["೦","೯"],["൦","൯"],["෦","෯"],["๐","๙"],["໐","໙"],["༠","༩"],["၀","၉"],["႐","႙"],["០","៩"],["᠐","᠙"],["᥆","᥏"],["᧐","᧙"],["᪀","᪉"],["᪐","᪙"],["᭐","᭙"],["᮰","᮹"],["᱀","᱉"],["᱐","᱙"],["꘠","꘩"],["꣐","꣙"],["꤀","꤉"],["꧐","꧙"],["꧰","꧹"],["꩐","꩙"],["꯰","꯹"],["0","9"]],!1,!1),Ri=/^[\u16EE-\u16F0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303A\uA6E6-\uA6EF]/,Vi=o([["ᛮ","ᛰ"],["Ⅰ","ↂ"],["ↅ","ↈ"],"〇",["〡","〩"],["〸","〺"],["ꛦ","ꛯ"]],!1,!1),Wi=/^[!#-&*+\--\/:-@[-`{-~\u203F-\u2040\u2054\uFE33-\uFE34\uFE4D-\uFE4F\uFF3F]/,Ui=o(["!",["#","&"],"*","+",["-","/"],[":","@"],["[","`"],["{","~"],["‿","⁀"],"⁔",["︳","︴"],["﹍","﹏"],"_"],!1,!1),ji=/^[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000]/,Hi=o([" "," "," ",[" "," "]," "," "," "],!1,!1),Gi="NOT",qi=a("NOT",!1),zi="OR",Ki=a("OR",!1),Ji="AND",Xi=a("AND",!1),Qi="from:",Zi=a("from:",!1),$i="to:",tn=a("to:",!1),en="subject:",nn=a("subject:",!1),an="in:",on=a("in:",!1),sn="label:",ln=a("label:",!1),rn="larger:",dn=a("larger:",!1),cn="smaller:",hn=a("smaller:",!1),un="before:",Sn=a("before:",!1),mn="after:",fn=a("after:",!1),pn="filename:",gn=a("filename:",!1),bn="(",Cn=a("(",!1),yn=")",xn=a(")",!1),_n=function(t){return t},Mn=function(t,e){return{type:"UnaryExpression",operator:t,left:e}},Dn=function(t,e){return Dt(t,e)},vn=function(t){return{type:"ExpressionStatement",expression:t}},On=0,Nn=0,En=[{line:1,column:1}],wn=0,Yn=[],Tn=0;if("startRule"in i){if(!(i.startRule in Nt))throw new Error("Can't start parsing from rule \""+i.startRule+'".');Et=Nt[i.startRule]}if((vt=Et())!==Ot&&On===e.length)return vt;throw vt!==Ot&&On<e.length&&d(function(){return{type:"end"}}()),c(Yn,wn<e.length?e.charAt(wn):null,wn<e.length?r(wn,wn+1):r(wn,wn))}return function(t,e){function i(){this.constructor=t}i.prototype=e.prototype,t.prototype=new i}(t,Error),t.buildMessage=function(t,e){function i(t){return t.charCodeAt(0).toString(16).toUpperCase()}function n(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(t){return"\\x0"+i(t)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(t){return"\\x"+i(t)})}function a(t){return t.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(t){return"\\x0"+i(t)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(t){return"\\x"+i(t)})}function o(t){return s[t.type](t)}var s={literal:function(t){return'"'+n(t.text)+'"'},class:function(t){var e,i="";for(e=0;e<t.parts.length;e++)i+=t.parts[e]instanceof Array?a(t.parts[e][0])+"-"+a(t.parts[e][1]):a(t.parts[e]);return"["+(t.inverted?"^":"")+i+"]"},any:function(t){return"any character"},end:function(t){return"end of input"},other:function(t){return t.description}};return"Expected "+function(t){var e,i,n=new Array(t.length);for(e=0;e<t.length;e++)n[e]=o(t[e]);if(n.sort(),n.length>0){for(e=1,i=1;e<n.length;e++)n[e-1]!==n[e]&&(n[i]=n[e],i++);n.length=i}switch(n.length){case 1:return n[0];case 2:return n[0]+" or "+n[1];default:return n.slice(0,-1).join(", ")+", or "+n[n.length-1]}}(t)+" but "+function(t){return t?'"'+n(t)+'"':"end of input"}(e)+" found."},{SyntaxError:t,parse:e}}(),Ext.define("SYNO.SDS.MailClient.History",{singleton:!0,extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition"],showMessageHash:!1,init:function(){this.currentHash=location.hash.substr(location.hash.indexOf("#")+1),SYNO.SDS.MailClient.Define.isNormalMode&&(SYNO.SDS.MailClient.Switch.on("offsetchange",this.offsetChange,this),SYNO.SDS.MailClient.Switch.on("settingchange",this.settingChange,this),Ext.EventManager.addListener(window,"hashchange",this.hashChange,this)),this.containThreadId=!1},loadByURL:function(){if(!this.currentHash)return!1;var t,e=this.currentHash,i=e.split("/");for(t=0;t<i.length;++t)i[t]=decodeURIComponent(i[t]);var n=i.shift().toLowerCase();return!!(SYNO.SDS.MailClient.Define.isSystemMailboxName(n)||-1<["mailbox","label","search"].indexOf(n))&&(this.load(n,i),!0)},load:function(t,e){var i,n,a,o,s=SYNO.SDS.MailClient.Define,l={paging:1,state:history.state||{}};l.state.condition&&(l.state.condition=new SYNO.SDS.MailClient.Condition(l.state.condition)),"mailbox"===t||s.isSystemMailboxName(t)?(n="mailbox"===t?e.shift():t,l.mailbox=n):"label"===t?l.label=e.shift():"search"===t&&(l.search=Ext.urlDecode(e.shift())),a=e[0],
a&&(i=this.isPaging(a))?l.paging=i:a&&!1!==(o=this.decodeThreadId(a))&&(this.showMessageHash?(l.thread_id=o,this.containThreadId=!0):window.history.replaceState(window.history.state,{},location.hash.substr(0,location.hash.indexOf(a)-1))),SYNO.SDS.MailClient.Control.History.loadByOption("mail",l)},isPaging:function(t){var e=t.match(/^p(\d+)$/i);return e?e[1]:0},_getThreadPrefix:function(){return SYNO.SDS.MailClient.Settings.conversation_view?"t":"mt"},encodeThreadId:function(t){return SYNO.SDS.Utils.bin2hex(this._getThreadPrefix()+t)},decodeThreadId:function(t){var e=SYNO.SDS.MailClient.Tool.hex2bin(t),i=this._getThreadPrefix();if(e.startsWith(i)){var n=e.substr(i.length);return!!/^\d+$/.test(n)&&parseInt(n,10)}return!1},back:function(t){t||(t=-1),window.history.go(t)},forward:function(t){t||(t=1),window.history.go(t)},changeStateToThread:function(t){this.updateThreadCondition(t)},changeStateToMessage:function(t,e){this.showMessageHash&&this.updateThreadCondition(t,this.encodeThreadId(e))},offsetChange:function(t,e){this.updateThreadCondition(SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition"),void 0,e)},settingChange:function(t){this.showMessageHash=3!==t.split_pane_mode,!this.showMessageHash&&this.containThreadId&&this.updateThreadCondition(SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition"),void 0,!0)},backToThread:function(){this.updateThreadCondition(SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition"))},updateThreadCondition:function(t,e,i){var n,a=t.toURLString(),o=SYNO.SDS.MailClient.Switch.getRegister("offset"),s=SYNO.SDS.MailClient.Switch.getRegister("limit");e&&this.showMessageHash?(this.containThreadId=!0,n=a+"/"+e):(n=a+this.getPaging(o,s),this.containThreadId=!1),this.currentHash=n;var l=location.hash.substr(1),r=!1;if(""===location.hash)r=!0;else if(l!==n)r=i;else{if(history.state&&history.state.condition)return;r=!0}window.history[r?"replaceState":"pushState"]({condition:t.toWebAPIParams(),offset:o,limit:s},"","#"+n)},getPaging:function(t,e){var i=t%e==0?t/e+1:Math.ceil(t/e);return 1!=i?"/p"+i:""},hashChange:function(){if(location.hash){var t=location.hash.substr(1);SYNO.SDS.MailClient.Define.isSystemMailboxName(t)&&t.toLowerCase()===this.currentHash.toLowerCase()||t==this.currentHash||(this.currentHash=t,this.loadByURL())}}}),Ext.define("SYNO.SDS.MailClient.KeyNavigator",{extend:"Object",statics:{ShortCut:function(){var t,e=["REPLY","REPLY_ALL","FORWARD","COMPOSE","SEARCH","DELETE","ARCHIVE","LABEL","STAR","DOWN_THREAD","UP_THREAD","BACK_TO_THREAD"],i={};for(t=0;t<e.length;t++)i[e[t]]=e[t].toLowerCase();return i}()},cmpHash:{},naviCodeMap:{},shortCutHash:{},shortCutCodeMap:{},group:{},constructor:function(t){this.callParent(arguments),this.initCodeMap(),window.kn=this},initCodeMap:function(){var t=Ext.EventObject,e=this.naviCodeMap;e[t.UP]=e[t.DOWN]=e[t.LEFT]=e[t.RIGHT]=!0;var i=SYNO.SDS.MailClient.KeyNavigator.ShortCut;e=this.shortCutCodeMap,e[t.R]=i.REPLY,e[t.A]=i.REPLY_ALL,e[t.F]=i.FORWARD,e[t.C]=i.COMPOSE,e[191]=i.SEARCH,e[t.D]=i.DELETE,e[t.E]=i.ARCHIVE,e[t.L]=i.LABEL,e[t.S]=i.STAR,e[t.J]=i.DOWN_THREAD,e[t.K]=i.UP_THREAD,e[t.U]=i.BACK_TO_THREAD},setupMainWin:function(t){t.el.dom.tabIndex="0",t.el.on("keydown",this.onWinKeyDown,this)},onWinKeyDown:function(t){if(!t.ctrlKey&&!t.altKey){var e=t.getTarget();if(-1===["INPUT","TEXTAREA"].indexOf(e.tagName)&&"true"!==e.contentEditable){var i=this.shortCutCodeMap[t.getKey()];if(SYNO.SDS.MailClient.Settings.enable_shortcut&&i)return t.preventDefault(),void this.shortCut(i);if(this.naviCodeMap[t.getKey()]){var n,a;for(n in this.cmpHash)if(this.cmpHash.hasOwnProperty(n)&&(a=Ext.getCmp(n),a.rendered&&a.el.dom.contains(e)))return;Ext.fly(e).hasClass("flexcrollactive")||this.defaultNaviCmp&&this.defaultNaviCmp.onNavigateIn(this.defaultNaviDir)&&t.preventDefault()}}}},regEvent:function(t){if(!this.cmpHash[t.id]){if(!Ext.isFunction(t.onNavigateIn)||!Ext.isFunction(t.onNavigateOut))throw"need implemention of onNavigateIn() and onNavigateOut()";this.cmpHash[t.id]={left:[],right:[],up:[],down:[]},t.addEvents("navigate"),t.on("navigate",function(e,i){this.navigate(t,e,i)},this)}},addDirection:function(t,e,i){var n=this.cmpHash[t.id][e];-1===n.indexOf(i)&&n.push(i)},regLeft:function(t,e){this.regEvent(t),this.addDirection(t,"left",e)},regRight:function(t,e){this.regEvent(t),this.addDirection(t,"right",e)},regUp:function(t,e){this.regEvent(t),this.addDirection(t,"up",e)},regDown:function(t,e){this.regEvent(t),this.addDirection(t,"down",e)},regLeftRight:function(t,e){this.regLeft(e,t),this.regRight(t,e)},regUpDown:function(t,e){this.regUp(e,t),this.regDown(t,e)},regDefault:function(t,e){if(!Ext.isFunction(t.onNavigateIn))throw"need implemention of onNavigateIn() for default navi cmp";this.defaultNaviCmp=t,this.defaultNaviDir=e||"down",this.startNavigationTask()},regGroup:function(t,e){this.group[t]||(this.group[t]={items:[],selection:-1,lastFocus:-1}),this.group[t].items.push(e),e.navigationGroup=t},findNextGroupCmp:function(t,e,i){var n,a=null,o=this.group[t].items,s=this.group[t].selection,l=function(t){return t.isVisible()&&t.store.getCount()>0};if("up"==i){for(n=e;n>=0;n--)if(l(o[n])){a=o[n];break}}else if("down"==i){for(n=e;n<o.length;n++)if(l(o[n])){a=o[n];break}}else if(s>=0&&l(o[s]))a=o[s];else for(n=e;n<o.length;n++)if(l(o[n])){a=o[n];break}return a},regGroupSelection:function(t,e){this.group[t].selection=e},regGroupLastFocus:function(t,e){this.group[t].lastFocus=e},getGroupSelection:function(t){return this.group[t].selection},getGroupLastFocus:function(t){return this.group[t].lastFocus},startNavigationTask:function(){this.naviTask||(this.naviTask=new Ext.util.TaskRunner,this.naviTask.start({interval:1e3,scope:this,run:function(){document.activeElement===document.body&&this.defaultNaviCmp&&this.defaultNaviCmp.onNavigateIn(this.defaultNaviDir)}}))},navigate:function(t,e,i){var n=this.cmpHash[t.id][e]||[];Ext.each(n,function(n){var a=n;if(Ext.isDefined(a.navigationGroup)&&a.store){var o=this.findNextGroupCmp(a.navigationGroup,a.store.sectionIdx,e);if(!o)return!1;a=o}if(a.onNavigateIn(e,i))return t.onNavigateOut(),!1},this)},regShortCut:function(t,e){if(Ext.isArray(e))return void Ext.each(e,function(e){this.regShortCut(t,e)},this);if(!Ext.isFunction(t.onShortCut))throw"need implemention of onShortCut()";this.shortCutHash[e]=this.shortCutHash[e]||[],-1===this.shortCutHash[e].indexOf(t)&&this.shortCutHash[e].push(t)},shortCut:function(t){var e=this.shortCutHash[t]||[];Ext.each(e,function(e){if(e.onShortCut(t))return!1},this)}}),Ext.define("SYNO.SDS.MailClient.TreeMenuButton",{extend:"SYNO.ux.Button",currentElementId:0,htmlEncode:!1,constructor:function(t){var e;t.hasOwnProperty("currentElementId")&&(this.currentElementId=t.currentElementId),t.hasOwnProperty("text")&&(this.defaultText=t.text),e={cls:"syno-mc-search-menu-btn",text:this.defaultText},Ext.apply(e,t),this.callParent([e]),this.addEvents("change"),this.mon(this.menu,"select",this.onItemSelected,this)},isValid:function(){return 0===this.getCurrentElementId()?(this.markAsInvalid(),!1):(this.clearInvalid(),!0)},markAsInvalid:function(){this.el.addClass("x-form-invalid")},clearInvalid:function(){this.el.removeClass("x-form-invalid")},onItemSelected:function(t,e){this.setText(e),this.currentElementId=t,this.fireEvent("change",this.currentElementId),this.clearInvalid()},setValue:function(t,e){this.currentElementId!==t&&this.fireEvent("change",t,e),this.currentElementId=t,void 0!==e&&this.setText(e),this.clearInvalid()},getCurrentElementId:function(){return this.currentElementId},getCurrentElementName:function(){this.menu.getItemName(this.currentElementId)},reset:function(){this.setText(this.defaultText),this.menu.resetSelect(),this.currentElementId=0,this.fireEvent("change",this.currentElementId),this.clearInvalid()}}),Ext.define("SYNO.SDS.MailClient.Menu",{extend:"SYNO.ux.Menu",needReload:!0,selectPartialCls:"select-partial",constructor:function(t){var e={cls:"syno-mc-menu",width:280,maxHeight:250,autoFlexcroll:!0,items:[]};this.callParent([Ext.apply(e,t)]),this.on("show",this.loadList,this)},loadList:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.Search.TextFilter",{extend:"Ext.form.TriggerField",ctCls:"syno-mc-textfilter",cls:"syno-mc-textfilter-text",triggerConfig:{tag:"div",cls:"x-form-trigger syno-mc-textfilter-trigger"},enableKeyEvents:!0,listeners:{keyup:{fn:function(t,e){t.trigger.setVisible(""!==t.getValue())}},render:{fn:function(t){t.trigger.hide()}}},queryDelay:500,queryAction:"find",enumAction:"enum",queryParam:"query",localFilter:!1,localFilterField:"",pageSize:20,constructor:function(t){SYNO.SDS.MailClient.Search.TextFilter.superclass.constructor.call(this,t),this.store&&!this.localFilter&&this.mon(this.store,"beforeload",this.onBeforeLoad,this),this.store&&!0===this.localFilter&&this.mon(this.store,"load",this.reset,this)},initEvents:function(){SYNO.SDS.MailClient.Search.TextFilter.superclass.initEvents.call(this),this.mon(this.el,"keyup",this.filter,this,{buffer:this.queryDelay})},setPageSize:function(t){this.pageSize=t},onBeforeLoad:function(t,e){var i=this.getValue();return i?(e.params[this.queryParam]=i,e.params.action=this.queryAction):e.params.action=this.enumAction,!0},filter:function(){var t,e=this.getValue();if(this.store){if(!0===this.localFilter)return void(e?this.store.filter(this.localFilterField,e,!0):this.store.clearFilter(!1));t={start:0,limit:this.pageSize},e?(t.action=this.queryAction,t[this.queryParam]=e,this.store.load({params:t})):(t.action=this.enumAction,this.store.load({params:t}))}},reset:function(){SYNO.SDS.MailClient.Search.TextFilter.superclass.reset.call(this),!1===this.localFilterField&&this.store&&(this.store.clearFilter(!1),this.trigger.hide())},onTriggerClick:function(){this.getValue()&&(this.setValue(""),this.filter())},setValue:function(t){SYNO.SDS.MailClient.Search.TextFilter.superclass.setValue.call(this,t),Ext.isEmpty(t)&&this.trigger.hide()}}),Ext.define("SYNO.SDS.MailClient.Search.SearchListMenu",{extend:"SYNO.SDS.MailClient.Menu",requires:["SYNO.SDS.MailClient.Search.TextFilter","SYNO.SDS.MailClient.Menu"],contentMaxHeight:256,constructor:function(t){t.selector&&(this.selector=t.selector,delete t.selector);var e=284;t.width&&(e=t.width-16),this.searchfield=new SYNO.SDS.MailClient.Search.TextFilter({width:e,itemId:"searchfield",listeners:{scope:this,keyup:{fn:this.onSearchFieldKeyUp,buffer:500},keydown:this.onSearchFieldKeyDown,afterrender:function(t){t.trigger.on("click",function(){this.onSearchFieldKeyUp(t)},this),t.wrap.addClass("syno-mc-searchlist-searchfield"),t.el.on("focus",function(){this.setActiveItem(this.searchfield)},this)}}});var i={width:300,autoFlexcroll:!1,maxHeight:void 0,items:[]};Ext.apply(i,t),i.items.unshift(this.searchfield,this.selector),this.callParent([i]),this.addClass("sds-window-v5 syno-mc-search-menu syno-mc-menu"),this.on({show:function(){this.setActiveItem(this.searchfield)},beforehide:function(t,e){t.reset()}})},reset:function(){this.el&&(this.searchText="",this.searchfield.reset(),this.match([],!1))},onSearchFieldKeyUp:function(t,e){var i,n,a=t.getValue().trim();if(this.searchText=a,!this.searchText)return void this.match([],!1);i=-1<this.store.findExact("name",a),this.store.filter(e,a,!0),n=this.store.getRange(),this.store.clearFilter(),this.match(n,i)},onSearchFieldKeyDown:function(t,e){var i,n=Ext.EventObject,a=e.getKey();if(n.TAB===a&&e.shiftKey||n.UP===a)i=-1;else{if(n.TAB!==a&&n.DOWN!==a)return;i=1}e.stopEvent();var o=this.items.indexOf(t),s=this.items.length;this.tryActivate((o+i+s)%s,i)},tryActivate:function(t,e){return this.step=e,this.callParent(arguments)},match:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.Search.SearchTreeMenu",{extend:"SYNO.SDS.MailClient.Search.SearchListMenu",menuType:"mailbox",constructor:function(t){var e;t||(t={}),t.ownerBtn&&(this.ownerBtn=t.ownerBtn,delete t.ownerBtn),t.menuType&&(this.menuType=t.menuType),this.disabledIds=[],this.store=new Ext.data.JsonStore({autoDestroy:!0,fields:"mailbox"===this.menuType?["id","path","name","parent_id","additional","subscribed","type","is_own"]:["id","path","name","parent_id","additional","full_name","background_color","text_color"]}),e={selector:this.getDataSelector(t)},this.addEvents("select"),this.callParent([Ext.apply(e,t)])},getDataSelector:function(t){var e;return e=t.isSearchMenu?"mailbox"===this.menuType?SYNO.SDS.MailClient._T("search","all_mailboxes"):SYNO.SDS.MailClient._T("search","all_labels"):"mailbox"===this.menuType?SYNO.SDS.MailClient._T("common","mailbox"):SYNO.SDS.MailClient._T("common","label"),new SYNO.ux.TreePanel({padding:0,border:!1,animate:!1,useGradient:!1,useArrows:!0,autoFlexcroll:!0,htmlEncode:!1,rootVisible:t.rootVisible,cls:"syno-mc-tree-panel",loader:new Ext.tree.TreeLoader,root:new Ext.tree.AsyncTreeNode({id:"tree_root",text:e,cls:"syno-mc-search-root",expanded:!0,children:[],listeners:{scope:this,beforecollapse:function(){return!1}}}),listeners:{scope:this,click:this.clickOK,expandnode:function(t){var e=-1!==this.disabledIds.indexOf(t.id);e&&t.disable(),t.childNodes.forEach(function(t){t.ui.show(),e&&this.disableChild&&(this.disabledIds.push(t.id),t.disable())},this),this.adjustContentHeight(!0)},collapsenode:function(t){this.adjustContentHeight(!0)}}})},adjustContentHeight:function(t){var e=this.contentMaxHeight,i=0,n=this.selector.getFrameHeight()+1;this.isVisible()&&(this.selector.getContentTarget()&&this.selector.getContentTarget().dom.fleXdata?(t||this.selector.getContentTarget().dom.fleXcroll.setScrollPos(!1,0),i=this.selector.getContentTarget().query(".contentwrapper")[0].offsetHeight+8):i=this.selector.getHeight(),e=i>e?e:i),this.selector.setHeight(e>n?e:n),this.doLayout(!0),this.selector.updateScroller()},resetSelect:function(){var t=this.selector.getRootNode().getPath();this.selector.selectPath(t)},selectItem:function(t){var e=this.selector.getNodeById(t);this.selector.selectPath(e?e.getPath():this.selector.getRootNode().getPath())},clickOK:function(t,e){var i;if(t){if(this.showHintForCurrentNode&&this.currentNodeId&&t.id===this.currentNodeId)return SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","move_to_same_mailbox")),void this.hide(!0);i="tree_root"===t.id||"Mailbox"===t.id||"Label"===t.id?0:"mailbox"===this.menuType&&SYNO.SDS.MailClient.Define.starredId==t.id?SYNO.SDS.MailClient.Define.starredId:parseInt(t.id,10),this.fireEvent("select",i,t.attributes.text),this.hide(!0)}},getItemName:function(t){var e=this.selector.getNodeById(t);return e?e.attributes.text:""},addDisabledIds:function(t){this.disabledIds=this.disabledIds.concat(t)},getDisabledIds:function(){return this.disabledIds},clearDisabledIds:function(){this.disabledIds=[]}}),Ext.define("SYNO.SDS.MailClient.Search.SearchLabelMenu",{extend:"SYNO.SDS.MailClient.Search.SearchTreeMenu",constructor:function(t){var e;this.hideCreate=!0===t.hideCreate,e={menuType:"label",contentMaxHeight:this.hideCreate?256:224,items:[{itemId:"sep",xtype:"menuseparator",hidden:this.hideCreate},{itemId:"create",text:SYNO.SDS.MailClient._T("common","create"),cls:"action blue",hidden:this.hideCreate,scope:this,handler:function(){new SYNO.SDS.MailClient.AddLabel({createName:this.searchText,owner:this.findWindow(),listeners:{scope:this,apply:this.onCreate}}).open()}}]},this.callParent([Ext.apply(e,t)])},onSearchFieldKeyUp:function(t,e){this.callParent([t,"name"])},match:function(t,e){var i,n=!this.hideCreate&&!e,a=[];Ext.isEmpty(this.searchText)&&(this.selector.getRootNode().collapseChildNodes(!0),this.currentNodeId&&this._expandNodeById(this.currentNodeId)),t.forEach(function(t){for(this._expandNodeById(t.id),i=this.selector.nodeHash[t.id.toString()];i;)a.push(i.id),i=i.parentNode}.bind(this)),Ext.iterate(this.selector.nodeHash,function(t,e){e!=this.selector.getRootNode()&&(Ext.isEmpty(this.searchText)||a.indexOf(e.id)>-1?e.ui.show():e.ui.hide())},this),this.getComponent("create").setVisible(n).setText(this.searchText?String.format(SYNO.SDS.MailClient._T("common","create_sth"),this.searchText):SYNO.SDS.MailClient._T("common","create")),this.getComponent("sep").setVisible(n),this.adjustContentHeight()},loadList:function(){return this.store.clearData(),SYNO.SDS.MailClient.Control.Model.getLabelJson().then(function(t){var e=SYNO.SDS.MailClient.Control.Model.parseLabelJsonToTreeNode(t,null,!0),i=this.selector.getRootNode();this.store.loadData(t),this.needReload=!1,i.removeAll(!0),i.appendChild(e),this.currentNodeId&&(this.disableChild&&this.addDisabledIds([this.currentNodeId]),this._expandNodeById(this.currentNodeId)),this.disableChild&&this.currentNodeId&&Ext.iterate(this.selector.nodeHash,function(t,e){-1!==this.getDisabledIds().indexOf(e.id)&&e.disable()},this),this.selectItem(this.ownerBtn?this.ownerBtn.getLabelId():0),this.adjustContentHeight()}.bind(this))},onCreate:function(t,e){var i=t.id,n=e.name;SYNO.SDS.MailClient.Control.Sidebar.reloadLabelList().then(function(){this.fireEvent("select",i,Ext.util.Format.htmlEncode(n))}.bind(this))},_expandNodeById:function(t){var e,i=this.selector.getRootNode().id,n=this.store.getById(t);Ext.isEmpty(n)||(e=n.get("path").substring(0,n.get("path").lastIndexOf("/")),this.selector.expandPath(Ext.util.Format.htmlEncode("/"+i+"/"+e),"id"))}}),Ext.define("SYNO.SDS.MailClient.LabelButton",{extend:"SYNO.SDS.MailClient.TreeMenuButton",requires:["SYNO.SDS.MailClient.Search.SearchLabelMenu"],xtype:"syno_mc_label_button",constructor:function(t){var e,i={};t.hasOwnProperty("menuCfg")&&(i=t.menuCfg,delete t.menuCfg),e={text:t.text||SYNO.SDS.MailClient._T("search","all_labels"),currentElementId:t.currentLabelId||0,menu:new SYNO.SDS.MailClient.Search.SearchLabelMenu(Ext.apply({ownerBtn:this},i))},Ext.apply(e,t),this.callParent([e])},getLabelId:function(){return this.getCurrentElementId()},getLabelName:function(){return this.getCurrentElementName()}}),Ext.define("SYNO.SDS.MailClient.AddEditWindow",{extend:"SYNO.SDS.MailClient.ModalWindow",mode:"",targetInfo:{},apiType:null,constructor:function(t){if(t.mode&&(this.mode=t.mode),!Ext.isString(this.apiType))throw"apiType is not a string";var e=Ext.apply({title:"add"==this.mode?_T("common","create"):_T("common","alt_edit"),items:this.getFormPanel(),resizable:!1,width:500,height:200,buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):"",handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})},t);this.callParent([e]),this.on("show",function(){this.setFocus()},this)},setFocus:Ext.emptyFn,getFormPanel:Ext.emptyFn,getParams:Ext.emptyFn,onApplyDone:Ext.emptyFn,onApply:function(){if(this.getFormPanel().getForm().isValid()){var t=this.getParams();t&&(this.setStatusBusy({text:_T("common","loading")}),SYNO.SDS.MailClient.WebAPI.send(this.apiType,t).then(function(e){this.clearStatusBusy(),this.onApplyDone(),this.fireEvent("apply",e,t),this.close()}.bind(this)).catch(function(t){this.clearStatusBusy(),this.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(t)})}.bind(this)))}},onCancel:function(){if("edit"!=this.mode||!this.isDirty())return void this.close();var t=function(t){"yes"===t&&this.close()};this.owner.getMsgBox().confirm(this.title,_T("common","confirm_lostchange"),t,this)},isDirty:Ext.emptyFn,mailboxNameValidator:function(t){if(!(t=t.trim()))return SYNO.SDS.MailClient._T("common","name_field_not_blank");var e=this.getFormPanel().getComponent("mailboxBtn"),i=0;return e&&(i=e.getMailboxId()),-1<t.indexOf(".")||-1<t.indexOf("/")?String.format(SYNO.SDS.MailClient._T("common","name_field_contain_invalid_character"),"'.', '/'"):t.startsWith("~")?SYNO.SDS.MailClient._T("common","name_field_start_with_tilde"):0!==i||!SYNO.SDS.MailClient.Define.isSystemMailboxName(t)||SYNO.SDS.MailClient._T("common","name_field_conflict_system_name")},labelNameValidator:function(t){return t=t.trim(),t?-1===t.indexOf("/")||String.format(SYNO.SDS.MailClient._T("common","name_field_contain_invalid_character"),"'/'"):SYNO.SDS.MailClient._T("common","name_field_not_blank")}}),Ext.define("SYNO.SDS.MailClient.AddMailbox",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="addMailbox";var e=t.targetInfo;this.mailboxId=e.id,this.name=e.name,delete t.targetInfo,this.createName=t.createName,this.callParent([t])},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define;return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_mc_mailbox_button",itemId:"mailboxBtn",fieldLabel:SYNO.SDS.MailClient._T("mailbox","create_in"),text:Ext.util.Format.htmlEncode(this.name),currentMailboxId:this.mailboxId,menuCfg:{width:250,hideCreate:!0,hideManageBtn:!0,hideInbox:!0,rootVisible:!SYNO.SDS.MailClient.Switch.getMailboxStore().isSubscribedSharedMailbox(),showSharedByOthers:!0,hideReadOnlyMailbox:!0,mailboxEnable:!0,currentNodeId:this.mailboxId,hideMailbox:[t.draftsId,t.sentId,t.junkId,t.trashId,t.starredId]}},{xtype:"syno_textfield",fieldLabel:_T("common","name"),itemId:"name",name:"name",validator:this.mailboxNameValidator.createDelegate(this),value:this.createName?this.createName:void 0}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm(),e={},i=t.getFieldValues(),n=i.name.trim(),a=this.getFormPanel().getComponent("mailboxBtn");return n&&(e.name=n),a&&(e.parent_id=a.getMailboxId()),e.name?-1<e.name.indexOf(".")?(t.markInvalid({name:SYNO.SDS.MailClient._T("common","name_field_contain_invalid_character")}),!1):(0!==e.parent_id||!SYNO.SDS.MailClient.Define.isSystemMailboxName(n))&&e:(t.markInvalid({name:SYNO.SDS.MailClient._T("common","name_field_not_blank")}),!1)},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.EditMailbox",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setMailbox";var e=t.targetInfo;if(!e)throw"no target";this.mailboxId=e.id,this.name=e.name,this.parent_id=e.parent_id||0,this.parent_name=this.getParentName(e.path),this.subscribed=e.subscribed,delete t.targetInfo,this.callParent([t])},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define;return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_mc_mailbox_button",itemId:"mailboxBtn",fieldLabel:SYNO.SDS.MailClient._T("filter","move_to"),text:Ext.util.Format.htmlEncode(this.parent_name),currentMailboxId:this.parent_id,menuCfg:{width:250,hideCreate:!0,hideManageBtn:!0,hideInbox:!0,disableChild:!0,rootVisible:!0,currentNodeId:this.mailboxId,hideMailbox:[t.draftsId,t.sentId,t.junkId,t.trashId,t.starredId]}},{xtype:"syno_textfield",fieldLabel:_T("common","name"),itemId:"name",value:this.name,allowBlank:!1,name:"name",disabled:0===this.parent_id&&SYNO.SDS.MailClient.Define.isSystemMailboxName(this.name),validator:this.mailboxNameValidator.createDelegate(this)},{xtype:"syno_checkbox",fieldLabel:SYNO.SDS.MailClient._T("mailbox","subscribed"),hideLabel:!1,hidden:!0,checked:this.subscribed,name:"subscribed"}]}),this.formPanel},getParams:function(){var t,e=this.getFormPanel().getForm(),i={},n=e.getFieldValues(),a=this.getFormPanel().getComponent("mailboxBtn");return i.id=this.mailboxId,n.name&&(t=n.name.trim())&&t!=this.name&&(i.name=t),n.subscribed!=this.subscribed&&(i.subscribed=!!n.subscribed),a&&a.getMailboxId()!==this.parent_id&&(i.parent_id=a.getMailboxId()),Ext.isEmpty(i.name)&&Ext.isEmpty(i.subscribed)&&Ext.isEmpty(i.parent_id)?void this.onCancel():!(!this.mailboxId||0===i.parent_id&&i.name&&SYNO.SDS.MailClient.Define.isSystemMailboxName(i.name))&&i},getParentName:function(t){var e=t.lastIndexOf("."),i=-1;return e<0?SYNO.SDS.MailClient._T("common","mailbox"):(i=t.lastIndexOf(".",e-1),-1==i?t.substr(0,e):t.substr(i+1,e-i-1))},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.EditShareMailbox",{extend:"SYNO.SDS.MailClient.EditMailbox",constructor:function(t){this.callParent([t])},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",fieldLabel:_T("common","name"),itemId:"name",value:this.name,allowBlank:!1,name:"name",disabled:0===this.parent_id&&SYNO.SDS.MailClient.Define.isSystemMailboxName(this.name),validator:this.mailboxNameValidator.createDelegate(this)},{xtype:"syno_checkbox",fieldLabel:SYNO.SDS.MailClient._T("mailbox","subscribed"),hideLabel:!1,hidden:!0,checked:this.subscribed,name:"subscribed"}]}),this.formPanel}}),Ext.define("SYNO.SDS.MailClient.AddLabel",{extend:"SYNO.SDS.MailClient.AddEditWindow",requires:["SYNO.SDS.MailClient.LabelButton"],mode:"add",apiType:"addLabel",constructor:function(t){var e=t.targetInfo||{id:0,name:SYNO.SDS.MailClient._T("common","label")};this.createName=t.createName,this.labelId=e.id,this.name=e.name,delete t.targetInfo,this.callParent([Ext.apply({width:528,height:276},t)])},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form add-label",border:!1,autoHeight:!0,items:[{itemCls:"label-parent",xtype:"syno_mc_label_button",itemId:"parent",width:250,fieldLabel:SYNO.SDS.MailClient._T("label","create_in"),text:Ext.util.Format.htmlEncode(this.name),currentLabelId:this.labelId,menuCfg:{width:250,hideCreate:!0,rootVisible:!0,currentNodeId:this.labelId}},{itemCls:"label-name",xtype:"syno_textfield",fieldLabel:_T("common","name"),name:"name",itemId:"name",width:250,validator:this.labelNameValidator,value:this.createName?this.createName:void 0},{itemCls:"label-color",xtype:"syno_mc_colorpalette",fieldLabel:SYNO.SDS.MailClient._T("label","color"),labelStyle:"width:147px;",itemId:"color",defaultColor:0,width:336}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm(),e=t.getFieldValues().name.trim(),i=this.getFormPanel().getComponent("parent"),n=this.formPanel.getComponent("color").getSelectedNode(),a={};return e&&(a.name=e),i&&(a.parent_id=i.getLabelId()),n&&(a.text_color=n.textColor,a.background_color=n.bgColor),a},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.EditLabel",{extend:"SYNO.SDS.MailClient.AddEditWindow",requires:["SYNO.SDS.MailClient.LabelButton"],mode:"edit",apiType:"setLabel",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e,i=t.targetInfo;if(!i)throw"no target";return this.labelId=i.id,this.parentId=i.parent_id,this.parentLabel=SYNO.SDS.MailClient.Switch.getLabelStore().getById(this.parentId),this.name=i.name,this.textColor=i.text_color,this.bgColor=i.background_color,delete t.targetInfo,e={width:528,height:276},Ext.apply(e,t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-add-edit-form edit-label",autoHeight:!0,border:!1,items:[{itemCls:"label-parent",xtype:"syno_mc_label_button",itemId:"parent",width:250,fieldLabel:SYNO.SDS.MailClient._T("filter","move_to"),text:Ext.isEmpty(this.parentLabel)?SYNO.SDS.MailClient._T("common","label"):Ext.util.Format.htmlEncode(this.parentLabel.get("name")),currentLabelId:this.parentId,menuCfg:{width:250,hideCreate:!0,rootVisible:!0,disableChild:!0,currentNodeId:this.labelId}},{itemCls:"label-name",xtype:"syno_textfield",fieldLabel:_T("common","name"),name:"name",itemId:"name",value:this.name,width:250,validator:this.labelNameValidator},{itemCls:"label-color",xtype:"syno_mc_colorpalette",fieldLabel:SYNO.SDS.MailClient._T("label","color"),labelStyle:"width:147px;",itemId:"color",defaultColor:SYNO.SDS.MailClient.Define.getColorIndex(this.textColor,this.bgColor),width:336}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm(),e=t.getFieldValues().name.trim(),i=this.getFormPanel().getComponent("parent"),n=this.formPanel.getComponent("color").getSelectedNode(),a={};return!!this.labelId&&(this.parentId===i.getLabelId()&&this.name===e&&this.textColor===n.textColor&&this.bgColor===n.bgColor?void this.onCancel():(a.id=this.labelId,i.getLabelId()!==this.parentId&&(a.parent_id=i.getLabelId()),e!==this.name&&(a.name=e),n&&n.bgColor!==this.bgColor&&(a.text_color=n.textColor,a.background_color=n.bgColor),a))},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},setFocus:function(){this.formPanel.getComponent("name").focus(!1,300)}}),Ext.define("SYNO.SDS.MailClient.OpContextMenu",{extend:"SYNO.ux.Menu",requires:["SYNO.SDS.MailClient.Condition"],opScope:null,constructor:function(t){var e=0,i=[{itemId:"name",xtype:"menuitem",ctCls:"syno-mc-menu-name-text",disableClearLastDom:!0,htmlEncode:!1,text:""},{xtype:"menuseparator",itemId:"sep"}],n={add:{itemId:"add-node",text:SYNO.SDS.MailClient._T("common","add")},edit:{itemId:"edit-node",text:t.editText?t.editText:SYNO.SDS.MailClient._T("common","alt_edit")},delete:{itemId:"delete-node",text:SYNO.SDS.MailClient._T("common","delete")},sharing:{itemId:"sharing-node",text:SYNO.SDS.MailClient._T("mailbox","sharing_and_permission")},clearJunk:{itemId:"clearJunk-node",text:SYNO.SDS.MailClient._T("common","clear_message")},clearTrash:{itemId:"clearTrash-node",text:SYNO.SDS.MailClient._T("common","clear_message")}};Ext.apply(n,t.ops);var a=t.op?Ext.isArray(t.op)?t.op:[t.op]:["add","edit","delete","sharing","clearJunk","clearTrash"];for(t.cls=t.cls?t.cls+" syno-mc-menu syno-mc-op-menu":"syno-mc-menu syno-mc-op-menu",this.deleteConfirmMsg=t.deleteConfirmMsg||SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),this.opScope=t.opScope||this,e=0;e<a.length;++e)n.hasOwnProperty(a[e])&&i.push(n[a[e]]);var o={items:i};this.callParent([Ext.apply(o,t)]),this.on("itemclick",this.onItemClick),this.on("show",this.showContactNodeText)},onItemClick:function(t){var e=t.parentMenu.contextNode,i=e.attributes.name||"";switch(t.itemId){case"add-node":this.addOp.apply(this.opScope,[t,e.attributes.data]);break;case"edit-node":this.editOp.apply(this.opScope,[t,e.attributes.data]);break;case"delete-node":SYNO.SDS.MailClient.Window.getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),String.format(this.deleteConfirmMsg,i),function(i){"yes"===i&&this.deleteOp.apply(this.opScope,[t,e.attributes.data])},this);break;case"sharing-node":this.sharingOp.apply(this.opScope,[t,e.attributes.data]);break;case"clearJunk-node":this.clearMailbox(SYNO.SDS.MailClient.Define.junkId);break;case"clearTrash-node":this.clearMailbox(SYNO.SDS.MailClient.Define.trashId);break;default:t.opfunction&&t.opfunction.apply(this.opScope,[t,e.attributes.data])}},clearMailbox:function(t){SYNO.SDS.MailClient.Window.getMsgBox().confirm("",SYNO.SDS.MailClient._T("common","confirm_remove_message"),function(e){"yes"==e&&SYNO.SDS.MailClient.WebAPI.addTask({condition:new SYNO.SDS.MailClient.Condition("mailbox",t).toWebAPIParams(),action:[SYNO.SDS.MailClient.Format.makeAction("delete","")]}).then(function(t){if(!t.task_key)return void this.findWindow().getMsgBox().alert("","mailbox clear message failed");SYNO.SDS.MailClient.Window.updateTaskIndicator(!0)}.bind(this)).catch(function(t){this.findWindow().getMsgBox().alert("","mailbox clear message failed")}.bind(this))},this)},showContactNodeText:function(t,e){this.getComponent("name").setText("["+this.contextNode.text+"]")},addOp:Ext.emptyFn,editOp:Ext.emptyFn,deleteOp:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.RootNode",{extend:"Ext.tree.AsyncTreeNode",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={cls:"syno-mc-root-node",expanded:!0,uiProvider:SYNO.SDS.MailClient.RootNodeUI,children:[]};return Ext.apply(e,t)}}),
Ext.define("SYNO.SDS.MailClient.TreePanelSelectionModel",{extend:"Ext.tree.DefaultSelectionModel",constructor:function(t){var e={listeners:{scope:this,beforeselect:function(t,e,i){if(e.id===this.tree.getRootNode().id)return!1}}};this.callParent([Ext.apply(e,t)])},onKeyDown:function(t){var e=this.selNode||this.lastSelNode;if(e){var i;switch(t.getKey()){case t.SPACE:case t.ENTER:i=this.getSelectedNode(),SYNO.SDS.MailClient.Define.isUserOrGroupNodeInMailboxList(i)?i.toggle():i&&this.tree.onDisplayNode(i);break;case t.DOWN:t.stopEvent(),this.selectNext()||this.tree.fireEvent("navigate","down");break;case t.UP:t.stopEvent(),this.selectPrevious()||this.tree.fireEvent("navigate","up");break;case t.RIGHT:if(t.preventDefault(),e.hasChildNodes()){if(!e.isExpanded()){e.expand();break}if(e.firstChild){this.select(e.firstChild,t);break}}this.tree.fireEvent("navigate","right");break;case t.LEFT:t.preventDefault(),e.hasChildNodes()&&e.isExpanded()?e.collapse():e.parentNode&&(this.tree.rootVisible||e.parentNode!=this.tree.getRootNode())?this.select(e.parentNode,t):this.tree.fireEvent("navigate","left")}}},selectPrevious:function(t){return t=this.callParent(arguments),t&&!t.isRoot?t:null},selectFirst:function(){return this.tree.root.childNodes[0]?this.select(this.tree.root.childNodes[0]):null},selectLast:function(){for(var t=this.tree.root;t.childNodes[t.childNodes.length-1]&&t.isExpanded();)t=t.childNodes[t.childNodes.length-1];return this.tree.root===t?null:this.select(t)}}),Ext.define("SYNO.SDS.MailClient.TreePanel",{extend:"SYNO.ux.TreePanel",requires:["SYNO.SDS.MailClient.TreePanelSelectionModel"],displayedNodeId:null,constructor:function(t){var e,i={},n={contextmenu:function(t,e){if(t.getOwnerTree().getRootNode().id==t.id)return!1;var i=t.getOwnerTree().contextMenu;i.contextNode=t,i.showAt(e.getXY())},beforeclick:function(t,e){if(t.getOwnerTree().getRootNode().id==t.id)return t.isExpanded()?t.collapse():t.expand(),!1},click:function(t,e){t.getOwnerTree().onDisplayNode(t)}};(t.enableDD||t.enableDrag)&&(e={ddGroup:t.ddGroup,scroll:!!t.ddScroll,dragSource:t.dragSource,getDragData:function(t){var e=Ext.dd.Registry.getHandleFromEvent(t);if(e)return e.node.getUI().anchor.focus(),e.node.getOwnerTree().getSelectionModel().getSelectedNode()||e.node.select(),Ext.apply(e,{source:this.dragSource,target:t.getTarget(".x-tree-node-el"),data:Ext.apply({},e.node.attributes.data)}),e},getRepairXY:function(t){return Ext.Element.fly(this.dragData.target).getXY()},onInitDrag:function(t){var e=this.dragData;this.tree.eventModel.disable(),this.proxy.update(""),e.node.ui.appendDDGhost(this.proxy.ghost.dom),this.tree.fireEvent("startdrag",this.tree,e.node,t)},beforeInvalidDrop:Ext.emptyFn});var a;(t.enableDD||t.enableDrop)&&(a={ddGroup:t.ddGroup,appendOnly:!!t.ddAppendOnly,dropSource:t.dropSource,getDropPoint:function(){return"append"}},Ext.apply(n,{nodedragover:function(t){return t.tree.isAllowDrop(t.target,t.data)},beforenodedrop:function(t){return!!t.tree.isAllowDrop(t.target,t.data)&&(t.source.proxy.hide(),t.tree.drop.defer(50,t.tree,[t.target,t.data]),!0)}})),t.listeners?(i=Ext.apply(n,t.listeners),delete t.listeners):i=n;var o={autoFlexcroll:!1,border:!1,expanded:!0,useGradient:!1,useArrows:!0,animate:!1,selModel:new SYNO.SDS.MailClient.TreePanelSelectionModel,listeners:i,dragConfig:e,dropConfig:a};this.callParent([Ext.apply(o,t)]),this.addClass("syno-mc-tree-panel reduce-indent"),this.addEvents("add","colorchange","displaynode")},updateNodes:function(t){var e,i,n=this.getRootNode(),a=this.getSelectionModel().getSelectedNode(),o=this.displayedNodeId,s=document.activeElement,l=Ext.fly(s);l&&l.parent(".x-tree")===this.el&&(l.hasClass("x-panel-body")?e=!0:l.hasClass("x-tree-node-anchor")&&(i=l.parent(".x-tree-node-el").getAttribute("ext:tree-node-id"))),n.removeAll(!0),n.appendChild(t);var r;a&&(r=this.getNodeById(a.id))&&r.select(),o&&(r=this.getNodeById(o))&&r.getUI().addClass("displayed"),e?this.body.focus():i&&(r=this.getNodeById(i),r?r.getUI().anchor.focus():this.body.focus())},onDisplayNode:function(t,e,i){this.clearDisplay(),t.getUI().addClass("displayed"),this.displayedNodeId=t.id,this.fireEvent("displaynode",t,e,i)},clearDisplay:function(){if(this.displayedNodeId){var t=this.getNodeById(this.displayedNodeId);t&&t.getUI().removeClass("displayed"),this.displayedNodeId=null}},selectNodeById:function(t,e,i){var n=this.getNodeById(t);return!n&&i&&(n=this.getNodeById(i),e={}),!!n&&(n.select(),Ext.isChrome?setTimeout(function(){n.getUI()&&n.getUI().anchor.focus()},0):n.getUI().anchor.focus(),this.onDisplayNode(n,e),!0)},clearSelections:function(t){this.getSelectionModel().clearSelections(!0),t||this.clearDisplay()},isAllowDrop:function(t,e){return!1},drop:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.Sidebar.LabelList",{extend:"SYNO.ux.Panel",xtype:"mc_LabelList",requires:["SYNO.SDS.MailClient.AddMailbox","SYNO.SDS.MailClient.EditMailbox","SYNO.SDS.MailClient.OpContextMenu","SYNO.SDS.MailClient.RootNode","SYNO.SDS.MailClient.TreePanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("contentchange","nodeclick")},fillConfig:function(t){var e={style:{marginBottom:"28px"},border:!1,items:this.createTreePanel()};return Ext.apply(e,t)},updateLabelList:function(t){this.parsedData=SYNO.SDS.MailClient.Control.Model.parseLabelJsonToTreeNode(t,!0),this.treePanel.updateNodes(this.parsedData),this.fireEvent("contentchange")},selectTreePanelNodeById:function(t){this.treePanel.selectNodeById(t,null),this.fireEvent("contentchange")},getIdByFullName:function(t,e){var i;return e=e||SYNO.SDS.MailClient.Control.Model.getLabelJsonFromCache(),i=e.findIndex(function(e){return e.full_name===t}),-1!==i?e[i].id:void 0},getLastLabelId:function(){return this.lastLabelId},setLastLabelId:function(t){this.lastLabelId=t},createTreePanel:function(){return this.treePanel=this.treePanel||new SYNO.SDS.MailClient.TreePanel({bodyStyle:"padding: 0 12px",loader:new Ext.tree.TreeLoader,root:new SYNO.SDS.MailClient.RootNode({id:"label_root",text:SYNO.SDS.MailClient._T("common","label"),qtip:SYNO.SDS.MailClient._T("common","label"),showAddBtn:!0,listeners:{scope:this,add:this.clickAdd}}),contextMenu:new SYNO.SDS.MailClient.OpContextMenu({op:["add","edit","delete"],addOp:this.clickAdd,editOp:this.clickEdit,deleteOp:this.clickDelete,deleteConfirmMsg:SYNO.SDS.MailClient._T("label","delete_confirm"),opScope:this}),listeners:{collapsenode:function(t){SYNO.SDS.MailClient.UserSettingProperty.addLabelCollapseNode(t.id)},expandnode:function(t){SYNO.SDS.MailClient.UserSettingProperty.removeLabelCollapseNode(t.id)},displaynode:function(t,e){var i=t.id,n=SYNO.SDS.MailClient.Control;n.Mail.clearSearchHighlight(),null!==e&&(this.getLastLabelId()!==i||n.Mail.isInMessageView()?n.Sidebar.openLabel(i,1):n.Sidebar.forceReloadLabel(i,1)),this.fireEvent("nodeclick")},colorchange:this.editLabel,enddrag:function(t,e,i){e&&e.ui&&e.ui.removeClass("x-tree-node-over")},scope:this},enableDD:!0,ddGroup:"threadDDGroup",dragSource:"label",dropSource:["thread"],drop:function(t,e){var i,n=t.attributes.data,a={id:n.id,name:n.name,full_name:n.full_name,path:n.path,background_color:n.background_color,text_color:n.text_color},o=[];if("thread"===e.source){if(Ext.isArray(e.data))for(i=0;i<e.data.length;i++)o.push(e.data[i].data);else o.push(e.data);e.threadAction.threadChangeLabel(o,[a],[],e.isSelectAll)}},isAllowDrop:function(t,e){var i=!1;return this.getRootNode()!==t&&(-1!==this.dropSource.indexOf(e.source)&&(Ext.each(e.data,function(e){if(i=!1,Ext.each(e.data.label,function(e){if(t.id===e.id)return i=!0,!1}),!1===i)return!1}),!0!==i))},onNavigateOut:function(){this.clearSelections(!0)},onNavigateIn:function(t){var e;if("left"===t?e=this.getNodeById(this.displayedNodeId):"down"===t&&(e=this.getSelectionModel().selectFirst()),e)return this.selectPath(e.getPath()),this.body.focus(),!0}}),this.treePanel},onLabelChange:function(t,e,i,n,a){var o;if("delete"!=t)return void SYNO.SDS.MailClient.Control.Sidebar.updateLabelList();o=this.treePanel.getNodeById(e),o&&o.remove(!0),e===this.treePanel.displayedNodeId&&SYNO.SDS.MailClient.Control.Main.toMailAppLandingPage(),this.fireEvent("contentchange")},applyDone:function(t,e,i,n,a,o){var s=SYNO.SDS.MailClient.Control;s.Sidebar.reloadLabelList().then(function(){s.Thread.modifyGlobalLabel(t,e,i,n,a,!Ext.isEmpty(o)),Ext.isEmpty(i)&&Ext.isEmpty(o)||s.Model.getChildLabelIds(e).forEach(function(e){s.Thread.modifyGlobalLabel(t,e,null,null,null,!0)}.bind(this))}.bind(this))},clearSelections:function(){this.treePanel.clearSelections()},clickAdd:function(t,e){new SYNO.SDS.MailClient.AddLabel({targetInfo:e,listeners:{scope:this,apply:function(t,e){var i=t.id,n=e.name,a=e.text_color,o=e.background_color,s=e.parent_id;this.applyDone("add",i,n,a,o,s)}}}).show()},clickEdit:function(t,e){new SYNO.SDS.MailClient.EditLabel({targetInfo:e,listeners:{scope:this,apply:function(t,e){var i=e.id,n=e.name,a=e.text_color,o=e.background_color,s=e.parent_id;this.applyDone("edit",i,n,a,o,s)}}}).show()},clickDelete:function(t,e){var i=SYNO.SDS.MailClient.Control.Model.getChildLabelIds(e.id).concat([e.id]),n={id:[e.id]};SYNO.SDS.MailClient.WebAPI.deleteLabel(n).then(function(t){return SYNO.SDS.MailClient.Control.Sidebar.reloadLabelList().then(function(){i.forEach(function(t){SYNO.SDS.MailClient.Control.Thread.modifyGlobalLabel("delete",t),this.treePanel.displayedNodeId===t&&SYNO.SDS.MailClient.Control.Main.toMailAppLandingPage()}.bind(this))}.bind(this))}.bind(this)).catch(function(t){SYNO.SDS.MailClient.Window.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t))}.bind(this))},editLabel:function(t,e,i,n){var a={id:t};return Ext.isEmpty(e)||(a.name=e),Ext.isEmpty(i)||(a.text_color=i),Ext.isEmpty(n)||(a.background_color=n),SYNO.SDS.MailClient.WebAPI.setLabel(a).then(function(t){this.applyDone("edit",a.id,a.name,a.text_color,a.background_color)}.bind(this)).catch(function(t){}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.MailboxNodeUI",{extend:"Ext.tree.TreeNodeUI",renderElements:function(t,e,i,n){var a,o,s,l,r="";this.indentMarkup=t.parentNode?t.parentNode.ui.getChildIndent():"",e.count&&(r=e.count>9999?"9999+":e.count.toString()),l=['<li class="x-tree-node">','<div ext:tree-node-id="',t.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',e.cls,e.count?"unread":"",'" unselectable="on">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img alt="" src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow" />','<img alt="" src="',e.icon||this.emptyIcon,'" class="x-tree-node-icon',e.icon?" x-tree-node-inline-icon":"",e.iconCls?" "+e.iconCls:"",'" unselectable="on" />','<a hidefocus="on" class="x-tree-node-anchor '+(e.has_permission?"shared":"")+'" tabIndex="1">','<span unselectable="on">'+t.text+"</span>",e.has_permission?'<div class="shared-icon"> </div>':"","</a>",'<div class="count">',r,"</div>","</div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join(""),!0!==n&&t.nextSibling&&(a=t.nextSibling.ui.getEl())?this.wrap=Ext.DomHelper.insertHtml("beforeBegin",a,l):this.wrap=Ext.DomHelper.insertHtml("beforeEnd",i,l),this.elNode=this.wrap.childNodes[0],this.ctNode=this.wrap.childNodes[1],s=0,o=this.elNode.childNodes,this.indentNode=o[s++],this.ecNode=o[s++],this.iconNode=o[s++],this.anchor=o[s++],this.shareIconNode=e.has_permission?this.anchor.childNodes[1]:null,this.textNode=this.anchor.firstChild,this.countNode=o[s]},getDDHandles:function(){var t=[this.iconNode,this.textNode,this.countNode,this.anchor,this.elNode];return this.shareIconNode&&t.splice(4,0,this.shareIconNode),t}}),Ext.define("SYNO.SDS.MailClient.EnableColumn",{extend:"SYNO.ux.EnableColumn",constructor:function(t){var e={renderer:t.disabled?SYNO.ux.EnableColumn.prototype.disableRenderer:SYNO.ux.EnableColumn.prototype.renderer};this.callParent([Ext.apply(e,t)])},onHeaderChange:function(){this.callParent(),this.disabled&&this.disableHeader()},onCellClick:function(t,e,i){this.disabled||this.callParent([t,e,i])},disableHeader:function(){this.box_el&&this.box_el.parent()&&(this.box_el.addClass("syno-ux-cb-disabled"),this.box_el.parent().addClass("syno-mc-disabled-header"))},enableHeader:function(){this.box_el&&this.box_el.parent()&&(this.box_el.removeClass("syno-ux-cb-disabled"),this.box_el.parent().removeClass("syno-mc-disabled-header"))}}),Ext.define("SYNO.SDS.MailClient.SelectServersUserWindow",{extend:"SYNO.SDS.MailClient.Editor.SelectContactWindow",constructor:function(t){t.windowType="server",t.hideSortBtn=!0,t.idProperty="name",t.keys=[{key:Ext.EventObject.ESC,scope:this,fn:this.onCancel}],this.targetInfo=t.targetInfo,this.callParent([t])},getContactStore:function(){return this.store?this.store:(this.store=new SYNO.API.Store({method:"POST",proxy:new SYNO.API.Proxy({api:"SYNO.MailPlusServer.Normal.Util",method:"list_user",version:1,listeners:{scope:this,beforeload:function(t,e){var i=t.activeRequest.read;i&&Ext.Ajax.abort(i)}}}),baseParams:{api:"SYNO.MailPlusServer.Normal.Util",method:"list_user",version:1,offset:0,limit:100},reader:new Ext.data.JsonReader({root:"user_list",idProperty:"name",totalProperty:"total",fields:["name","status","description"]}),listeners:{scope:this,beforeload:function(t,e){var i=e.params;this.groupId&&SYNO.SDS.MailClient.Define.allContactGroupId!==this.groupId&&(i.group=this.groupId),this.textfilter&&(i.query=this.textfilter.getValue())},load:function(t,e,i){if(this.clearStatusBusy(),!t||0!==t.getCount()){var n=this.contactView.getNode(e[0]);n&&this.contactView.fleXcrollTo(n),SYNO.SDS.MailClient.Format.removeUserFromStore(t,_S("user")),SYNO.SDS.MailClient.Format.removeUserFromStore(t,this.targetInfo.owner)}},loadexception:function(t,e,i){this.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(i),this.close,this)}}}),this.store)},getGroupStore:function(){return this.groupStore?this.groupStore:(this.groupStore=new SYNO.API.Store({method:"POST",proxy:new SYNO.API.Proxy({api:"SYNO.MailPlusServer.Normal.Util",method:"list_group",version:1,listeners:{scope:this,beforeload:function(t,e){var i=t.activeRequest.read;i&&Ext.Ajax.abort(i)}}}),baseParams:{api:"SYNO.MailPlusServer.Normal.Util",method:"list_group",version:1,offset:0,limit:-1},reader:new Ext.data.JsonReader({root:"group_list",idProperty:"name",totalProperty:"total",fields:["name","status","description"]}),doFilter:function(){this.load()},listeners:{scope:this,beforeload:function(t,e){this.textfilter&&(e.params.query=this.textfilter.getValue())},load:function(t,e,i){this.clearStatusBusy(),t&&t.getCount()},loadexception:function(t,e,i){this.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(i),this.close,this)}}}),this.groupStore)},onApply:function(){this.fireEvent("selectdone",this.contactData,this.groupData),this.close()},onCancel:function(){this.close()}}),Ext.define("SYNO.SDS.MailClient.SelectServersContactListView",{extend:"SYNO.SDS.MailClient.Editor.SelectContactListView",createTpl:function(){return new Ext.XTemplate('<tpl for=".">','<div class="item-wrap select-contact-layout">','<div class="item-icon">','<div class="check-area">','<div class="align"></div>','<div class="syno-ux-checkbox-icon"></div>',"</div>","</div>",'<div class="summary">','<div class="from" ext:qtip="{values.name:htmlEncode}">{values.name:htmlEncode}</div>',"</div>","</div>","</tpl>",'<div class="x-clear"></div>')}}),Ext.define("SYNO.SDS.MailClient.SelectServersGroupListView",{extend:"SYNO.SDS.MailClient.Editor.SelectContactListView",createTpl:function(){return new Ext.XTemplate('<tpl for=".">','<div class="item-wrap select-contact-layout">','<div class="item-icon">','<div class="check-area">','<div class="align"></div>','<div class="syno-ux-checkbox-icon"></div>',"</div>","</div>",'<div class="summary">','<div class="from" ext:qtip="{[Ext.util.Format.htmlEncode(values.name)]}">{[Ext.util.Format.htmlEncode(values.name)]}</div>',"</div>","</div>","</tpl>",'<div class="x-clear"></div>')}}),Ext.define("SYNO.SDS.MailClient.SharingMailbox",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.ModalWindow","SYNO.SDS.MailClient.SharingMailboxGridPanel"],gridRowRemove:!1,constructor:function(t){this.mailboxId=t.targetInfo.id,this.callParent([this.fillConfig(t)]),this.on("show",function(){this.gridPanel.getStore().loadData(t.targetInfo.additional.permission)})},fillConfig:function(t){this.gridPanel=new SYNO.SDS.MailClient.SharingMailboxGridPanel({targetInfo:t.targetInfo,listeners:{scope:this,grid_row_removed:function(){this.gridRowRemove=!0}}});var e=t.targetInfo.name,i=SYNO.SDS.MailClient.Define;i.isSystemMailboxName(e)&&(e=i.getSystemMailboxNameString(e));var n={width:700,height:400,title:e+" - "+SYNO.SDS.MailClient._T("mailbox","sharing_and_permission"),resizable:!1,collapsible:!1,closable:!0,closeAction:"onCancel",layout:"fit",buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),items:[this.gridPanel]};return Ext.apply(n,t)},isEnterFromTextFilter:function(t){var e=t.getTarget("","",!0).dom,i=this.gridPanel.getTopToolbar().getComponent("textFilter").getEl().dom;return e.isSameNode(i)},onApply:function(){if(!this.isEnterFromTextFilter(arguments[1])){if(!this.isGridPanelDirty())return void this.close();if(!this.isPermissionsValid())return void this.setStatusError({text:SYNO.SDS.MailClient._T("sharing","permission_error")});this.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("setMailbox",this.getParams()).then(function(){this.clearStatusBusy(),this.fireEvent("apply"),this.close()}.bind(this)).catch(function(t){this.clearStatusBusy(),this.setStatusError({text:t.text?t.text:SYNO.SDS.MailClient.Error.getErrorString(t)}),SYNO.Debug.error(t)}.bind(this))}},onCancel:function(){this.isGridPanelDirty()?this.getMsgBox().confirm("",_T("common","confirm_lostchange"),function(t){"yes"===t&&this.close()},this):this.close()},getParams:function(){var t=[];return this.gridPanel.getStore().each(function(e){var i=this.getApiPermission(e);""!==i&&t.push({name:e.get("name"),is_user:e.get("is_user"),permission:i})},this),{id:this.mailboxId,permission:t}},getApiPermission:function(t){var e=SYNO.SDS.MailClient.Define.MailboxPermission,i="";return t.get("read")?i=e.READ_ONLY:t.get("write")?i=e.READ_WRITE:t.get("admin")&&(i=e.ADMIN),i},isGridPanelDirty:function(){return this.gridRowRemove||!Ext.isEmpty(this.gridPanel.getStore().modified)},isPermissionsValid:function(){var t=!0;return this.gridPanel.getStore().each(function(e){if(""===this.getApiPermission(e))return t=!1,!1},this),t}}),Ext.define("SYNO.SDS.MailClient.SharingMailboxGridPanel",{extend:"SYNO.ux.EditorGridPanel",requires:["SYNO.SDS.MailClient.EnableColumn","SYNO.SDS.MailClient.SelectServersUserWindow"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("cellclick",this.onCellClick,this),this.on("headerclick",function(t,e,i){var n=t.getColumnModel(),a=n.getColumnId(e);this.onHeaderClick(n.getColumnById(a))},this)},fillConfig:function(t){var e,i,n,a,o=SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable;return e=new SYNO.SDS.MailClient.EnableColumn({header:_T("nfs","nfs_read_only"),dataIndex:"read",itemId:"read",width:50,menuDisabled:!0,align:"center",disabled:o}),i=new SYNO.SDS.MailClient.EnableColumn({header:_T("nfs","nfs_read_write"),dataIndex:"write",itemId:"write",width:50,menuDisabled:!0,align:"center",disabled:o}),n=new SYNO.SDS.MailClient.EnableColumn({header:SYNO.SDS.MailClient._T("mailbox","admin"),dataIndex:"admin",itemId:"admin",width:50,menuDisabled:!0,align:"center",disabled:o}),a={cls:"syno-mc-sharing-mailbox-grid",autoExpandColumn:"name",enableColumnMove:!1,enableHdMenu:!1,clicksToEdit:1,store:this.getStore(),tbar:this.createTbar(),bbar:{hidden:!o,height:"auto",items:[{xtype:"syno_displayfield",cls:"syno-mc-note",html:"<span>"+SYNO.SDS.MailClient._T("common","note")+":</span> "+SYNO.SDS.MailClient._T("mailbox","sharing_disabled_desc")}]},view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1,listeners:{scope:this,rowremoved:function(t,e,i){i.get("name")!=_S("user")&&this.fireEvent("grid_row_removed")}}}),colModel:new Ext.grid.ColumnModel({scope:this,columns:[{header:SYNO.SDS.MailClient._T("mailbox","user_or_group"),dataIndex:"name",align:"left",menuDisabled:!0,width:70,renderer:function(t,e,i,n,a,o){return i.get("is_user")?e.css+=" syno-mc-icon-combo-item-user":e.css+=" syno-mc-combo-item-group",e.attr+='ext:qtip="'+t+'"',t}},e,i,n]}),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection())}}}),plugins:[e,i,n]},Ext.apply(a,t),a},createTbar:function(){return new SYNO.ux.Toolbar({defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),hidden:SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable,handler:this.onAddPermission},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:this.onDeletePermission},"->",this.getTextFilter(this.getStore())]})},getStore:function(){var t=SYNO.SDS.MailClient.Define.MailboxPermission,e=function(e,i){return i.permission===t.READ_ONLY},i=function(e,i){return i.permission===t.READ_WRITE},n=function(e,i){return i.permission===t.ADMIN};return this.store=this.store||new Ext.data.JsonStore({fields:[{name:"name"},{name:"is_user"},{name:"read",convert:e},{name:"write",convert:i},{name:"admin",convert:n}],listeners:{load:function(t,e,i){SYNO.SDS.MailClient.Format.removeUserFromStore(t,_S("user"))}}}),this.store},getTextFilter:function(t){return this.textFilter=this.textFilter||new SYNO.ux.TextFilter({itemId:"textFilter",store:t,localFilter:!0,localFilterField:["name"]}),this.textFilter},onAddPermission:function(){new SYNO.SDS.MailClient.SelectServersUserWindow({owner:this.findWindow(),targetInfo:this.targetInfo,listeners:{scope:this,selectdone:function(t,e){t.each(function(t){var e=this.store.findExact("name",t.name);-1!==e&&this.store.getAt(e).get("is_user")&&this.store.removeAt(e),this.store.add(new Ext.data.Record({name:t.name,is_user:!0,read:!0}))},this),e.each(function(t){var e=this.store.findExact("name",t.name);-1===e||this.store.getAt(e).get("is_user")||this.store.removeAt(e),this.store.add(new Ext.data.Record({name:t.name,is_user:!1,read:!0}))},this)}}}).open()},onDeletePermission:function(){var t=this.getSelectionModel().getSelections();Ext.each(t,function(t){this.getStore().remove(t)},this)},onHeaderClick:function(t){var e=this.getColumnModel().getColumnAt(1),i=this.getColumnModel().getColumnAt(2),n=this.getColumnModel().getColumnAt(3);t.box_el&&t.box_el.hasClass("syno-ux-cb-checked")&&("read"!==t.dataIndex&&(e.box_el.removeClass("syno-ux-cb-checked"),e.onSelectAll()),"write"!==t.dataIndex&&(i.box_el.removeClass("syno-ux-cb-checked"),i.onSelectAll()),"admin"!==t.dataIndex&&(n.box_el.removeClass("syno-ux-cb-checked"),n.onSelectAll()),t.box_el.addClass("syno-ux-cb-checked"))},onCellClick:function(t,e,i,n){var a=t.getStore().getAt(e),o=t.getColumnModel().getDataIndex(i),s=this.getColumnModel().getColumnAt(1),l=this.getColumnModel().getColumnAt(2),r=this.getColumnModel().getColumnAt(3);!0===a.get(o)&&function(e,i){"read"!==e&&(i.set("read",!1),s.checkSelectAll(t.getStore())),"write"!==e&&(i.set("write",!1),l.checkSelectAll(t.getStore())),"admin"!==e&&(i.set("admin",!1),r.checkSelectAll(t.getStore()))}(o,a)}}),Ext.define("SYNO.SDS.MailClient.Sidebar.BaseMailboxList",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.AddMailbox","SYNO.SDS.MailClient.EditMailbox","SYNO.SDS.MailClient.MailboxNodeUI","SYNO.SDS.MailClient.RootNode","SYNO.SDS.MailClient.SharingMailbox","SYNO.SDS.MailClient.TreePanel"],defaultMailboxId:null,lastMailboxId:null,constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("contentchange","nodeclick","lastNodeDeleted"),this.defaultMailboxId=SYNO.SDS.MailClient.Define.inboxId},fillConfig:function(t){var e={style:{marginBottom:"8px"},border:!1,items:this.createTreePanel()};return Ext.apply(e,t)},updateMailboxList:function(t){this.parsedData=SYNO.SDS.MailClient.Format.parseMailboxResp(t,SYNO.SDS.MailClient.MailboxNodeUI,!0,!0),this.treePanel.updateNodes(this.parsedData),this.checkIfLastMailboxIdExist(),this.fireEvent("contentchange")},selectTreePanelNodeById:function(t){this.treePanel.selectNodeById(t,null),this.fireEvent("contentchange")},selectTreePanelNodeByName:function(t,e){var i;i=this.getIdByName(t,e),this.selectTreePanelNodeById(i)},setLastMailboxId:function(t){this.lastMailboxId=t},getLastMailboxId:function(){return this.lastMailboxId},getIdByName:function(t,e){e=e||SYNO.SDS.MailClient.Control.Model.getMailboxJsonFromCache();var i,n,a=SYNO.SDS.MailClient.Define.isSystemMailboxName(t);for(i=0;i<e.length;++i){if(SYNO.SDS.MailClient.Define.starredId===t){n=SYNO.SDS.MailClient.Define.starredId;break}if(SYNO.SDS.MailClient.Define.priorityId===t){n=SYNO.SDS.MailClient.Define.priorityId;break}if(a&&e[i].path.toLowerCase()===t.toLowerCase()){n=e[i].id;break}if(e[i].path===t){n=e[i].id;break}}return n},checkIfLastMailboxIdExist:function(){var t=this.getLastMailboxId();t&&-1===SYNO.SDS.MailClient.Control.Model.isMailboxIdExist(t)&&this.fireEvent("lastNodeDeleted")},applyDone:function(t,e,i,n,a){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},clearSelections:function(){this.setLastMailboxId(null),this.treePanel.clearSelections()},clickAdd:function(t,e){new SYNO.SDS.MailClient.AddMailbox({targetInfo:e,listeners:{scope:this,apply:this.applyDone}}).show()},clickEdit:function(t,e){new SYNO.SDS.MailClient.EditMailbox({targetInfo:e,listeners:{scope:this,apply:this.applyDone}}).show()},clickDelete:function(t,e){SYNO.SDS.MailClient.Control.Sidebar.deleteMailbox(e.id)},clickSharing:function(t,e){new SYNO.SDS.MailClient.SharingMailbox({targetInfo:e,listeners:{scope:this,apply:this.applyDone}}).show()}}),Ext.define("SYNO.SDS.MailClient.Sidebar.MailboxList",{extend:"SYNO.SDS.MailClient.Sidebar.BaseMailboxList",xtype:"mc_MailboxList",createTreePanel:function(){return this.treePanel=this.treePanel||new SYNO.SDS.MailClient.TreePanel({bodyStyle:"padding: 0 12px",loader:new Ext.tree.TreeLoader,root:new SYNO.SDS.MailClient.RootNode({id:"mail_root",text:SYNO.SDS.MailClient._T("common","mailbox"),qtip:SYNO.SDS.MailClient._T("common","mailbox"),showAddBtn:!0,listeners:{scope:this,add:function(){this.clickAdd(null,{id:0,name:SYNO.SDS.MailClient._T("common","mailbox")})}}}),contextMenu:new SYNO.SDS.MailClient.OpContextMenu({addOp:this.clickAdd,editOp:this.clickEdit,deleteOp:this.clickDelete,sharingOp:this.clickSharing,deleteConfirmMsg:SYNO.SDS.MailClient._T("mailbox","delete_confirm"),opScope:this}),listeners:{collapsenode:function(t){SYNO.SDS.MailClient.UserSettingProperty.addMailboxCollapseNode(t.id),this.fireEvent("contentchange")},expandnode:function(t){SYNO.SDS.MailClient.UserSettingProperty.removeMailboxCollapseNode(t.id),this.fireEvent("contentchange")},displaynode:function(t,e){var i=t.id,n=SYNO.SDS.MailClient.Control,a=SYNO.SDS.MailClient.Define,o=n.Mail.isInMessageView();null!==e&&(i!==a.priorityId||o||n.Vault.markUnreadSectionHavingReadThreadDirty(),n.Mail.clearSearchHighlight(),this.getLastMailboxId()!==i||o?n.Sidebar.openMailbox(i,1):n.Sidebar.forceReloadMailbox(i,1)),this.fireEvent("nodeclick")},contextmenu:function(t,e){var i=t.getOwnerTree(),n=i.getRootNode(),a=t.attributes.data.path.toLowerCase(),o=t.getOwnerTree().contextMenu,s=[];if(n.id==t.id)return!1;s=t.attributes.isFakeNode?[]:-1<SYNO.SDS.MailClient.Define.SystemMailboxName.indexOf(a)?t.id===SYNO.SDS.MailClient.Define.junkId?["clearJunk-node"]:t.id===SYNO.SDS.MailClient.Define.trashId?["clearTrash-node"]:t.id===SYNO.SDS.MailClient.Define.draftsId||t.id===SYNO.SDS.MailClient.Define.sentId||SYNO.SDS.MailClient.Define.isVirtualMailbox(t.attributes)?[]:t.id===SYNO.SDS.MailClient.Define.inboxId?["add-node","sharing-node"]:["sharing-node"]:t.id===SYNO.SDS.MailClient.Settings.archive_mailbox?["add-node"]:t.findChild("id",SYNO.SDS.MailClient.Settings.archive_mailbox,!0)?["add-node","sharing-node"]:["add-node","edit-node","delete-node","sharing-node"],SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable&&!t.attributes.has_permission&&(s=s.filter(function(t){return"sharing-node"!==t})),0!==s.length&&(!function(t,e){var i=["add-node","edit-node","delete-node","sharing-node","clearJunk-node","clearTrash-node"];Ext.each(i,function(i){t.getComponent(i).setVisible(-1!==e.indexOf(i))})}(o,s),o.contextNode=t,o.showAt(e.getXY()))},scope:this},enableDrop:!0,ddGroup:"threadDDGroup",dropSource:["thread"],drop:function(t,e){"thread"===e.source&&e.threadAction.setMailbox(e.data,t.id,e.isSelectAll)},isAllowDrop:function(t,e){var i=SYNO.SDS.MailClient.Define,n=SYNO.SDS.MailClient.Control;return this.getRootNode()!==t&&!t.attributes.isFakeNode&&(-1!==this.dropSource.indexOf(e.source)&&(!!i.isMailboxAllowDropByDragData(e)&&(t.id!==n.Main.getInMailboxId()&&!(-1<[i.priorityId,i.draftsId,i.starredId].indexOf(t.id)))))},onNavigateOut:function(){this.clearSelections(!0)},onNavigateIn:function(t){var e;if("left"===t?e=this.getNodeById(this.displayedNodeId):"up"===t?e=this.getSelectionModel().selectLast():"down"===t&&(e=this.getSelectionModel().selectFirst()),e)return this.selectPath(e.getPath()),this.body.focus(),!0}}),this.treePanel}}),Ext.define("SYNO.SDS.MailClient.Sidebar.OthersMailboxList",{extend:"SYNO.SDS.MailClient.Sidebar.BaseMailboxList",xtype:"mc_OthersMailboxList",updateMailboxList:function(t){this.parsedData=SYNO.SDS.MailClient.Format.parseOthersMailboxResp(t,SYNO.SDS.MailClient.MailboxNodeUI,!1),Ext.isEmpty(this.parsedData)?this.hide():this.show(),this.parsedData=SYNO.SDS.MailClient.Format.parseOthersMailboxResp(t,SYNO.SDS.MailClient.MailboxNodeUI,!0),this.treePanel.updateNodes(this.parsedData),this.checkIfLastMailboxIdExist(),this.fireEvent("contentchange")},createTreePanel:function(){return this.treePanel=this.treePanel||new SYNO.SDS.MailClient.TreePanel({bodyStyle:"padding: 0 12px",loader:new Ext.tree.TreeLoader,root:new SYNO.SDS.MailClient.RootNode({id:"mail_root",text:SYNO.SDS.MailClient._T("common","shared_mailbox"),qtip:SYNO.SDS.MailClient._T("common","shared_mailbox"),showManageBtn:!0,listeners:{add:function(){new SYNO.SDS.MailClient.Setting.Window({owner:SYNO.SDS.MailClient.Window}).open("tab_shared_mailbox")}}}),contextMenu:new SYNO.SDS.MailClient.OpContextMenu({addOp:this.clickAdd,editOp:this.clickEdit,deleteOp:this.clickDelete,sharingOp:this.clickSharing,deleteConfirmMsg:SYNO.SDS.MailClient._T("mailbox","delete_confirm"),opScope:this}),listeners:{collapsenode:function(t){SYNO.SDS.MailClient.UserSettingProperty.addMailboxCollapseNode(t.id),this.fireEvent("contentchange")},expandnode:function(t){SYNO.SDS.MailClient.UserSettingProperty.removeMailboxCollapseNode(t.id),this.fireEvent("contentchange")},displaynode:function(t,e){var i=t.id,n=SYNO.SDS.MailClient.Control;if(SYNO.SDS.MailClient.Define.isUserOrGroupNodeInMailboxList(t))return!1;null!==e&&(n.Mail.clearSearchHighlight(),this.getLastMailboxId()!==i||n.Mail.isInMessageView()?n.Sidebar.openMailbox(i,1):n.Sidebar.forceReloadMailbox(i,1)),this.fireEvent("nodeclick")},contextmenu:function(t,e){var i=SYNO.SDS.MailClient.Define;if(i.isUserOrGroupNodeInMailboxList(t))return!1;var n=t.getOwnerTree().getRootNode(),a=i.MailboxPermission,o=t.attributes.data.my_permission,s=t.attributes.parent_id;if(o===a.READ_ONLY||n.id==t.id)return!1;var l=t.getOwnerTree().contextMenu,r=[];if(i.isMailboxAddable(o,t.attributes.data.name)&&r.push("add-node"),(t.attributes.has_permission||!SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable&&i.isMailboxShareable(o))&&r.push("sharing-node"),i.isMailboxDeletable(o,t.attributes.data.name)&&r.push("delete-node"),i.isMailboxEditable(o,s)&&r.push("edit-node"),Ext.isEmpty(r))return!1;!function(t,e){var i=["add-node","edit-node","delete-node","sharing-node","clearJunk-node","clearTrash-node"]
;Ext.each(i,function(i){t.getComponent(i).setVisible(-1!==e.indexOf(i))})}(l,r),l.contextNode=t,l.showAt(e.getXY())},scope:this},enableDrop:!0,ddGroup:"threadDDGroup",dropSource:["thread"],drop:function(t,e){"thread"===e.source&&e.threadAction.setMailbox(e.data,t.id,e.isSelectAll)},isAllowDrop:function(t,e){var i=SYNO.SDS.MailClient.Define,n=SYNO.SDS.MailClient.Control;return this.getRootNode()!==t&&!i.isUserOrGroupNodeInMailboxList(t)&&(-1!==this.dropSource.indexOf(e.source)&&(!!i.isMailboxAllowDropByDragData(e)&&(t.id!==n.Main.getInMailboxId()&&t.attributes.data.my_permission!==i.MailboxPermission.READ_ONLY)))},onNavigateOut:function(){this.clearSelections(!0)},onNavigateIn:function(t){var e;if("left"===t?e=this.getNodeById(this.displayedNodeId):"up"===t?e=this.getSelectionModel().selectLast():"down"===t&&(e=this.getSelectionModel().selectFirst()),e)return this.selectPath(e.getPath()),this.body.focus(),!0}}),this.treePanel},clickEdit:function(t,e){new SYNO.SDS.MailClient.EditShareMailbox({targetInfo:e,listeners:{scope:this,apply:this.applyDone}}).show()}}),Ext.define("SYNO.SDS.MailClient.Sidebar.MailList",{extend:"SYNO.SDS.MailClient.BasePanel",xtype:"mc_MailList",requires:["SYNO.SDS.MailClient.Sidebar.LabelList","SYNO.SDS.MailClient.Sidebar.MailboxList","SYNO.SDS.MailClient.Sidebar.OthersMailboxList"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("resize",function(t,e,i,n,a,o){var s=Ext.getCmp(t.composeBtn),l=Ext.getCmp(t.composeImgBtn);t.composeButtonWidth||(t.composeButtonWidth=s.btnEl.dom.offsetWidth),e-24<=t.composeButtonWidth?(s.hide(),l.show()):(s.show(),l.hide())}),SYNO.SDS.MailClient.Window.regShortCut(this,SYNO.SDS.MailClient.KeyNavigator.ShortCut.COMPOSE),this.updateQuotaInfo()},fillConfig:function(t){this.labelList=new SYNO.SDS.MailClient.Sidebar.LabelList({listeners:{contentchange:this.updateScroller,nodeclick:function(){this.mailboxList.clearSelections(),this.othersMailboxList.clearSelections()},scope:this}}),this.mailboxList=new SYNO.SDS.MailClient.Sidebar.MailboxList({listeners:{contentchange:this.updateScroller,nodeclick:function(){this.labelList.clearSelections(),this.othersMailboxList.clearSelections()},lastNodeDeleted:function(){this.mailboxList.treePanel.selectNodeById(this.mailboxList.defaultMailboxId,{})},scope:this}}),this.othersMailboxList=new SYNO.SDS.MailClient.Sidebar.OthersMailboxList({hidden:!0,listeners:{contentchange:this.updateScroller,nodeclick:function(){this.mailboxList.clearSelections(),this.labelList.clearSelections()},lastNodeDeleted:function(){this.mailboxList.treePanel.selectNodeById(this.mailboxList.defaultMailboxId,{})},scope:this}});var e={border:!1,autoFlexcroll:!0,tbar:{xtype:"container",cls:"left-action-button",items:[{id:this.composeBtn=Ext.id(),xtype:"syno_mc_button",cls:"compose-button",iconCls:"compose",text:SYNO.SDS.MailClient._T("common","compose"),tooltip:SYNO.SDS.MailClient._T("common","compose"),handler:this.compose},{id:this.composeImgBtn=Ext.id(),xtype:"syno_mc_button",cls:"compose-image-button",iconCls:"compose",tooltip:SYNO.SDS.MailClient._T("common","compose"),hidden:!0,handler:this.compose}]},bbar:{xtype:"container",layout:{type:"vbox",align:"stretch",pack:"start"},cls:"syno-mc-quota-info",items:[{itemId:"quotaProgressBar",xtype:"progress",cls:"syno-mc-quota-progressbar"},{itemId:"quotaString",xtype:"syno_displayfield",cls:"syno-mc-quota-string",listeners:{render:function(t){Ext.QuickTips.register({target:t.getEl(),text:Ext.util.Format.htmlEncode(t.value)})}}}]},items:[this.mailboxList,this.othersMailboxList,this.labelList]};return Ext.apply(e,t)},compose:function(){SYNO.SDS.MailClient.Window.popOutWinManager.openComposer()},clearSelections:function(){this.mailboxList.clearSelections(),this.othersMailboxList.clearSelections(),this.labelList.clearSelections()},updatePriorityUnreadCount:function(){var t,e,i=SYNO.SDS.MailClient.Control.Model,n=SYNO.SDS.MailClient.Lib.PriorityMailbox.getUnreadCountRelatedIds(),a=n.mailboxIds,o=n.labelIds;Ext.isDefined(this.mailboxList.parsedData)&&(t=a.reduce(function(t,e){var n=i.getMailboxRecordByAttr("id",e);return n?t+n.get("additional").unread_count:t},0),e=o.reduce(function(t,e){var n=i.getLabelRecordByAttr("id",e);return n?t+n.get("additional").unread_count:t},0),Ext.each(this.mailboxList.parsedData,function(i,n){"priority"===i.id&&(i.count=t+e,SYNO.SDS.MailClient.Lib.PriorityMailbox.setUnreadCount(i.count))},this),this.mailboxList.treePanel.updateNodes(this.mailboxList.parsedData),SYNO.SDS.MailClient.Switch.updateDocumentTitle())},onShortCut:function(t){if(SYNO.SDS.MailClient.KeyNavigator.ShortCut.COMPOSE===t)return this.compose(),!0},updateQuotaString:function(){var t=SYNO.SDS.MailClient.Info.quota_info,e=this.getBottomToolbar().getComponent("quotaString"),i=Ext.QuickTips.getQuickTip().targets[Ext.id(e.getEl())],n=SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(t.usage_byte,2),a=SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(t.limit_byte,2),o=String.format(SYNO.SDS.MailClient._T("common","usage"),n[0],a[0],(n[1]/a[1]*100).toFixed(1));if(!t||0===t.limit_byte)return e.setValue(""),void e.hide();e.setValue(o),i&&(i.text=Ext.util.Format.htmlEncode(o)),e.show()},updateQuotaProgressBar:function(){var t=SYNO.SDS.MailClient.Info.quota_info,e=this.getBottomToolbar().getComponent("quotaProgressBar");if(!t||0===t.limit_byte)return void e.hide();e.updateProgress(t.usage_byte/t.limit_byte),t.usage_byte<=t.warning_byte?(e.addClass("normal"),e.removeClass("warning"),e.removeClass("alert")):t.usage_byte<.99*t.limit_byte?(e.addClass("warning"),e.removeClass("normal"),e.removeClass("alert")):(e.addClass("alert"),e.removeClass("normal"),e.removeClass("warning")),e.show()},updateQuotaInfo:function(){this.updateQuotaProgressBar(),this.updateQuotaString(),this.doLayout()}}),Ext.define("SYNO.SDS.MailClient.Sidebar.ListPanel",{extend:"SYNO.ux.Panel",xtype:"mc_ListPanel",requires:["SYNO.SDS.MailClient.Sidebar.MailList"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("resize",function(t,e,i,n,a,o){SYNO.SDS.MailClient.UserSettingProperty.setListWidth(e)}),this.addClass("syno-mc-sidebar")},fillConfig:function(t){this.mailList=new SYNO.SDS.MailClient.Sidebar.MailList({itemId:"mail"});var e=SYNO.SDS.MailClient.UserSettingProperty.getListWidth(),i={bodyCssClass:"syno-mc-list-body",border:!1,region:"west",layout:"card",width:e,split:!0,minSize:69,maxSize:280,activeItem:0,autoFlexcroll:!1,items:[this.mailList]};return Ext.apply(i,t)},switchToMail:function(){this.layout.activeItem&&this.layout.setActiveItem("mail")}}),Ext.define("SYNO.SDS.MailClient.MenuCheckItem",{extend:"Ext.menu.CheckItem",xtype:"syno_mc_menucheckitem",selectPartialCls:"select-partial",constructor:function(t){this.itemTpl=this.getTpl(),this.callParent([t]),this.on("render",function(t){t.el.dom.qtip=t.text,t.textEl.dom.qtip=t.text}),this.on("checkchange",function(t,e){t.removeClass(t.selectPartialCls),t.parentMenu&&(Ext.fly(t.getId()).removeClass(t.parentMenu.selectPartialCls||t.selectPartialCls),t.parentMenu.fireEvent("checkchange",t,e))})},getTpl:function(){return new Ext.XTemplate('<a class="x-menu-list-item" hidefocus="true" unselectable="on" href="{href}"','<tpl if="hrefTarget">',' target="{hrefTarget}"',"</tpl>",">",'<div id="{id}" class="{cls} x-unselectable">','<img alt="{altText}" src="{icon}" class="x-menu-item-icon {iconCls}"/>','<tpl if="backgroundColor">','<div class="color" style="background-color:#{backgroundColor}; color:#{textColor};"></div>',"</tpl>",'<span class="x-menu-item-text">{text}</span>',"</div>","</a>")},getTemplateArgs:function(){return{id:this.id,cls:this.itemCls+(this.menu?" x-menu-item-arrow":"")+(this.cls?" "+this.cls:""),href:this.href||"#",hrefTarget:this.hrefTarget,icon:this.icon||Ext.BLANK_IMAGE_URL,iconCls:this.iconCls||"",text:this.itemText||this.text||" ",altText:this.altText||"",backgroundColor:this.backgroundColor||"",textColor:this.textColor||""}}}),Ext.define("SYNO.SDS.MailClient.MenuSelectorNav",{extend:"Ext.menu.MenuNav",up:function(t,e){e.tryActivate(e.items.indexOf(e.activeItem)-1,-1)||e.activateOuterItem(-1)},down:function(t,e){e.tryActivate(e.items.indexOf(e.activeItem)+1,1)||e.activateOuterItem(1)},tab:function(t,e){t.stopEvent(),this.keyNav[t.shiftKey?"up":"down"](t,e)}}),Ext.define("SYNO.SDS.MailClient.Search.SearchLabelCheckItemMenu",{extend:"SYNO.SDS.MailClient.Search.SearchListMenu",requires:["SYNO.SDS.MailClient.AddLabel","SYNO.SDS.MailClient.MenuCheckItem","SYNO.SDS.MailClient.MenuSelectorNav"],constructor:function(t){var e,i=this;this.hideCreate=!0===t.hideCreate,e={contentMaxHeight:this.hideCreate?256:224,selector:new SYNO.ux.Menu({cls:"syno-mc-menu syno-mc-scrollbar-fix",floating:!1,autoFlexcroll:!0,canActivate:!1,listeners:{scope:this,checkchange:this.onCheckChange},hide:Ext.emptyFn,updateCanActivate:function(){this.canActivate=!!this.items.length},activate:this.activateSelector.createDelegate(this),deactivate:function(){this.deactivateActive()},setActiveItem:function(){if(SYNO.ux.Menu.prototype.setActiveItem.apply(this,arguments),this.activeItem&&(i.setActiveItem(this),this.ul.dom.fleXdata&&this.ul.dom.fleXdata.scrollPosition[1])){var t=this.ul.dom.fleXdata.scrollPosition[1],e=this.activeItem.el.dom,n=e.offsetTop,a=e.offsetTop+e.offsetHeight;(n<t[0]||a>t[0]+this.getHeight())&&this.fleXcrollTo(this.activeItem.id)}},activateOuterItem:this.activateOuterItem.createDelegate(this)}),cls:"syno-mc-label-searchlist",items:[{itemId:"sep",xtype:"menuseparator",hidden:this.hideCreate},{itemId:"create",text:SYNO.SDS.MailClient._T("common","create"),cls:"action blue",hidden:this.hideCreate,scope:this,handler:function(){new SYNO.SDS.MailClient.AddLabel({createName:this.searchText,owner:this.findWindow(),listeners:{scope:this,apply:this.onCreate}}).open()}},{itemId:"apply",text:SYNO.SDS.MailClient._T("common","commit"),scope:this,cls:"action blue",hidden:!0,handler:this.onApply}]},this.callParent([Ext.apply(e,t)]),this.store||(this.store=new Ext.data.JsonStore({autoDestroy:!0,fields:["id","full_name","name","path","parent_id","background_color","text_color","additional"]})),this.addEvents("apply"),this.itemLabels={},this.itemRecords=[],this.isForSelectAll=!1,this.currentLabels=[],this.on("show",function(){this.firstChecked=!1},this),this.selector.on("afterrender",function(t){this.keyNav&&this.keyNav.disable(),this.keyNav=new SYNO.SDS.MailClient.MenuSelectorNav(this)})},activateSelector:function(){var t=this.selector,e=this.step;t.activeItem||t.tryActivate(-1===e?t.items.length-1:0,e)},activateOuterItem:function(t){var e=this.items.indexOf(this.selector);this.tryActivate(e+t,t)||this.tryActivate(-1===t?this.items.length-1:0,t)},adjustContentHeight:function(){var t,e=this.selector.el.query(".contentwrapper"),i=this.contentMaxHeight;t=e.length?e[0].offsetHeight:this.selector.getHeight(),i=t>i?i:t,this.selector.setHeight(i||1),this.doLayout(),this.selector.ul.setHeight(i?i+1:2),this.selector.updateScroller()},getCheckedResult:function(){if(this.isForSelectAll)return this.getCheckedResultForSelectAll();var t={};this.selector.items.each(function(e,i,n){e.checked&&(t[e.data.id]=e)},this);var e={add:[],remove:[],checkedList:[]};return Ext.iterate(this.itemLabels,function(i,n,a){!t.hasOwnProperty(i)&&this.store.getById(parseInt(i,10))&&e.remove.push(this.store.getById(parseInt(i,10)).data)},this),Ext.iterate(t,function(t,i,n){e.checkedList.push(i.data),this.itemLabels.hasOwnProperty(t)&&(i.el.hasClass(this.selectPartialCls)||this.itemLabels[t]==this.itemRecords.length)||e.add.push(i.data)},this),this.checkResult=e,e},getCheckedResultForSelectAll:function(){var t={add:[],remove:[],checkedList:[]};return this.selector.items.each(function(e,i,n){e.checked?(t.checkedList.push(e.data),e.el.hasClass(this.selectPartialCls)||-1!=this.currentLabels.indexOf(e.data.id)||t.add.push(e.data)):t.remove.push(e.data)},this),this.checkResult=t,t},onSearchFieldKeyUp:function(t,e){this.callParent([t,"full_name"])},match:function(t,e){var i=[],n=!this.searchText;i=t.map(function(t){return t.id}),this.selector.canActivate=!1,this.selector.items.each(function(t,e,a){n||-1<i.indexOf(t.data.id)?(this.selector.canActivate=!0,t.show()):t.hide()},this),this.completeMatch=e;var a=!this.hideCreate&&!e;this.getComponent("create").setVisible(a).setText(this.searchText?String.format(SYNO.SDS.MailClient._T("common","create_sth"),this.searchText):SYNO.SDS.MailClient._T("common","create")),this.getComponent("sep").setVisible(a||this.getComponent("apply").isVisible()),this.adjustContentHeight()},onCheckChange:function(t,e){this.firstChecked=!0;var i=this.getCheckedResult(),n=i.add.length||i.remove.length;this.getComponent("apply").setVisible(n);var a=!this.hideCreate&&!this.completeMatch;this.getComponent("create").setVisible(a&&!n),this.getComponent("sep").setVisible(a||n),this.adjustContentHeight()},onApply:function(){(this.checkResult.add.length||this.checkResult.remove.length)&&this.fireEvent("apply",this.checkResult.add,this.checkResult.remove,this.checkResult.checkedList),this.hide(!0)},onCreate:function(t,e){var i,n,a=t.id;SYNO.SDS.MailClient.Control.Sidebar.reloadLabelList().then(function(){(i=SYNO.SDS.MailClient.Switch.getLabelStore().getById(a))&&(n={id:a,name:i.get("name"),full_name:i.get("full_name"),path:i.get("path"),background_color:i.get("background_color"),text_color:i.get("text_color")},this.checkResult.add.push(n),this.checkResult.checkedList.push(n),this.onApply())}.bind(this))},setItem:function(t,e,i){var n={};Ext.each(t,function(t,e,i){Ext.each(t.data.label,function(t,e,i){n.hasOwnProperty(t.id)||(n[t.id]=0),n[t.id]++})},this),this.itemRecords=t,this.itemLabels=n,this.isForSelectAll=!!e,this.currentLabels=[],e&&Ext.isArray(i)&&(this.currentLabels=i)},loadList:function(){this.store.clearData(),this.checkResult={add:[],remove:[],checkedList:[]},this.getComponent("apply").setVisible(!1),this.getComponent("sep").setVisible(!this.hideCreate),this.getComponent("create").setVisible(!this.hideCreate),this.selector.ul.dom&&this.selector.ul.dom.fleXcroll&&this.selector.ul.dom.fleXcroll.setScrollPos(!1,0),SYNO.SDS.MailClient.Control.Model.getLabelJson().then(function(t){var e=[],i={},n=[];this.needReload=!1,Ext.each(t,function(t,a,o){i={xtype:"syno_mc_menucheckitem",hideOnClick:!1,data:t,textColor:t.text_color,backgroundColor:t.background_color,text:Ext.util.Format.htmlEncode(t.full_name),group:this.singleSelect?"label_group":"",listeners:{scope:this,click:function(t,e){Ext.fly(e.getTarget()).hasClass("x-menu-item-text")&&!this.firstChecked&&(!0===t.checked?t.checked=!1:(this.singleSelect&&this.selector.items.each(function(t,e,i){t.checked=!1}),t.checked=!0),this.onCheckChange(),this.onApply())}}},this.isForSelectAll?(i.checked=!0,i.cls=-1!=this.currentLabels.indexOf(t.id)?"":this.selectPartialCls):this.itemLabels.hasOwnProperty(t.id)&&(i.checked=!0,i.cls=this.itemLabels[t.id]!=this.itemRecords.length?this.selectPartialCls:""),i.checked?n.push(i):e.push(i)},this);var a=n.concat(e);this.selector.suspendEvents(),this.selector.removeAll(),this.selector.add(a),this.selector.resumeEvents(),this.selector.canActivate=!!a.length,this.selector.doLayout(),this.store.loadData(t),this.adjustContentHeight()}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.Setting.General",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.ComboBox"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("contentchange",this.updateTinyMCEMask,this)},fillConfig:function(t){function e(t){var e=[[0,t]],i=[3,7,14,30].map(function(t){return[t,String.format(SYNO.SDS.MailClient._T("setting","older_than_day"),t)]},this);return e.concat(i)}this.signature={};var i=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[25,25],[50,50],[100,100]]}),n=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("setting","set_immediately")],[1,"1 "+_T("common","time_second")],[3,"3 "+_T("common","time_seconds")],[10,"10 "+_T("common","time_seconds")]]}),a=new Ext.data.SimpleStore({autoDestroy:!0,fields:["id","value","display"],data:[[0,!0,SYNO.SDS.MailClient._T("setting","always_display")],[1,!1,SYNO.SDS.MailClient._T("setting","ask_before")]]}),o=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("thread","one_line_without_preview")],[1,SYNO.SDS.MailClient._T("thread","one_line_with_preview")],[2,SYNO.SDS.MailClient._T("thread","two_line")]]}),s=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("common","comfortable")],[1,SYNO.SDS.MailClient._T("common","cozy")],[2,SYNO.SDS.MailClient._T("common","compact")]]}),l=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:SYNO.SDS.Utils.getSupportedLanguageCodepage().concat([["utf8",SYNO.SDS.MailClient._T("common","unicode")]])}),r=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("setting","set_immediately")],[5,"5 "+_T("common","time_seconds")],[10,"10 "+_T("common","time_seconds")],[15,"15 "+_T("common","time_seconds")],[20,"20 "+_T("common","time_seconds")],[30,"30 "+_T("common","time_seconds")]]}),d=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:e(SYNO.SDS.MailClient._T("setting","dont_regular_delete"))}),c=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:e(SYNO.SDS.MailClient._T("setting","dont_regular_delete"))}),h=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:e(SYNO.SDS.MailClient._T("setting","dont_regular_archive"))}),u=new Ext.data.SimpleStore({fields:["value","display"],data:[["def",_TT("SYNO.Application.Service.Instance","common","def_lang")]].concat(SYNO.SDS.Utils.getSupportedLanguage())}),S=this,m=SYNO.SDS.MailClient.Settings;this.prepareTinyMCE();var f={webapi:{api:"SYNO.MailClient.Setting.General",methods:{get:"get",set:"set"},version:"1"},listeners:{scope:this,flexcrollinitdone:function(){this.getContentTarget().dom.fleXdata.fixIEDispBug=Ext.emptyFn,this.addTinyMCE()},upload:function(t){this.onImageUpload(t)},activate:this.resetSignatureFieldSet,deactivate:this.recordSMTPSignature},fieldWidth:240,labelWidth:215,items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","general"),cls:"syno-mc-setting-general-panel",itemId:"general_fieldset",items:[{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"conversations_per_page",fieldLabel:SYNO.SDS.MailClient._T("setting","conversations_per_page"),mode:"local",store:i,displayField:"display",valueField:"value",value:m.conversations_per_page},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"display_external_image",fieldLabel:SYNO.SDS.MailClient._T("setting","external_image_display"),mode:"local",store:a,displayField:"display",valueField:"value",value:m.display_external_image},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","split_pane_mode")+":"},{xtype:"syno_radio",inputValue:2,boxLabel:SYNO.SDS.MailClient._T("common","no_split"),indent:1,name:"split_pane_mode",checked:2==m.split_pane_mode,scope:this,handler:function(t,e){this.setFieldDisabled("previewLayout",!e);var i=t.nextSibling();i&&"previewLayout"==i.itemId&&this.setFieldDisabled("displayDensity",!e||2===i.getValue())}},{xtype:"syno_combobox",itemId:"previewLayout",cls:"syno-mc-combobox",itemCls:"preview-layout-item-cls",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"preview_layout",mode:"local",hideLabel:!0,store:o,displayField:"display",valueField:"value",value:m.preview_layout,listeners:{scope:this,select:function(t,e,i,n){2==e.get("value")?this.setFieldDisabled("displayDensity",!0):this.setFieldDisabled("displayDensity",!1)}}},{xtype:"syno_radio",inputValue:3,indent:1,boxLabel:SYNO.SDS.MailClient._T("common","vertical_split"),name:"split_pane_mode",checked:3==m.split_pane_mode},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","message_organization")+":"},{xtype:"syno_radio",inputValue:"on",indent:1,boxLabel:SYNO.SDS.MailClient._T("setting","by_conversation"),name:"conversation_view",checked:m.conversation_view},{xtype:"syno_radio",inputValue:"off",indent:1,boxLabel:SYNO.SDS.MailClient._T("setting","by_message"),name:"conversation_view",checked:!m.conversation_view},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"user_lang",fieldLabel:_TT("SYNO.Application.Service.Instance","common","language"),displayField:"display",valueField:"value",value:this.getUserLang(),store:u},{xtype:"syno_combobox",itemId:"displayDensity",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"display_density",fieldLabel:SYNO.SDS.MailClient._T("setting","display_density"),mode:"local",store:s,displayField:"display",valueField:"value",value:m.display_density},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"mark_as_read_time",fieldLabel:SYNO.SDS.MailClient._T("setting","set_preview_readed"),mode:"local",store:n,displayField:"display",valueField:"value",value:m.mark_as_read_time},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"delay_send_time",fieldLabel:SYNO.SDS.MailClient._T("setting","delay_send_time"),mode:"local",store:r,displayField:"display",valueField:"value",value:m.delay_send_time},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","archive_mailbox")+":",width:215},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:Ext.util.Format.htmlEncode(SYNO.SDS.MailClient.Switch.getMailboxStore().getById(m.archive_mailbox).data.name),value:SYNO.SDS.MailClient.Switch.getMailboxStore().getById(m.archive_mailbox).data.path,width:240,menuCfg:{width:240,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,disableSharedToOthers:!0},listeners:{scope:this,change:function(t){this.getForm().findField("archive_mailbox").setValue(t)}}},{xtype:"hidden",name:"archive_mailbox",value:m.archive_mailbox}]},{xtype:"syno_checkbox",name:"enable_smtp_detecting",boxLabel:SYNO.SDS.MailClient._T("setting","enable_smtp_detecting"),checked:m.enable_smtp_detecting},{xtype:"syno_checkbox",name:"enable_shortcut",boxLabel:SYNO.SDS.MailClient._T("setting","enable_shortcut"),checked:m.enable_shortcut},{xtype:"syno_checkbox",name:"enable_floating_button",htmlEncode:!1,boxLabel:SYNO.SDS.MailClient._T("setting","enable_floating_button")+String.format('<span class="syno-mc-white-tip" ext:qtip="{0}"></span>',SYNO.SDS.MailClient._T("setting","floating_button_desc")),checked:m.enable_floating_button},{xtype:"syno_checkbox",name:"disable_show_mailbox",boxLabel:SYNO.SDS.MailClient._T("setting","disable_show_mailbox"),checked:m.disable_show_mailbox},{xtype:"syno_checkbox",name:"enlarge_image_cache_threshold",boxLabel:SYNO.SDS.MailClient._T("setting","enlarge_image_cache_threshold"),checked:m.enlarge_image_cache_threshold},{xtype:"syno_checkbox",name:"enable_upload_external_image",boxLabel:SYNO.SDS.MailClient._T("lab","enable_upload_external_image"),checked:m.enable_upload_external_image}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("common","lang_codepage"),items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","download_compress_codepage_desc")},{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("common","lang_codepage"),hiddenName:"codepage",store:l,displayField:"display",valueField:"value",value:m.codepage,triggerAction:"all",editable:!1,mode:"local"}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("common","mailbox"),items:[{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("setting","trash_retaining_day"),hiddenName:"trash_retaining_day",store:d,displayField:"display",valueField:"value",value:m.trash_retaining_day,tpl:'<tpl for="."><div ext:qtip="{display}" class="x-combo-list-item">{display}</div></tpl>',mode:"local"},{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("setting","junk_retaining_day"),hiddenName:"junk_retaining_day",store:c,displayField:"display",valueField:"value",value:m.junk_retaining_day,tpl:'<tpl for="."><div ext:qtip="{display}" class="x-combo-list-item">{display}</div></tpl>',mode:"local"},{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("setting","inbox_archiving_day"),hiddenName:"inbox_archiving_day",store:h,displayField:"display",valueField:"value",value:m.inbox_archiving_day,tpl:'<tpl for="."><div ext:qtip="{display}" class="x-combo-list-item">{display}</div></tpl>',mode:"local"},{xtype:"syno_checkbox",name:"clear_trash_on_logout",boxLabel:SYNO.SDS.MailClient._T("setting","clear_trash_on_logout"),checked:m.clear_trash_on_logout},{xtype:"syno_checkbox",name:"clear_junk_on_logout",boxLabel:SYNO.SDS.MailClient._T("setting","clear_junk_on_logout"),checked:m.clear_junk_on_logout}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","date_parser"),hidden:!SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application"),items:[{xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("setting","disable_date_parser"),name:"disable_date_highlight"}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","signature"),itemId:"signature_fieldset",items:[{xtype:"syno_checkbox",name:"enable_signature",boxLabel:SYNO.SDS.MailClient._T("setting","use_signature"),listeners:{scope:this,check:this.onEnableSignatureCheck}},{xtype:"syno_mc_combobox",name:"smtp_account",itemId:"smtp_account",hideLabel:!0,mode:"local",store:t.smtpStore,displayField:"mail",valueField:"id",disabled:!0,listeners:{scope:this,beforeselect:function(t,e,i){this.recordSMTPSignature();var n=this.signature[e.get("id")]?this.signature[e.get("id")]:e.get("signature");this.signature_tinymce.getEditor().setContent(n),this.readonly_tinymce.getEditor().setContent(n)}},isDirty:function(){return S.recordSMTPSignature(),!SYNO.SDS.MailClient.Tool.isEmptyObject(S.signature)}},{xtype:"container",itemId:"signature"},{xtype:"container",itemId:"signature_readonly",cls:"syno-mc-readonly-tinymce"}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","default_text_style"),itemId:"font_style_fieldset",items:[{xtype:"hidden",name:"composer_fontname",value:""},{xtype:"hidden",name:"composer_fontsize",value:""},{xtype:"hidden",name:"composer_forecolor",value:""}]}]};return Ext.apply(f,t),f},updateScrollCls:function(){this.getEl()&&this.getEl().dom&&this.callParent(arguments)},prepareTinyMCE:function(){var t="SYNO.SDS.MailClient.Application",e=t+SYNO.SDS.Config.FnMap[t].config.version;this.ddupload=new SYNO.SDS.MailClient.Editor.DDUpload({skip_check_big_size_file:!0,owner:this});var i={plugins:["syno_mc_fontselect","syno_fontsizeselect","syno_mc_textcolor","syno_mc_autoresize"],toolbar:"syno_mc_fontselect syno_fontsizeselect forecolor removeformat",synoPostfix:e,statusbar:!1,menubar:!1,forced_root_block:"div",body_class:"mc-setting",content_css:"webman/3rdparty/MailClient/mc-tinymce.css",min_height:Ext.isModernIE?162:56,autoresize_min_height:Ext.isModernIE?162:56,autoresize_bottom_margin:0,autoresize_on_init:!1,owner:this,module:this},n={automatic_uploads:!1,images_dataimg_filter:Ext.emptyFn,paste_data_images:!0,skip_check_big_size_file:!0,paste_retain_style_properties:"border border-collapse border-spacing border-top border-left border-bottom border-right width vertical-align padding",paste_webkit_styles:"all",syno_word_keep_all_format:!0,plugins:["syno_mc_fontselect","syno_fontsizeselect","textcolor","hr","syno_mc_lists","syno_mc_link","syno_mc_autolink","syno_mc_autoresize","syno_mc_formupload","syno_mc_ddupload","syno_mc_image","syno_mc_pastelink","syno_mc_tab","syno_mc_indent_outdent"],toolbar:["syno_mc_fontselect syno_fontsizeselect forecolor backcolor bold italic underline removeformat | ","alignleft aligncenter alignright alignjustify numlist bullist syno_mc_outdent syno_mc_indent | ","syno_mc_link xxxtable syno_mc_image"].join(),synoPostfix:e,statusbar:!1,menubar:!1,convert_urls:!1,forced_root_block:"div",body_class:"mc-setting",content_css:"webman/3rdparty/MailClient/mc-tinymce.css",min_height:Ext.isModernIE?162:100,syno_mc_ddupload:{instance:this.ddupload},autoresize_min_height:Ext.isModernIE?162:100,autoresize_bottom_margin:12,autoresize_on_init:!1,is_signature:!0,owner:this,module:this};this.tinymce_ready_count=0,this.style_tinymce=new SYNO.ux.TinyMCE({owner:this,width:560,mceConfig:Ext.apply({},{min_height:34,autoresize_min_height:34},i),listeners:{scope:this,initialize:this.onTinyMCEInitialize}}),this.signature_tinymce=new SYNO.ux.TinyMCE({owner:this,width:560,mceConfig:Ext.apply({},n),listeners:{scope:this,initialize:this.onTinyMCEInitialize}}),this.readonly_tinymce=new SYNO.ux.TinyMCE({owner:this,width:560,mceConfig:Ext.apply({},{readonly:!0},n),listeners:{scope:this,initialize:this.onTinyMCEInitialize}})},getSenderUploadLimit:function(){return SYNO.SDS.MailClient.Define.SingleAttachmentSizeLimit},refreshInlineImage:function(){},addTinyMCE:function(){this.getComponent("font_style_fieldset").add(this.style_tinymce);var t=this.getComponent("signature_fieldset");t.getComponent("signature").add(this.signature_tinymce),t.getComponent("signature_readonly").add(this.readonly_tinymce),this.doLayout()},addFile:function(t,e,i){this.ddupload.addFile(t,e,i)},adjSignatureTinyMCESize:function(){this.getEditor().execCommand("mceAutoResize")},getEditor:function(){return this.signature_tinymce.editor},modifyResetStyle:function(t){var e=t.getContainer().querySelectorAll(".mce-btn.mce-last")[0];e&&(Ext.fly(e).addClass("syno-mc-default-text-style-reset"),e.childNodes[0].innerHTML=SYNO.SDS.MailClient._T("setting","default_text_style_reset"))},onEnableSignatureCheck:function(t,e){var i=this.smtpStore.getCount()>0;i||(e=!1),t.setDisabled(!i),this.tinymce_init_done&&(this.getComponent("signature_fieldset").getComponent("signature_readonly").setVisible(!e),this.getComponent("signature_fieldset").getComponent("signature").setVisible(e),this.getComponent("signature_fieldset").getComponent("smtp_account").setDisabled(!e),e?this.signature_tinymce.getEditor().getBody().focus():this.readonly_tinymce.getEditor().setContent(this.signature_tinymce.getEditor().getContent()))},resetSignatureFieldSet:function(){var t,e=this.smtpStore.getCount()>0,i=this.getComponent("signature_fieldset").getComponent("smtp_account");this.tinymce_init_done&&(e?(i.setValue(this.smtpStore.getAt(0).get("id")),t=this.signature[this.smtpStore.getAt(0).get("id")]?this.signature[this.smtpStore.getAt(0).get("id")]:this.smtpStore.getAt(0).get("signature"),this.signature_tinymce.getEditor().setContent(t)):(i.setValue(""),this.signature_tinymce.getEditor().setContent("")),this.onEnableSignatureCheck(this.getForm().findField("enable_signature"),this.getForm().findField("enable_signature").getValue()))},onTinyMCEInitialize:function(t,e){++this.tinymce_ready_count<3||(this.tinymce_init_done=!0,this.initStyleEditor(),this.initSignatureEditor())},initSignatureEditor:function(){var t,e,i=this.smtpStore.getCount()>0;for(t=0;t<this.smtpStore.getCount();++t)e=this.smtpStore.getAt(t),e.get("updated")||(this.signature_tinymce.getEditor().setContent(e.get("signature")),e.data.signature=this.signature_tinymce.getEditor().getContent(),e.data.updated=!0,e.commit());i&&(this.signature_tinymce.getEditor().setContent(this.smtpStore.getAt(0).get("signature")),this.readonly_tinymce.getEditor().setContent(this.smtpStore.getAt(0).get("signature"))),this.ddupload.renderTo(this.signature_tinymce.getEditor().getBody()),this.resetSignatureFieldSet()},onImageUpload:function(t){t.size>1048576&&this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("setting","img_too_large_msg")),this.updateImage(t,this.getEditor())},initStyleEditor:function(){var t=this.style_tinymce.getEditor();t.iframeElement.tabIndex=-1,this.modifyResetStyle(t),
t.setContent(SYNO.SDS.MailClient._T("setting","default_text_style_preview_text"));var e=this;t.on("BeforeExecCommand",function(i){if(Ext.isObject(i)){var n,a,o=!0;switch(i.command){case"FontName":n="composer_fontname",a=i.value;break;case"FontSize":n="composer_fontsize",a=i.value;break;case"syno_mc_pre_forecolor":n="composer_forecolor",a=i.value.substr(1,6);break;case"RemoveFormat":e.getForm().findField("composer_fontname").setValue(""),e.getForm().findField("composer_fontsize").setValue(""),e.getForm().findField("composer_forecolor").setValue("");break;default:o=!1}a&&e.getForm().findField(n).setValue(a),o&&t.selection.select(t.getBody(),!0)}}),t.on("ExecCommand",function(i){Ext.isObject(i)&&-1!==["FontName","FontSize","syno_mc_post_forecolor","RemoveFormat"].indexOf(i.command)&&(t.selection.collapse(),e.findWindow().focus())}),this.updateTinyMCEStyle()},updateTinyMCEStyle:function(){if(Ext.isDefined(this.style_tinymce)&&this.style_tinymce.getEditor()&&this.style_tinymce.getEditor().initialized&&this.isReturned){var t,e=this.getForm(),i=this.style_tinymce.getEditor();t=e.findField("composer_fontname").getValue(),t&&i.execCommand("FontName",!1,t),t=e.findField("composer_fontsize").getValue(),t&&i.execCommand("FontSize",!1,t),t=e.findField("composer_forecolor").getValue(),t&&(t="#"+t,i.execCommand("syno_mc_pre_forecolor",!1,t),i.plugins.syno_mc_textcolor.applyFormat("forecolor",t),i.execCommand("syno_mc_post_forecolor",!1,t)),this.findWindow().focus(),this.fleXcrollTo(this.getComponent("general_fieldset").getEl())}},updateTinyMCEMask:function(){if(this.updateScroller(),this.style_tinymce.getEditor()&&this.style_tinymce.getEditor().initialized){var t=this.style_tinymce.getEditor();this.tinymceMask||(this.tinymceMask=Ext.fly(t.contentAreaContainer).createChild({tag:"div",style:"position: absolute; top: 0;"}),t.contentAreaContainer.style.position="relative"),this.tinymceMask.setSize(Ext.fly(t.contentAreaContainer).getSize())}},updateImage:function(t,e){if(t.inline&&!Ext.isEmpty(t.name)&&!Ext.isEmpty(t.ref)&&e){var i=this.findImageDom(t,e);i&&(this.updateImageAttribute(i,t),this.convertImageToDataUri(i))}},findImageDom:function(t,e){var i,n,a,o;for(n=String.format('img[data-ref="{0}"]',t.ref),o=e.getBody().querySelectorAll(n),i=0;i<o.length;++i)if(!o[i].getAttribute("cid")){a=o[i];break}return a},updateImageAttribute:function(t,e){var i={src:Ext.isString(e.source)?this.getDSImageUrl(e.source)+"&"+Math.random():URL.createObjectURL(e)};Ext.fly(t).set(i,!0),t.removeAttribute("data-temp"),t.removeAttribute("data-ref"),t.removeAttribute("data-synomc-uploading-img"),t.removeAttribute("data-mce-src")},convertImageToDataUri:function(t){this.getDataUri(t.src).then(function(e){t.src=e,Ext.fly(t).on("load",this.adjSignatureTinyMCESize.bind(this))}.bind(this)).catch(function(t){})},getDataUri:function(t){return new Promise(function(e,i){var n=new Image;n.crossOrigin="anonymous",n.onload=function(t){var i=document.createElement("canvas"),n=t.target,a=this.getEditor().getBody().clientWidth-20;n.naturalWidth>a?(i.width=a,i.height=n.naturalHeight*(a/n.naturalWidth)):(i.width=n.naturalWidth,i.height=n.naturalHeight),i.getContext("2d").drawImage(n,0,0,i.width,i.height),e(i.toDataURL("image/png"))}.bind(this),n.onerror=function(t){i(t)},n.src=t}.bind(this))},getDSImageUrl:function(t){var e=SYNO.API.currentManager.getBaseURL("SYNO.FileStation.Thumb","get",1);return e=Ext.urlAppend(e,Ext.urlEncode({size:"large",path:t}))},recordSMTPSignature:function(){var t=this.getForm().findField("smtp_account"),e=t.getStore().getById(parseInt(t.getValue(),10));if(this.signature_tinymce&&this.signature_tinymce.getEditor()){var i=this.signature_tinymce.getEditor().getContent();e&&e.get("signature")!==i&&(this.signature[e.get("id")]=i)}},processReturnData:function(t,e,i){var n=this.getForm();"get"==t&&Ext.each(e.result,function(t){if(t.api==this.webapi.api){if(3===t.data.split_pane_mode&&this.setFieldDisabled("previewLayout",!0),3!==t.data.split_pane_mode&&2!==t.data.preview_layout||this.setFieldDisabled("displayDensity",!0),t.data.conversation_view=t.data.conversation_view?"on":"off",t.data.codepage=t.data.codepage||_S("lang"),Ext.isDefined(t.data.archive_mailbox)){var e=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t.data.archive_mailbox);e&&Ext.getCmp(this.mailboxBtnId).setValue(e.get("id"),e.get("name"))}}else"SYNO.MailClient.Setting.SMTP"===t.api&&"getinfo"===t.method&&(SYNO.SDS.MailClient.AdminSettings.SMTP=t.data)},this),i&&Ext.isArray(i.compound)&&(n.loadRecords(e.result,i.compound),this.isReturned=!0,this.updateTinyMCEStyle())},processParams:function(t,e){if("set"!==t)return e.push({api:"SYNO.MailClient.Setting.SMTP",method:"getinfo",version:1}),e;if(this.blLangChanged=!1,this.hasConversationViewChange=!1,Ext.each(e,function(t){if(t.api==this.webapi.api&&"set"==t.method){Ext.isDefined(t.params.conversation_view)&&(t.params.conversation_view="on"==t.params.conversation_view,this.hasConversationViewChange=SYNO.SDS.MailClient.Settings.conversation_view!==t.params.conversation_view),Ext.isDefined(t.params.user_lang)&&(t.params.user_lang!=this.getUserLang()&&(SYNO.SDS.UserSettings.setProperty("Personal","lang",t.params.user_lang),this.blLangChanged=!0),delete t.params.user_lang);var e=Ext.getCmp(this.mailboxBtnId).getMailboxId();0!==e&&"starred"!==e&&(t.params.archive_mailbox=e)}},this),this.recordSMTPSignature(),!0===this.getForm().getValues().enable_signature){var i,n=this.getForm().findField("smtp_account").getStore();for(i in this.signature)this.signature.hasOwnProperty(i)&&n.getById(i)&&e.push({api:"SYNO.MailClient.Setting.SMTP",method:"set",version:"1",params:{id:parseInt(i,10),signature:this.signature[i]}})}return e},setFieldDisabled:function(t,e){var i=this.items.itemAt(0);e?i.getComponent(t).disable():i.getComponent(t).enable()},getUserLang:function(){return Ext.isDefined(SYNO.SDS.UserSettings.data.Personal)&&Ext.isDefined(SYNO.SDS.UserSettings.data.Personal.lang)?SYNO.SDS.UserSettings.data.Personal.lang:"def"}}),Ext.define("SYNO.SDS.MailClient.ReplySettingAddDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="createCustomAutoReply",this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:500};return Ext.apply(e,t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({itemId:"setting_panel",trackResetOnLoad:!0,items:[{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","mail_from"),emptyText:SYNO.SDS.MailClient._T("auto_reply","mail_from_hint"),name:"sender",maxlength:256,allowBlank:!1},{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),name:"subject",value:SYNO.SDS.MailClient._T("auto_reply","reply_subject"),maxlength:256,allowBlank:!1},{xtype:"syno_textarea",width:400,height:120,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","message"),name:"message",value:String.format(SYNO.SDS.MailClient._T("auto_reply","reply_msg"),"\r\n\r\n"),allowBlank:!1,listeners:{keydown:function(t,e,i){e.getKey()==e.ENTER&&e.stopPropagation()}}}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={};return e.sender=t.sender.trim(),e.subject=t.subject.trim(),e.message=t.message.trim(),!!(e.sender&&e.subject&&e.message)&&e},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.ReplySettingEditDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setCustomAutoReply";var e=t.targetInfo;if(!e)throw"no target";this.orgsender=e.sender,this.subject=e.subject,this.message=e.message,this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:500};return Ext.apply(e,t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({itemId:"setting_panel",trackResetOnLoad:!0,items:[{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","mail_from"),value:this.orgsender,emptyText:SYNO.SDS.MailClient._T("auto_reply","mail_from_hint"),name:"sender",maxlength:256,allowBlank:!1},{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),name:"subject",value:this.subject,maxlength:256,allowBlank:!1},{xtype:"syno_textarea",width:400,height:120,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","message"),name:"message",value:this.message,allowBlank:!1,listeners:{keydown:function(t,e,i){e.getKey()==e.ENTER&&e.stopPropagation()}}}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={};return e.orgsender=this.orgsender,e.sender=t.sender.trim(),e.subject=t.subject.trim(),e.message=t.message.trim(),e},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.Setting.AutoReply",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.ReplyDialog"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",function(t,e){new SYNO.SDS.Utils.EnableCheckGroup(this.getForm(),"forward_enable",["forward_addr","keep_copy"]),new SYNO.SDS.Utils.EnableCheckGroup(this.getForm(),"reply_enable",["reply_time","subject","message","reply_begin_time","reply_end_time",this.btnCustomReply])},this,{single:!0})},fillConfig:function(t){var e=SYNO.SDS.MailClient.Format.isDSM6()?"syno_datefield":"syno_datetimefield";this.btnCustomReply=Ext.id();var i={webapi:{api:"SYNO.MailClient.Setting.ForwardReply",methods:{get:"get",set:"set"},version:"1"},items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("auto_reply","desc_auto_reply")},{xtype:"syno_checkbox",htmlEncode:!1,boxLabel:SYNO.SDS.MailClient._T("auto_reply","enable_forward")+String.format('<span class="syno-mc-white-tip" ext:qtip="{0}"></span>',String.format(SYNO.SDS.MailClient._T("setting","redirects_desc"),SYNO.SDS.MailClient.Info.max_redirects)),name:"forward_enable",listeners:{scope:this,check:function(t,e){e&&this.getForm().findField("keep_copy").setValue(!0)}}},{xtype:"syno_textfield",indent:1,width:320,fieldLabel:SYNO.SDS.MailClient._T("filter","forward_to"),name:"forward_addr",maxlength:256,allowBlank:!1,validator:SYNO.SDS.MailClient.Format.IsValidForwardAddress},{xtype:"syno_checkbox",indent:1,boxLabel:SYNO.SDS.MailClient._T("auto_reply","keep_copy"),name:"keep_copy"},{xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("auto_reply","enable_reply"),name:"reply_enable"},{xtype:"syno_compositefield",indent:1,name:"reply_time",items:[{xtype:e,name:"reply_begin_time",fieldLabel:SYNO.SDS.MailClient._T("auto_reply","reply_time"),isAllDay:!0,dateFormat:"m/d/Y",format:"m/d/Y",width:157,emptyText:_T("log","date_from"),listeners:{scope:this,select:function(t,e){this.getForm().findField("reply_end_time").setMinValue(e)}}},{xtype:e,name:"reply_end_time",isAllDay:!0,dateFormat:"m/d/Y",format:"m/d/Y",width:157,emptyText:_T("log","date_to"),listeners:{scope:this,select:function(t,e){this.getForm().findField("reply_begin_time").setMaxValue(e)}}}]},{xtype:"syno_textfield",indent:1,width:320,fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),name:"subject",value:SYNO.SDS.MailClient._T("auto_reply","reply_subject"),maxlength:256,allowBlank:!1},{xtype:"syno_textarea",indent:1,width:320,height:120,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","message"),name:"message",value:String.format(SYNO.SDS.MailClient._T("auto_reply","reply_msg"),"\r\n\r\n"),allowBlank:!1},{height:10,border:!1},{xtype:"syno_button",id:this.btnCustomReply,indent:1,text:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply"),handler:function(){new SYNO.SDS.MailClient.ReplyDialog({owner:this.findWindow()}).show()},scope:this}]};return Ext.apply(i,t),i},processReturnData:function(t,e,i){if(e.has_fail)return void this.callParent(arguments);var n;if(Ext.each(e.result,function(t){if(t.api===this.webapi.api)return n=t.data,!1},this),n.reply_begin_time){var a=new Date;a.setTime(1e3*n.reply_begin_time),n.reply_begin_time=a}else n.reply_begin_time="";if(n.reply_end_time){var o=new Date;o.setTime(1e3*n.reply_end_time),n.reply_end_time=o}else n.reply_end_time="";""===n.message&&delete n.message,""===n.subject&&delete n.subject,this.callParent(arguments)},processParams:function(t,e){if("set"!==t)return e;var i;return Ext.each(e,function(t){if(t.api===this.webapi.api&&"set"===t.method)return i=t.params,!1},this),i.reply_begin_time?i.reply_begin_time=Date.parse(i.reply_begin_time)/1e3:delete i.reply_begin_time,i.reply_end_time?i.reply_end_time=Date.parse(i.reply_end_time)/1e3+86399:delete i.reply_end_time,e}}),Ext.define("SYNO.SDS.MailClient.ReplyDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.ReplyPanel"],constructor:function(t){this.panel=new SYNO.SDS.MailClient.ReplyPanel;var e=Ext.apply(t,{title:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply"),height:500,width:650,resizable:!1,layout:"fit",items:this.panel,buttons:[{xtype:"syno_button",btnStyle:"blue",text:_T("common","alt_finish"),handler:this.close,scope:this}]});this.callParent([e]),this.on("show",function(){this.panel.getStore().load()},this)}}),Ext.define("SYNO.SDS.MailClient.ReplyPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.ReplySettingAddDialog","SYNO.SDS.MailClient.ReplySettingEditDialog"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("auto_reply","empty_auto_reply"),this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=function(t,e){var i=Ext.util.Format.htmlEncode(t);return e.attr='ext:qtip="'+Ext.util.Format.htmlEncode(i)+'"',i},i={itemId:"replyPanel",height:400,enableHdMenu:!1,enableColumnMove:!1,autoExpandColumn:"reply_msg_column",loadMask:!0,tbar:this.getTbarCfg(),store:this.getStore(),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=this.getTopToolbar(),i=t.getSelections();1===i.length?e.getComponent("edit").enable():e.getComponent("edit").disable();var n=0<i.length;Ext.each(i,function(t){if(0===t.get("id"))return n=!1,!1},this),n?e.getComponent("delete").enable():e.getComponent("delete").disable()}}}),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),cm:new Ext.grid.ColumnModel({columns:[{id:"reply_sender_column",dataIndex:"sender",width:100,header:SYNO.SDS.MailClient._T("auto_reply","mail_from"),align:"left",renderer:e},{id:"reply_subject_column",dataIndex:"subject",width:300,header:SYNO.SDS.MailClient._T("mail","subject"),align:"left",renderer:e},{id:"reply_msg_column",dataIndex:"message",width:300,header:SYNO.SDS.MailClient._T("auto_reply","message"),align:"left",renderer:e}],defaults:{sortable:!1,menuDisabled:!1}}),listeners:{scope:this,rowdblclick:function(){1===this.getSelectionModel().getSelections().length&&this.onEdit()}}};return Ext.apply(i,t),i},getStore:function(){return this.store=this.store||new SYNO.API.Store({proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Setting.CustomAutoReply",method:"list",version:1,listeners:{scope:this,beforeload:function(t,e){var i=t.activeRequest.read;if(i)return void Ext.Ajax.abort(i);this.findWindow().setStatusBusy()},load:function(){this.findWindow().clearStatusBusy()}}}),reader:new Ext.data.JsonReader({root:"custom_auto_reply",totalProperty:"total",fields:["sender","subject","message"]})}),this.store},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),scope:this,handler:this.onCreate},{itemId:"edit",text:_T("common","alt_edit"),disabled:!0,scope:this,handler:this.onEdit},{itemId:"delete",text:_T("common","delete"),disabled:!0,scope:this,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),function(t){"yes"===t&&this.onDelete()},this)}}]}},onCreate:function(){new SYNO.SDS.MailClient.ReplySettingAddDialog({title:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply")+" - "+_T("common","add"),height:325,width:650,owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()},onDelete:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e,i,n){t.push(e.get("sender"))},this),0!==t.length)return this.findWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteCustomAutoReply({sender_list:t}).then(function(t){this.findWindow().clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy()}.bind(this))},onEdit:function(){new SYNO.SDS.MailClient.ReplySettingEditDialog({title:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply")+" - "+_T("common","alt_edit"),height:300,width:650,owner:this.findWindow(),targetInfo:this.getSelectionModel().getSelected().data,listeners:{scope:this,apply:function(){this.store.reload()}}}).open()}}),Ext.define("SYNO.SDS.MailClient.SMTPAddDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="createSMTP",this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",this.onBindCheckbox,this,{single:!0}),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:435};return Ext.apply(e,t)},stringNameValidator:function(t){return t.trim().length>0},emailValidator:function(t){return this.stringNameValidator(t)&&SYNO.SDS.MailClient.Format.isAddrSpec(t)},isLocalhost:function(){var t=this.formPanel.getComponent("host_name").getValue();return t.trim().startsWith("127.")||"LOCALHOST"===t.trim().toUpperCase()},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"host_name",name:"host_name",validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!0)},width:250,allowBlank:!1,fieldLabel:_T("notification","alert_smtp")},{xtype:"syno_textfield",itemId:"port",name:"port",width:250,allowBlank:!1,value:25,fieldLabel:_T("notification","alert_port"),vtype:"port"},{xtype:"syno_checkbox",itemId:"enable_auth_checkbox",name:"auth",boxLabel:_T("notification","alert_smtp_need_auth")},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",validator:this.stringNameValidator,width:250,allowBlank:!1,indent:1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",width:250,inputType:"password",indent:1,fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"tls",name:"tls",width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_tls"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("ssl").setValue(!1),this.formPanel.getComponent("port").setValue(587)}},{xtype:"syno_checkbox",itemId:"ssl",name:"ssl",width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_ssl"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("tls").setValue(!1),this.formPanel.getComponent("port").setValue(465)}},{xtype:"syno_textfield",itemId:"mail",name:"mail",width:250,allowBlank:!1,validator:this.emailValidator.bind(this),fieldLabel:_T("notification","label_smtp_sender_mail")},{xtype:"syno_textfield",itemId:"display_name",name:"display_name",validator:this.stringNameValidator,width:250,fieldLabel:_T("notification","label_smtp_sender_name")}]}),this.formPanel},onBindCheckbox:function(){new SYNO.ux.Utils.EnableCheckGroup(this.getFormPanel().getForm(),"auth",["user_name","password"])},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={},i=0;return"true"===t.tls?i=1:"true"===t.ssl&&(i=2),e.display_name=t.display_name.trim(),e.mail=t.mail.trim(),e.host_name=t.host_name.trim(),e.port=parseInt(t.port,10),"true"===t.auth&&(e.user_name=t.user_name.trim(),e.password=t.password?t.password:""),e.connection_type=i,!!(e.display_name&&e.mail&&e.host_name&&Ext.isNumber(e.port))&&e},onApply:function(){if(this.isLocalhost()&&!1===this.formPanel.getComponent("enable_auth_checkbox").getValue())return void this.setStatusError({text:SYNO.SDS.MailClient._T("error","auth_is_required")});this.clearStatus(),this.callParent(arguments)},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.SMTPEditDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setSMTP";var e=t.targetInfo;if(!e)throw"no target";this.info_id=e.id,this.is_localhost=this.info_id<0,this.display_name=e.display_name,this.mail=e.mail,this.host_name=e.host_name,this.port=e.port,this.user_name=e.user_name,this.password=Ext.isEmpty(this.user_name)?void 0:"\t\t\t\t\t\t\t\t",this.connection_type=e.connection_type,delete t.targetInfo,this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",this.onBindCheckbox,this,{single:!0}),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:435};return Ext.apply(e,t)},isLocalhost:function(){var t=this.formPanel.getComponent("host_name").getValue();return t.trim().startsWith("127.")||"LOCALHOST"===t.trim().toUpperCase()},stringNameValidator:function(t){return t.trim().length>0},emailValidator:function(t){return this.stringNameValidator(t)&&SYNO.SDS.MailClient.Format.isAddrSpec(t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"host_name",name:"host_name",width:250,value:this.host_name,disabled:this.is_localhost,validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!0)},allowBlank:!1,fieldLabel:_T("notification","alert_smtp")},{xtype:"syno_textfield",itemId:"port",name:"port",value:String(this.port),disabled:this.is_localhost,width:250,allowBlank:!1,fieldLabel:_T("notification","alert_port"),vtype:"port"},{xtype:"syno_checkbox",itemId:"enable_auth_checkbox",name:"auth",checked:!Ext.isEmpty(this.user_name),disabled:this.is_localhost,boxLabel:_T("notification","alert_smtp_need_auth")},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",value:this.user_name,disabled:this.is_localhost,validator:this.stringNameValidator,width:250,allowBlank:!1,indent:1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",value:this.password,disabled:this.is_localhost,width:250,inputType:"password",indent:1,fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"tls",name:"tls",checked:1===this.connection_type,disabled:this.is_localhost,width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_tls"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("ssl").setValue(!1),this.formPanel.getComponent("port").setValue(587)}},{xtype:"syno_checkbox",itemId:"ssl",name:"ssl",checked:2===this.connection_type,disabled:this.is_localhost,width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_ssl"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("tls").setValue(!1),this.formPanel.getComponent("port").setValue(465)}},{xtype:"syno_textfield",itemId:"mail",name:"mail",value:this.mail,disabled:this.is_localhost,validator:this.emailValidator.bind(this),width:250,allowBlank:!1,fieldLabel:_T("notification","label_smtp_sender_mail")},{xtype:"syno_textfield",itemId:"display_name",name:"display_name",disabled:this.is_localhost&&SYNO.SDS.MailClient.AdminSettings.SMTP.disable_smtp_sender_name,value:this.display_name,validator:this.stringNameValidator,width:250,fieldLabel:_T("notification","label_smtp_sender_name")}]}),this.formPanel},onBindCheckbox:function(){if(!this.is_localhost){new SYNO.ux.Utils.EnableCheckGroup(this.getFormPanel().getForm(),"auth",["user_name","password"])}},getParams:function(){var t,e=this.getFormPanel().getForm().getValues(),i={},n=0;return"true"===e.tls?n=1:"true"===e.ssl&&(n=2),i.id=this.info_id,e.display_name&&(t=e.display_name.trim())&&t!=this.display_name&&(i.display_name=t),e.mail&&(t=e.mail.trim())&&t!=this.mail&&(i.mail=t),e.host_name&&(t=e.host_name.trim())&&t!=this.host_name&&(i.host_name=t),e.port&&parseInt(e.port,10)!=this.port&&(i.port=parseInt(e.port,10)),"true"===e.auth?(e.user_name&&(t=e.user_name.trim())&&t!=this.user_name&&(i.user_name=t),this.password!==e.password&&(i.password=e.password)):Ext.isEmpty(this.user_name)||this.is_localhost||(i.user_name="",i.password=""),n!=this.connection_type&&(i.connection_type=n),i},onApply:function(){if(0<this.info_id&&this.isLocalhost()&&!1===this.formPanel.getComponent("enable_auth_checkbox").getValue())return void this.setStatusError({text:SYNO.SDS.MailClient._T("error","auth_is_required")});this.clearStatus(),this.callParent(arguments)},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.Setting.SMTP",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.SMTPAddDialog","SYNO.SDS.MailClient.SMTPEditDialog"],constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={autoExpandColumn:"host_name",enableColumnMove:!1,tbar:this.getTbarCfg(),store:t.smtpStore,sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=this.getTopToolbar(),i=t.getSelections();1===i.length?e.getComponent("edit").enable():e.getComponent("edit").disable(),1===i.length&&i[0].id!=SYNO.SDS.MailClient.SMTP.smtp_default_id?e.getComponent("set_default").enable():e.getComponent("set_default").disable();var n=0<i.length;Ext.each(i,function(t){if(0>t.get("id"))return n=!1,!1},this),n?e.getComponent("delete").enable():e.getComponent("delete").disable()}}}),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),colModel:new Ext.grid.ColumnModel({columns:[{header:_T("notification","label_smtp_sender_mail"),dataIndex:"mail",align:"left",menuDisabled:!0,width:100},{header:SYNO.SDS.MailClient._T("smtp","set_default"),dataIndex:"id",align:"left",menuDisabled:!0,width:100,renderer:function(t,e,i){return t===SYNO.SDS.MailClient.SMTP.smtp_default_id?SYNO.SDS.MailClient._T("smtp","default"):""}}]}),listeners:{scope:this,rowdblclick:function(){1===this.getSelectionModel().getSelections().length&&this.onSMTPEdit()}}};return Ext.apply(e,t),e},onSMTPEdit:function(){new SYNO.SDS.MailClient.SMTPEditDialog({targetInfo:this.getSelectionModel().getSelected().data,owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()},onSMTPSetDefault:function(){if(this.getSelectionModel().hasSelection())return this.findWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.setDefaultSMTP({id:this.getSelectionModel().getSelected().data.id}).then(function(t){this.findWindow().clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy()}.bind(this))},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),scope:this,handler:function(){new SYNO.SDS.MailClient.SMTPAddDialog({owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()}},{itemId:"edit",text:_T("common","alt_edit"),disabled:!0,scope:this,handler:this.onSMTPEdit},{itemId:"delete",text:_T("common","delete"),disabled:!0,scope:this,handler:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length)return this.findWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteSMTP({id:t}).then(function(t){this.findWindow().clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy()}.bind(this))}},{itemId:"set_default",text:SYNO.SDS.MailClient._T("smtp","default"),disabled:!0,scope:this,handler:this.onSMTPSetDefault}]}}}),Ext.define("SYNO.SDS.MailClient.POP3AddDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="createPOP3",this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:530};return Ext.apply(e,t)},stringNameValidator:function(t){return t.trim().length>0},fetchDaysValidator:function(t){var e=new Date;return!(t<1)&&!(parseInt(e.getTime()/1e3,10)-24*t*60*60<0)},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define,e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[-1,SYNO.SDS.MailClient._T("pop","custom_pop")],[0,SYNO.SDS.MailClient._T("pop","provider_yahoo")],[1,SYNO.SDS.MailClient._T("pop","provider_gmail")],[2,SYNO.SDS.MailClient._T("pop","provider_outlook")],[3,SYNO.SDS.MailClient._T("pop","provider_qq")]]});return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"mail",name:"mail",width:250,allowBlank:!1,validator:function(t){return SYNO.SDS.MailClient.Format.isAddrSpec(t)||_JSLIBSTR("extlang","emailText")},fieldLabel:SYNO.SDS.MailClient._T("pop","email_address")},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"server_provider",fieldLabel:SYNO.SDS.MailClient._T("pop","service_provider"),mode:"local",store:e,displayField:"display",valueField:"value",value:-1,listeners:{scope:this,select:function(t,e){if(-1<e.data.value){var i=this.serverProviderConfig(e.data.value);this.formPanel.getComponent("host_name").hide().setValue(i.host_name),this.formPanel.getComponent("port").hide().setValue(i.port),this.formPanel.getComponent("enable_ssl").hide().setValue(!0),this.formPanel.getComponent("verify_cert").hide().setValue(!0)}else this.formPanel.getComponent("host_name").show().setValue(""),this.formPanel.getComponent("port").show().setValue(110),this.formPanel.getComponent("enable_ssl").show().setValue(!1),this.formPanel.getComponent("verify_cert").show().setValue(!0)}}},{xtype:"syno_textfield",itemId:"host_name",name:"host_name",validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!1)},width:250,allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_server")},{xtype:"syno_textfield",itemId:"port",name:"port",width:250,allowBlank:!1,value:110,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_port"),vtype:"port"},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",validator:this.stringNameValidator,width:250,allowBlank:!1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",width:250,inputType:"password",fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"enable_ssl",name:"enable_ssl",width:400,boxLabel:SYNO.SDS.MailClient._T("pop","use_secure_connection"),scope:this,handler:function(t,e){if(!e)return this.formPanel.getComponent("verify_cert").disable(),void this.formPanel.getComponent("port").setValue(110);this.formPanel.getComponent("verify_cert").enable(),this.formPanel.getComponent("verify_cert").setValue(!0),this.formPanel.getComponent("port").setValue(995)}},{xtype:"syno_checkbox",itemId:"verify_cert",name:"verify_cert",disabled:!0,indent:1,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","verify_cert"),scope:this},{xtype:"syno_checkbox",itemId:"delete_after_fetch",name:"delete_after_fetch",width:400,boxLabel:SYNO.SDS.MailClient._T("pop","remove_original_copy"),scope:this},{xtype:"syno_compositefield",hideLabel:!0,width:450,items:[{xtype:"syno_displayfield",
value:SYNO.SDS.MailClient._T("pop","select_mailbox"),width:180},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:SYNO.SDS.MailClient._T("mailbox","inbox"),value:SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t.inboxId).data.path,width:250,menuCfg:{width:250,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.junkId,t.draftsId,t.trashId,t.starredId]},listeners:{scope:this,change:function(t){var e=function(e,i,n){if(!n)return!1;Ext.getCmp(this.mailboxBtnId).value=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t).data.path};SYNO.SDS.MailClient.Switch.getMailboxStore().load({callback:e,scope:this})}}}]},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","select_fetch_days"),width:360},{xtype:"syno_compositefield",hideLabel:!0,indent:1,width:400,items:[{xtype:"syno_radio",checked:!0,inputValue:"recent",boxLabel:SYNO.SDS.MailClient._T("pop","fetch_recently"),name:"fetchmail_config",width:150,listeners:{scope:this,check:function(t,e){e?Ext.getCmp(this.fetchDaysId).enable():Ext.getCmp(this.fetchDaysId).disable()}}},{xtype:"syno_numberfield",id:this.fetchDaysId=Ext.id(),allowBlank:!1,width:200,value:7,validator:this.fetchDaysValidator},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","fetch_days")}]},{xtype:"syno_radio",itemId:"all_message",inputValue:"all",boxLabel:SYNO.SDS.MailClient._T("pop","fetch_all"),indent:1,name:"fetchmail_config"},{xtype:"syno_radio",itemId:"new_message",inputValue:"new",boxLabel:SYNO.SDS.MailClient._T("pop","fetch_only_new"),indent:1,name:"fetchmail_config"}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={},i=new Date;return e.mail=t.mail.trim(),e.server_provider=parseInt(t.server_provider,10),e.host_name=t.host_name.trim(),e.port=parseInt(t.port,10),e.user_name=t.user_name.trim(),e.password=t.password?t.password:"",e.enable_ssl="true"===t.enable_ssl,e.verify_cert="true"===t.verify_cert,e.delete_after_fetch="true"===t.delete_after_fetch,e.mailbox_path=Ext.getCmp(this.mailboxBtnId).value,this.getFormPanel().getComponent("new_message").getValue()?e.fetch_begin_date=parseInt(i.getTime()/1e3,10):this.getFormPanel().getComponent("all_message").getValue()?e.fetch_begin_date=-1:e.fetch_begin_date=parseInt(i.getTime()/1e3,10)-24*Ext.getCmp(this.fetchDaysId).getValue()*60*60,!!(e.mail&&e.host_name&&Ext.isNumber(e.port)&&e.user_name&&e.mailbox_path)&&e},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},serverProviderConfig:function(t){return[{host_name:"pop.mail.yahoo.com",port:995},{host_name:"pop.gmail.com",port:995},{host_name:"pop-mail.outlook.com",port:995},{host_name:"pop.qq.com",port:995}][t]}}),Ext.define("SYNO.SDS.MailClient.POP3EditDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setPOP3";var e=t.targetInfo;if(!e)throw"no target";this.info_id=e.id,this.is_localhost=0===this.info_id,this.mail=e.mail,this.server_provider=e.server_provider,this.host_name=e.host_name,this.port=e.port,this.user_name=e.user_name,this.password=Ext.isEmpty(this.user_name)?void 0:"\t\t\t\t\t\t\t\t",this.enable_ssl=e.enable_ssl,this.verify_cert=e.verify_cert,this.delete_after_fetch=e.delete_after_fetch,this.mailbox_path=e.mailbox_path,delete t.targetInfo,this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:400};return Ext.apply(e,t)},stringNameValidator:function(t){return t.trim().length>0},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define,e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[-1,SYNO.SDS.MailClient._T("pop","custom_pop")],[0,SYNO.SDS.MailClient._T("pop","provider_yahoo")],[1,SYNO.SDS.MailClient._T("pop","provider_gmail")],[2,SYNO.SDS.MailClient._T("pop","provider_outlook")],[3,SYNO.SDS.MailClient._T("pop","provider_qq")]]});return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"mail",name:"mail",width:250,value:this.mail,allowBlank:!1,validator:function(t){return SYNO.SDS.MailClient.Format.isAddrSpec(t)||_JSLIBSTR("extlang","emailText")},fieldLabel:SYNO.SDS.MailClient._T("pop","email_address")},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"server_provider",fieldLabel:SYNO.SDS.MailClient._T("pop","service_provider"),mode:"local",store:e,displayField:"display",valueField:"value",value:this.server_provider,listeners:{scope:this,select:function(t,e){if(-1<e.data.value){var i=this.serverProviderConfig(e.data.value);this.formPanel.getComponent("host_name").hide().setValue(i.host_name),this.formPanel.getComponent("port").hide().setValue(i.port),this.formPanel.getComponent("enable_ssl").hide().setValue(!0),this.formPanel.getComponent("verify_cert").hide().setValue(!0)}else this.formPanel.getComponent("host_name").show().setValue(""),this.formPanel.getComponent("port").show().setValue(110),this.formPanel.getComponent("enable_ssl").show().setValue(!1),this.formPanel.getComponent("verify_cert").show().setValue(!1)},afterrender:function(t){-1<t.value&&(this.formPanel.getComponent("host_name").hide(),this.formPanel.getComponent("port").hide(),this.formPanel.getComponent("enable_ssl").hide(),this.formPanel.getComponent("verify_cert").hide())}}},{xtype:"syno_textfield",itemId:"host_name",name:"host_name",width:250,value:this.host_name,validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!1)},allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_server")},{xtype:"syno_textfield",itemId:"port",name:"port",value:this.port,width:250,allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_port"),vtype:"port"},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",value:this.user_name,validator:this.stringNameValidator,width:250,allowBlank:!1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",value:this.password,width:250,inputType:"password",fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"enable_ssl",name:"enable_ssl",checked:this.enable_ssl,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","use_secure_connection"),scope:this,handler:function(t,e){if(!e)return this.formPanel.getComponent("verify_cert").disable(),void this.formPanel.getComponent("port").setValue(110);this.formPanel.getComponent("verify_cert").enable(),this.formPanel.getComponent("port").setValue(995)}},{xtype:"syno_checkbox",itemId:"verify_cert",name:"verify_cert",disabled:!this.enable_ssl,indent:1,checked:this.verify_cert,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","verify_cert"),scope:this},{xtype:"syno_checkbox",itemId:"delete_after_fetch",name:"delete_after_fetch",checked:this.delete_after_fetch,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","remove_original_copy"),scope:this},{xtype:"syno_compositefield",hideLabel:!0,width:450,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","select_mailbox"),width:180},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:Ext.util.Format.htmlEncode(t.isSystemMailboxName(this.mailbox_path)?t.getSystemMailboxNameString(this.mailbox_path):this.mailbox_path.split(".")[this.mailbox_path.split(".").length-1]),value:this.mailbox_path,width:250,menuCfg:{width:250,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.junkId,t.draftsId,t.trashId,t.starredId]},listeners:{scope:this,change:function(t){var e=function(e,i,n){if(!n)return!1;Ext.getCmp(this.mailboxBtnId).value=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t).data.path};SYNO.SDS.MailClient.Switch.getMailboxStore().load({callback:e,scope:this})}}}]}]}),this.formPanel},getParams:function(){var t,e=this.getFormPanel().getForm().getValues(),i={};return i.id=this.info_id,e.mail&&(t=e.mail.trim())&&t!=this.mail&&(i.mail=t),e.server_provider&&parseInt(e.server_provider,10)!=this.server_provider&&(i.server_provider=parseInt(e.server_provider,10)),e.host_name&&(t=e.host_name.trim())&&t!=this.host_name&&(i.host_name=t),e.port&&parseInt(e.port,10)!=this.port&&(i.port=parseInt(e.port,10)),e.user_name&&(t=e.user_name.trim())&&t!=this.user_name&&(i.user_name=t),e.password&&(t=e.password.trim())&&t!=this.password&&(i.password=t),e.enable_ssl&&(t="true"==e.enable_ssl)!=this.enable_ssl&&(i.enable_ssl=t),e.verify_cert&&(t="true"==e.verify_cert)!=this.verify_cert&&(i.verify_cert=t),e.delete_after_fetch&&(t="true"==e.delete_after_fetch)!=this.delete_after_fetch&&(i.delete_after_fetch=t),Ext.getCmp(this.mailboxBtnId).value&&Ext.getCmp(this.mailboxBtnId).value!=this.mailbox_path&&(i.mailbox_path=Ext.getCmp(this.mailboxBtnId).value),i},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},serverProviderConfig:function(t){return[{host_name:"pop.mail.yahoo.com",port:995},{host_name:"pop.gmail.com",port:995},{host_name:"pop-mail.outlook.com",port:995},{host_name:"pop.qq.com",port:995}][t]}}),Ext.define("SYNO.SDS.MailClient.Setting.POP3",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.POP3AddDialog","SYNO.SDS.MailClient.POP3EditDialog"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("setting","empty_pop3"),this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=SYNO.SDS.MailClient.Define,i={autoExpandColumn:"mail",enableColumnMove:!1,tbar:this.getTbarCfg(),store:this.getStore(),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=this.getTopToolbar(),i=t.getSelections();1===i.length?e.getComponent("edit").enable():e.getComponent("edit").disable();var n=0<i.length;Ext.each(i,function(t){if(0===t.get("id"))return n=!1,!1},this),n?e.getComponent("delete").enable():e.getComponent("delete").disable()}}}),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),colModel:new Ext.grid.ColumnModel({columns:[{header:SYNO.SDS.MailClient._T("pop","email_address"),dataIndex:"mail",align:"left",menuDisabled:!0,width:100},{header:SYNO.SDS.MailClient._T("common","mailbox"),dataIndex:"mailbox_path",align:"left",menuDisabled:!0,width:100,renderer:function(t){var i=e.isSystemMailboxName(t)?e.getSystemMailboxNameString(t):t.split(".")[t.split(".").length-1];return Ext.util.Format.htmlEncode(i)}},{header:SYNO.SDS.MailClient._T("pop","fetch_begin_date_title"),dataIndex:"fetch_begin_date",align:"left",menuDisabled:!0,width:200,renderer:function(t){if(-1===t)return SYNO.SDS.MailClient._T("pop","fetch_all");var e=new Date(1e3*t);return String.format(SYNO.SDS.MailClient._T("pop","fetch_begin_date"),e.format("m/d/Y"))}}]}),listeners:{scope:this,activate:function(){this.store.load()},rowdblclick:function(){1===this.getSelectionModel().getSelections().length&&this.onPOP3Edit()}}};return Ext.apply(i,t),i},getStore:function(){return this.store=this.store||new SYNO.API.Store({method:"POST",reader:new Ext.data.JsonReader({root:"pop3",totalProperty:"total",fields:["id","mail","server_provider","host_name","port","user_name","enable_ssl","verify_cert","delete_after_fetch","mailbox_path","fetch_begin_date"]}),load:function(){return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listPOP3").then(function(t){this.store.loadData(t)}.bind(this)).catch(function(t){this.owner.clearStatusBusy(),this.owner.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(t),clear:!0})}.bind(this))}.bind(this),listeners:{scope:this,load:function(t,e,i){this.owner.clearStatusBusy()}}}),this.store},onPOP3Edit:function(){new SYNO.SDS.MailClient.POP3EditDialog({targetInfo:this.getSelectionModel().getSelected().data,owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),scope:this,handler:function(){new SYNO.SDS.MailClient.POP3AddDialog({owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()}},{itemId:"edit",text:_T("common","alt_edit"),disabled:!0,scope:this,handler:this.onPOP3Edit},{itemId:"delete",text:_T("common","delete"),disabled:!0,scope:this,handler:function(){var t=[],e=this.getSelectionModel().getSelections();Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length&&(this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deletePOP3({id:t}).then(function(t){this.owner.clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.owner.clearStatusBusy(),this.owner.setStatusError({text:SYNO.SDS.MailClient._T("api_error","pop_error"),clear:!0})}.bind(this)))}}]}}}),Ext.define("SYNO.SDS.MailClient.Grid.TreeView",{extend:"SYNO.ux.FleXcroll.grid.TreeView",constructor:function(t){this.callParent(arguments)},hideCollapseNodes:function(){for(var t,e,i,n=this.grid,a=n.store,o=n.view,s=0;s<a.getCount();)t=o.getRow(s),e=a.getAt(t.rowIndex).node,e&&!e.isLeaf()&&!1===e.expanded&&(i=Ext.fly(t).next(".x-tree-node-ct",!1))&&i.setStyle({display:"none"}),e&&e.attributes.isFakeNode&&Ext.fly(t).addClass("fake-node"),s++},toggleNode:function(t){var e=Ext.get(this.findRow(t)),i=this.grid.getStore().getAt(e.dom.rowIndex).node,n=e.next(".x-tree-node-ct",!1),a=e.child(".syno-gridtree-node-control",!1);n&&a&&(i.expanded?(n.enableDisplayMode("block"),n.stopFx(),e.removeClass("x-tree-node-expanded"),a.removeClass(i.isLast()?"x-tree-elbow-end-minus":"x-tree-elbow-minus"),e.addClass("x-tree-node-collapsed"),a.addClass(i.isLast()?"x-tree-elbow-end-plus":"x-tree-elbow-plus"),n.slideOut("t",{callback:function(){i.expanded=!1,this.updateScroller()},scope:this,duration:.25})):(n.stopFx(),e.addClass("x-tree-node-expanded"),a.addClass(i.isLast()?"x-tree-elbow-end-minus":"x-tree-elbow-minus"),e.removeClass("x-tree-node-collapsed"),a.removeClass(i.isLast()?"x-tree-elbow-end-plus":"x-tree-elbow-plus"),n.slideIn("t",{callback:function(){i.expanded=!0,this.updateScroller()},scope:this,duration:.25})))}}),Ext.define("SYNO.SDS.MailClient.Setting.Mailbox",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",xtype:"mc_MailboxSettingGridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.Grid.TreeView"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("setting","empty_mailbox"),this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=new SYNO.ux.EnableColumn({header:_T("common","hide"),dataIndex:"hide",width:50,menuDisabled:!0,align:"center",listeners:{scope:this,click:this.onHideColumnClick},scope:this,renderer:function(t,e,i){return i.id===SYNO.SDS.MailClient.Define.inboxId?"":this.renderCheckBox(t,e,i)}}),i={cls:"mailbox-grid",autoExpandColumn:"name",enableColumnMove:!1,tbar:this.getTbarCfg(),store:this.getStore(),view:new SYNO.SDS.MailClient.Grid.TreeView({useArrows:!0,staticTree:!1}),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=SYNO.SDS.MailClient.Define,i=t.getSelections(),n=!0,a=!0,o=!0;Ext.each(i,function(t){if((t.node.attributes.isFakeNode||-1!==[e.draftsId,e.sentId,e.junkId,e.trashId].indexOf(t.id))&&(n=a=o=!1),t.id===SYNO.SDS.MailClient.Settings.archive_mailbox&&(o=a=!1),SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable&&!t.node.attributes.has_permission&&(o=!1),t.id===e.inboxId||t.node.findChild("id",SYNO.SDS.MailClient.Settings.archive_mailbox,!0))return a=!1,!1}),this.getTopToolbar().getComponent("add").setDisabled(!n),this.getTopToolbar().getComponent("delete").setDisabled(!(t.hasSelection()&&a)),this.getTopToolbar().getComponent("edit").setDisabled(1!==i.length||!a),this.getTopToolbar().getComponent("sharing").setDisabled(1!==i.length||!o)}}}),colModel:new Ext.grid.ColumnModel({columns:[{header:SYNO.SDS.MailClient._T("common","mailbox"),dataIndex:"name",align:"left",width:100,treeCol:!0,menuDisabled:!0,renderer:function(t,e,i){return t}},e]}),plugins:[e],listeners:{scope:this,activate:{fn:this.loadMailbox,single:!0}}};return Ext.apply(i,t),i},_hasMailboxSharedToOthers:function(){return this.store.findBy(function(t){return t.node.attributes&&t.node.attributes.has_permission})>-1},loadMailbox:function(){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(t){var e=SYNO.SDS.MailClient.Format.parseMailboxResp(t,null,null,null,!0);this.store.loadData(e),this.getTopToolbar().getComponent("sharing").setVisible(!SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable||this._hasMailboxSharedToOthers())}.bind(this))},getStore:function(){return this.store=this.store||new Ext.data.Store({autoDestroy:!0,method:"GET",idProperty:"id",totalProperty:"total",pruneModifiedRecords:!0,reader:new SYNO.ux.data.TreeReader({root:"",fields:[{name:"name",mapping:"text"},{name:"hide",convert:function(t,e){return!e.attributes.data.subscribed}}]})}),this.store},onHideColumnClick:function(t,e,i,n){var a,o,s=i,l=this.store.getAt(s);if(l.get("hide")){for(a=s+1;a<this.store.getCount();++a)if(o=this.store.getAt(a),o.depth>l.depth)o.set("hide",!0);else if(o.depth<=l.depth)break}else for(a=s-1;a>=0;--a)(o=this.store.getAt(a))&&o.depth<l.depth&&(o.set("hide",!1),l=o)},onChange:function(t,e,i,n,a){this.loadMailbox()},getExtraActions:function(){var t=[];return this.store.getModifiedRecords().forEach(function(e){Ext.isString(e.id)||t.push({api:"SYNO.MailClient.Mailbox",method:"set",params:{id:e.id,subscribed:!e.get("hide")},version:6})},this),t},isDirty:function(){return this.store.getModifiedRecords().length>0},onAddMailbox:function(){var t,e={},i=this.getSelectionModel().getSelections();e.id=1!=i.length?0:i[0].node.attributes.data.id,e.name=1!=i.length?SYNO.SDS.MailClient._T("common","mailbox"):i[0].get("name"),t=new SYNO.SDS.MailClient.AddMailbox({targetInfo:e,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.open()},onEditMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.EditMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onDeleteMailbox:function(){var t=this.getSelectionModel().getSelections(),e=[];this.owner.setStatusBusy({text:_T("common","msg_waiting")}),Ext.each(t,function(t,i,n){e.push(t.node.attributes.data.id)},this),SYNO.SDS.MailClient.Control.Sidebar.deleteMailbox(e).then(function(t){this.owner.clearStatusBusy(),this.loadMailbox()}.bind(this))},onSharingMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.SharingMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onMailboxActionDoneCb:function(t,e,i,n,a){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),handler:this.onAddMailbox,itemId:"add"},{text:_T("common","alt_edit"),handler:this.onEditMailbox,itemId:"edit",disabled:!0},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("mailbox","delete_confirm"),function(t){"yes"===t&&this.onDeleteMailbox()},this)}},{text:SYNO.SDS.MailClient._T("mailbox","sharing_and_permission"),itemId:"sharing",disabled:!0,handler:this.onSharingMailbox}]}}}),Ext.define("SYNO.SDS.MailClient.Setting.SharedMailbox",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",xtype:"mc_OthersMailboxSettingGridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.Grid.TreeView"],enableColumnIdx:2,constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=new SYNO.ux.EnableColumn({header:SYNO.SDS.MailClient._T("common","subscribe"),dataIndex:"subscribed",menuDisabled:!0,align:"center",fixed:!0,listeners:{scope:this,click:this.onSubscribeColumnClick}}),i={cls:"mailbox-grid",tbar:this.getTbarCfg(),region:"center",autoExpandColumn:"name",enableColumnMove:!1,store:this.getStore(),view:new SYNO.SDS.MailClient.Grid.TreeView({useArrows:!0,staticTree:!1,hideCollapseNodes:function(){for(var t,e,i,n=this.grid,a=n.store,o=n.view,s=0;s<a.getCount();)t=o.getRow(s),e=a.getAt(t.rowIndex).node,e&&!e.isLeaf()&&!1===e.expanded&&(i=Ext.fly(t).next(".x-tree-node-ct",!1))&&i.setStyle({display:"none"}),s++}}),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=t.getSelections(),i=!0,n=!0,a=!0,o=!0,s=SYNO.SDS.MailClient.Define;Ext.each(e,function(t){if(s.isUserOrGroupNodeInMailboxList(t))return i=n=a=o=!1,!1;var e=s.getMailboxPermissionById(t.id),l=t.node.attributes.data.name,r=t.node.attributes.has_permission,d=t.get("parent_id");SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable&&!r&&(o=!1),i=i&&s.isMailboxAddable(e,l),n=n&&s.isMailboxDeletable(e,l),a=a&&s.isMailboxEditable(e,d),o=o&&s.isMailboxShareable(e)}),this.getTopToolbar().getComponent("add").setDisabled(1!==e.length||!i),this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection()||!n),this.getTopToolbar().getComponent("edit").setDisabled(1!==e.length||!a),this.getTopToolbar().getComponent("sharing").setDisabled(1!==e.length||!o)}}}),colModel:new Ext.grid.ColumnModel({defaultWidth:150,columns:[{header:SYNO.SDS.MailClient._T("common","mailbox"),dataIndex:"name",align:"left",treeCol:!0,menuDisabled:!0,resizable:!1,renderer:function(t,e,i){return t}},{header:SYNO.SDS.MailClient._T("mailbox","permission"),dataIndex:"my_permission",align:"left",fixed:!0},e]}),plugins:[e],listeners:{scope:this,afterrender:{fn:this.loadMailbox,single:!0},activate:{fn:this.handleMask},viewready:function(){this.view.hideCollapseNodes()}}};return Ext.apply(i,t),i},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),itemId:"add",handler:this.onAddMailbox,disabled:!0},{text:_T("common","alt_edit"),handler:this.onEditMailbox,itemId:"edit",disabled:!0},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("mailbox","delete_confirm"),function(t){"yes"===t&&this.onDeleteMailbox()},this)}},{text:SYNO.SDS.MailClient._T("mailbox","sharing_and_permission"),itemId:"sharing",disabled:!0,handler:this.onSharingMailbox}]}},onAddMailbox:function(){var t,e={},i=this.getSelectionModel().getSelections();e.id=1!=i.length?0:i[0].node.attributes.data.id,e.name=1!=i.length?SYNO.SDS.MailClient._T("common","mailbox"):i[0].get("name"),t=new SYNO.SDS.MailClient.AddMailbox({targetInfo:e,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.open()},onEditMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.EditShareMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onDeleteMailbox:function(){var t=this.getSelectionModel().getSelections(),e=[];this.owner.setStatusBusy({text:_T("common","msg_waiting")}),Ext.each(t,function(t,i,n){e.push(t.node.attributes.data.id)},this),SYNO.SDS.MailClient.Control.Sidebar.deleteMailbox(e).then(function(t){this.owner.clearStatusBusy(),this.loadMailbox()}.bind(this))},onSharingMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.SharingMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onMailboxActionDoneCb:function(t,e,i,n,a){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},_hasMailboxSharedToOthers:function(){return this.store.findBy(function(t){return t.node.attributes&&t.node.attributes.has_permission})>-1},loadMailbox:function(){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(t){var e=SYNO.SDS.MailClient.Format.parseOthersMailboxResp(t,null,null,null,!0),i=[];Ext.each(e,function(t,e,n){if(t.id<0)return!0;i.push(t)},this),this.store.loadData(i),this.checkUserGroupNodeStatus(),this.getTopToolbar().getComponent("sharing").setVisible(!SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable||this._hasMailboxSharedToOthers())}.bind(this))},handleMask:function(){0===this.store.getCount()?this.el.mask(SYNO.SDS.MailClient._T("setting","no_mailbox_share_to_you")):this.el.unmask()},getStore:function(){return this.store=this.store||new Ext.data.Store({autoDestroy:!0,method:"GET",idProperty:"id",totalProperty:"total",pruneModifiedRecords:!0,reader:new SYNO.ux.data.TreeReader({root:"",fields:[{name:"name",mapping:"text"},{name:"subscribed",convert:function(t,e){return!Ext.isString(e.id)&&e.attributes.data.subscribed}},{name:"parent_id",mapping:"parent_id"},{name:"my_permission",mapping:"my_permission",convert:function(t,e){var i=SYNO.SDS.MailClient.Define.MailboxPermission;return t===i.READ_ONLY?_T("nfs","nfs_read_only"):t===i.READ_WRITE?_T("nfs","nfs_read_write"):t===i.ADMIN?SYNO.SDS.MailClient._T("mailbox","admin"):""}}]}),listeners:{scope:this,load:this.handleMask}}),this.store},onSubscribeColumnClick:function(t,e,i,n){var a,o,s=i,l=this.store.getAt(s);if(Ext.isString(l.id)){for(a=s+1;a<this.store.getCount()&&(o=this.store.getAt(a),!(o.depth<=l.depth));++a)o.set("subscribed",l.get("subscribed"));return void this.checkEnableColumnHeaderStatus()}this.checkUserGroupNodeStatus()},checkUserGroupNodeStatus:function(){var t,e,i,n,a,o,s,l;for(i=0;i<this.store.getCount();++i)if(s=0,l=0,t=this.store.getAt(i),Ext.isString(t.id)){for(n=i+1;n<this.store.getCount()&&((e=this.store.getAt(n))&&!(e.depth<=t.depth));++n)!0===e.get("subscribed")?s++:l++;var r=n-i-1;a=r===s,o=r===l,a?t.set("subscribed",!0):o?t.set("subscribed",!1):t.set("subscribed","gray"),t.commit()}this.checkEnableColumnHeaderStatus()},checkEnableColumnHeaderStatus:function(){this.colModel.getColumnAt(this.enableColumnIdx).checkSelectAll(this.getStore())},onChange:function(t,e,i,n,a){this.loadMailbox()},isDirty:function(){return this.store.getModifiedRecords().length>0},getExtraActions:function(){var t=[];return this.store.getModifiedRecords().forEach(function(e){Ext.isString(e.id)||t.push({api:"SYNO.MailClient.Mailbox",method:"set",params:{id:e.id,subscribed:e.get("subscribed")},version:3})},this),t}}),Ext.define("SYNO.SDS.MailClient.Model.PagingMemoryProxy",{extend:"Ext.data.MemoryProxy",requires:[],constructor:function(t){SYNO.SDS.MailClient.Model.PagingMemoryProxy.superclass.constructor.call(this),this.data=t},doRequest:function(t,e,i,n,a,o,s){i=i||{};var l;try{l=n.readRecords(this.data)}catch(t){return this.fireEvent("loadexception",this,s,null,t),void a.call(o,null,s,!1)}if(void 0!==i.filter&&(l.records=l.records.filter(function(t){if("object"==typeof t){var e=i.filterCol||0;return!!String(t.data[e]).match(i.filter)}return!!String(t).match(i.filter)}),l.totalRecords=l.records.length),void 0!==i.filterFn&&(l.records=l.records.filter(i.filterFn),l.totalRecords=l.records.length),void 0!==i.sort){var r="DESC"==String(i.dir).toUpperCase()?-1:1,d=function(t,e){return t>e?1:t<e?-1:0};l.records.sort(function(t,e){var n=0;return n="object"==typeof t?d(t.data[i.sort],e.data[i.sort])*r:d(t,e)*r,0===n&&(n=t.index<e.index?-1:1),n})}void 0!==i.start&&void 0!==i.limit&&(l.records=l.records.slice(i.start,i.start+i.limit)),a.call(o,l,s,!0)},setData:function(t){this.data=t}}),Ext.define("SYNO.SDS.MailClient.Filter.AddressComboBox",{extend:"SYNO.ux.ComboBox",xtype:"syno_mc_address_combo",requires:["SYNO.SDS.MailClient.Model.PagingMemoryProxy"],constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={store:new Ext.data.JsonStore({autoDestroy:!0,root:"contact",idProperty:"id",totalProperty:"total",remoteSort:!0,fields:["id","full_name","primary_mail","mail","search_field","name_with_nickname","combobox_display","combobox_display_encode","address_value","address_encode","address_display","members","mail_for_search","type"],proxy:SYNO.SDS.MailClient.Switch.getAutoCompleteMemProxy()}),mode:"remote",cls:"address-combo",editable:!0,hideTrigger:!0,minChars:1,queryParam:"keyword",displayField:"address_display",valueField:"address_value",searchField:"search_field",tpl:new Ext.XTemplate('<tpl for=".">','<div class="x-combo-list-item" ext:qtip="{search_field_encode:htmlEncode}">{search_field:htmlEncode}','<tpl if="values.members">','<tpl for="values.members">',"<span> {[Ext.util.Format.htmlEncode(SYNO.SDS.MailClient.Format.composeNameAddr(values.full_name, values.primary_mail))]},</span>","</tpl>","</tpl>","</div>","</tpl>",{})};return Ext.apply(e,t),e},findCurrentKeyword:function(){var t=this.getRawValue().split(/[\s,]/).pop().trim();return Ext.isEmpty(t)||"AND"==t||"OR"==t?"":t},initQuery:function(){var t=this.findCurrentKeyword();Ext.isEmpty(t)&&this.isExpanded()&&this.collapse(),this.doQuery(t)},onSelect:function(t,e){var i="",n=this.getRawValue();if("contact"!==t.get("type")){var a=SYNO.SDS.MailClient.Switch.getContactByGroupData(t.get("id"));Ext.each(a,function(t){i+=t.primary_mail+" "},this)}else i=SYNO.SDS.MailClient.Format.toEmail(t.data[this.valueField]);i=n.split(/[\s,]/).length>1?n.substring(0,Math.max(n.lastIndexOf(" "),n.lastIndexOf(","))+1)+i:i,i+=" ",!1!==this.fireEvent("beforeselect",this,t,e)&&(this.setValue(i),this.collapse(),this.fireEvent("select",this,t,e)),this.el.dom.scrollLeft=this.el.dom.scrollWidth},getValue:function(){return this.getRawValue()},doQuery:function(t,e){t=Ext.isEmpty(t)?"":t;var i={query:t,forceAll:e,combo:this,cancel:!1};if(!1===this.fireEvent("beforequery",i)||i.cancel)return!1;if(t=i.query,!0===(e=i.forceAll)||t.length>=this.minChars)if(this.lastQuery!==t)if(this.lastQuery=t,"local"==this.mode)this.selectedIndex=-1,e?this.store.clearFilter():this.store.filter(this.displayField,t),this.onLoad();else{var n,a=this.searchField,o=this.store.data.createValueMatcher(t,!0);n=t.indexOf("@")<0?function(t){return o.test(t.data[a])}:function(e){return o.test(e.data.name_with_nickname)||e.data.mail_for_search&&e.data.mail_for_search.startsWith(t)},this.store.load({params:{start:0,limit:100,filterFn:n}})}else this.selectedIndex=-1,this.onLoad()}}),Ext.define("SYNO.SDS.MailClient.DateField",{extend:"SYNO.ux.DateField",xtype:"syno_mc_datefield",constructor:function(t){this.callParent([t]),this.addEvents("menuShow","menuHide")},onTriggerClick:function(t){this.callParent(arguments),this.menu.addClass("syno-mc-menu"),this.fireEvent("menuShow")},onMenuHide:function(){this.callParent(arguments),this.fireEvent("menuHide")}}),Ext.define("SYNO.SDS.MailClient.DateTimeField",{extend:"SYNO.ux.DateTimeField",xtype:"syno_mc_datetimefield",constructor:function(t){this.callParent([t]),this.addEvents("menuShow","menuHide")},onTriggerClick:function(t){this.callParent(arguments),this.menu.addClass("syno-mc-menu"),this.fireEvent("menuShow")},onMenuHide:function(){this.callParent(arguments),this.fireEvent("menuHide")}});Ext.define("SYNO.SDS.MailClient.LabelCheckMenuButton",{extend:"SYNO.ux.Button",xtype:"syno_mc_label_checkmenu_button",requires:["SYNO.SDS.MailClient.Search.SearchLabelCheckItemMenu"],selectedLabels:[],htmlEncode:!1,constructor:function(t){var e={};t.hasOwnProperty("menuCfg")&&(e=t.menuCfg,delete t.menuCfg),t.hasOwnProperty("text")?this.defaultText=t.text:this.defaultText=SYNO.SDS.MailClient._T("search","all_labels");var i={cls:"syno-mc-search-menu-btn",text:this.defaultText,menu:new SYNO.SDS.MailClient.Search.SearchLabelCheckItemMenu(Ext.apply({ownerBtn:this},e))};Ext.apply(i,t),this.callParent([i]),this.addEvents("change"),this.mon(this.menu,"apply",this.selectLabels,this)},isValid:function(){
return this.getLabelIds().length<=0?(this.markAsInvalid(),!1):(this.clearInvalid(),!0)},markAsInvalid:function(){this.el.addClass("x-form-invalid")},clearInvalid:function(){this.el.removeClass("x-form-invalid")},setValue:function(t){this.selectLabels([],[],t),this.setLabelText(t)},selectLabels:function(t,e,i){this.selectedLabels=i,this.setLabelText(this.selectedLabels),this.menu.setItem([{data:{label:this.selectedLabels}}]),this.fireEvent("change",this.selectedLabels),this.clearInvalid()},setLabelText:function(t){var e=[];t.forEach(function(t,i,n){e.push(t.name)},this),this.setText(e.length>0?Ext.util.Format.htmlEncode(e.join(", ")):this.defaultText),this.clearInvalid()},getLabelIds:function(){var t=[];return this.selectedLabels.forEach(function(e,i,n){t.push(e.id)},this),t},isLabelSelected:function(t){var e;for(e=0;e<this.selectedLabels.length;++e)if(t==this.selectedLabels[e].id)return!0;return!1},reset:function(){this.setText(this.defaultText),this.selectedLabels=[],this.menu.setItem([{data:{label:this.selectedLabels}}]),this.fireEvent("change",this.selectedLabels),this.clearInvalid()}}),Ext.define("SYNO.SDS.MailClient.TextItem",{extend:"Ext.Toolbar.TextItem",xtype:"syno_mc_tbtext",onRender:function(t,e){this.autoEl={cls:"xtb-text",html:this.text||"","ext:qtip":this.text||""},SYNO.SDS.MailClient.TextItem.superclass.onRender.call(this,t,e)},setText:function(t){SYNO.SDS.MailClient.TextItem.superclass.setText.call(this,t),this.rendered&&this.el.set({"ext:qtip":t})}}),Ext.define("SYNO.SDS.MailClient.ConditionPanel",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.Filter.AddressComboBox","SYNO.SDS.MailClient.DateField","SYNO.SDS.MailClient.DateTimeField","SYNO.SDS.MailClient.LabelCheckMenuButton","SYNO.SDS.MailClient.TextItem"],hasDropDownMenu:!1,defaultAnimation:["888888",1,{duration:.35}],exception_keys:["from","to","subject","keyword"],inWindow:!1,constructor:function(t){this.callParent([this.fillConfig(t)]),this.centerPanel=this.getComponent("center"),this.southPanel=this.getComponent("south"),this.addEvents("reset","mailboxchange"),this.allowKeyword()||(this.exception_keys=["from","to","subject"])},fillConfig:function(t){this.inWindow=t.owner instanceof SYNO.SDS.BaseWindow,this.fieldWidth=372;var e={cls:"syno-mc-condition-panel",border:!1,layout:"border",items:[{region:"center",xtype:"form",itemId:"center",border:!1,padding:this.inWindow?"0px 10px 0px 20px":"20px 10px 0px 20px",labelAlign:"left",labelWidth:201,trackResetOnLoad:!0,waitMsgTarget:!0,autoFlexcroll:!0,updateFormForScrollbar:!0,defaults:{width:this.fieldWidth},items:this.getItemConfig()},{region:"south",itemId:"south",height:64,border:!1,padding:"0px 10px 20px 20px",items:this.getPanelFooterBar()}],keys:[{key:[13],fn:function(){this.inWindow||this.onSearch()},scope:this},{key:27,fn:function(){this.inWindow||this.owner.hide()},scope:this}]};return Ext.apply(e,t),e},setConditions:function(t,e){var i,n=this.allowKeyword()?"keyword":"subject",a=this.centerPanel.form.findField(n),o=this.centerPanel.getComponent("mailbox_btn");this.resetPanel("skip_search_field"),"starred"===t?o.setValue("starred",SYNO.SDS.MailClient._T("mailbox","starred")):(i=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t),i?o.setValue(i.get("id"),i.get("name")):o.setValue(0,SYNO.SDS.MailClient._T("search","all_mailboxes"))),this.loadTargetInfo(e),a.selectText(),a.focus()},loadTargetInfo:function(t){var e=this.centerPanel.form,i=this.centerPanel.getComponent("label_btn"),n=e.findField("size_opt"),a=e.findField("size"),o=[],s=["from","to","subject","keyword"],l={from:[],to:[],subject:[],keyword:[]},r={from:[],to:[],subject:[],keyword:[]};Ext.each(t,function(t){var i,d=t.name,c=t.value;if(this.allowKeyword()||"keyword"!==d)if(t.not_operator)s.indexOf(d)>-1&&r[d].push(c);else if("label"===d){var h=SYNO.SDS.MailClient.Switch.getLabelStore().getById(c);h&&o.push(h.data)}else"larger"===d||"smaller"===d?(n.setValue(d),a.setValue(c/1048576),a.enable()):"before"===d||"after"===d?(i=e.findField("searchdate"+("after"===d?"from":"to")),i.setValue(new Date(1e3*parseInt(c,10)))):"starred"===d?l.keyword.push("is:starred"):s.indexOf(d)>-1?l[d].push(c):(i=e.findField(d))&&i.setValue(!0)},this),o.length>0&&i.setValue(o),s.forEach(function(t){var i=e.findField(t);l[t].length>0&&i&&i.setValue(l[t].join(" ")),r[t].length>0&&this.addException({itemId:t},null,r[t].join(" "))},this),this.doLayout()},isFieldDirty:function(t){return this.centerPanel.form.findField(t).isDirty()},getExceptions:function(){var t,e,i,n=this.centerPanel.form,a=new SYNO.SDS.MailClient.Condition;for(i=0;i<this.exception_keys.length;i++)(t=n.findField(this.exception_keys[i]+"_exp_field"))&&(e=t.getRawValue().trim(),Ext.isEmpty(e)||a.addCondition(this.exception_keys[i],e,!0));return a},allowKeyword:function(){return this.inWindow||SYNO.SDS.MailClient.Info.fts_enabled},validateForm:function(){if(!this.centerPanel.form.isValid())return!1;var t=this.centerPanel.getComponent("label_btn").getLabelIds(),e=this.getExceptions();return this.isFieldDirty("from")||this.isFieldDirty("to")||this.isFieldDirty("subject")||this.isFieldDirty("keyword")||this.isFieldDirty("searchdatefrom")||this.isFieldDirty("searchdateto")||this.isFieldDirty("size")||this.isFieldDirty("has_attachment")||this.isFieldDirty("unread")||t.length>0||e.length>0},getConditions:function(t){var e,i,n,a=this.centerPanel.form,o=new SYNO.SDS.MailClient.Condition;return t&&(o.addCondition("mailbox",this.centerPanel.getComponent("mailbox_btn").getMailboxId()),n=this.centerPanel.getComponent("label_btn").getLabelIds(),n.forEach(function(t,e,i){o.addCondition("label",t)},this)),e=a.findField("from").getRawValue().trim(),Ext.isEmpty(e)||o.addCondition("from",e),e=a.findField("to").getRawValue().trim(),Ext.isEmpty(e)||o.addCondition("to",e),e=a.findField("subject").getValue().trim(),Ext.isEmpty(e)||o.addCondition("subject",e),e=a.findField("keyword").getValue().trim(),Ext.isEmpty(e)||o.addCondition("keyword",e),t&&(this.isFieldDirty("searchdatefrom")||this.isFieldDirty("searchdateto"))&&(a.findField("searchdatefrom").value&&(e=new Date(this.centerPanel.form.findField("searchdatefrom").value).valueOf()/1e3,o.addCondition("after",e)),a.findField("searchdateto").value&&(e=new Date(this.centerPanel.form.findField("searchdateto").value).valueOf()/1e3+86400-1,o.addCondition("before",e))),i=a.findField("size_opt").getValue(),e=1048576*a.findField("size").getValue(),"larger"!==i&&"smaller"!==i||o.addCondition(i,e),t&&(o.addCondition("is_search",!0),e=a.findField("has_attachment").getValue(),!0===e&&o.addCondition("has_attachment",!0),!0===(e=a.findField("unread").getValue())&&o.addCondition("unread",!0)),o=o.concat(this.getExceptions())},addException:function(t,e,i){var n,a,o=this.centerPanel.getComponent("exception_panel"),s=t.itemId+"_exp_field";if(!this.centerPanel.form.findField(s)){a=Ext.isDefined(i)?i:"";var l={xtype:"syno_button",cls:"exp-del-btn",iconCls:"exp-del-btn-icon",scope:this,handler:function(){o.remove(n),this.updateExceptionMenu(),o.doLayout()}},r={xtype:"syno_textfield",width:340,msgTarget:"qtip",validateOnBlur:!0,validationEvent:"blur",name:s,value:a},d={xtype:"syno_mc_address_combo",width:340,msgTarget:"qtip",validateOnBlur:!0,validationEvent:"blur",name:s,value:a,listeners:{expand:this.setHasDropDown.createDelegate(this,[!0]),collapse:this.setHasDropDown.createDelegate(this,[!1])}},c="from"==t.itemId||"to"==t.itemId;n=new SYNO.ux.CompositeField({fieldLabel:this.findExceptionLabelString(t.itemId),itemId:t.itemId+"_exp_cmp",items:[c?d:r,l]}),o.add(n),this.updateExceptionMenu(),o.on("afterlayout",function(){this.centerPanel.fleXcrollTo(n.getEl())},this,{single:!0,buffer:200}),o.doLayout()}},updateExceptionMenu:function(){var t=this.centerPanel.getComponent("exception_btn"),e=this.centerPanel.form.findField("exception_title"),i=0;Ext.each(this.exception_keys,function(e,n,a){this.centerPanel.form.findField(e+"_exp_field")?(t.menu.getComponent(e).hide(),i++):("keyword"!==e||this.allowKeyword())&&t.menu.getComponent(e).show()},this),i==this.exception_keys.length?t.disable():t.enable(),0===i?e.hide():e.show()},onSearch:function(t,e){if(!this.validateForm())return void this.owner.alertMessage(SYNO.SDS.MailClient._T("search","least_one"));var i=this.getConditions(!0);this.owner.hide(),SYNO.SDS.MailClient.Control.Mail.search(i)},resetPanel:function(t,e){var i=this.centerPanel.form;i.items.each(function(t){t.isDirty()&&this.frameAnimation(t.el,this.defaultAnimation)},this),this.resetException(),i.reset(),i.findField("searchdatefrom").setMaxValue(null),i.findField("searchdateto").setMinValue(null),i.findField("size").disable(),this.centerPanel.getComponent("label_btn").reset(),e&&this.centerPanel.getComponent("mailbox_btn").setValue(0,SYNO.SDS.MailClient._T("search","all_mailboxes")),this.fireEvent("reset",t)},resetException:function(){var t,e,i=this.centerPanel.getComponent("exception_panel");for(t=0;t<this.exception_keys.length;t++)(e=i.getComponent(this.exception_keys[t]+"_exp_cmp"))&&this.centerPanel.getComponent("exception_panel").remove(e);this.updateExceptionMenu(),this.centerPanel.getComponent("exception_panel").doLayout()},isNeedRemind:function(){var t=this.centerPanel.form;return 0!==this.centerPanel.getComponent("mailbox_btn").getMailboxId()||(0<this.centerPanel.getComponent("label_btn").getLabelIds().length||(!(!this.isFieldDirty("searchdatefrom")&&!this.isFieldDirty("searchdateto"))||!(!t.findField("has_attachment").getValue()&&!t.findField("unread").getValue())))},gotoActionPanel:function(){function t(){e.length<=0||(this.owner.conditions=e,this.owner.switchPanel("action"))}if(!this.validateForm())return void this.owner.alertMessage(SYNO.SDS.MailClient._T("search","least_one"));var e=this.getConditions();if(this.isNeedRemind()){var i=[SYNO.SDS.MailClient._T("common","mailbox"),SYNO.SDS.MailClient._T("common","label"),SYNO.SDS.MailClient._T("search","date"),SYNO.SDS.MailClient._T("search","has_attachment"),SYNO.SDS.MailClient._T("search","unread"),SYNO.SDS.MailClient._T("mailbox","starred")],n=String.format(SYNO.SDS.MailClient._T("filter","condition_remind"),i.join(", "));this.owner.alertMessage(n,t,this)}else this.owner.conditions=e,this.owner.switchPanel("action")},setHasDropDown:function(t){this.hasDropDownMenu=t},hasDropDown:function(){return this.hasDropDownMenu},frameAnimation:function(t,e){t&&t.isVisible()&&Ext.Element.prototype.frame.apply(t,e)},getItemConfig:function(){var t=SYNO.SDS.MailClient.Format.isDSM6()?"syno_mc_datefield":"syno_mc_datetimefield",e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[["any",SYNO.SDS.MailClient._T("search","any")],["larger",SYNO.SDS.MailClient._T("search","size_greater")],["smaller",SYNO.SDS.MailClient._T("search","size_less")]]});return[{xtype:"syno_mc_mailbox_button",itemId:"mailbox_btn",fieldLabel:SYNO.SDS.MailClient._T("common","mailbox"),text:SYNO.SDS.MailClient._T("search","all_mailboxes"),hidden:this.inWindow,menuCfg:{width:this.fieldWidth,hideInbox:!0,hideCreate:!0,hideManageBtn:!0,hideMailbox:[],isSearchMenu:!0,showSharedByOthers:!0,hideReadOnlyMailbox:!1,rootVisible:!0},listeners:{scope:this,menushow:this.setHasDropDown.createDelegate(this,[!0]),menuhide:this.setHasDropDown.createDelegate(this,[!1]),change:function(t){this.fireEvent("mailboxchange",t)}}},{xtype:"syno_mc_label_checkmenu_button",itemId:"label_btn",fieldLabel:SYNO.SDS.MailClient._T("common","label"),hidden:this.inWindow,menuCfg:{width:this.fieldWidth,hideCreate:!0},listeners:{menushow:this.setHasDropDown.createDelegate(this,[!0]),menuhide:this.setHasDropDown.createDelegate(this,[!1])}},{xtype:"syno_mc_address_combo",fieldLabel:SYNO.SDS.MailClient._T("mail","sender"),msgTarget:"qtip",validateOnBlur:!0,validationEvent:"blur",name:"from",listeners:{expand:this.setHasDropDown.createDelegate(this,[!0]),collapse:this.setHasDropDown.createDelegate(this,[!1])}},{xtype:"syno_mc_address_combo",fieldLabel:SYNO.SDS.MailClient._T("mail","receiver"),msgTarget:"qtip",validateOnBlur:!0,validationEvent:"blur",name:"to",listeners:{expand:this.setHasDropDown.createDelegate(this,[!0]),collapse:this.setHasDropDown.createDelegate(this,[!1])}},{xtype:"syno_textfield",fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),msgTarget:"qtip",validateOnBlur:!0,validationEvent:"blur",name:"subject"},{xtype:"syno_textfield",fieldLabel:SYNO.SDS.MailClient._T("search","keyword"),msgTarget:"qtip",validateOnBlur:!0,validationEvent:"blur",emptyText:this.allowKeyword()?"":SYNO.SDS.MailClient._T("search","fts_is_disabled"),disabled:!this.allowKeyword(),name:"keyword"},{xtype:"syno_compositefield",hidden:this.inWindow,fieldLabel:SYNO.SDS.MailClient._T("search","date"),defaults:{flex:1,width:182},defaultMargins:"0 8 0 0",items:[{xtype:t,name:"searchdatefrom",editable:!1,isAllDay:!0,dateFormat:"Y/m/d",format:"Y/m/d",emptyText:SYNO.SDS.MailClient._T("search","date_from"),value:"",listeners:{menuShow:this.setHasDropDown.createDelegate(this,[!0]),menuHide:this.setHasDropDown.createDelegate(this,[!1]),select:{fn:function(t,e){this.centerPanel.form.findField("searchdateto").setMinValue(e)},scope:this}}},{xtype:t,name:"searchdateto",editable:!1,isAllDay:!0,dateFormat:"Y/m/d",format:"Y/m/d",emptyText:SYNO.SDS.MailClient._T("search","date_to"),value:"",listeners:{menuShow:this.setHasDropDown.createDelegate(this,[!0]),menuHide:this.setHasDropDown.createDelegate(this,[!1]),select:{fn:function(t,e){this.centerPanel.form.findField("searchdatefrom").setMaxValue(e)},scope:this}}}]},{xtype:"syno_compositefield",fieldLabel:SYNO.SDS.MailClient._T("search","size"),defaults:{flex:1},defaultMargins:"0 8 0 0",items:[{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"size_opt",editable:!1,width:182,mode:"local",store:e,displayField:"display",valueField:"value",triggerAction:"all",lazyRender:!0,value:"any",listeners:{expand:this.setHasDropDown.createDelegate(this,[!0]),collapse:this.setHasDropDown.createDelegate(this,[!1]),select:{fn:function(t,e,i){var n=this.centerPanel.form.findField("size");return"any"!==e.get("value")?(this.frameAnimation(n.el,this.defaultAnimation),n.enable(),1):(n.reset(),n.disable(),0)},scope:this}}},{xtype:"syno_numberfield",name:"size",minValue:0,disabled:!0,width:154},{xtype:"syno_displayfield",value:"MB",width:24}]},{xtype:"syno_checkbox",name:"has_attachment",hidden:this.inWindow,boxLabel:SYNO.SDS.MailClient._T("search","has_attachment")},{xtype:"syno_checkbox",name:"unread",hidden:this.inWindow,boxLabel:SYNO.SDS.MailClient._T("search","unread")},{xtype:"syno_fieldset",itemId:"exception_panel",width:586,items:[{xtype:"syno_displayfield",cls:"exception-title",name:"exception_title",hidden:!0,value:SYNO.SDS.MailClient._T("search","exception")}],listeners:{scope:this,afterlayout:function(){this.centerPanel.updateFleXcroll()}}},{xtype:"syno_button",itemId:"exception_btn",cls:"exception_btn",text:SYNO.SDS.MailClient._T("search","add_exception"),autoWidth:!0,menu:{cls:"syno-mc-menu",width:150,defaults:{scope:this,handler:this.addException},items:[{text:SYNO.SDS.MailClient._T("mail","sender"),itemId:"from"},{text:SYNO.SDS.MailClient._T("mail","receiver"),itemId:"to"},{text:SYNO.SDS.MailClient._T("mail","subject"),itemId:"subject"},{text:SYNO.SDS.MailClient._T("search","keyword"),itemId:"keyword",hidden:!this.allowKeyword()}]},listeners:{menuShow:this.setHasDropDown.createDelegate(this,[!0]),menuHide:this.setHasDropDown.createDelegate(this,[!1])}}]},findExceptionLabelString:function(t){switch(t){case"from":return SYNO.SDS.MailClient._T("mail","sender");case"to":return SYNO.SDS.MailClient._T("mail","receiver");case"subject":return SYNO.SDS.MailClient._T("mail","subject");case"keyword":return SYNO.SDS.MailClient._T("search","keyword");default:return""}},getPanelFooterBar:function(){return{xtype:"container",cls:"condition_footer",items:[{xtype:"syno_button",minWidth:80,text:_T("common","reset"),handler:this.resetPanel.bind(this,!1,!0),scope:this},{xtype:"container",cls:"condition_footer_right",items:[{xtype:"syno_button",btnStyle:this.inWindow?"blue":"default",text:this.inWindow?_T("common","continue"):SYNO.SDS.MailClient._T("filter","create_filter"),itemId:"btn_filter",handler:this.gotoActionPanel,scope:this,disabled:!1},{xtype:"syno_button",btnStyle:"blue",text:SYNO.SDS.MailClient._T("search","search"),itemId:"btn_search",hidden:this.inWindow,handler:this.onSearch,scope:this}]}]}}}),Ext.define("SYNO.SDS.MailClient.ActionPanel",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.LabelCheckMenuButton"],hasDropDownMenu:!1,inWindow:!1,constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("createfilter"),this.actionForm=this.getComponent("center").getComponent("desc").getComponent("action").getForm()},fillConfig:function(t){this.inWindow=t.owner instanceof SYNO.SDS.BaseWindow;var e={layout:"border",cls:"syno-mc-action-panel",border:!1,defaults:{border:!1},items:this.getItemConfig(),keys:[{key:[13],fn:function(){this.createFilter()},scope:this}],listeners:{scope:this,afterrender:function(){this.addCheckGroup()},activate:function(){this.getComponent("south").getComponent("apply_exist").enable(),Ext.each(this.owner.conditions.get(),function(t){"keyword"!=t.name||SYNO.SDS.MailClient.Info.fts_enabled||this.getComponent("south").getComponent("apply_exist").disable()},this)}}};return Ext.apply(e,t),e},loadTargetInfo:function(t){var e=this.getComponent("center").getComponent("desc").getComponent("action").getForm(),i=[],n=[];Ext.each(t,function(t){var a,o=t.name;if("set_label"==o){var s=SYNO.SDS.MailClient.Switch.getLabelStore().getById(t.value);s&&i.push(s.data)}else if("move_to"==o){var l=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t.value);l&&(e.findField("move_to").setValue(!0),Ext.getCmp(this.mailboxBtnId).setValue(l.get("id"),l.get("name")))}else"redirect"==o?t.value&&n.push(t.value):(a=e.findField(t.name))&&a.setValue(!0)},this),i.length>0&&(e.findField("set_label").setValue(!0),Ext.getCmp(this.labelBtnId).selectLabels([],[],i),Ext.getCmp(this.labelBtnId).setLabelText(i)),n.length>0&&(e.findField("redirect").setValue(!0),e.findField("redirect_text").setValue(n.toString()))},backtoSearch:function(){this.owner.switchPanel("condition")},makeAction:function(t,e){var i={};return i.name=t,i.value=e.toString(),i},getActions:function(){var t,e,i,n=[],a=this.getComponent("center").getComponent("desc").getComponent("action").getForm();return a.findField("archive").getValue()&&n.push(this.makeAction("archive",!0)),a.findField("set_read").getValue()&&n.push(this.makeAction("set_read",!0)),a.findField("set_star").getValue()&&n.push(this.makeAction("set_star",!0)),a.findField("move_to").getValue()&&0!==(e=Ext.getCmp(this.mailboxBtnId).getMailboxId())&&"starred"!==e&&n.push(this.makeAction("move_to",e)),a.findField("set_label").getValue()&&(t=Ext.getCmp(this.labelBtnId).getLabelIds(),t.length>0&&t.forEach(function(t,e,i){n.push(this.makeAction("set_label",t))},this)),a.findField("redirect").getValue()&&a.findField("redirect_text").isValid()&&(i=a.findField("redirect_text").getValue().split(","),i.forEach(function(t,e,i){n.push(this.makeAction("redirect",t.trim()))},this)),a.findField("trash").getValue()&&n.push(this.makeAction("trash",!0)),n},validateForm:function(){var t=this.getComponent("center").getComponent("desc").getComponent("action").getForm(),e=!0;return t.findField("set_label").getValue()&&!Ext.getCmp(this.labelBtnId).isValid()&&(e=!1),t.findField("redirect").getValue()&&!t.findField("redirect_text").isValid()&&(e=!1),t.findField("move_to").getValue()&&!Ext.getCmp(this.mailboxBtnId).isValid()&&(e=!1),e},createFilter:function(){if(this.validateForm()){var t,e=this.getActions(),i={};return e.length<=0?void this.owner.alertMessage(SYNO.SDS.MailClient._T("filter","least_one_action")):(i.condition=this.owner.conditions.toWebAPIParams(),i.action=e,i.apply_exist=this.getComponent("south").getComponent("apply_exist").getValue(),"edit"===this.owner.mode?(i.id=this.owner.targetInfo.id,t="setFilter"):t="addFilter",this.owner.el.mask(),SYNO.SDS.MailClient.WebAPI.send(t,i).then(function(t){try{this.owner.el.unmask(),this.fireEvent("createfilter"),i.apply_exist&&SYNO.SDS.MailClient.Window.updateTaskIndicator(!0)}catch(t){SYNO.SDS.MailClient.Lib.Logger.error("ActionPanel.js createFilter"+t)}}.bind(this)).catch(function(t){this.owner.el.unmask(),this.owner.alertMessage(SYNO.SDS.MailClient.Error.getErrorString(t))}.bind(this)))}},resetPanel:function(){this.getComponent("center").getComponent("desc").getComponent("action").getForm().reset(),Ext.getCmp(this.mailboxBtnId).reset(),Ext.getCmp(this.labelBtnId).reset(),this.getComponent("south").getComponent("apply_exist").reset()},addCheckGroup:function(){function t(t,e){e&&Ext.each(o,function(e,i){e!==t&&e.setValue(!1)},this)}var e=this.getComponent("center").getComponent("desc").getComponent("action"),i=e.getComponent("trash"),n=e.getComponent("archive"),a=Ext.getCmp(this.moveToId),o=[i,n,a];Ext.each(o,function(e,i){e.on("check",t,this)},this)},updateNoteMsg:function(){var t=this.getComponent("center").getComponent("desc").getComponent("action").getForm().findField("redirect"),e=this.getComponent("south").getComponent("apply_exist"),i=this.getComponent("south").getForm().findField("note_msg");t.getValue()&&e.getValue()?i.setValue(_T("common","note")+" : "+SYNO.SDS.MailClient._T("filter","forward_to_remind")):i.setValue("")},setHasDropDown:function(t){this.hasDropDownMenu=t},hasDropDown:function(){return this.hasDropDownMenu},getItemConfig:function(){var t=SYNO.SDS.MailClient.Define,e=SYNO.SDS.MailClient.Settings.conversation_view;return[{region:"center",itemId:"center",items:[{xtype:"container",cls:"action-top",items:[{xtype:"syno_button",cls:"back-to-search-btn",text:SYNO.SDS.MailClient._T("filter","back_to_condition"),handler:this.backtoSearch,scope:this}]},{xtype:"container",cls:"action-desc",itemId:"desc",items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("filter","action_desc")},{xtype:"form",cls:"action-item",border:!1,itemId:"action",items:[{xtype:"syno_checkbox",name:"set_read",boxLabel:SYNO.SDS.MailClient._T("filter","mark_as_read")},{xtype:"syno_checkbox",name:"set_star",boxLabel:SYNO.SDS.MailClient._T("filter","mark_as_star")},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_checkbox",name:"set_label",boxLabel:SYNO.SDS.MailClient._T("filter","apply_label"),width:243},{xtype:"syno_mc_label_checkmenu_button",id:this.labelBtnId=Ext.id(),fieldLabel:SYNO.SDS.MailClient._T("common","label"),text:SYNO.SDS.MailClient._T("filter","select_label"),width:310,menuCfg:{width:310},listeners:{scope:this,menushow:this.setHasDropDown.createDelegate(this,[!0]),menuhide:this.setHasDropDown.createDelegate(this,[!1]),change:function(t){this.actionForm.findField("set_label").setValue(t.length>0)}}}]},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_checkbox",name:"redirect",htmlEncode:!1,boxLabel:SYNO.SDS.MailClient._T("filter","forward_to")+String.format('<span class="syno-mc-white-tip" ext:qtip="{0}"></span>',String.format(SYNO.SDS.MailClient._T("setting","redirects_desc"),SYNO.SDS.MailClient.Info.max_redirects)),width:243,listeners:{scope:this,check:function(t,e){this.updateNoteMsg()}}},{xtype:"syno_textfield",name:"redirect_text",width:310,maxlength:256,validator:SYNO.SDS.MailClient.Format.IsValidForwardAddress,validationEvent:"blur",listeners:{scope:this,change:function(t,e,i){this.actionForm.findField("redirect").setValue(e.trim().length>0)}}}]},{xtype:"syno_checkbox",name:"archive",itemId:"archive",boxLabel:SYNO.SDS.MailClient._T("common","archive")},{xtype:"syno_checkbox",name:"trash",itemId:"trash",boxLabel:_T("common","delete")},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_checkbox",name:"move_to",id:this.moveToId=Ext.id(),boxLabel:SYNO.SDS.MailClient._T("filter","move_to"),width:243},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:SYNO.SDS.MailClient._T("filter","select_mailbox"),width:310,menuCfg:{width:310,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.draftsId,t.sentId,t.trashId,t.starredId]},listeners:{scope:this,menushow:this.setHasDropDown.createDelegate(this,[!0]),menuhide:this.setHasDropDown.createDelegate(this,[!1]),change:function(t){this.actionForm.findField("move_to").setValue(0!==t)}}}]}]}]}]},{region:"south",itemId:"south",xtype:"syno_formpanel",height:80,autoFlexcroll:!1,useGradient:!1,padding:"0 20px 20px 20px",items:[{xtype:"syno_checkbox",ctCls:"apply-exist-btn",itemId:"apply_exist",boxLabel:SYNO.SDS.MailClient._T("filter",e?"apply_exist_conversation":"apply_exist_message"),listeners:{scope:this,check:this.updateNoteMsg}},{xtype:"container",items:[{xtype:"syno_displayfield",cls:"action-note-msg",name:"note_msg",value:"",width:this.inWindow?495:494},{xtype:"syno_button",cls:"create-btn",text:this.inWindow?_T("common","ok"):_T("common","create"),btnStyle:"blue",width:"auto",handler:this.createFilter,scope:this}]}]}]}}),Ext.define("SYNO.SDS.MailClient.FilterAddEditDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.ConditionPanel","SYNO.SDS.MailClient.ActionPanel"],mode:"",constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this.action_panel,"createfilter",this.onApplyDone,this),this.on("show",this.loadInfo,this)},fillConfig:function(t){var e={layout:"card",cls:"syno-mc-filter-win",padding:SYNO.SDS.MailClient.Format.isDSM6()?void 0:"16px 0 0 0",title:"add"==t.mode?_T("common","create"):_T("common","alt_edit"),width:618,height:462,minWidth:618,minHeight:462,useStatusBar:!1,closable:!0,activeItem:0,items:[this.condition_panel=new SYNO.SDS.MailClient.ConditionPanel({owner:this,itemId:"condition"}),this.action_panel=new SYNO.SDS.MailClient.ActionPanel({owner:this,itemId:"action"})]};return Ext.apply(e,t)},loadInfo:function(){"edit"===this.mode&&(this.condition_panel.loadTargetInfo(this.targetInfo.condition),this.action_panel.loadTargetInfo(this.targetInfo.action))},switchPanel:function(t){this.layout.setActiveItem(t)},onApplyDone:function(){this.fireEvent("apply"),this.close()},alertMessage:function(t,e,i){this.getMsgBox().alert("",t,e,i)}}),Ext.define("SYNO.SDS.MailClient.Setting.Filter",{extend:"SYNO.SDS.MailClient.Setting.DDGridPanel",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.FilterAddEditDialog"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("setting","empty_filter"),this.callParent([this.fillConfig(t)]),this.mon(this.getSelectionModel(),"selectionchange",this.onRowSelectionChange,this)},fillConfig:function(t){var e={cls:"syno_mc_setting_filter_panel",autoExpandColumn:"name",enableColumnMove:!1,hideHeaders:!0,enableDragDrop:!0,tbar:this.getTbarCfg(),bbar:{buttonAlign:"left",height:"auto",items:[{xtype:"syno_displayfield",style:{whiteSpace:"pre-wrap"},value:SYNO.SDS.MailClient._T("filter","action_note")}]},store:this.getStore(),sm:new Ext.grid.RowSelectionModel,viewConfig:{ddGroup:"FilterDDGroup"},colModel:new Ext.grid.ColumnModel({columns:[{dataIndex:"name",align:"left",width:100,treeCol:!0,renderer:this.filterRenderer.createDelegate(this)}]}),listeners:{scope:this,afterDrop:this.setFilterOrder,activate:this.onPanelActivate,rowdblclick:this.editFilter}};return Ext.apply(e,t),e},onPanelActivate:function(t){this.store.load()},filterRenderer:function(t,e,i){var n,a,o="<div class='syno-mc-setting-filter {0}'><div>{1} <span>{2}</span></div><div>{3} <span>{4}</span></div></div>";return n=new SYNO.SDS.MailClient.Condition(i.get("condition")).toSyntaxString(),a=this.getDisplayAction(i.get("action")),Ext.isEmpty(a)&&(o="<div class='syno-mc-setting-filter {0}'><div>{1} <span>{2}</span></div><div>{3} <span style='color:red;'>{4}</span></div></div>",a=SYNO.SDS.MailClient._T("filter","can_not_apply")),String.format(o,i.get("enabled")?"":"disabled",SYNO.SDS.MailClient._T("filter","match")+": ",Ext.util.Format.htmlEncode(n),SYNO.SDS.MailClient._T("filter","do_action")+": ",a)},getDisplayAction:function(t){var e,i,n,a,o=[],s=SYNO.SDS.MailClient.Switch.getMailboxStore(),l=SYNO.SDS.MailClient.Switch.getLabelStore(),r=[];for(e=0;e<t.length;e++)i=this.getActionString(t[e].name),a=t[e].value,"set_label"!=t[e].name?("move_to"==t[e].name&&(n=s.getById(t[e].value),a=n?n.get("name"):""),"move_to"!=t[e].name&&"redirect"!=t[e].name||(i+=a?": ("+a+")":""),o.push(i)):(n=l.getById(t[e].value))&&r.push(n.get("name"));return r.length>0&&(i=this.getActionString("set_label")+": ("+r.join(", ")+")",o.push(i)),Ext.util.Format.htmlEncode(o.join(", "))},getActionString:function(t){switch(t){case"archive":return SYNO.SDS.MailClient._T("common","archive");case"set_read":return SYNO.SDS.MailClient._T("filter","mark_as_read");case"set_star":return SYNO.SDS.MailClient._T("filter","mark_as_star");case"set_label":return SYNO.SDS.MailClient._T("filter","apply_label");case"move_to":return SYNO.SDS.MailClient._T("filter","move_to");case"redirect":return SYNO.SDS.MailClient._T("filter","forward_to");case"trash":return _T("common","delete")}return""},onRowSelectionChange:function(t){this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection()),this.getTopToolbar().getComponent("edit").setDisabled(1!==t.getSelections().length),this.getTopToolbar().getComponent("btn_enable").setDisabled(!t.hasSelection());var e=this.getTopToolbar().getComponent("btn_enable").menu.getComponent("enable"),i=this.getTopToolbar().getComponent("btn_enable").menu.getComponent("disable"),n=!1,a=!1;e.enable(),i.enable(),t.getSelections().forEach(function(t){if(t.get("enabled")?n=!0:a=!0,n&&a)return!1},this),n||i.disable(),a||e.disable()},addFilter:function(){new SYNO.SDS.MailClient.FilterAddEditDialog({owner:this.findWindow(),mode:"add",listeners:{scope:this,apply:function(){this.store.reload()}}}).open()},editFilter:function(){new SYNO.SDS.MailClient.FilterAddEditDialog({owner:this.findWindow(),mode:"edit",targetInfo:this.getSelectionModel().getSelected().data,listeners:{scope:this,apply:function(){this.store.reload()}}}).open()},deleteFilter:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length)return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteFilter({id:t}).then(function(t){this.owner.clearStatusBusy(),this.store.reload()}.bind(this)).catch(function(t){this.owner.clearStatusBusy()}.bind(this))},setFilterOrder:function(){var t=[];if(this.getStore().each(function(e){t.push(e.get("id"))},this),0!==t.length)return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.setFilterOrder({id:t}).then(function(t){this.owner.clearStatusBusy(),this.store.reload()}.bind(this)).catch(function(t){this.owner.clearStatusBusy()}.bind(this))},setFilterEnable:function(t){var e=[],i=this.getSelectionModel().getSelections();if(Ext.each(i,function(t){e.push(t.get("id"))},this),0!==e.length)return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.setFilterEnabled({id:e,enabled:t}).then(function(t){this.owner.clearStatusBusy(),this.store.reload()}.bind(this)).catch(function(t){this.owner.clearStatusBusy()}.bind(this))},getStore:function(){return this.store=this.store||new SYNO.API.Store({method:"POST",reader:new Ext.data.JsonReader({root:"filter",totalProperty:"total",fields:["id","condition","action","enabled"]}),load:function(){return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listFilter").then(function(t){this.store.loadData(t)}.bind(this)).catch(function(t){this.owner.clearStatusBusy(),this.owner.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(t),clear:!0})}.bind(this))}.bind(this),listeners:{scope:this,load:function(t,e,i){this.owner.clearStatusBusy()}}}),this.store},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),handler:this.addFilter},{
text:_T("common","alt_edit"),handler:this.editFilter,itemId:"edit",disabled:!0},{text:SYNO.SDS.MailClient._T("common","enable"),itemId:"btn_enable",disabled:!0,menu:[{text:SYNO.SDS.MailClient._T("common","enable"),handler:this.setFilterEnable.createDelegate(this,[!0]),itemId:"enable"},{text:SYNO.SDS.MailClient._T("common","disable"),handler:this.setFilterEnable.createDelegate(this,[!1]),itemId:"disable"}]},{text:_T("common","delete"),handler:this.deleteFilter,itemId:"delete",disabled:!0}]}}}),Ext.define("SYNO.SDS.MailClient.SectionEditDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",constructor:function(t){this.record=t.record,this.callParent([this.fillConfig(t)]),this.on("show",this.loadInfo,this)},fillConfig:function(t){var e={title:_T("common","alt_edit"),layout:"fit",width:540,height:365,cls:"syno-mc-section-edit-win",items:[this.getFormPanel()],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):"",handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})};return Ext.apply(e,t)},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define,e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("priority_mailbox","all")],[1,SYNO.SDS.MailClient._T("thread","unread")]]}),i=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[5,5],[10,10],[25,25],[50,50]]});return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({trackResetOnLoad:!0,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("priority_mailbox","section")+":"},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_radio",width:180,inputValue:1,boxLabel:SYNO.SDS.MailClient._T("common","mailbox"),indent:1,name:"type",checked:2!==this.record.get("type"),scope:this,handler:function(t,e){Ext.getCmp(this.mailboxBtnId).setDisabled(!e),Ext.getCmp(this.labelBtnId).setDisabled(e)}},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:SYNO.SDS.MailClient._T("filter","select_mailbox"),width:280,disabled:!0,menuCfg:{width:280,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.draftsId,t.sentId,t.trashId,t.junkId]},listeners:{scope:this,change:function(t){}}}]},{xtype:"syno_compositefield",hideLabel:!0,ctCls:"high-field",items:[{xtype:"syno_radio",width:180,inputValue:2,boxLabel:SYNO.SDS.MailClient._T("common","label"),indent:1,name:"type",checked:2==this.record.get("type"),scope:this,handler:function(t,e){Ext.getCmp(this.mailboxBtnId).setDisabled(e),Ext.getCmp(this.labelBtnId).setDisabled(!e)}},{xtype:"syno_mc_label_button",id:this.labelBtnId=Ext.id(),fieldLabel:SYNO.SDS.MailClient._T("common","label"),text:SYNO.SDS.MailClient._T("filter","select_label"),disabled:!0,width:280,menuCfg:{width:280,rootVisible:!1},listeners:{scope:this,change:function(t){}}}]},{xtype:"syno_combobox",cls:"syno-mc-combobox",ctCls:"high-field",listClass:"syno-ux-combobox-list syno-mc-combobox-list",width:280,name:"status",fieldLabel:SYNO.SDS.MailClient._T("priority_mailbox","display_status"),mode:"local",store:e,displayField:"display",valueField:"value",value:this.record.get("status")},{xtype:"syno_combobox",cls:"syno-mc-combobox",ctCls:"high-field",listClass:"syno-ux-combobox-list syno-mc-combobox-list",width:280,name:"page_size",fieldLabel:SYNO.SDS.MailClient._T("priority_mailbox","show_up_to"),mode:"local",store:i,displayField:"display",valueField:"value",value:this.record.get("page_size")},{xtype:"syno_checkbox",name:"hide_when_empty",boxLabel:SYNO.SDS.MailClient._T("priority_mailbox","hide_when_empty"),checked:this.record.get("hide_when_empty")}]}),this.formPanel},loadInfo:function(){var t=this.record.get("type");if(2==t){Ext.getCmp(this.mailboxBtnId).setDisabled(!0),Ext.getCmp(this.labelBtnId).setDisabled(!1);var e=SYNO.SDS.MailClient.Switch.getLabelStore().getById(this.record.get("type_id"));e&&Ext.getCmp(this.labelBtnId).setValue(e.get("id"),e.get("name"))}else if(Ext.getCmp(this.mailboxBtnId).setDisabled(!1),Ext.getCmp(this.labelBtnId).setDisabled(!0),1==t){var i=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(this.record.get("type_id"));i&&Ext.getCmp(this.mailboxBtnId).setValue(i.get("id"),SYNO.SDS.MailClient.Format.getMailboxText(i.data))}else 3==t&&Ext.getCmp(this.mailboxBtnId).setValue("starred",SYNO.SDS.MailClient._T("mailbox","starred"))},isDirty:function(){return this.getFormPanel().getForm().isDirty()},onApply:function(){var t=this.getFormPanel().getForm().getValues(),e=parseInt(t.type,10);if(1==e){if(!Ext.getCmp(this.mailboxBtnId).isValid())return!1}else if(!Ext.getCmp(this.labelBtnId).isValid())return!1;if(this.record.set("type",e),this.record.set("status",parseInt(t.status,10)),this.record.set("page_size",parseInt(t.page_size,10)),this.record.set("hide_when_empty","true"==t.hide_when_empty),1==this.record.get("type")){var i=Ext.getCmp(this.mailboxBtnId).getMailboxId();"starred"==i?(this.record.set("type_id",0),this.record.set("type",3)):this.record.set("type_id",i)}else 2==this.record.get("type")&&this.record.set("type_id",Ext.getCmp(this.labelBtnId).getLabelId());this.fireEvent("apply"),this.close()},onCancel:function(){if(!this.isDirty())return void this.close();var t=function(t){"yes"===t&&this.close()};this.owner.getMsgBox().confirm(this.title,_T("common","confirm_lostchange"),t,this)}}),Ext.define("SYNO.SDS.MailClient.Setting.PriorityMailbox",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.SectionEditDialog"],constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={cls:"syno_mc_setting_pm_panel",webapi:{api:"SYNO.MailClient.Setting.PriorityMailbox",methods:{get:"get",set:"set"},version:"1"},items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),itemId:"pm_fieldset",items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("priority_mailbox","setting_desc")},{xtype:"syno_checkbox",name:"enable_priority_mailbox",boxLabel:SYNO.SDS.MailClient._T("priority_mailbox","enable_priority_mailbox"),listeners:{scope:this,check:function(t,e){var i=this.getComponent("pm_fieldset").getComponent("section_grid");i&&(e?(i.removeClass("pm-disabled"),i.enable(),i.getView().dragZone.unlock()):(i.addClass("pm-disabled"),i.disable(),i.getView().dragZone.lock()))}}},{xtype:"syno_dd_gridpanel",itemId:"section_grid",autoExpandColumn:"desc",enableColumnMove:!1,hideHeaders:!0,enableDragDrop:!0,cls:"section-grid pm-disabled",width:460,store:this.getStore(),sm:new Ext.grid.RowSelectionModel,viewConfig:{ddGroup:"SectionDDGroup"},colModel:new Ext.grid.ColumnModel({columns:[{dataIndex:"desc",align:"left",width:100,renderer:this.sectionRenderer.createDelegate(this)},{dataIndex:"edit",align:"center",width:50,renderer:function(){return String.format('<a class="edit-link">{0}</a>',_T("common","alt_edit"))}},{dataIndex:"reset",align:"center",width:50,renderer:function(t,e,i){return String.format('<a class="reset-link {0}">{1}</a>',0===i.get("type")?"disabled":"",SYNO.SDS.MailClient._T("setting","default_text_style_reset"))}}]}),listeners:{scope:this,afterrender:function(t){t.getView().dragZone.lock()},cellclick:this.onGridCellClick,rowmousedown:this.onRowMouseDown,afterDrop:this.afterSectionDrop}},{xtype:"hidden",name:"section-hidden",value:""}]}]};return Ext.apply(e,t)},adjustSectionTitleText:function(t,e){var i=!1,n=Ext.DomHelper.createDom({tag:"div",cls:"syno-mc-modal-window",html:'<div class="syno-ux-gridpanel"><div></div></div>'}),a=Ext.fly(n);for(document.body.appendChild(n);170<Ext.util.TextMetrics.measure(a,t+(i?"...: ":": ")+e).width&&!(t.length-3<=0);)t=t.substr(0,t.length-3),i=!0;return document.body.removeChild(n),t+(i?"...":"")},sectionRenderer:function(t,e,i,n,a,o){var s="",l="";if(1==i.get("type")){var r=SYNO.SDS.MailClient.Switch.getMailboxStore(),d=r.getById(i.get("type_id"));d&&(s=SYNO.SDS.MailClient.Format.getMailboxText(d.data))}else if(2==i.get("type")){var c=SYNO.SDS.MailClient.Switch.getLabelStore(),h=c.getById(i.get("type_id"));h&&(s=Ext.util.Format.htmlEncode(h.get("name")))}else 3==i.get("type")&&(s=SYNO.SDS.MailClient._T("mailbox","starred"));return Ext.isEmpty(s)?'<div class="section empty">'+SYNO.SDS.MailClient._T("priority_mailbox","empty_section")+"</div>":(l=0===i.get("status")?SYNO.SDS.MailClient._T("pop","fetch_all"):SYNO.SDS.MailClient._T("thread","unread"),s=this.adjustSectionTitleText(s,l),String.format("<div class='section'>{0}: {1}</div>",s,l))},setSectionDirty:function(){this.getForm().findField("section-hidden").setValue("123456")},editSection:function(t){new SYNO.SDS.MailClient.SectionEditDialog({owner:this.findWindow(),record:this.store.getAt(t),listeners:{scope:this,apply:function(){this.getForm().findField("enable_priority_mailbox").getValue()&&this.getStore().getModifiedRecords().length>0&&this.setSectionDirty()}}}).open()},resetSection:function(t){var e=this.store.getAt(t);e.set("type",0),e.set("status",1),e.set("page_size",10),e.set("hide_when_empty",!1),e.set("type_id",0),this.setSectionDirty()},onGridCellClick:function(t,e,i,n){var a=n.getTarget("a",t.body,!0);a&&this.getForm().findField("enable_priority_mailbox").getValue()&&(a.hasClass("edit-link")?this.editSection(e):a.hasClass("reset-link")&&this.resetSection(e))},onRowMouseDown:function(t,e,i){i.ctrlKey||i.shiftKey||t.getSelectionModel().selectRow(e)},afterSectionDrop:function(){this.setSectionDirty()},onBeforeRequest:function(t){var e=!1;return"set"==t&&(this.getStore().each(function(t){if(0!==t.get("type"))return e=!0,!1},this),this.getForm().findField("enable_priority_mailbox").getValue()&&!e)?(this.owner.setStatusError({text:SYNO.SDS.MailClient._T("priority_mailbox","least_one_section"),clear:!0}),this.owner.setActiveByForm(this.getForm()),!1):this.callParent(arguments)},processReturnData:function(t,e,i){"get"==t&&Ext.each(e.result,function(t){t.api==this.webapi.api&&(this.store.loadData(t.data.section),this.getComponent("pm_fieldset").getComponent("section_grid").setDisabled(!t.data.enable_priority_mailbox))},this),this.callParent(arguments)},processParams:function(t,e){return"set"!==t?e:(Ext.each(e,function(t){if(t.api==this.webapi.api&&"set"==t.method&&(delete t.params["section-hidden"],t.params.enable_priority_mailbox&&this.getStore().getModifiedRecords().length>0)){var e=[];this.getStore().each(function(t){e.push(t.data)},this),t.params.section=e}},this),e)},getStore:function(){return this.store=this.store||new Ext.data.Store({autoDestroy:!0,pruneModifiedRecords:!0,reader:new Ext.data.JsonReader({fields:["type","status","type_id","page_size","hide_when_empty"]})}),this.store}}),Ext.define("SYNO.SDS.MailClient.Setting.PGP.Main",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.Setting.PGP.KeyMgrDialog"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",function(t,e){new SYNO.SDS.Utils.EnableCheckGroup(this.getForm(),"enable_pgp",[this.keyManagementBtnId,"default_enable_encrypt","default_enable_sign"])},this,{single:!0})},fillConfig:function(t){this.keyManagementBtnId=Ext.id();var e={webapi:{api:"SYNO.MailClient.Setting.PGP",methods:{get:"get",set:"set"},version:"1"},items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("pgp","open_pgp"),itemId:"PGP_fieldset",items:[{xtype:"syno_checkbox",name:"enable_pgp",boxLabel:SYNO.SDS.MailClient._T("pgp","enable_pgp")},{xtype:"syno_button",id:this.keyManagementBtnId,indent:1,name:"key_management",text:SYNO.SDS.MailClient._T("pgp","key_management"),style:"margin-bottom: 8px",handler:function(){new SYNO.SDS.MailClient.PGP.KeyMgrDialog({owner:this.findWindow()}).show()},scope:this},{xtype:"syno_checkbox",name:"default_enable_encrypt",indent:1,boxLabel:SYNO.SDS.MailClient._T("pgp","default_enable_encrypt")},{xtype:"syno_checkbox",name:"default_enable_sign",indent:1,boxLabel:SYNO.SDS.MailClient._T("pgp","default_enable_sign")}]}]};return Ext.apply(e,t)}}),Ext.define("SYNO.SDS.MailClient.SpamRule.AddEditDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",isBlacklist:!0,mode:"",constructor:function(t){this.spamRuleTypeString=t.isBlacklist?SYNO.SDS.MailClient._T("spam_rule","black_list"):SYNO.SDS.MailClient._T("spam_rule","white_list"),this.callParent([this.fillConfig(t)]),this.on("show",this.loadInfo,this)},fillConfig:function(t){var e={cls:"syno-mc-setting-spam-rule-add-edit-dialog",title:"add"===t.mode?_T("common","create"):_T("common","alt_edit"),border:!1,width:500,height:288,minWidth:500,minHeight:288,items:[this.getFormPanel()],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({btnStyle:"blue",text:_T("common","ok"),scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),keys:[{key:27,scope:this,handler:this.onCancel}]};return Ext.apply(e,t),e},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({xtype:"syno_formpanel",items:[{xtype:"syno_displayfield",htmlEncode:!1,value:String.format(SYNO.SDS.MailClient._T("spam_rule","add_edit_dialog_desc"),this.spamRuleTypeString),style:{paddingTop:"6px",paddingBottom:"12px"}},{xtype:"syno_textfield",itemId:"condition",name:"condition",width:250,allowBlank:!1,validator:this.conditionValidator.bind(this),fieldLabel:SYNO.SDS.MailClient._T("mail","sender")}]}),this.formPanel},stringNotEmptyValidator:function(t){return t.trim().length>0},conditionValidator:function(t){var e=-1!==t.indexOf("@")?SYNO.SDS.MailClient.Format.isAddrSpec:SYNO.SDS.MailClient.Format.isDomainSpec;return this.stringNotEmptyValidator(t)&&e(t)},loadInfo:function(){"edit"===this.mode&&this.formPanel.getComponent("condition").setValue(this.targetInfo.condition)},prepareSpamRule:function(){var t=SYNO.SDS.MailClient.Define.SpamRuleType,e=SYNO.SDS.MailClient.Define.SpamRuleConditionType,i=this.formPanel.getComponent("condition").getValue(),n=-1!==i.indexOf("@")?e.ADDRESS:e.DOMAIN,a={type:this.isBlacklist?t.BLACK_LIST:t.WHITE_LIST,condition:i,condition_type:n};return"edit"===this.mode&&(a.id=this.targetInfo.id),a},doApply:function(t){var e="add"===this.mode?SYNO.SDS.MailClient.WebAPI.addSpamRule:SYNO.SDS.MailClient.WebAPI.setSpamRule,i={force:t};return Ext.apply(i,this.prepareSpamRule()),this.setStatusBusy(),e(i).then(function(t){this.clearStatusBusy(),this.fireEvent("apply"),this.close()}.bind(this)).catch(function(t){var e=SYNO.SDS.MailClient.Define.SpamRuleConditionType;switch(this.clearStatusBusy(),SYNO.SDS.MailClient.Error.getErrorCode(t)){case 601:this.handleAlreadyExistError(i.condition_type===e.ADDRESS,!0);break;case 602:this.handleAlreadyExistError(i.condition_type===e.ADDRESS,!1);break;case 603:this.getMsgBox().alert("",String.format(SYNO.SDS.MailClient._T("spam_rule","self_address_dialog_desc"),this.spamRuleTypeString));break;case 604:this.getMsgBox().alert("",String.format(SYNO.SDS.MailClient._T("spam_rule","maximum_limit_dialog_desc"),SYNO.SDS.MailClient.Define.spamRuleMaximumLimit))}}.bind(this))},onApply:function(){if(this.getFormPanel().getForm().isValid())return this.doApply(!1)},onCancel:function(){this.close()},handleAlreadyExistError:function(t,e){var i=t?SYNO.SDS.MailClient._T("spam_rule","email_address"):SYNO.SDS.MailClient._T("spam_rule","domain"),n=e?SYNO.SDS.MailClient._T("spam_rule","black_list"):SYNO.SDS.MailClient._T("spam_rule","white_list");if(n===this.spamRuleTypeString)return void this.getMsgBox().alert("",String.format(SYNO.SDS.MailClient._T("spam_rule","already_exist_dialog_desc"),i,n));this.getMsgBox().confirm("",String.format(SYNO.SDS.MailClient._T("spam_rule","move_exist_dialog_desc"),i,n,this.spamRuleTypeString),function(t){"yes"===t&&this.doApply(!0)},this)}}),Ext.define("SYNO.SDS.MailClient.Setting.SpamRule.GridPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Search.TextFilter","SYNO.SDS.MailClient.SpamRule.AddEditDialog"],isBlacklist:!0,constructor:function(t){this.isBlacklist=t.isBlacklist,this.emptyString=this.isBlacklist?SYNO.SDS.MailClient._T("spam_rule","empty_black_list"):SYNO.SDS.MailClient._T("spam_rule","empty_white_list"),this.spamRuleTypeString=this.isBlacklist?SYNO.SDS.MailClient._T("spam_rule","black_list"):SYNO.SDS.MailClient._T("spam_rule","white_list"),this.callParent([this.fillConfig(t)]),this.addEvents("maximumrule","storereload"),this.mon(this.getSelectionModel(),"selectionchange",this.onRowSelectionChange,this),this.mon(this,"rowdblclick",this.editSpamRule,this)},fillConfig:function(t){var e={cls:"syno-mc-setting-spam-rule-grid-panel",title:this.isBlacklist?SYNO.SDS.MailClient._T("spam_rule","black_list_title"):SYNO.SDS.MailClient._T("spam_rule","white_list_title"),autoExpandColumn:"condition",enableColumnMove:!1,enableHdMenu:!1,tbar:this.getTbarCfg(),bbar:this.getPagingToolbar(),store:this.getStore(),sm:new Ext.grid.RowSelectionModel,colModel:new Ext.grid.ColumnModel({columns:[{header:SYNO.SDS.MailClient._T("spam_rule","email_address_or_domain"),dataIndex:"condition",align:"left",width:100,treeCol:!0}]})};return Ext.apply(e,t),e},onRowSelectionChange:function(t){this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection()),this.getTopToolbar().getComponent("edit").setDisabled(1!==t.getSelections().length)},activate:function(){this.getStore().load()},checkRuleLimit:function(t){t>=SYNO.SDS.MailClient.Define.spamRuleMaximumLimit?(this.getTopToolbar().getComponent("add").setDisabled(!0),this.fireEvent("maximumrule")):this.getTopToolbar().getComponent("add").setDisabled(!1)},addSpamRule:function(){new SYNO.SDS.MailClient.SpamRule.AddEditDialog({owner:this.findWindow(),isBlacklist:this.isBlacklist,mode:"add",listeners:{scope:this,apply:function(){this.fireEvent("storereload")}}}).open()},editSpamRule:function(){new SYNO.SDS.MailClient.SpamRule.AddEditDialog({owner:this.findWindow(),isBlacklist:this.isBlacklist,mode:"edit",targetInfo:this.getSelectionModel().getSelected().data,listeners:{scope:this,apply:function(){this.fireEvent("storereload")}}}).open()},deleteSpamRule:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length)return this.ownerCt.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteSpamRule({id:t}).then(function(t){this.ownerCt.owner.clearStatusBusy(),this.getStore().reload()}.bind(this)).catch(function(t){this.ownerCt.owner.clearStatusBusy()}.bind(this))},getStore:function(){var t=SYNO.SDS.MailClient.Define.SpamRuleType;return this.store=this.store||new SYNO.API.Store({autoLoad:!1,method:"POST",proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.SpamRule",method:"list",version:1,listeners:{scope:this,beforeload:function(t,e){this.ownerCt.owner.setStatusBusy()},load:function(t,e){this.ownerCt.owner.clearStatusBusy(),this.checkRuleLimit(e.total),this.getPagingToolbar().updateInfo()},loadexception:function(t,e,i){this.ownerCt.owner.clearStatusBusy(),this.ownerCt.owner.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(i),clear:!0})}}}),reader:new Ext.data.JsonReader({root:"spam_rule",totalProperty:"total",fields:["id","type","condition","condition_type"]}),baseParams:{type:this.isBlacklist?t.BLACK_LIST:t.WHITE_LIST,offset:0,limit:SYNO.SDS.MailClient.Define.spamRulePageSize}}),this.store},getSearchField:function(){return this.searchField=this.searchField||new SYNO.SDS.MailClient.Search.TextFilter({width:198,itemId:"searchfield",store:this.getStore(),pageSize:SYNO.SDS.MailClient.Define.spamRulePageSize}),this.searchField},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this},items:[{text:_T("common","add"),handler:this.addSpamRule,itemId:"add"},{text:_T("common","alt_edit"),handler:this.editSpamRule,itemId:"edit",disabled:!0},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:function(){var t=1===this.getSelectionModel().getSelections().length?String.format(SYNO.SDS.MailClient._T("spam_rule","delete_dialog_desc"),this.spamRuleTypeString):String.format(SYNO.SDS.MailClient._T("spam_rule","delete_multiple_dialog_desc"),this.spamRuleTypeString);this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),t,function(t){"yes"===t&&this.deleteSpamRule()},this)}},"->",this.getSearchField()]}},getPagingToolbar:function(){return this.pagingToolbar=this.pagingToolbar||new SYNO.ux.PagingToolbar({store:this.getStore(),pageSize:SYNO.SDS.MailClient.Define.spamRulePageSize,displayInfo:!0}),this.pagingToolbar}}),Ext.define("SYNO.SDS.MailClient.Setting.SpamRule.Main",{extend:"SYNO.ux.TabPanel",requires:["SYNO.SDS.MailClient.Setting.SpamRule.GridPanel"],haveAlertedMaximumRule:!1,constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={activeTab:0,items:this.getTabs(),listeners:{scope:this,activate:this.onActivate,deactivate:this.onDeactivate}};return Ext.apply(e,t),e},getTabs:function(){return this.tabs=this.tabs||[new SYNO.SDS.MailClient.Setting.SpamRule.GridPanel({isBlacklist:!0,owner:this,listeners:{scope:this,maximumrule:this.onMaximumRule,storereload:this.onStoreReload}}),new SYNO.SDS.MailClient.Setting.SpamRule.GridPanel({isBlacklist:!1,owner:this,listeners:{scope:this,maximumrule:this.onMaximumRule,storereload:this.onStoreReload}})],this.tabs},onActivate:function(){this.getTabs().forEach(function(t){t.activate()})},onDeactivate:function(){this.haveAlertedMaximumRule=!1},onMaximumRule:function(){this.haveAlertedMaximumRule||(this.haveAlertedMaximumRule=!0,this.findWindow().getMsgBox().alert("",String.format(SYNO.SDS.MailClient._T("spam_rule","maximum_limit_dialog_desc"),SYNO.SDS.MailClient.Define.spamRuleMaximumLimit)))},onStoreReload:function(){this.getTabs().forEach(function(t){t.getStore().reload()})}}),Ext.define("SYNO.SDS.MailClient.ThumbContainer",{extend:"Ext.Container",xtype:"syno_mc_thumb_container",constructor:function(t){var e={items:[{xtype:"container",cls:"thumb-container",overCls:"thumb-container-over",items:[{id:this.addImageId=Ext.id(),xtype:"container",cls:"add-image",overCls:"add-image-over",hideMode:"display",items:[{xtype:"container",cls:"add-image-icon"}]},{id:this.thumbImageId=Ext.id(),xtype:"box",cls:"thumb-image",overCls:"thumb-image-over",autoEl:{tag:"img"}}]}]};this.callParent([Ext.apply(e,t)])},getAddImageCmp:function(){return Ext.getCmp(this.addImageId)},getThumbImageCmp:function(){return Ext.getCmp(this.thumbImageId)}}),Ext.define("SYNO.SDS.MailClient.ColorField",{extend:"SYNO.ux.ColorField",xtype:"mc_colorfield",constructor:function(t){this.callParent(arguments),this.menu&&(this.menu.shadow=!1)}}),Ext.define("SYNO.SDS.MailClient.ImageDataView",{extend:"SYNO.SDS.Utils.DataView.LazyDataView",constructor:function(t){var e={cls:"view-thumbnails",itemSelector:"div.thumb-wrap",singleSelect:!0,tpl:new Ext.XTemplate('<tpl for=".">','<div class="thumb-wrap">','<div ext:qtip="{filename:qtipHtmlEncode}" class="thumb">','<div class="thumb-hover thumb-loading">','<img src="../scripts/ext-3/resources/images/default/s.gif" url="{preview}">',"</div>","<span>{displayname:htmlEncode}</span>","</div>","</div>","</tpl>",'<div class="x-clear"></div>')};this.imageLoader=new SYNO.SDS.Utils.ImageLoad,this.isRetina=SYNO.SDS.UIFeatures.IconSizeManager.getRetinaAndSynohdpackStatus(),this.callParent([Ext.apply(e,t)])},onUserResize:function(){this.el.dom&&this.callParent(arguments)},onLoadItem:function(t){var e,i=t.select("img");i.elements.length&&(e=i.elements[0])&&(e.src=e.getAttribute("url"),this.imageLoader.loadImg(e,{load:function(t){var e=Ext.fly(t).parent();e&&e.removeClass("thumb-loading")},error:function(t){var e=Ext.fly(t).parent();e&&e.removeClass("thumb-loading"),t.src=this.isRetina?"webman/modules/PhotoViewer/images/2x/no_thumbnail.png":"webman/modules/PhotoViewer/images/1x/no_thumbnail.png"}}))}}),Ext.define("SYNO.SDS.MailClient.BackgroundSelector",{extend:"SYNO.SDS.MailClient.ModalWindow",constructor:function(t){var e={cls:"syno-sds-image-selector",itemId:"backgroundSelector",width:616,height:444,layout:"card",title:SYNO.SDS.MailClient._T("common","select_image"),activeItem:"default_wallpaper",items:[{itemId:"default_wallpaper",xtype:"syno_panel",layout:"fit",border:!1,padding:"0 12px 0 20px",items:this.view=new SYNO.SDS.MailClient.ImageDataView({store:t.wallpaper_defaultstore,listeners:{scope:this,dblclick:this.onApply}})}],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","choose"),btnStyle:"blue",scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):"",handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})};this.addEvents("choose"),this.callParent([Ext.apply(e,t)])},onApply:function(){var t=this.view.getSelectedRecords();this.fireEvent("choose",this.view,t[0]),this.close()}}),Ext.define("SYNO.SDS.MailClient.Setting.ThemeForm",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.ThumbContainer"],themeDefaultSetting:{0:{color:"#ffffff",default_filename:"",image:!1,mask_opacity:20,position:1,theme:0,type:0},1:{color:"#ffffff",default_filename:"01.jpg",image:!0,mask_opacity:20,position:1,theme:1,type:0},2:{color:"#000000",default_filename:"04.jpg",image:!0,mask_opacity:20,position:1,theme:2,type:0}},constructor:function(t){var e={labelWidth:124,labelPad:16,height:440,cls:"syno-mc-theme",title:SYNO.SDS.MailClient._T("setting","theme_setting"),webapi:{api:"SYNO.MailClient.Theme",methods:{get:"getinfo",set:"set"},version:"1"},items:[this.getTplField(),this.getBackgroundField(),{fieldLabel:SYNO.SDS.MailClient._T("common","opacity"),width:168,xtype:"syno_sliderfield",name:"mask_opacity",listeners:{scope:this,valuechange:this.maskOpacityChange,buffer:50}},{xtype:"container",cls:"reset_default",items:{xtype:"box",autoEl:{tag:"span",html:SYNO.SDS.MailClient._T("setting","reset_default")},listeners:{scope:this,afterrender:function(t){t.el.on("click",function(){var t=this.tplDataView.getSelectedRecords()[0];this.resetToDefault(t.get("id"))},this)}}}}],listeners:{scope:this,change:this.onChange}};this.theme_setting={},this.db_theme_setting={},this.addEvents("change","apisuccess"),this.callParent([Ext.apply(e,t)]),this.on("afterrender",function(t){this.form=t.getForm(),this.backgroundImage=Ext.getCmp(this.thumbContainerId).getThumbImageCmp(),this.backgroundAdd=Ext.getCmp(this.thumbContainerId).getAddImageCmp(),this.backgroundPosition=this.form.findField("position"),this.backgroundColor=this.form.findField("color"),this.backgroundImage.el.on("click",this.onBackgroundClick,this),this.backgroundAdd.el.on("click",this.onBackgroundClick,this)},this,{buffer:100})},onChange:function(t,e){var i;if("all"!=t)if("image"===t)SYNO.SDS.MailClient.Window.el.setStyle("background-image",e?"url("+e.url+")":"none");else if("color"===t)"#"!==e[0]&&(e="#"+e),SYNO.SDS.MailClient.Window.el.setStyle("background-color",e);else if("position"===t){var n={};switch(e){case 0:n["background-position"]="50% 50%",n["background-repeat"]="no-repeat",n["background-size"]="auto";break;case 1:n["background-position"]="50% 50%",n["background-repeat"]="no-repeat",n["background-size"]="cover";break;case 2:n["background-position"]="50% 50%",n["background-repeat"]="no-repeat",n["background-size"]="contain";break;case 3:n["background-position"]="0 0",n["background-repeat"]="no-repeat",n["background-size"]="100%";break;case 4:n["background-position"]="0 0",n["background-repeat"]="repeat",n["background-size"]="auto"}SYNO.SDS.MailClient.Window.el.setStyle(n)}else"mask_opacity"===t?(SYNO.SDS.MailClient.Window.bwrap.setStyle("background",e),Ext.fly(SYNO.SDS.MailClient.Window.tl).setStyle("background",e)):"theme"===t&&SYNO.SDS.MailClient.AppLib.StyleLoader.loadThemeStyle(e);else for(i in e)e.hasOwnProperty(i)&&this.onChange(i,e[i])},processReturnData:function(t,e,i){var n=this.getForm();"get"==t&&Ext.each(e.result,function(t){if(t.api==this.webapi.api){var e=this.tplDataView.store.indexOfId(t.data.theme);-1!=e?this.tplDataView.select(e):this.tplDataView.select(0),this.db_theme_setting=Ext.apply({},t.data),t.data.color="#"+t.data.color.toUpperCase(),t.data.image&&t.data.default_filename?(e=this.getDefaultStore().find("filename",t.data.default_filename),-1!=e?this.setBackgroundImage(!0,this.getDefaultStore().getAt(e).get("preview")):this.setBackgroundImage(!1)):t.data.image||this.setBackgroundImage(!1)}},this),i&&Ext.isArray(i.compound)&&n.loadRecords(e.result,i.compound)},processParams:function(t,e){return"set"!==t?e:(Ext.each(e,function(t){t.api==this.webapi.api&&"set"==t.method&&(t.params.color=t.params.color.substr(t.params.color.indexOf("#")+1),Ext.copyTo(t.params,this.theme_setting,"image,type,default_filename,theme"))},this),e)},allIsDefault:function(t){var e=this.themeDefaultSetting[t],i=this.getForm().getValues();return!(i.mask_opacity!==e.mask_opacity||i.color.toLowerCase()!==e.color.toLowerCase()||i.hasOwnProperty("position")&&i.position!==e.position)&&!(Ext.isDefined(this.theme_setting.image)&&this.theme_setting.image!==e.image||Ext.isDefined(this.theme_setting.default_filename)&&this.theme_setting.default_filename!==e.default_filename||Ext.isDefined(this.theme_setting.type)&&this.theme_setting.type!==e.type)},resetToDefault:function(t){Ext.copyTo(this.theme_setting,this.themeDefaultSetting[t],"color,default_filename,image,mask_opacity,position,theme,type");var e,i=null,n=this.getDefaultStore().find("filename",this.theme_setting.default_filename);-1!=n&&(i=this.getDefaultStore().getAt(n).data,e=i.preview),this.setBackgroundImage(this.theme_setting.image,e),this.fireEvent("change","theme",t),this.backgroundPosition.setValue(this.theme_setting.position),this.fireEvent("change","position",this.theme_setting.position),this.backgroundColor.setValue(this.theme_setting.color.toUpperCase()),this.fireEvent("change","color",this.theme_setting.color),this.getForm().findField("mask_opacity").setValue(this.theme_setting.mask_opacity),this.fireEvent("change","mask_opacity",this.formatMaskOpacity(t,this.theme_setting.mask_opacity)),this.fireEvent("change","image",i)},isDirty:function(){var t=this.tplDataView.getSelectedRecords();if(0!==t.length){if(t[0].get("id")!==SYNO.SDS.MailClient.Settings.theme)return!0;var e,i=["type","image","default_filename"];for(e=0;e<i.length;++e)if(this.theme_setting.hasOwnProperty(i[e])&&this.theme_setting[i[e]]!==this.db_theme_setting[i[e]])return!0;return this.getForm().isDirty()}},reset:function(){this.callParent(arguments),this.theme_setting={}},afterRender:function(){this.callParent(arguments),this.loadForm()},applyForm:function(){this.checkFormDirty&&!this.isDirty()||this.callParent(arguments)},getTplField:function(){var t=SYNO.SDS.MailClient._T;return this.tplDataView=this.tplDataView||new Ext.DataView({fieldLabel:t("common","template"),labelWidth:124,overClass:"x-view-over",singleSelect:!0,itemSelector:"div.template-thumb",cls:"theme-tpl-dataview",store:new Ext.data.ArrayStore({autoDestroy:!0,fields:["id","name","string"],idIndex:0,data:[[0,"style",t("setting","standard_style")],[1,"light",t("setting","light_style")],[2,"dark",t("setting","dark_style")]]}),tabIndex:-1,tpl:new Ext.XTemplate('<tpl for=".">','<div class="template-item">','<div class="template-thumb template-{name}"></div>','<div class="template-text">{string}</div>',"</div>","</tpl>",'<div class="x-clear"></div>'),listeners:{scope:this,containerclick:this.onThumbContainerClick,click:this.onThumbClick}}),this.tplDataView},getBackgroundField:function(){var t=SYNO.SDS.MailClient._T,e=new Ext.data.ArrayStore({fields:["id","display"],data:[[0,t("common","center")],[1,t("common","fill")],[2,t("common","fit")],[3,t("common","stretch")],[4,t("common","tile")]]});return{fieldLabel:t("common","background"),layout:"column",border:!1,tabIndex:-1,cls:"syno-mc-image-upload",items:[{xtype:"syno_mc_thumb_container",id:this.thumbContainerId=Ext.id()},{xtype:"container",cls:"option-container",items:[{name:"position",xtype:"syno_combobox",tabIndex:-1,hideLabel:!0,forceSelection:!0,allowBlank:!1,displayField:"display",valueField:"id",width:160,store:e,listeners:{scope:this,
select:this.positionSelect}},{name:"color",xtype:"mc_colorfield",tabIndex:-1,width:160,hideLabel:!0,onColorSelect:function(t,e){this.setValue("#"+e),this.fireEvent("colorselect",this,e)},listeners:{scope:this,colorselect:this.colorSelected,change:this.colorSelected}},{xtype:"syno_button",tabIndex:-1,cls:"thumb-remove-btn",text:t("composer","remove"),handler:this.setBackgroundImage.createDelegate(this,[!1,""])}]}]}},onThumbContainerClick:function(){return!1},onThumbClick:function(t,e,i,n,a){var o=t.store.getAt(e),s=o.get("id"),l=Ext.isDefined(this.theme_setting.theme)?this.theme_setting.theme:this.db_theme_setting.theme;this.allIsDefault(l)?this.resetToDefault(s):(this.theme_setting.theme=s,this.fireEvent("change","theme",s),this.fireEvent("change","mask_opacity",this.formatMaskOpacity(s,Ext.isDefined(this.theme_setting.mask_opacity)?this.theme_setting.mask_opacity:this.db_theme_setting.mask_opacity)))},positionSelect:function(t,e,i){e.data.id!==this.theme_setting.position&&(this.theme_setting.position=e.data.id,this.fireEvent("change","position",e.data.id))},formatMaskOpacity:function(t,e){return 2==t?"rgba(0,0,0,"+e/100+")":"rgba(255,255,255,"+e/100+")"},maskOpacityChange:function(t,e){var i=Ext.isDefined(this.theme_setting.theme)?this.theme_setting.theme:SYNO.SDS.MailClient.Settings.theme;this.theme_setting.mask_opacity=e,this.fireEvent("change","mask_opacity",this.formatMaskOpacity(i,e))},colorSelected:function(t,e){this.fireEvent("change","color",e)},setBackgroundImage:function(t,e,i){!0===t||i?(this.backgroundImage.el.dom.src=e,this.backgroundImage.show(),this.backgroundAdd.hide(),i?(this.backgroundPosition.setDisabled(!0),this.backgroundColor.setDisabled(!0)):(this.backgroundPosition.setDisabled(!1),this.backgroundColor.setDisabled(!1)),this.theme_setting.image=!0):(this.backgroundImage.hide(),this.backgroundAdd.show(),this.backgroundPosition.setDisabled(!0),this.backgroundColor.setDisabled(!1),this.theme_setting.image=!1,this.fireEvent("change","image",null))},onBackgroundClick:function(){new SYNO.SDS.MailClient.BackgroundSelector({owner:this.findWindow(),wallpaper_defaultstore:this.getDefaultStore(),listeners:{scope:this,choose:this.backgroundSelected}}).show()},backgroundSelected:function(t,e){e&&(this.setBackgroundImage(!0,e.get("preview")),this.theme_setting.type=e.data.type,this.theme_setting.default_filename=e.data.filename,this.fireEvent("change","image",e.data))},getDefaultStore:function(){return this.defaultStore=this.defaultStore||new Ext.data.ArrayStore({fields:["type","filename","preview","url","displayname"],data:function(){var t,e,i,n=[],a=["01.jpg","02.jpg","03.jpg","04.jpg","05.jpg","06.jpg","07.jpg","08.png"],o=SYNO.SDS.UIFeatures.IconSizeManager.getRetinaAndSynohdpackStatus(),s=String.format("webman/3rdparty/MailClient/images/{0}x/_Wallpaper",o?2:1);for(t=0;t<8;t++)e=String.format("{0}/thumbnail_{1}.jpg",s,String.leftPad(t+1,2,"0")),i=String.format("{0}/{1}",s,a[t]),n.push([0,a[t],e,i,"Wallpaper "+(t+1)]);return n}()}),this.defaultStore},resetToDBConfig:function(){var t={};Ext.copyTo(t,this.db_theme_setting,"color,type,position,theme,default_filename");var e=null,i=this.getDefaultStore().find("filename",t.default_filename);-1!=i&&(e=this.getDefaultStore().getAt(i).data),this.fireEvent("change","image",e),this.fireEvent("change","mask_opacity",this.formatMaskOpacity(t.theme,this.db_theme_setting.mask_opacity)),this.fireEvent("change","all",t)},resetPreview:function(){this.resetToDBConfig()}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.Main",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.Setting.Notification.SelectDialog","SYNO.Personal.Notification.SettingFormPanel","SYNO.SDS.MailClient.Grid.TreeView"],constructor:function(t){var e={cls:"syno-mc-setting-notification-panel",items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","general"),items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("setting","enable_extension_desc")},{xtype:"container",cls:"paired-link-container",items:{xtype:"box",cls:"paired-link",autoEl:{tag:"span",html:SYNO.SDS.MailClient._T("setting","enable_extension_link")},listeners:{afterrender:function(t){t.el.on("click",this.onClickPairedLink,this)},scope:this}}},{xtype:"syno_button",text:SYNO.SDS.MailClient._T("setting","select_mailbox_label"),handler:function(){new SYNO.SDS.MailClient.Setting.Notification.SelectDialog({owner:this.findWindow()}).open()},scope:this},this.notifySetting=new SYNO.Personal.Notification.SettingFormPanel({autoFlexcroll:!1,useGradient:!1,desktopHidden:!0,emailHidden:!0,mobileHidden:!0,browserHidden:!0,pkgName:"MailClient"})]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","paired_device"),items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("setting","paired_device_desc")},{xtype:"syno_button",text:SYNO.SDS.MailClient._T("setting","device_list"),handler:function(){new SYNO.SDS.MailClient.Setting.Notification.PairDialog({owner:this.findWindow()}).open()},scope:this}]}]};this.callParent([Ext.apply(e,t)])},onClickPairedLink:function(){var t=window.location,e=t.origin+t.pathname;SYNO.Personal.Notification.Utils.enableBrowserPush("MailClient",e).catch(function(t){}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.SelectDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.Setting.Notification.SelectTabPanel"],constructor:function(t){var e={title:SYNO.SDS.MailClient._T("setting","select_mailbox_label"),width:500,height:500,closable:!0,closeAction:"onCancel",items:[this.selectPanel=new SYNO.SDS.MailClient.Setting.Notification.SelectTabPanel({owner:this})],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),listeners:{scope:this,afterrender:function(t,e){this.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listNotification").then(function(t){var e,i;e=t.config.filter(function(t){return"label"!==t.type}),i=t.config.filter(function(t){return"label"===t.type}),this.selectPanel.loadDataIntoStore(e,i)}.bind(this)).then(function(){this.clearStatusBusy()}.bind(this)).catch(function(t){SYNO.Debug.warn(t),this.owner.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("common","error_system")),this.close()}.bind(this))}}};this.callParent([Ext.apply(e,t)])},onApply:function(){var t=this.selectPanel.getModifiedConfigs();if(Ext.isEmpty(t))return void this.close();this.setStatusBusy(),this.sendWebAPI({api:"SYNO.MailClient.Setting.Notification",method:"set",version:1,params:{config:t},scope:this,callback:function(t,e){this.clearStatusBusy(),t?this.close():this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("common","error_system"))}})},onCancel:function(){if(!this.isDirty())return void this.close();var t=function(t){"yes"===t&&this.close()};this.owner.getMsgBox().confirm(this.title,_T("common","confirm_lostchange"),t,this)},isDirty:function(){return 0<this.selectPanel.getModifiedConfigs().length}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.SelectTabPanel",{extend:"SYNO.ux.TabPanel",requires:["SYNO.SDS.MailClient.Setting.Notification.SelectGridPanel"],constructor:function(t){var e={height:400,activeTab:0,items:[new SYNO.SDS.MailClient.Setting.Notification.MailboxSelectGridPanel,new SYNO.SDS.MailClient.Setting.Notification.LabelSelectGridPanel,new SYNO.SDS.MailClient.Setting.Notification.OthersMailboxSelectGridPanel]};this.callParent([Ext.apply(e,t)])},loadDataIntoStore:function(t,e){return Promise.all([this.getItem("tab_mailbox").loadDataIntoStore(t),this.getItem("tab_label").loadDataIntoStore(e),this.getItem("tab_others_mailbox").loadDataIntoStore(t)])},getModifiedConfigs:function(){var t=[];return t=t.concat(this.getItem("tab_mailbox").getModifiedConfigs()),t=t.concat(this.getItem("tab_label").getModifiedConfigs()),t=t.concat(this.getItem("tab_others_mailbox").getModifiedConfigs())}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",constructor:function(t){var e=this,i=function(t){return t.node.attributes.isFakeNode||e.disableFirstLayerEnableColumn&&1===t.depth},n=new SYNO.ux.EnableColumn({header:SYNO.SDS.MailClient._T("setting","recieve_notification"),dataIndex:"select",width:80,menuDisabled:!0,align:"center",isIgnore:function(t,e){return i(e)},renderer:function(t,n,a){return i(a)?"":e.renderCheckBox.call(this,t,n,a)}}),a={cls:"mailbox-grid",type:null,id:null,title:"",colHeader:"",disableFirstLayerEnableColumn:!1,autoExpandColumn:"name",enableColumnMove:!1,store:this.getStore(),view:new SYNO.SDS.MailClient.Grid.TreeView({useArrows:!0,staticTree:!1,hideCollapseNodes:function(){for(var t,e,i,n=this.grid,a=n.store,o=n.view,s=0;s<a.getCount();)t=o.getRow(s),e=a.getAt(t.rowIndex).node,e&&!e.isLeaf()&&!1===e.expanded&&(i=Ext.fly(t).next(".x-tree-node-ct",!1))&&i.setStyle({display:"none"}),e&&e.attributes.isFakeNode&&Ext.fly(t).addClass("fake-node"),s++}}),sm:new Ext.grid.RowSelectionModel({singelSelect:!0}),colModel:new Ext.grid.ColumnModel({columns:[{header:this.colHeader,dataIndex:"name",align:"left",width:100,treeCol:!0,menuDisabled:!0,renderer:function(t,e,i){return t}},n]}),plugins:[n],listeners:{scope:this,viewready:function(){this.view.hideCollapseNodes(),this.view.updateScroller()}}};this.callParent([Ext.apply(a,t)])},createStore:function(){},loadDataIntoStore:function(){},getModifiedConfigs:function(){},fillSelectStatus:function(t,e){Ext.each(t,function(t){var i=e.findIndex(function(e){return e.id===t.id});-1!==i&&(t.select=e[i].enabled)},this)},getStore:function(){return this.store?this.store:(this.store=this.createStore(),this.store)},doCreateStore:function(t){return new Ext.data.Store({autoDestroy:!0,method:"GET",idProperty:"id",totalProperty:"total",pruneModifiedRecords:!0,reader:new SYNO.ux.data.TreeReader({root:"",fields:[{name:"name",mapping:t},{name:"select",convert:function(t,e){return e.attributes.data&&e.attributes.data.select}}]})})}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.MailboxSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",constructor:function(t){var e={type:"mailbox",id:"tab_mailbox",title:SYNO.SDS.MailClient._T("common","mailbox"),colHeader:SYNO.SDS.MailClient._T("common","mailbox")};this.callParent([Ext.apply(e,t)])},createStore:function(){return this.doCreateStore("text")},loadDataIntoStore:function(t){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(e){var i,n,a,o=SYNO.SDS.MailClient.Define,s=[o.draftsId,o.sentId,o.junkId,o.trashId];this.fillSelectStatus(e,t),i=SYNO.SDS.MailClient.Format.parseMailboxResp(e,null,!0,!0,!0).filter(function(t){return-1===s.indexOf(t.id)}),n=i.findIndex(function(t){return"starred"===t.id}),a=t.findIndex(function(t){return"star"===t.type}),-1!==n&&-1!==a&&(i[n].data.select=t[a].enabled),this.store.loadData(i)}.bind(this))},getModifiedConfigs:function(){var t=[];return Ext.each(this.store.getModifiedRecords(),function(e){if("starred"===e.id)return void t.push({enabled:e.data.select,id:0,type:"star"});t.push({enabled:e.data.select,id:e.id,type:"mailbox"})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.OthersMailboxSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",constructor:function(t){var e={type:"others_mailbox",id:"tab_others_mailbox",title:SYNO.SDS.MailClient._T("common","shared_mailbox"),colHeader:SYNO.SDS.MailClient._T("common","shared_mailbox"),disableFirstLayerEnableColumn:!0};this.callParent([Ext.apply(e,t)])},createStore:function(){return this.doCreateStore("text")},loadDataIntoStore:function(t){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(e){this.fillSelectStatus(e,t),this.store.loadData(SYNO.SDS.MailClient.Format.parseOthersMailboxResp(e,null,!0,!1,!0))}.bind(this))},getModifiedConfigs:function(){var t=[];return Ext.each(this.store.getModifiedRecords(),function(e){1!==e.depth&&t.push({enabled:e.data.select,id:e.id,type:"mailbox"})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.LabelSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",constructor:function(t){var e={type:"label",id:"tab_label",title:SYNO.SDS.MailClient._T("common","label"),colHeader:SYNO.SDS.MailClient._T("common","label")};this.callParent([Ext.apply(e,t)])},createStore:function(){return this.doCreateStore("name")},loadDataIntoStore:function(t){return SYNO.SDS.MailClient.Control.Model.getLabelJson().then(function(e){this.fillSelectStatus(e,t),this.store.loadData(SYNO.SDS.MailClient.Control.Model.parseLabelJsonToTreeNode(e,null,!0))}.bind(this))},getModifiedConfigs:function(){var t=[];return Ext.each(this.store.getModifiedRecords(),function(e){t.push({enabled:e.data.select,id:e.id,type:"label"})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.PairDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.Personal.Notification.PairedInfo"],constructor:function(t){var e={title:SYNO.SDS.MailClient._T("setting","paired_device"),width:500,height:500,layout:"fit",items:[this.pairedGrid=new SYNO.Personal.Notification.PairedInfo({desktopHidden:!0,pkgName:"MailClient",tbar:{xtype:"syno_toolbar",items:[{text:_T("common","refresh"),handler:function(){this.refresh()},scope:this}]}})],buttons:[{text:_T("common","close"),scope:this,handler:this.close}]};this.callParent([Ext.apply(e,t)])},refresh:function(){this.pairedGrid.getBottomToolbar()?this.pairedGrid.getBottomToolbar().doRefresh():this.pairedGrid.loadData()},onShow:function(){this.pairedGrid.fireEvent("show");var t=this.pairedGrid.getBottomToolbar();t&&(t.items.itemAt(2).hide(),t.items.itemAt(3).hide(),t.items.itemAt(4).hide()),this.callParent(arguments)}}),Ext.define("SYNO.SDS.MailClient.Setting.Lab",{extend:"SYNO.SDS.Utils.FormPanel",constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=SYNO.SDS.MailClient.MailClientLab,i={webapi:{api:"SYNO.MailClient.Setting.Lab",methods:{get:"get",set:"set"},version:"1"},labelWidth:370,fieldWidth:80,autoHeight:!0,items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("lab","lab_title"),items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("lab","lab_desc")},{xtype:"syno_checkbox",name:"enable_upload_external_image",boxLabel:SYNO.SDS.MailClient._T("lab","enable_upload_external_image"),checked:e.enable_upload_external_image}]}]};return Ext.apply(i,t),i}}),Ext.define("SYNO.SDS.MailClient.Setting.List",{extend:"SYNO.ux.ModuleList",constructor:function(t){this.callParent([this.fillConfig(t)]),this.removeClass("syno-ux-modulelist"),this.addClass("syno-ux-treepanel")},fillConfig:function(t){var e={cls:"syno-mc-setting-list",listItems:this.getListItems()};return Ext.apply(e,t),e},getListItems:function(){return[{text:SYNO.SDS.MailClient._T("setting","general"),qtip:SYNO.SDS.MailClient._T("setting","general"),fn:"tab_general"},{text:SYNO.SDS.MailClient._T("setting","theme_setting"),qtip:SYNO.SDS.MailClient._T("setting","theme_setting"),fn:"tab_theme"},{text:SYNO.SDS.MailClient._T("setting","auto_reply_forward"),qtip:SYNO.SDS.MailClient._T("setting","auto_reply_forward"),fn:"tab_autoReply"},{text:SYNO.SDS.MailClient._T("common","mailbox"),qtip:SYNO.SDS.MailClient._T("common","mailbox"),fn:"tab_mailbox"},{text:SYNO.SDS.MailClient._T("common","shared_mailbox"),qtip:SYNO.SDS.MailClient._T("common","shared_mailbox"),fn:"tab_shared_mailbox"},{text:SYNO.SDS.MailClient._T("setting","filter"),qtip:SYNO.SDS.MailClient._T("setting","filter"),fn:"tab_filter"},{text:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),qtip:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),fn:"tab_priority_mailbox"},{text:SYNO.SDS.MailClient._T("setting","smtp_title"),qtip:SYNO.SDS.MailClient._T("setting","smtp_title"),fn:"tab_smtp"},{text:SYNO.SDS.MailClient._T("setting","pop3_title"),qtip:SYNO.SDS.MailClient._T("setting","pop3_title"),fn:"tab_pop3",hidden:!SYNO.SDS.MailClient.AdminSettings.POP3.enable_pop3},{text:SYNO.SDS.MailClient._T("pgp","open_pgp"),qtip:SYNO.SDS.MailClient._T("pgp","open_pgp"),fn:"tab_pgp",hidden:SYNO.SDS.MailClient.PGPSettings.pgp_disabled},{text:SYNO.SDS.MailClient._T("setting","notification_title"),qtip:SYNO.SDS.MailClient._T("setting","notification_title"),fn:"tab_notification"},{text:SYNO.SDS.MailClient._T("spam_rule","black_list_and_white_list"),qtip:SYNO.SDS.MailClient._T("spam_rule","black_list_and_white_list"),fn:"tab_spam_rule"},{text:SYNO.SDS.MailClient._T("lab","lab_title"),qtip:SYNO.SDS.MailClient._T("lab","lab_title"),fn:"tab_lab",hidden:!SYNO.SDS.MailClient.MailClientLab.enable_lab}]}}),Ext.define("SYNO.SDS.MailClient.Setting.Card",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.Setting.General","SYNO.SDS.MailClient.Setting.PGP.KeyMgrDialog","SYNO.SDS.MailClient.Setting.AutoReply","SYNO.SDS.MailClient.Setting.SMTP","SYNO.SDS.MailClient.Setting.POP3","SYNO.SDS.MailClient.Setting.Mailbox","SYNO.SDS.MailClient.Setting.SharedMailbox","SYNO.SDS.MailClient.Setting.Filter","SYNO.SDS.MailClient.Setting.PriorityMailbox","SYNO.SDS.MailClient.Setting.PGP.Main","SYNO.SDS.MailClient.Setting.SpamRule.Main","SYNO.SDS.MailClient.Setting.ThemeForm","SYNO.SDS.MailClient.Setting.Notification.Main","SYNO.SDS.MailClient.Setting.Lab"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addClass("syno-ux-formpanel")},fillConfig:function(t){var e=[this.general_panel=new SYNO.SDS.MailClient.Setting.General({itemId:"tab_general",smtpStore:this.getSMTPStore(),owner:this}),this.theme_panel=new SYNO.SDS.MailClient.Setting.ThemeForm({itemId:"tab_theme",owner:this}),this.auto_reply_panel=new SYNO.SDS.MailClient.Setting.AutoReply({itemId:"tab_autoReply",owner:this}),this.smtp_panel=new SYNO.SDS.MailClient.Setting.SMTP({itemId:"tab_smtp",smtpStore:this.getSMTPStore(),owner:this}),this.pop3_panel=new SYNO.SDS.MailClient.Setting.POP3({itemId:"tab_pop3",owner:this}),this.shared_mailbox_panel=new SYNO.SDS.MailClient.Setting.SharedMailbox({itemId:"tab_shared_mailbox",owner:this}),this.mailbox_panel=new SYNO.SDS.MailClient.Setting.Mailbox({itemId:"tab_mailbox",owner:this}),this.filter_panel=new SYNO.SDS.MailClient.Setting.Filter({itemId:"tab_filter",owner:this}),this.spam_rule_panel=new SYNO.SDS.MailClient.Setting.SpamRule.Main({itemId:"tab_spam_rule",owner:this}),this.priority_mailbox_panel=new SYNO.SDS.MailClient.Setting.PriorityMailbox({itemId:"tab_priority_mailbox",owner:this}),this.pgp_panel=new SYNO.SDS.MailClient.Setting.PGP.Main({itemId:"tab_pgp",owner:this}),this.notification_panel=new SYNO.SDS.MailClient.Setting.Notification.Main({itemId:"tab_notification",owner:this}),this.lab_panel=new SYNO.SDS.MailClient.Setting.Lab({itemId:"tab_lab",owner:this})],i={layout:"card",cls:"syno-mc-setting-card",activeItem:0,items:e,fbar:{xtype:"statusbar",defaultText:" ",statusAlign:"left",buttonAlign:"left",items:SYNO.SDS.MailClient.Format.orderButtonsByDSM({xtype:"syno_button",btnStyle:"blue",text:_T("common","apply"),scope:this,handler:this.applyHandler},{xtype:"syno_button",text:_T("common","cancel"),scope:this,handler:this.cancelHandler})}};return Ext.apply(i,t),i},getSMTPStore:function(){return this.smtpStore=this.smtpStore||new Ext.data.JsonStore({autoDestroy:!0,root:"smtp",idProperty:"id",fields:["id","display_name","mail","host_name","port","user_name","password","connection_type","signature"],data:SYNO.SDS.MailClient.SMTP,proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Setting.SMTP",method:"list",version:1,listeners:{load:function(t,e,i,n){SYNO.SDS.MailClient.SMTP=e}}}),listeners:{scope:this,beforeload:function(){this.setStatusBusy()},load:function(){this.clearStatusBusy()}}}),this.smtpStore},applyHandler:function(){this.applyAllForm()},cancelHandler:function(){this.isAnyFormDirty()?this.findWindow().getMsgBox().confirm("",_T("common","confirm_lostchange"),function(t){"yes"==t?(this.theme_panel.isDirty()&&this.theme_panel.resetPreview(),this.findWindow().close()):this.findWindow().list_panel.selectModule(this.getDirtyPanel())},this):this.findWindow().close()},getApiArray:function(t,e){var i=[];return this.items.each(function(n,a,o){n instanceof SYNO.SDS.Utils.FormPanel&&(!e||n.getForm().isDirty()||n.isDirty&&n.isDirty())&&(i=i.concat(n.getApiArray(t)))},this),SYNO.ux.Utils.uniqueApiArray(i)},getAllForms:function(){var t=[];return this.items.each(function(e,i,n){if(e.getForm){var a=e.getForm();t.push(a)}},this),t},loadAllForm:function(t){var e;if(!1===this.onBeforeRequest("get"))return!1;e=this.getApiArray("get"),e=this.processParams("get",e),this.sendAjaxRequest("get",e)},setActiveByForm:function(t,e){this.items.each(function(e,i,n){if(e.getForm&&e.getForm()===t)return this.findWindow().list_panel.selectModule(e.itemId),!1},this)},applyAllForm:function(t){var e,i=[],n={};return!1!==this.onBeforeRequest("set")&&(this.items.each(function(t,e,a){if(!(t instanceof SYNO.SDS.Utils.FormPanel))return void(Ext.isFunction(t.getExtraActions)&&(i=i.concat(t.getExtraActions())));var o=t.getForm(),s=Ext.isDefined(t.isDirty)&&t.isDirty();if(o.isDirty()||s){var l=o.getValues(!1,"set");Ext.apply(n,l)}},this),e=this.constructApplyParams(n),e=e.concat(i),0===e.length?void this.findWindow().close():(e=e.concat(this.getApiArray("get",!0)),e=this.processParams("set",e),e.push({api:"SYNO.MailClient.Setting.SMTP",method:"list",version:1}),void this.sendAjaxRequest("set",e)))},processParams:function(t,e){return this.items.each(function(i,n,a){if(i instanceof SYNO.SDS.Utils.FormPanel){var o=i.getForm();if("set"===t){var s=Ext.isDefined(i.isDirty)&&i.isDirty();if(!o.isDirty()&&!s)return}e=i.processParams(t,e)}},this),e},clearStatus:function(t){var e=this.getFooterToolbar();e&&Ext.isFunction(e.clearStatus)&&e.clearStatus(t)},resetAllForm:function(){var t=this.getAllForms();Ext.each(t,function(t,e,i){t.reset()},this)},isAnyFormDirty:function(){var t=this.getAllForms(),e=!1;return Ext.each(t,function(t,i,n){if(t.isDirty())return e=!0,!1},this),this.getComponent("tab_mailbox").isDirty()&&(e=!0),this.getComponent("tab_shared_mailbox").isDirty()&&(e=!0),this.theme_panel.isDirty()&&(e=!0),e},getDirtyPanel:function(){var t=this.getAllForms(),e="";return Ext.each(t,function(t,i,n){if(t.isDirty())return e=t.itemId,!1},this),this.getComponent("tab_mailbox").isDirty()&&(e="tab_mailbox"),this.getComponent("tab_shared_mailbox").isDirty()&&(e="tab_shared_mailbox"),this.theme_panel.isDirty()&&(e="tab_theme"),e},getAjaxCfg:function(t){return{}},getCompoundCfg:function(t){return{}},sendAjaxRequest:function(t,e){"get"===t?this.setStatusBusy():this.setStatusBusy({text:_T("common","saving")});var i=this.getAjaxCfg(t),n=this.getCompoundCfg(t),a=Ext.apply({params:{},compound:{stopwhenerror:!1,params:e},scope:this,callback:function(e,i,n){this.clearStatusBusy(),e?this.onApiSuccess(t,i,n):this.onApiFailure(t,i,n)}},i);a.compound=Ext.apply(a.compound,n),this.sendWebAPI(a)},onBeforeRequest:function(t){var e=!1;if(this.items.each(function(i,n,a){if(i instanceof SYNO.SDS.Utils.FormPanel)return i.onBeforeRequest(t)?void 0:(e=!0,!1)},this),e)return!1;if("get"===t)return!0;if(this.checkFormDirty&&!this.isAnyFormDirty()){var i=_T("error","nochange_subject");return this.setStatusError({text:i,clear:!0}),!1}var n=this.getAllForms(),a=!0;return Ext.each(n,function(t,e,i){if(!t.isValid())return a=!1,this.setStatusError({text:_T("common","forminvalid"),clear:!0}),this.setActiveByForm(t,e),!1},this),a},checkNeedRefresh:function(){var t=this.getComponent("tab_general");(t.hasConversationViewChange||t.blLangChanged)&&(SYNO.SDS.UserSettings.save(),SYNO.SDS.UserSettings.onSaveSuccess({callback:function(){this.findAppWindow().getMsgBox().confirm("",SYNO.SDS.MailClient._T("setting","refresh_confirm"),function(t){"yes"===t&&(window.onbeforeunload=null,SYNO.SDS.MailClient.Control.Mail.backToThread(),location.reload(!0))})},scope:this}))},handleSetSuccess:function(t){var e,i=this.getComponent("tab_general"),n=this.getComponent("tab_pgp"),a=this.getComponent("tab_theme"),o=this.getComponent("tab_priority_mailbox"),s=!1,l=!1;for(e=0;e<t.result.length;++e){if(i.webapi.api===t.result[e].api&&i.webapi.methods.get===t.result[e].method&&(t.result[e].data.split_pane_mode!==SYNO.SDS.MailClient.Settings.split_pane_mode&&(2===t.result[e].data.split_pane_mode?SYNO.SDS.MailClient.Control.View.toTwoCol():SYNO.SDS.MailClient.Control.View.toThreeCol()),t.result[e].data.archive_mailbox!==SYNO.SDS.MailClient.Settings.archive_mailbox&&(s=!0),SYNO.SDS.MailClient.UserSettingProperty.setSetting({general:t.result[e].data}),i.hasConversationViewChange&&(t.result[e].data.conversation_view=SYNO.SDS.MailClient.Settings.conversation_view),SYNO.SDS.MailClient.Switch.changeSettings(t.result[e].data),l=!0),o.webapi.api===t.result[e].api&&o.webapi.methods.get===t.result[e].method&&(t.result[e].data.enable_priority_mailbox!==SYNO.SDS.MailClient.Lib.PriorityMailbox.isEnablePriorityMailbox()&&(s=!0),SYNO.SDS.MailClient.Control.Sidebar.setPriorityMailboxSetting(t.result[e].data),SYNO.SDS.MailClient.UserSettingProperty.setPriorityMailboxSetting(t.result[e].data)),(s||"SYNO.MailClient.Mailbox"==t.result[e].api&&"set"==t.result[e].method)&&SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList(),n.webapi.api===t.result[e].api&&n.webapi.methods.get===t.result[e].method&&(SYNO.SDS.MailClient.PGPSettings=t.result[e].data,SYNO.SDS.MailClient.UserSettingProperty.setSetting({pgp:t.result[e].data})),"SYNO.MailClient.Setting.SMTP"==t.result[e].api&&"list"==t.result[e].method&&(SYNO.SDS.MailClient.SMTP=t.result[e].data),a.webapi.api===t.result[e].api&&a.webapi.methods.get===t.result[e].method){var r=SYNO.SDS.MailClient.UserSettingProperty.getSettingInfo().general;SYNO.SDS.MailClient.Settings.theme=t.result[e].data.theme,r.theme=t.result[e].data.theme,SYNO.SDS.MailClient.UserSettingProperty.setSetting({general:r}),SYNO.SDS.MailClient.AppLib.StyleLoader.loadCustomStyle()}"SYNO.MailClient.Setting.Lab"==t.result[e].api&&"get"==t.result[e].method&&(SYNO.SDS.MailClient.MailClientLab=t.result[e].data)}this.checkNeedRefresh(),l&&SYNO.SDS.MailClient.Control.Main.reloadContent()},onApiSuccess:function(t,e,i){var n=this.getComponent("tab_pgp"),a=this.getComponent("tab_lab");if("set"===t)return void(e.has_fail?this.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(e)}):(this.handleSetSuccess(e),this.setStatusOK(),this.findWindow().close()));"get"===t&&e.result.forEach(function(t){n.webapi.api===t.api&&n.webapi.methods.get===t.method&&(SYNO.SDS.MailClient.PGPSettings=t.data),a.webapi.api===t.api&&a.webapi.methods.get===t.method&&(SYNO.SDS.MailClient.MailClientLab=t.data)}),this.fireEvent("configload"),this.processReturnData(t,e,i)},processReturnData:function(t,e,i){this.items.each(function(n,a,o){if(n instanceof SYNO.SDS.Utils.FormPanel){var s=n.getForm();("set"!==t||s.isDirty())&&n.processReturnData(t,e,i)}},this)},onApiFailure:function(t,e,i){"get"===t?this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(e),function(){this.findWindow().close()},this):this.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(e)})},constructApplyParams:function(t){var e,i,n,a,o,s,l={},r=[];for(i in t)if(t.hasOwnProperty(i)){if(e=i.split("|"),4!=e.length)continue;n=i.substr(0,i.lastIndexOf("|")),a=i.substr(i.lastIndexOf("|")+1),o=t[i],l[n]||(l[n]={}),l[n][a]=o}for(n in l)if(l.hasOwnProperty(n)){e=n.split("|"),s={api:e[0],method:e[1],version:e[2]},s.params=SYNO.ux.Utils.getApiParams(s,this.getApiArray("set"));for(a in l[n])l[n].hasOwnProperty(a)&&(s.params[a]=l[n][a]);r.push(s)}return r},clearStatusBusy:function(t){this.clearStatus(t),this.unmaskAppWin()},setStatus:function(t){t=t||{};var e=this.getFooterToolbar();e&&Ext.isFunction(e.setStatus)&&e.setStatus(t)},maskAppWin:function(){var t=this.findWindow();t&&Ext.isDefined(t.maskForBusy)&&t.maskForBusy()},unmaskAppWin:function(){var t=this.findWindow();t&&Ext.isDefined(t.unmask)&&t.unmask()},setStatusBusy:function(t){t=t||{},Ext.applyIf(t,{text:_T("common","loading"),iconCls:"syno-ux-statusbar-loading"}),this.setStatus(t),this.maskAppWin()},setStatusOK:function(t){t=t||{},Ext.applyIf(t,{text:_T("common","setting_applied"),iconCls:"syno-ux-statusbar-success",clear:!0}),this.setStatus(t)},setStatusError:function(t){t=t||{},Ext.applyIf(t,{text:_T("common","error_system"),iconCls:"syno-ux-statusbar-error"}),this.setStatus(t)}}),Ext.define("SYNO.SDS.MailClient.Setting.Window",{extend:"SYNO.SDS.ModalWindow",requires:["SYNO.SDS.MailClient.Setting.Card","SYNO.SDS.MailClient.Setting.List"],activePage:"tab_general",constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this.list_panel.getSelectionModel(),"selectionchange",this.onListSelect,this),this.mon(this.card_panel,"configload",this.onConfigLoad,this)},fillConfig:function(t){var e={cls:"syno-mc-setting-win syno-mc-modal-window",title:_T("common","common_settings"),width:920,height:520,minWidth:600,minHeight:400,layout:"fit",fbar:!1,closable:!0,closeAction:"onCancel",items:[{xtype:"syno_panel",layout:"border",items:[this.list_panel=new SYNO.SDS.MailClient.Setting.List({region:"west",width:220,listeners:{scope:this,afterlayout:{buffer:80,single:!0,fn:function(t,e){t.selectModule(this.activePage),this.card_panel.loadAllForm(),SYNO.SDS.MailClient.WebAPI.getInfoPOP3({}).then(function(t){SYNO.SDS.MailClient.AdminSettings.POP3=t,this.list_panel.setModuleVisible("tab_pop3",t.enable_pop3)}.bind(this)).catch(function(t){}.bind(this))}}}}),this.card_panel=new SYNO.SDS.MailClient.Setting.Card({region:"center"})]}]};return Ext.apply(e,t),e},onListSelect:function(t,e){this.activePage=e.id,this.card_panel.getLayout().setActiveItem(e.id)},onConfigLoad:function(){this.list_panel.setModuleVisible("tab_pgp",!SYNO.SDS.MailClient.PGPSettings.pgp_disabled),this.list_panel.setModuleVisible("tab_lab",SYNO.SDS.MailClient.MailClientLab.enable_lab)},onOpen:function(t){this.callParent(arguments),t&&(this.activePage=t)},onCancel:function(){this.card_panel.cancelHandler()}}),Ext.define("SYNO.SDS.MailClient.Search.SearchMailboxMenu",{extend:"SYNO.SDS.MailClient.Search.SearchTreeMenu",requires:["SYNO.SDS.MailClient.AddMailbox","SYNO.SDS.MailClient.Setting.Window"],constructor:function(t){var e=SYNO.SDS.MailClient.Define;this.hideManageBtn=!0===t.hideManageBtn,this.hideInbox=!0===t.hideInbox,this.hideCreate=!0===t.hideCreate,Ext.isArray(t.hideMailbox)?(this.hideMailbox=t.hideMailbox,delete t.hideMailbox):this.hideMailbox=[e.starredId,e.draftsId,e.junkId,e.trashId],this.callParent([this.fillConfig(t)]),this.hideCreate||(this.contentMaxHeight=224),this.hideCreate||this.hideManageBtn||(this.contentMaxHeight=196)},fillConfig:function(t){var e={menuType:"mailbox",items:[{xtype:"menuseparator",itemId:"createManageSep",hidden:this.hideManageBtn&&this.hideCreate},{itemId:"create",text:SYNO.SDS.MailClient._T("common","create"),cls:"action blue",hidden:this.hideCreate,scope:this,handler:function(){new SYNO.SDS.MailClient.AddMailbox({targetInfo:{id:0,name:SYNO.SDS.MailClient._T("common","mailbox")},createName:this.searchText,owner:this.findWindow(),listeners:{scope:this,apply:this.onCreate}}).open()}},{itemId:"manage",text:SYNO.SDS.MailClient._T("mailbox","manage"),hidden:this.hideManageBtn,cls:"action blue",handler:function(){new SYNO.SDS.MailClient.Setting.Window({owner:SYNO.SDS.MailClient.Window}).open("tab_mailbox")}}]};return Ext.apply(e,t)},onCreate:function(t,e){var i=t.id,n=e.name;SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList().then(function(){this.fireEvent("select",i,Ext.util.Format.htmlEncode(n))}.bind(this))},onSearchFieldKeyUp:function(t,e){this.callParent([t,"name"])},match:function(t,e){var i,n=!this.hideCreate&&!e,a=SYNO.SDS.MailClient.Switch.getMailboxStore().isSubscribedSharedMailbox(),o=!1,s=!1,l=[];Ext.isEmpty(this.searchText)&&(this.selector.getRootNode().collapseChildNodes(!0),this.currentNodeId&&this._expandNodeById(this.currentNodeId)),
t.forEach(function(t){for(this._expandNodeById(t.id),i=this.selector.nodeHash[t.id.toString()],i&&(!1===t.get("is_own")?s=!0:!0===t.get("is_own")&&(o=a));i;)l.push(i.id),i=i.parentNode},this),Ext.iterate(this.selector.nodeHash,function(t,e){e!=this.selector.getRootNode()&&("account"===e.attributes.type&&e.expand(),Ext.isEmpty(this.searchText)||l.indexOf(e.id)>-1||"Mailbox"===e.id&&o||"SharedMailbox"===e.id&&s?e.ui.show():e.ui.hide())},this),this.getComponent("create").setVisible(n).setText(this.searchText?String.format(SYNO.SDS.MailClient._T("common","create_sth"),this.searchText):SYNO.SDS.MailClient._T("common","create")),this.getComponent("createManageSep").setVisible(n||!this.hideManageBtn),this.adjustContentHeight()},loadList:function(){return this.store.clearData(),this.clearDisabledIds(),SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(t){var e=SYNO.SDS.MailClient.Format.parseMailboxResp(t,null,!0,!0,!0),i=this.selector.getRootNode();this.store.loadData(t),this.showSharedByOthers&&(e=this.addOthersMailbox(t,e)),this.needReload=!1,i.removeAll(!0),i.appendChild(e),this.disableSharedToOthers&&this.addDisabledIds(SYNO.SDS.MailClient.Switch.getMailboxStore().getMailboxIdsSharedToOthers()),this.currentNodeId&&(this.disableChild&&this.addDisabledIds([this.currentNodeId]),this._expandNodeById(this.currentNodeId)),(this.hideMailbox.length||this.getDisabledIds().length)&&Ext.iterate(this.selector.nodeHash,function(t,e){if(-1!==this.hideMailbox.indexOf(e.id))return void(e.isLeaf()&&Ext.isString(e.parentNode.id)&&1===e.parentNode.childNodes.length?e.parentNode.remove():e.remove());-1!==this.getDisabledIds().indexOf(e.id)&&e.disable()},this),this.selectItem(this.ownerBtn?this.ownerBtn.getMailboxId():0),this.adjustContentHeight()}.bind(this))},addOthersMailbox:function(t,e){var i=SYNO.SDS.MailClient.Format.parseOthersMailboxResp(t,null,!0,this.hideReadOnlyMailbox,!0);return Ext.isEmpty(i)?e:(e.unshift({nodoType:"async",uiProvider:Ext.tree.TreeNodeUI,cls:"syno-mc-shared-mailbox-root-node",id:"Mailbox",text:SYNO.SDS.MailClient._T("common","mailbox"),disabled:!this.mailboxEnable,children:[],qtip:SYNO.SDS.MailClient._T("common","mailbox"),leaf:!0}),e.push({nodoType:"async",uiProvider:Ext.tree.TreeNodeUI,cls:"syno-mc-shared-mailbox-root-node",id:"SharedMailbox",text:SYNO.SDS.MailClient._T("common","shared_mailbox"),disabled:!0,children:[],qtip:SYNO.SDS.MailClient._T("common","shared_mailbox"),leaf:!0}),e=e.concat(i))},selectItem:function(t){var e=this.selector.getNodeById(t),i=this.selector.getRootNode().getPath();e?i=e.getPath():this.mailboxEnable&&this.selector.nodeHash.Mailbox&&(i=this.selector.nodeHash.Mailbox.getPath()),this.selector.selectPath(i)},setCurrentMailbox:function(t){this.currentNodeId=t},getMailBoxName:function(t){var e=this.selector.getNodeById(t);return e?e.attributes.text:""},_expandNodeById:function(t){var e,i,n=SYNO.SDS.MailClient.Define,a=this.selector.getRootNode().text,o=this.store.getById(t);Ext.isEmpty(o)||(i=o.get("path"),e=i.substring(0,o.get("path").indexOf(".")),n.isSystemMailboxName(e)&&(i=i.replace(e,n.getSystemMailboxNameString(e))),i=i.substring(0,i.lastIndexOf(".")).replace(/\./g,"/"),0===i.indexOf("synology_internal_shared_namespace/")&&(i=i.substring("synology_internal_shared_namespace/".length)),this.selector.expandPath(Ext.util.Format.htmlEncode("/"+a+"/"+i),"text"))}}),Ext.define("SYNO.SDS.MailClient.ToolbarLib.BaseActionObject",{extend:"Ext.Action",constructor:function(t){this.invalid=t.invalid,this.callParent([t])},setMenuItem:function(t,e,i){var n=this.initialConfig.menu;n&&(n.setItem(t,e,i),this.callEachMenu("setItem",[t,e,i]))},checkMenuItemVisible:function(t,e){if(Ext.isFunction(t))for(var i=this.items,n=0,a=i.length;n<a;n++)i[n].menu&&i[n].menu.items.each(t,e)},callEachMenu:function(t,e){for(var i=this.items,n=0,a=i.length;n<a;n++)i[n].menu&&i[n].menu[t].apply(i[n].menu,e)}}),Ext.define("SYNO.SDS.MailClient.ToolbarLib.SplitButtonActionObject",{extend:"SYNO.SDS.MailClient.SplitButton",constructor:function(t){this.invalid=t.invalid,this.callParent([t])},setHidden:function(t){this.setVisible(!t)}}),Ext.define("SYNO.SDS.MailClient.ToolbarLib.ActionObject",{extend:"Object",requires:["SYNO.SDS.MailClient.Search.SearchLabelCheckItemMenu","SYNO.SDS.MailClient.Search.SearchMailboxMenu","SYNO.SDS.MailClient.ToolbarLib.BaseActionObject","SYNO.SDS.MailClient.ToolbarLib.SplitButtonActionObject"],singleton:!0,constructor:function(t){var e,i=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,n=SYNO.SDS.MailClient._T,a=[[i.Reload,this.reload,"reload",void 0,n("common","reload_res")],[i.DeleteMail,this.deleteMail,"delete",void 0,n("common","delete")],[i.DeleteForever,this.threadDelete,"delete",void 0,n("common","delete_forever")],[i.DiscardDraft,this.threadDiscardDraft,"delete",void 0,n("composer","discard")],[i.MoveTo,null,"move-to",new SYNO.SDS.MailClient.Search.SearchMailboxMenu({showSharedByOthers:!0,hideReadOnlyMailbox:!0,showHintForCurrentNode:!0,defaultOffsets:[0,1],listeners:{scope:this,select:function(t,e){this.threadSetMailbox(t)}}}),n("common","move_to")],[i.Label,null,"label",new SYNO.SDS.MailClient.Search.SearchLabelCheckItemMenu({defaultOffsets:[0,1],listeners:{apply:this.threadChangeLabel,scope:this}}),n("common","label")],[i.Archive,this.archiveFn,"archive",void 0,n("common","archive")],[i.ArchiveInLabel,this.archiveFn,"archive",void 0,n("common","archive")],[i.RemoveLabel,this.removeLabel,"remove-label",void 0,n("common","remove_label")],[i.AddToTodoList,this.addToTodoList,"add-todo-list",void 0,n("calendar","add_to_todo_list")]];for(e=0;e<a.length;++e)this[a[e][0]]=new SYNO.SDS.MailClient.ToolbarLib.BaseActionObject({itemId:a[e][0],handler:a[e][1],cls:"syno-mc-"+a[e][2],iconCls:"syno-mc-"+a[e][2]+"-icon",menu:a[e][3],tooltip:a[e][4],invalid:!0,hidden:-1<[i.RemoveLabel,i.DeleteForever,i.DiscardDraft].indexOf(a[e][0]),hideParent:!1,scope:this});this[i.Spam]=new SYNO.SDS.MailClient.ToolbarLib.BaseActionObject({itemId:i.Spam,handler:this.junk,scope:this,cls:"syno-mc-junk",iconCls:"syno-mc-junk-icon",tooltip:n("common","mark_spam"),invalid:!0,hidden:!1,hideParent:!1,menu:new SYNO.ux.Menu({defaultOffsets:[0,1],cls:"syno-mc-menu",items:[{itemId:i.Spam,text:n("common","mark_spam"),handler:this.junk,scope:this},{itemId:i.AddToBlackList,text:SYNO.SDS.MailClient._T("spam_rule","add_to_black_list"),handler:this.addToBlackList,scope:this}]})}),this[i.NotSpam]=new SYNO.SDS.MailClient.ToolbarLib.BaseActionObject({itemId:i.NotSpam,handler:this.notJunk,scope:this,cls:"syno-mc-not-junk",iconCls:"syno-mc-not-junk-icon",tooltip:n("common","non_spam"),invalid:!0,hidden:!1,hideParent:!1,menu:new SYNO.ux.Menu({defaultOffsets:[0,1],cls:"syno-mc-menu",items:[{itemId:i.NotSpam,text:n("common","non_spam"),handler:this.notJunk,scope:this},{itemId:i.AddToWhiteList,text:SYNO.SDS.MailClient._T("spam_rule","add_to_white_list"),handler:this.addToWhiteList,scope:this}]})}),this[i.More]=new SYNO.SDS.MailClient.ToolbarLib.BaseActionObject({itemId:i.More,cls:"syno-mc-more",iconCls:"syno-mc-more-icon",tooltip:n("common","more"),hideParent:!1,menu:new SYNO.ux.Menu({defaultOffsets:[0,1],items:[{itemId:i.MarkAllRead,text:n("common","mark_all_read"),handler:this.markAllRead,scope:this},{itemId:i.MarkRead,text:n("filter","mark_as_read"),handler:function(){this.markThreadRead(!0)},scope:this},{itemId:i.MarkUnRead,text:n("common","mark_unread"),handler:function(){this.markThreadRead(!1)},scope:this},{itemId:i.AddStar,text:n("filter","mark_as_star"),handler:function(){this.setStar(1)},scope:this},{itemId:i.RemoveStar,text:n("common","remove_star"),handler:function(){this.setStar(0)},scope:this},{itemId:i.AddToCalendar,text:n("calendar","add_to_calendar"),handler:this.addToCalendar,scope:this},{itemId:i.AddToTodoList,text:n("calendar","add_to_todo_list"),handler:this.addToTodoList,scope:this}]})}),this.list=SYNO.SDS.MailClient.Define.mainActionBarBtnList,this.callParent([t])},init:function(){this.threadStore=SYNO.SDS.MailClient.Lib.Thread.store,this.priorityThreadStores=SYNO.SDS.MailClient.Lib.PriorityMailbox.getStores(),this.threadAction=SYNO.SDS.MailClient.Lib.ThreadAction,this.threadStore.on("load",this.onStoreLoad,this);var t=SYNO.SDS.MailClient.KeyNavigator.ShortCut;SYNO.SDS.MailClient.Window.regShortCut(this,[t.DELETE,t.ARCHIVE,t.LABEL])},webAPIError:function(t){var e=SYNO.SDS.MailClient.Error.getErrorString(t);SYNO.SDS.MailClient.Window.getMsgBox().alert("",e)},reload:function(){SYNO.SDS.MailClient.Control.Main.reloadApp()},deleteMail:function(){this.threadSetMailbox(SYNO.SDS.MailClient.Define.trashId)},archiveFn:function(){this.threadSetMailbox(SYNO.SDS.MailClient.Settings.archive_mailbox)},junk:function(){var t=this.getSelectedRecords();return this.threadAction.reportSpam(t)},notJunk:function(){var t=this.getSelectedRecords();return this.threadAction.reportNotSpam(t)},addToBlackList:function(){var t=this.getSelectedRecords();return this.threadAction.addToBlackList(t)},addToWhiteList:function(){var t=this.getSelectedRecords();return this.threadAction.addToWhiteList(t)},getSelectedRecords:function(){return this.selectedRecords},getSelectedRecordIds:function(){return this.selectedRecords.map(function(t){return t.id})},getSelectedRecordData:function(){return this.selectedRecords.map(function(t){return t.data})},threadSetMailbox:function(t){var e=this.getSelectedRecords();return this.threadAction.setMailbox(e,t,this.selectedAll)},threadDelete:function(){this.threadAction.deleteForever(this.getSelectedRecordIds())},threadDiscardDraft:function(){this.threadAction.discard(this.getSelectedRecordData())},threadChangeLabel:function(t,e){var i=[];Ext.each(this.selectedRecords,function(t,e,n){i.push(t.data)},this),this.threadAction.threadChangeLabel(i,t,e,this.selectedAll)},removeLabel:function(){if(this.selectedRecords.length||this.selectedAll){var t,e=[];Ext.each(this.selectedRecords,function(i,n,a){e.push(i.data),t||Ext.each(i.get("label"),function(e,i,n){if(e.id==SYNO.SDS.MailClient.Switch.inLabelId)return t=e,!1},this)},this),this.threadAction.threadChangeLabel(e,[],[t],this.selectedAll,SYNO.SDS.MailClient.Switch.inLabelId)}},markAllRead:function(){function t(t,n,a){t.get("unread")&&(e.push(t.id),i.push(t.data))}var e=[],i=[];SYNO.SDS.MailClient.Switch.inPriority?Ext.each(this.priorityThreadStores,function(e,i){Ext.each(e.getRange(),t,this)},this):Ext.each(this.threadStore.getRange(),t,this),this.threadAction.markRead(i,!0)},markThreadRead:function(t){var e=[],i=[];Ext.each(this.selectedRecords,function(n,a,o){t&&n.get("unread")?(e.push(n.id),i.push(n.data)):t||n.get("unread")||(e.push(n.id),i.push(n.data))},this),this.threadAction.markRead(i,t,this.selectedAll)},setStar:function(t){var e=[];Ext.each(this.selectedRecords,function(i,n,a){t&&!i.get("star")?e.push(i.data):!t&&i.get("star")&&e.push(i.data)},this),this.threadAction.setStar(e,t,this.selectedAll)},onStoreLoad:function(t,e,i,n){this[SYNO.SDS.MailClient.Define.mainActionBarBtnItemId.More].setDisabled(!t.getCount())},syncWithSwitch:function(){var t=SYNO.SDS.MailClient.Switch;this.setActionBtns(t.inMailboxId,t.inLabel,t.inStar)},setActionBtns:function(t,e,i){var n=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId;this[n.MoveTo].callEachMenu("setCurrentMailbox",[t]),this.disabledMailboxActionBtns(t),e&&!SYNO.SDS.MailClient.Define.isMessageMode?(this.setBtnAvailable(n.RemoveLabel,!0),this.setBtnAvailable(n.Archive,!1)):this.setBtnAvailable(n.ArchiveInLabel,!1),i&&0===t&&this.setBtnAvailable(n.MoveTo,!1)},setBtnAvailable:function(t,e){this[t].invalid=!e,this[t].setDisabled(!e),this[t].setHidden(!e)},disabledMailboxActionBtns:function(t){var e=SYNO.SDS.MailClient.Define.mailboxDisabled(t);Ext.each(this.list.mail,function(t,i,n){var a=this[t];if(a){var o=e.indexOf(t)>-1;a.invalid=o,a.setHidden(o),a.setDisabled(o)}},this)},threadStatus:function(){var t,e,i,n=this.selectedRecords,a=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,o=!1,s=!1,l={},r=!1,d=!1;for(t=0;t<n.length;++t)e=n[t].get("unread"),i=n[t].get("star"),o=!e||o,s=!!e||s,r=i||r,d=!i||d;return l[a.MarkRead]=s,l[a.MarkUnRead]=o,l[a.AddStar]=d,l[a.RemoveStar]=r,l},handleViewSelectAll:function(){var t=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,e=this.list.selectionchange,i=[t.MarkAllRead,t.AddToCalendar,t.AddToTodoList],n=this[t.More];Ext.each(e,function(e,i,n){var a,o=this[e];if(o){switch(e){case t.DeleteMail:case t.MoveTo:case t.Archive:case t.ArchiveInLabel:a=this.isReadOnly;break;case t.Spam:a=!0;break;default:a=!1}o.setDisabled(a)}},this),n.checkMenuItemVisible(function(t){var e=-1===i.indexOf(t.itemId);t.setVisible(e)},this);var a=[];Ext.each(this.threadStore.lastOptions.params.condition,function(t,e,i){"label"==t.name&&a.push(parseInt(t.value,10))},this),this[t.Label].setMenuItem([],!0,a)},isRecordsReadOnly:function(t){var e=SYNO.SDS.MailClient.Define;return e.isInVirtaulOrLabel()?e.isThreadRecordsReadOnly(t):e.isInReadOnlyMailbox()},onViewCheckChange:function(t){if("allthread"===t)return this.selectedAll=!0,void this.handleViewSelectAll();this.selectedAll=!1,this.isReadOnly=this.isRecordsReadOnly(t),this.selectedRecords=t;var e=SYNO.SDS.MailClient.Control.Mail,i=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,n=this.list.selectionchange,a=this[i.More],o=this.threadStatus();Ext.each(n,function(e,n,a){var o=this[e];if(o)switch(e){case i.DeleteMail:case i.MoveTo:case i.Archive:case i.ArchiveInLabel:case i.Spam:o.setDisabled(0===t.length||this.isReadOnly);break;default:o.setDisabled(0===t.length)}},this),!SYNO.SDS.MailClient.Define.isMessageMode&&a.isDisabled()||a.checkMenuItemVisible(function(t){var n=!1;t.disabled||(-1<[i.MarkAllRead].indexOf(t.itemId)&&SYNO.SDS.MailClient.Define.isNormalMode?n=!this.selectedRecords.length:-1<[i.MarkRead,i.MarkUnRead,i.AddStar,i.RemoveStar].indexOf(t.itemId)?n=o[t.itemId]:SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")&&(-1<[i.AddToCalendar].indexOf(t.itemId)&&(n=1===this.selectedRecords.length),-1<[i.AddToTodoList].indexOf(t.itemId)&&SYNO.SDS.MailClient.Define.isSupportTodoPlugin()&&(n=1===this.selectedRecords.length&&!e.isInMessageView()&&!e.isThreeColAndViewMsg()))),t.setVisible(n)},this),this[i.Label].setMenuItem(t)},switchMailMode:function(){this.selectedRecords=[];var t,e=SYNO.SDS.MailClient.Define.mainActionBarBtnItemId,i=this.list.mail;for(t=0;t<i.length;++t)this[i[t]]&&!this[i[t]].invalid&&this[i[t]].show();var n=this.threadStore.getCount();this[e.More].setDisabled(!n),this.onViewCheckChange(SYNO.SDS.MailClient.Control.Selection.getCheckedThreads())},onShortCut:function(t){var e=SYNO.SDS.MailClient.KeyNavigator.ShortCut,i=SYNO.SDS.MailClient.Switch,n=SYNO.SDS.MailClient.Define;return t===e.DELETE?(i.inMailboxId==n.trashId||i.inMailboxId==n.junkId?this.threadDelete():this.deleteMail(),!0):t===e.ARCHIVE?(this.archiveFn(),!0):t===e.LABEL?this.onShortCutLabel():void 0},onShortCutLabel:function(){var t,e,i=this[SYNO.SDS.MailClient.Define.mainActionBarBtnItemId.Label],n=SYNO.SDS.MailClient.Window.getPanel("SYNO.SDS.MailClient.CardPanel").layout.activeItem;for(t=0;t<i.items.length;t++)if(e=i.items[t],e.rendered&&n.el.dom.contains(e.el.dom)&&!e.disabled&&e.menu&&!e.hasVisibleMenu()&&!e.ignoreNextClick)return e.showMenu(),!0},addToCalendar:function(){var t=this.selectedRecords[0].data.message,e=t[t.length-1].body_preview;SYNO.SDS.MailClient.SynoCalendarPlugin.setMessage({message_id:t[t.length-1].id,subject:t[t.length-1].subject,body:e.length>256?e.substr(0,255):e,rfc_message_id:t[t.length-1].rfc_message_id}),SYNO.SDS.MailClient.SynoCalendarPlugin.createCalendarAndAddEvent()},addToTodoList:function(){this.threadAction.addToTodoList(this.getSelectedRecordData())}}),Ext.define("SYNO.SDS.MailClient.Control.DefaultRef",{singleton:!0,ref:{ThreadCardPanel:function(){return this.isTwoCol()?"TwoColThreadCardPanel":"ThreeColThreadCardPanel"},PriorityThreadPanel:function(){return this.isTwoCol()?"TwoColPriorityThreadPanel":"ThreeColPriorityThreadPanel"},ThreadPanel:function(){return this.isTwoCol()?"TwoColThreadPanel":"ThreeColThreadPanel"},MessagePanel:function(){return this.isTwoCol()||this.isMessageMode()?"TwoColMessagePanel":"ThreeColMessagePanel"},TwoColPriorityThreadPanel:"mc_PriorityThreadPanel[!smallLayout]",TwoColThreadCardPanel:"mc_ThreadCardPanel[!smallLayout]",TwoColThreadPanel:"mc_ThreadPanel[!smallLayout]",TwoColMessagePanel:"mc_CardPanel > mc_MessagePanel",ThreeColPriorityThreadPanel:"mc_PriorityThreadPanel[smallLayout]",ThreeColThreadCardPanel:"mc_ThreadCardPanel[smallLayout]",ThreeColThreadPanel:"mc_ThreadPanel[smallLayout]",ThreeColMessagePanel:"mc_ThreadMessagePanel > mc_MessagePanel",MailSearchField:"mc_MailSearchField",MailList:"mc_MailList",MailboxList:"mc_MailboxList",OthersMailboxList:"mc_OthersMailboxList",LabelList:"mc_LabelList",MailboxSettingGridPanel:"mc_MailboxSettingGridPanel",OthersMailboxSettingGridPanel:"mc_OthersMailboxSettingGridPanel",PrioritySectionPanel:"mc_SplitThreadPanel",SplitThreadToolbar:"mc_SplitThreadToolbar",CardPanel:"mc_CardPanel",ListPanel:"mc_ListPanel",Main:"mc_Main",ComposePage:"mc_ComposePage",MailboxStore:function(){return[SYNO.SDS.MailClient.Switch.getMailboxStore()]},LabelStore:function(){return[SYNO.SDS.MailClient.Switch.getLabelStore()]},ThreadStore:function(){return[SYNO.SDS.MailClient.Lib.Thread.store]},GroupStore:function(){return[SYNO.SDS.MailClient.Switch.getGroupStore()]},ContactStore:function(){return[SYNO.SDS.MailClient.Switch.getContactStore()]},DraftManager:function(){return[SYNO.SDS.MailClient.Window.draftManager]},History:function(){return[SYNO.SDS.MailClient.History]},MsgBox:function(){return[SYNO.SDS.MailClient.Window.getMsgBox()]},MsgVault:function(){return[SYNO.SDS.MailClient.Lib.MsgVault]},PopOutWindowManager:function(){return[SYNO.SDS.MailClient.PopOutWindowManager]},PriorityMailbox:function(){return[SYNO.SDS.MailClient.Lib.PriorityMailbox]},Switch:function(){return[SYNO.SDS.MailClient.Switch]},ToolbarActionObject:function(){return[SYNO.SDS.MailClient.ToolbarLib.ActionObject]},ThreadLib:function(){return[SYNO.SDS.MailClient.Lib.Thread]},ThreadVault:function(){return[SYNO.SDS.MailClient.Lib.ThreadVault]},UIActor:function(){return[SYNO.SDS.MailClient.Lib.UIActor]},Window:function(){return[SYNO.SDS.MailClient.Window]}}}),Ext.define("SYNO.SDS.MailClient.Control.Base",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Control.DefaultRef"],mixins:["SYNO.SDS.MailClient.Mixin.Constructable","SYNO.SDS.MailClient.Mixin.Queryable"],config:{},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments)},forEach:function(t,e,i){this.gets(t).forEach(e,i||this)},get:function(t){return this.doGet(t)[0]||null},gets:function(t){return this.doGet(t)},ctrl:function(t){return SYNO.SDS.MailClient.Control[t]},tryTo:function(t,e,i){this.gets(t).forEach(function(t){t[e].apply(t,i)})},doGet:function(t){var e,i=this.config.ref&&this.config.ref[t],n=SYNO.SDS.MailClient.Control.DefaultRef.ref[t],a=i||n;return Ext.isFunction(a)?(e=a.call(this),Ext.isString(e)?this.doGet(e):e):this.cmpQuery(a,null)},isTwoCol:function(){return 2===SYNO.SDS.MailClient.Settings.split_pane_mode},isInMessageView:function(){return this.isTwoCol()&&this.get("MessagePanel").isVisible()},isThreeCol:function(){return 3===SYNO.SDS.MailClient.Settings.split_pane_mode},isThreeColAndViewMsg:function(){return this.isThreeCol()&&!this.get("MessagePanel").getComponent("messageSelection").isVisible()},isInPriorityMailbox:function(){return this.get("Switch").inPriority},isInMailbox:function(){return this.get("Switch").inMailbox},isEnablePriorityMailbox:function(){return this.get("PriorityMailbox").isEnablePriorityMailbox()},isNormalMode:function(){return SYNO.SDS.MailClient.Define.isNormalMode},isMessageMode:function(){return SYNO.SDS.MailClient.Define.isMessageMode},getInMailboxId:function(){return this.get("Switch").inMailboxId},getPriorityMailboxId:function(){return this.isInPriorityMailbox()&&this.get("PriorityMailbox").isDisplayingMailbox()?this.get("PriorityMailbox").getDisplayingMailboxId():null},getGlobal:function(t){return SYNO.SDS.MailClient.Switch.getRegister(t)},setGlobal:function(t,e){SYNO.SDS.MailClient.Switch.register(t,e)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Contact",{extend:"SYNO.SDS.MailClient.Control.Base",singleton:!0,config:{},updateUsageFrequency:function(t,e){return SYNO.SDS.MailClient.WebAPI.updateContactUsageFrequency({mails:t,create_if_not_owned:e}).catch(function(t){})}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Draft",{extend:"SYNO.SDS.MailClient.Control.Base",singleton:!0,config:{},beforeSend:function(t,e,i){if(this.ctrl("Thread").deleteDraftBeforeSend([{id:t,data:[e]}]),SYNO.SDS.MailClient.Settings.conversation_view){var n=this.get("ThreadLib").getCurrentThreadStore().getById(t);if(n){var a,o=n.get("message");for(a=0;a<o.length;a++)if(o[a].id===e)return;this.ctrl("Thread").modifyThread("edit",[{id:t,prop:{add_message:[SYNO.SDS.MailClient.Format.draftDataToFakeMessage(t,e,i,!0)]}}])}}},updateSendingDraft:function(t,e,i){this.ctrl("Thread").modifyThread("edit",[{id:t,prop:{edit_message:SYNO.SDS.MailClient.Format.draftDataToFakeMessage(t,e,i,!1)}}])},updateSentDraft:function(t){this.ctrl("Thread").modifyThread("edit",[{id:t.thread_id,prop:{edit_message:SYNO.SDS.MailClient.Format.fullMessageToPreviewMessage(t)}}]),this.get("MessagePanel").updateSentDraft(t)},resumeEditor:function(t){var e=this.get("DraftManager").getIdObj("send discard"),i=t.id,n=t.threadId,a=this.get("MessagePanel").getThreadSubject(),o=t.newData;e[n]&&-1!==e[n].indexOf(i)&&(this.ctrl("Thread").addDraft([{id:n,data:Ext.apply({id:i},o)}]),this.ctrl("Thread").modifyThread("edit",[{id:n,prop:{delete_message:i}}])),this.get("MessagePanel").isThreadId(n)&&null!==a&&SYNO.SDS.MailClient.ComposerLib.Draft.isSameSubject(a,o.subject)?this.get("MessagePanel").resumeEditor(o,i,n):t.editors.length||SYNO.SDS.MailClient.Window.popOutWinManager.openComposer(Ext.apply({id:i,thread_id:n},o),t)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.History",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.Condition"],singleton:!0,config:{},loadByOption:function(t,e){var i;"mail"===t&&(this.ctrl("Main").toMailApp(),i=e.state||{}),"mail"===t&&!e.thread_id&&i&&i.condition&&i.condition.equals(this.getGlobal("lastThreadCondition"))&&i.offset===this.getGlobal("offset")&&i.limit===this.getGlobal("limit")||this.ctrl("Sidebar").updateMailSidebar().then(function(){return this._execLoadOption(Ext.applyIf({type:t},e))}.bind(this))},_execLoadOption:function(t){var e=t.type,i=t.id,n=t.paging,a=t.thread_id,o=t.state,s=t.mailbox,l=t.label,r=t.search;switch(e){case"mailbox":return this.ctrl("Sidebar").openMailbox(i,n,a,o);case"label":return this.ctrl("Sidebar").openLabel(i,n,a,o);case"update":return Promise.resolve();case"mail":return s?this.ctrl("Sidebar").openMailboxByName(s,n,a,o):l?this.ctrl("Sidebar").openLabelByFullName(l,n,a,o):r?this._restoreSearchState(r,n,a,o):Promise.resolve();default:return Promise.resolve()}},_restoreSearchState:function(t,e,i,n){var a=this.get("MailSearchField"),o=this._getConditionBySearchOption(t),s=(e-1)*this.getGlobal("limit");return this.setGlobal("showSearchingToast",!0),i?(a.updateConditionAfterThreadStoreLoad(this.get("ThreadStore"),o),this.ctrl("Mail").openThread(i,n,o)):this.ctrl("Mail").loadThread(o,s)},_getConditionBySearchOption:function(t){var e=new SYNO.SDS.MailClient.Condition;return Ext.iterate(t,function(t,i){e.addCondition(t,i)},this),t.mailbox||e.addCondition("mailbox",0),e.addCondition("is_search",!0),e}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Mail",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.Condition"],singleton:!0,config:{},openMailbox:function(t,e,i,n){var a,o,s;return e=e||1,a=this.getGlobal("limit"),o=(e-1)*a,s=new SYNO.SDS.MailClient.Condition("mailbox",t),this.ctrl("Session").addOpenedCondition(s),this.tryTo("MailboxList","setLastMailboxId",[t]),this.tryTo("OthersMailboxList","setLastMailboxId",[t]),this.tryTo("LabelList","setLastLabelId",[null]),i?this.openThread(i,n,s):this.loadThread(s,o)},openLabel:function(t,e,i,n){var a,o,s;return e=e||1,a=this.getGlobal("limit"),o=(e-1)*a,s=new SYNO.SDS.MailClient.Condition("label",t),this.ctrl("Session").addOpenedCondition(s),this.tryTo("LabelList","setLastLabelId",[t]),this.tryTo("MailboxList","setLastMailboxId",[null]),this.tryTo("OthersMailboxList","setLastMailboxId",[null]),i?this.openThread(i,n,s):this.loadThread(s,o)},clickThreadByIdx:function(t){this.get("ThreadPanel").clickByIdx(t)},search:function(t){var e=[];this.setGlobal("showSearchingToast",!0),t.addCondition("is_search",!0),this.tryTo("MailSearchField","updateHistoryAfterThreadStoreLoad",[this.get("ThreadStore"),t]),this.loadThread(t,0);for(var i=0;i<t.length;i++)"from"!==t.conditions[i].name&&"to"!==t.conditions[i].name||t.conditions[i].not_operator||e.push(t.conditions[i].value);this.ctrl("Contact").updateUsageFrequency(e,!1)},searchWithAddress:function(t){var e=new SYNO.SDS.MailClient.Condition;Ext.isEmpty(t.trim())||(e.addCondition("mailbox",0),e.addCondition("keyword",String.format("from:{0} OR to:{1}",t,t)),this.search(e))},reloadMail:function(){var t=this.getGlobal("offset"),e=this.getGlobal("limit");this.ctrl("Vault").markCurrentConditionDirty(),this.isInPriorityMailbox()?this.get("PriorityMailbox").loadData():this.get("ThreadStore").reloadThread(t,e)},silentReloadMail:function(){var t=this.getGlobal("offset"),e=this.getGlobal("limit");return this.ctrl("Vault").refetchCurrentCondition().then(function(){this.isInPriorityMailbox()?this.get("PriorityMailbox").silentLoad():this.get("ThreadStore").silentLoad(t,e)}.bind(this))},updateMailByToolbar:function(){if(!this.isInPriorityMailbox()){0===this.get("ThreadPanel").getCount()?this.get("ThreadPanel").refreshPageByToolbar():this.updateMail()}},updateMail:function(t){var e=this.getGlobal("offset"),i=this.getGlobal("limit");this.isInPriorityMailbox()?this.get("PriorityMailbox").loadData(t):this.get("ThreadStore").reloadThread(e,i)},silentUpdateMail:function(){var t=this.getGlobal("offset"),e=this.getGlobal("limit");this.isInPriorityMailbox()?this.get("PriorityMailbox").silentLoad():this.get("ThreadStore").silentLoad(t,e)},updateMailIfViewIsDirty:function(t){this.isViewDirty()&&(this.setIsViewDirty(!1),SYNO.Debug("updateMailIfViewIsDirty"),this.updateMail(t))},applyPostProcessor:function(){this.get("ThreadStore").applyPostProcessor()},openThread:function(t,e,i){return i.isPriorityMailbox()?this.openPriorityMailboxThread(t,i):e&&e.condition?this.doOpenThread(t,e):this.openThreadByCondition(t,i)},doOpenThread:function(t,e){var i=this.get("ThreadStore"),n=e.condition;return this._setLastThreadCondition(n),i.loadByState(e).then(function(e){var a=i.getById(t);a?this.loadMessage(a.id):this.openThreadByCondition(t,n)}.bind(this)).catch(function(t){})},openThreadByCondition:function(t,e,i){var n=this.get("ThreadStore");return this._setLastThreadCondition(e),n.setCondition(e),n.loadSingleThread(t).then(function(t){this.get("ToolbarActionObject").syncWithSwitch(),t?(this.loadMessage(t),i||this.ctrl("Main").reloadContent()):this.loadMessage(null)}.bind(this))},openPriorityMailboxThread:function(t,e){return this._loadPriorityThread().then(function(){var i=this.get("PriorityMailbox").getStoreByThreadId(t);return i?(this.get("ThreadLib").setCurrentThreadStore(i.sectionIdx),this.loadMessage(t)):(this.get("ThreadLib").setCurrentThreadStore(-1),this.openThreadByCondition(t,e))}.bind(this)).catch(function(t){})},backToThread:function(){this.doBackToThread()},backToThreadAndKeepUrl:function(){this.doBackToThread(!0)},doBackToThread:function(t){this.ctrl("View").hideToast(),this.isMessageMode()||this.ctrl("View").backToThread(),t||(this.ctrl("Selection").updateToolbarByCheckStatus(),this.updateMailIfViewIsDirty(),this.get("History").backToThread())},loadThread:function(t,e){return this._loadThread(t,e)},_loadThread:function(t,e,i){return this.ctrl("View").backToThread(),i||this.ctrl("View").hideToast(),e=e||0,this.setGlobal("offset",e),this._setLastThreadCondition(t),this.get("MessagePanel").reloadMask=!0,this.tryTo("MailSearchField","updateByCondition",[t]),this.get("History").changeStateToThread(t),this._applyKeepSearchResultWorkaround(t),this.ctrl("View").updateDocumentTitle(),this.isThreeCol()&&!this.isMessageMode()&&this.get("MessagePanel").loadMessage(null),Ext.defer(function(){this.isMessageMode()||this.ctrl("Selection").clearSelect()},50,this),t.isPriorityMailbox()?this._loadPriorityThread():this._loadNormalThread(t,e,this.getGlobal("limit"))},_loadNormalThread:function(t,e,i){return this.ctrl("View").toNormalMailbox(),this.ctrl("Selection").selectThread([]),this._tryToShowOldCachedResult(t,e,i).then(function(){return this.get("ThreadStore").loadByCondition(t,e,i)}.bind(this)).then(function(t){0!==e&&0===t.length&&(this.get("Switch").offsetChange(0,!0),this.get("ThreadStore").reloadThread(0,i))}.bind(this))},_tryToShowOldCachedResult:function(t,e,i){return this.get("ThreadVault").isDirty(t)&&this.get("ThreadVault").has(t)?(this.get("ThreadVault").markClean(t),this.get("ThreadStore").loadByCondition(t,e,i).then(function(){this.get("ThreadVault").markDirty(t)}.bind(this))):Promise.resolve()},_loadPriorityThread:function(){return this.ctrl("View").toPriorityMailbox(),this.ctrl("Selection").selectThread([]),this.get("PriorityThreadPanel").loadPriorityThread()},loadMessage:function(t){if(SYNO.SDS.MailClient.Define.isMessageMode)return void this.get("MessagePanel").loadMessage(t);this.ctrl("View").hideToast(),this.ctrl("View").to("threadCardPanel","messagePanel"),this.get("ThreadStore").checkAndAbortExistingSearchingRequest(),this.get("MessagePanel").loadMessage(t),this.get("History").changeStateToMessage(this.getGlobal("lastThreadCondition"),t),this.ctrl("View").updateDocumentTitle()},checkNewMsg:function(t){this.get("MsgVault").checkNewMsg(t)},clearMessage:function(){return this.get("MessagePanel").showEmptyPanel(),Promise.resolve()},prefetchPriorityMailbox:function(){if(!this.isEnablePriorityMailbox())return Promise.resolve();var t=this.get("PriorityMailbox").getConditions();return this.get("ThreadVault").prefetch(Ext.unique(t))},getCurrentUnreadConditions:function(){var t=this.getCurrentConditions(),e=t.map(function(t){var e=new SYNO.SDS.MailClient.Condition(t);return e.addUnreadCondition(),e},this);return SYNO.SDS.MailClient.Array.uniqueBy(e,function(t){return t.toString()})},getCurrentConditions:function(){var t;return this.isInPriorityMailbox()?this.get("PriorityMailbox").getConditions():(t=this.get("ThreadStore").condition,t?[t]:[])},_setLastThreadCondition:function(t){this.setGlobal("lastThreadCondition",t),this.get("ToolbarActionObject").syncWithSwitch()},isDisplayingCondition:function(t){var e=t.getMailboxId(),i=t.getLabelId();return e?this.isDisplayingAnyOf([e],[]):!!i&&this.isDisplayingAnyOf([],[i])},isDisplayingAnyOf:function(t,e,i){return i&&t.push("starred"),this.isInPriorityMailbox()?this._isPriorityMailboxDisplayingAnyOf(t,e):this._isNormalMailboxDisplayingAnyOf(t,e)},_isPriorityMailboxDisplayingAnyOf:function(t,e){return this.get("PriorityMailbox").getConditionsHasMailboxId(t).length>0||this.get("PriorityMailbox").getConditionsHasLabelId(e).length>0},_isNormalMailboxDisplayingAnyOf:function(t,e){var i=t.some(function(t){return this.isDisplayingMailboxId(t)},this),n=e.some(function(t){return this.isDisplayingLabelId(t)},this);return i||n},isDisplayingMailboxId:function(t){var e=this.get("Switch");return t===SYNO.SDS.MailClient.Define.starredId?e.inStar:e.inMailboxId===t},isDisplayingLabelId:function(t){var e=this.get("Switch");return e.inLabel&&e.inLabelId===t},_applyKeepSearchResultWorkaround:function(t){var e=this.get("MailList");t.length>1&&e.mon(this.get("ThreadStore"),"load",function(){e.clearSelections()},e,{single:!0})},isOpenEditor:function(){return this.get("MessagePanel").hasEditor()},
clearSearchHighlight:function(){this.setGlobal("lastMatchedIds",[]),this.setGlobal("lastSplitKeyword","")},isViewDirty:function(){return this.__isViewDirty},setIsViewDirty:function(t){SYNO.Debug("setIsViewDirty",t),this.__isViewDirty=t}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Model",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.Condition"],singleton:!0,config:{},getMailboxJson:function(){return this.get("MailboxStore").getMailboxJson()},getMailboxJsonFromCache:function(){return this.get("MailboxStore").getMailboxJsonFromCache()},reloadMailboxJson:function(){return this.get("MailboxStore").reloadMailboxJson()},getMailboxIds:function(){return this.getMailboxJsonFromCache().map(this._objToId)},getLabelJson:function(){return this.get("LabelStore").getLabelJson()},getLabelJsonFromCache:function(){return this.get("LabelStore").getLabelJsonFromCache()},reloadLabelJson:function(){return this.get("LabelStore").reloadLabelJson()},parseLabelJsonToTreeNode:function(t,e,i){return this.get("LabelStore").parseLabelJsonToTreeNode(t,e,i)},getLabelIds:function(){return this.getLabelJsonFromCache().map(this._objToId)},getGroupJson:function(t){return this.get("GroupStore").getGroupJson(t)},getGroupJsonFromCache:function(){return this.get("GroupStore").getGroupJsonFromCache()},getContactJson:function(){return this.get("ContactStore").getContactJson()},getContactJsonFromCache:function(){return this.get("ContactStore").getContactJsonFromCache()},getAllCondition:function(){var t,e,i=this.getMailboxIds(),n=this.getLabelIds();return t=i.map(function(t){return new SYNO.SDS.MailClient.Condition("mailbox",t)}),t.push(new SYNO.SDS.MailClient.Condition("starred",!0)),e=n.map(function(t){return new SYNO.SDS.MailClient.Condition("label",t)}),[].concat(t,e)},isMailboxIdExist:function(t){return-1!==this.getMailboxJsonFromCache().findIndex(function(e){return e.id===t})},isLabelIdExist:function(t){return-1!==this.getLabelJsonFromCache().findIndex(function(e){return e.id===t})},getMailboxRecordByAttr:function(t,e){var i=this.get("MailboxStore").findExact(t,e);return this.get("MailboxStore").getAt(i)},getLabelRecordByAttr:function(t,e){var i=this.get("LabelStore").findExact(t,e);return this.get("LabelStore").getAt(i)},getMailboxPathById:function(t){var e=this.getMailboxRecordByAttr("id",t);return e?e.get("path"):""},getLabelFullNameById:function(t){var e=this.getLabelRecordByAttr("id",t);return e?e.get("full_name"):""},getLabelDisplayNameById:function(t,e){var i=this.getLabelRecordByAttr("id",t);return i?e?i.get("display_name"):Ext.util.Format.htmlEncode(i.get("display_name")):""},getChildLabelIds:function(t){var e=this.getLabelRecordByAttr("id",t),i=[];return Ext.isEmpty(e)?[]:(this.get("LabelStore").each(function(t){0===t.get("path").indexOf(e.get("path")+"/")&&i.push(t.get("id"))}),i)},_objToId:function(t){return t.id}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Selection",{extend:"SYNO.SDS.MailClient.Control.Base",singleton:!0,config:{},getCheckedThreads:function(){return this.isMessageMode()?[this.get("MessagePanel").getThread()]:this.isInPriorityMailbox()?this.get("PriorityThreadPanel").getTotalCheckedItemRecords():this.get("ThreadPanel").view.getCheckedItemRecords()},clearSelect:function(){this.selectThread([]),this.get("ThreadCardPanel").clearSelections(),this.forEach("ThreadPanel",function(t){t.view.clearDisplay()},this),this.forEach("PrioritySectionPanel",function(t){t.view.clearDisplay()},this),this.isInPriorityMailbox()&&this.get("PriorityThreadPanel").toolbar.checkNone()},selectThread:function(t){this.get("ToolbarActionObject").onViewCheckChange(t)},selectThreadOnNormal:function(t){this._checkListView(t),this.isTwoCol()&&this.selectThread(t),0===t.length&&this.clearOthersSelection(-1)},selectThreadOnPriority:function(t,e){this._checkListView(t),this.isTwoCol()&&this.selectThread(t),0===t.length&&this.clearOthersSelection(e)},updateToolbar:function(){this.selectThread(this.get("ToolbarActionObject").getSelectedRecords())},updateToolbarByCheckStatus:function(){this.selectThread(this.getCheckedThreads())},_checkListView:function(t){this.get("ThreadPanel").checkListView(t),this.isThreeCol()&&this.get("MessagePanel").checkListView(t)},clearOthersSelection:function(t){this.gets("PrioritySectionPanel").forEach(function(t,e){t.sectionIdx!==e&&t.view.uncheckAll()},this),-1===t&&this.get("ThreadPanel").view.uncheckAll()}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.ConditionCounter",{extend:"Ext.util.Observable",requires:[],constructor:function(t){var e={};this.callParent([Ext.apply(e,t)]),this.table={},this.condKeyToCond={}},add:function(t,e){var i;t.isPriorityMailbox()||(this._updateCondKeyToCond(t),i=t.toString(),e=e||1,void 0===this.table[i]&&(this.table[i]=0),this.table[i]+=e)},getConditions:function(){return Object.keys(this.table).sort(function(t,e){return this.table[e]-this.table[t]}.bind(this)).map(this._condKeyToCond.bind(this))},clear:function(){this.table={},this.condKeytoCond={}},_updateCondKeyToCond:function(t){this.condKeyToCond[t.toString()]=t},_condKeyToCond:function(t){return this.condKeyToCond[t]}}),Ext.define("SYNO.SDS.MailClient.Control.Session",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.ThreadVaultLib.ConditionCounter"],singleton:!0,config:{},constructor:function(){this.callParent(arguments),this.openedCounter=new SYNO.SDS.MailClient.ThreadVaultLib.ConditionCounter},addOpenedCondition:function(t){this.openedCounter.add(t)},getOftenOpenedConditions:function(){return this.openedCounter.getConditions()}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Sidebar",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.Condition"],singleton:!0,config:{},reloadMailbox:function(t,e,i,n){return this.ctrl("Vault").markMailboxDirty(t),this.ctrl("Mail").openMailbox(t,e,i,n)},reloadLabel:function(t,e,i,n){return this.ctrl("Vault").markLabelDirty(t),this.ctrl("Mail").openLabel(t,e,i,n)},forceReloadMailbox:function(t,e,i,n){return Promise.all([this.reloadMailbox(t,e,i,n),this.reloadMailSidebar()])},forceReloadLabel:function(t,e,i,n){return Promise.all([this.reloadLabel(t,e,i,n),this.reloadMailSidebar()])},reloadMailSidebar:function(){return this.isMessageMode()?Promise.resolve():Promise.all([this.reloadMailboxList(),this.reloadLabelList()]).then(function(){this._updatePriorityUnreadCount()}.bind(this))},updateMailSidebar:function(){return this.isMessageMode()?Promise.resolve():Promise.all([this.updateMailboxList(),this.updateLabelList()]).then(function(){this._updatePriorityUnreadCount()}.bind(this))},updateMailSidebarIfNeeded:function(){var t,e;return this.isMessageMode()?Promise.resolve():Promise.all([this._updateMailboxList().then(function(e){t=e[1]}),this._updateLabelList().then(function(t){e=t[1]})]).then(function(){(t||e)&&this._updatePriorityUnreadCount()}.bind(this))},openMsgId:function(t){var e,i,n;return SYNO.SDS.MailClient.WebAPI.send("getMessageOffsetInThreadEx",t).then(function(t){var a=t.mailbox_id,o=t.offset,s=this.getGlobal("limit"),l=Math.floor(o/s)+1;if(-1===o)throw"msg not found";return e=o%s,i=t.thread_id,n=new SYNO.SDS.MailClient.Condition("mailbox",a),this.ctrl("Vault").markMailboxDirty(a),this.openMailbox(a,l)}.bind(this)).then(function(){return this.isMessageMode()?this.ctrl("Mail").openThreadByCondition(i,n):(this.isThreeCol()?this._getSetTimeoutPromise(25):Promise.resolve()).then(function(){return this.ctrl("Mail").clickThreadByIdx(e)}.bind(this))}.bind(this)).catch(function(t){var e=SYNO.SDS.MailClient._T,i="msg not found"===t?e("mail","message_not_exist"):e("error","ui");this.get("MsgBox").alert("",i)}.bind(this))},_getSetTimeoutPromise:function(t){return new Promise(function(e,i){setTimeout(function(){e()},t)})},openDefaultMailbox:function(){var t=SYNO.SDS.MailClient.Define;return this.isEnablePriorityMailbox()?this.openMailbox(t.priorityId,1):this.openMailbox(t.inboxId,1)},openMailboxByName:function(t,e,i,n){return this.getMailboxJson().then(function(a){var o=this.get("MailboxList").getIdByName(t);return o?this._doOpenMailbox(a,o,e,i,n):this.openDefaultMailbox()}.bind(this)).then(this.updateMailSidebarIfNeeded.bind(this))},openMailbox:function(t,e,i,n){return this.getMailboxJson().then(function(a){return this._doOpenMailbox(a,t,e,i,n)}.bind(this)).then(this.updateMailSidebarIfNeeded.bind(this))},_doOpenMailbox:function(t,e,i,n,a){return e=e||this._getDefaultMailboxId(),this.tryTo("MailboxList","selectTreePanelNodeById",[e]),this.tryTo("OthersMailboxList","selectTreePanelNodeById",[e]),this.ctrl("Mail").openMailbox(e,i,n,a).then(function(){return t})},isMailboxListDirty:function(){return this.get("MailboxStore").isDirty()},reloadMailboxList:function(){return this.lastMailboxList=null,this.ctrl("Model").reloadMailboxJson().then(this.updateMailboxList.bind(this))},updateMailboxList:function(t){return t&&(this.lastMailboxList=null),this._updateMailboxList().then(function(t){return t[0]})},_updateMailboxList:function(){return this.getMailboxJson().then(function(t){var e=Ext.encode(t);return e===this.lastMailboxList?[t,!1]:(this.lastMailboxList=e,this.isMessageMode()||this._updateMailboxListUI(t),[t,!0])}.bind(this))},_updateMailboxListUI:function(t){this.get("MailboxList").updateMailboxList(t),this.forEach("MailboxSettingGridPanel",function(t){t.loadMailbox()}),this.get("OthersMailboxList").updateMailboxList(t),this.forEach("OthersMailboxSettingGridPanel",function(t){t.loadMailbox()}),this.updatePriorityMailbox()},getMailboxJson:function(){return this.ctrl("Model").getMailboxJson()},deleteMailbox:function(t){return Ext.isArray(t)||(t=[t]),SYNO.SDS.MailClient.WebAPI.deleteMailbox({id:t}).then(this._afterDeleteMailbox.bind(this)).catch(function(t){this.get("MsgBox").alert("",SYNO.SDS.MailClient.Error.getErrorString(t))}.bind(this))},_afterDeleteMailbox:function(){return this.reloadMailboxList().then(function(){this.get("PriorityMailbox").handleDeletedMailbox(),this.updatePriorityMailbox()}.bind(this))},openLabelByFullName:function(t,e,i,n){return this.getLabelJson().then(function(a){var o=this.get("LabelList").getIdByFullName(t);return o?this._doOpenLabel(a,o,e,i,n):this.openDefaultMailbox()}.bind(this))},openLabel:function(t,e,i,n){return this.getLabelJson().then(function(a){return this._doOpenLabel(a,t,e,i,n)}.bind(this)).then(this.updateMailSidebarIfNeeded.bind(this))},_doOpenLabel:function(t,e,i,n,a){return this.get("LabelList").selectTreePanelNodeById(e),this.ctrl("Mail").openLabel(e,i,n,a)},isLabelListDirty:function(){return this.get("LabelStore").isDirty()},reloadLabelList:function(){return this.ctrl("Model").reloadLabelJson().then(this.updateLabelList.bind(this))},updateLabelList:function(){return this._updateLabelList().then(function(t){return t[1]})},_updateLabelList:function(){return this.getLabelJson().then(function(t){var e=Ext.encode(t);return e===this.lastLabelList?[t,!1]:(this.lastLabelList=e,this.isMessageMode()||this._updateLabelListUI(t),[t,!0])}.bind(this))},_updateLabelListUI:function(t){this.get("LabelList").updateLabelList(t)},getLabelJson:function(){return this.ctrl("Model").getLabelJson()},_getDefaultMailboxId:function(){return this.get("PriorityMailbox").isEnablePriorityMailbox()?SYNO.SDS.MailClient.Define.priorityId:this.defaultMailboxId},setPriorityMailboxSetting:function(t){return this.get("PriorityMailbox").setSetting(t),this.updatePriorityMailboxSetting()},updatePriorityMailboxSetting:function(){return!this.get("PriorityMailbox").isEnablePriorityMailbox()&&this.isInPriorityMailbox()?this.openMailbox(SYNO.SDS.MailClient.Define.inboxId):(this.updatePriorityMailbox(),this.ctrl("Main").reloadContent())},updatePriorityMailbox:function(){this.get("PriorityThreadPanel").updateSections(),this._syncPriorityMailboxToolbar(),this._updatePriorityUnreadCount()},_updatePriorityUnreadCount:function(){this.get("MailList").updatePriorityUnreadCount()},_syncPriorityMailboxToolbar:function(){this.gets("SplitThreadToolbar").forEach(function(t){t.onPriorityMailboxChange()})},updateQuotaInfo:function(){this.isMessageMode()||this.get("MailList").updateQuotaInfo()}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Thread",{extend:"SYNO.SDS.MailClient.Control.Base",singleton:!0,config:{},addLabel:function(t,e){var i=this._getStoreToHandle(),n=this._getConditionToHandle();this.get("UIActor").actLabelApply(i,t,e),this.get("ThreadVault").updateCacheByApplyLabel(n,t,e),this.ctrl("Sidebar").updateLabelList()},removeLabel:function(t,e){var i,n=this._getStoreToHandle(),a=this._getConditionToHandle(),o=SYNO.SDS.MailClient.Switch.getLabelStore();i=e.map(function(t){return o.getById(t)}),this.get("UIActor").actLabelRemove(n,t,i),this.get("ThreadVault").updateCacheByRemoveLabel(a,t,i),this.get("ThreadVault").clearAllHiddenThread(),this.ctrl("Sidebar").updateLabelList()},modifyGlobalLabel:function(t,e,i,n,a,o){var s=this._getStoreToHandle(),l=this._getConditionToHandle();this.get("UIActor").actGlobalLabelChange(s,t,e,i,n,a,o),this.get("PriorityMailbox").onLabelChange(t,e,i,n,a),SYNO.SDS.MailClient.enableThreadVault&&this.get("ThreadVault").updateCacheByGlobalLabelChange(l,t,e,i,n,a,o)},modifyThread:function(t,e){var i=this._getStoreToHandle(),n=this._getConditionToHandle();SYNO.SDS.MailClient.Define.isNormalMode&&"refresh"===t&&(this.ctrl("Mail").backToThreadAndKeepUrl(),this.ctrl("Main").reloadContent()),this.get("UIActor").actThreadChange(i,t,e),SYNO.SDS.MailClient.enableThreadVault&&(this.get("ThreadVault").updateCacheByThreadChange(n,t,e),this.get("ThreadVault").clearAllHiddenThread())},addNewThreadToDraftMailboxIfNeeded:function(t){var e=SYNO.SDS.MailClient.Switch,i=SYNO.SDS.MailClient.Define;if(e.inMailboxId===i.draftsId&&0===e.getRegister("offset")){var n=SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore();if(!n.getById(this.threadId)){var a=e.getRegister("limit"),o=n.getCount();a===o&&n.removeAt(o-1);var s=SYNO.Util.copy(t);s.body_preview=SYNO.SDS.MailClient.Format.htmlToPlain(s.body.html,!0);var l=new n.recordType({draft:[s],id:this.threadId,label:[],last_modified:t.last_modified,message:[],star:t.star},this.threadId);n.insert(0,l)}}},addDraft:function(t){this._modifyDraft("add",t)},editDraft:function(t){this._modifyDraft("edit",t)},deleteDraft:function(t){this._modifyDraft("delete",t)},deleteDraftBeforeSend:function(t){this._modifyDraft("delete",t,!0)},_modifyDraft:function(t,e,i){var n=this._getStoreToHandle(),a=this._getConditionToHandle();i||this.get("MessagePanel").onSwitchDraftChange(t,e),this.get("PopOutWindowManager").onSwitchDraftChange(t,e),this.get("UIActor").actDraftChange(n,t,e),SYNO.SDS.MailClient.enableThreadVault&&this.get("ThreadVault").updateCacheByDraftChange(a,t,e)},_getStoreToHandle:function(){return this.get("ThreadLib").getStoreToHandle()},_getCurrentThreadStore:function(){return this.get("ThreadLib").getCurrentThreadStore()},_getConditionToHandle:function(){return this.get("ThreadLib").getConditionToHandle()}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.Vault",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.Condition"],singleton:!0,config:{},markCurrentConditionDirty:function(){var t=this.ctrl("Mail").getCurrentConditions();this._markDirtyByCondition(t)},refetchCurrentCondition:function(){var t=this.ctrl("Mail").getCurrentConditions();return this.refetchByConditions(t)},refetchAll:function(t,e,i){var n=this._getRefetchAllConditions(t,e,i);return this.refetchByConditions(n)},refetchDisplaying:function(t,e,i){var n=this._getRefetchDisplayingConditions(t,e,i);return this.refetchByConditions(n)},refetchDisplayingAndOftenOpened:function(t,e,i){var n=this._getRefetchDisplayingConditions(t,e,i),a=this._getRefetchOftenOpenedConditions(t,e,i),o=n;return SYNO.SDS.MailClient.enableFetchOftenOpenedThread&&(o=o.concat(a)),this.refetchByConditions(o)},_getRefetchAllConditions:function(t,e,i){var n,a;return i&&t.push(SYNO.SDS.MailClient.Define.starredId),n=this._getRefetchMailboxConditions(t),a=this._getRefetchLabelConditions(e),n.concat(a)},_getRefetchDisplayingConditions:function(t,e,i){var n=this._getRefetchAllConditions(t,e,i);return n.filter(function(t){return this.ctrl("Mail").isDisplayingCondition(t)},this)},_getRefetchOftenOpenedConditions:function(t,e,i){var n=this.ctrl("Session").getOftenOpenedConditions().slice(0,5),a=new SYNO.SDS.MailClient.Condition("mailbox",SYNO.SDS.MailClient.Define.inboxId);return n.push(a),i&&t.push(SYNO.SDS.MailClient.Define.starredId),n=n.filter(function(i){return i.hasAnyMailboxOrLabelId(t,e)},this)},markDirty:function(t,e,i){i&&t.push(SYNO.SDS.MailClient.Define.starredId),this.markMailboxDirty(t),this.markLabelDirty(e)},refetchMailbox:function(t){return this.refetchByConditions(this._getRefetchMailboxConditions(t))},_getRefetchMailboxConditions:function(t){var e=[],i=[];return Ext.isArray(t)||(t=[t]),e=t.map(this._mailboxIdToCondition),i=this.get("PriorityMailbox").getConditionsHasMailboxId(t),e.concat(i)},refetchPriorityMailbox:function(){var t=this.get("PriorityMailbox").getConditions();return this.refetchByConditions(t)},markUnreadSectionHavingReadThreadDirty:function(){var t=this.get("PriorityMailbox").getConditionsOfUnreadSectionHavingReadThread();this._markDirtyByCondition(t)},markMailboxDirty:function(t){this._forEach(t,this._markMailboxDirty,this),this.markUnreadMailboxDirty(t)},markUnreadMailboxDirty:function(t){this._forEach(t,this._markUnreadMailboxDirty,this)},_markMailboxDirty:function(t){var e=new SYNO.SDS.MailClient.Condition("mailbox",t);e.isPriorityMailbox()?this.markPriorityMailboxDirty():this._markDirtyByCondition(e)},_markUnreadMailboxDirty:function(t){var e=new SYNO.SDS.MailClient.Condition("mailbox",t);e.isPriorityMailbox()?this.markPriorityMailboxDirty():(e.addUnreadCondition(),this._markDirtyByCondition(e))},markPriorityMailboxDirty:function(){var t=this.get("PriorityMailbox").getConditions();this._markDirtyByCondition(t)},markConditionDirty:function(t){this._markDirtyByCondition(t)},markLabelDirty:function(t){this._forEach(t,this._markLabelDirty,this),this.markUnreadLabelDirty(t)},markUnreadLabelDirty:function(t){this._forEach(t,this._markUnreadLabelDirty,this)},_markLabelDirty:function(t){var e=new SYNO.SDS.MailClient.Condition("label",t);this._markDirtyByCondition(e)},_markUnreadLabelDirty:function(t){var e=new SYNO.SDS.MailClient.Condition("label",t);e.addUnreadCondition(),this._markDirtyByCondition(e)},refetchLabel:function(t){return this.refetchByConditions(this._getRefetchLabelConditions(t))},_getRefetchLabelConditions:function(t){var e=[],i=[];return Ext.isArray(t)||(t=[t]),e=t.map(this._labelIdToCondition),i=this.get("PriorityMailbox").getConditionsHasLabelId(t),e.concat(i)},_markDirtyByCondition:function(t){this._forEach(t,function(t){this.get("ThreadVault").markDirty(t)}.bind(this))},refetchByConditions:function(t){return Ext.isArray(t)||(t=[t]),t=Ext.unique(t),t=t.filter(function(t){return!t.isPriorityMailbox()}),this.get("ThreadVault").refetchByCompound(t)},getStockCount:function(){var t=this.get("ThreadLib").store,e=t.condition,i=t.getLastOffset(),n=t.getLastLimit(),a=t.getTotalCount(),o=i+n;return this.get("ThreadVault").getCount(e)-Math.min(o,a)},isInStock:function(){return this.isInPriorityMailbox()||!this.isInNoCacheCondition()&&this.getStockCount()>=0},isInNoCacheCondition:function(){var t=this.get("ThreadLib").store,e=t.condition;return this.get("ThreadVault").isNoCacheCondition(e)},_forEach:function(t,e,i){Ext.isArray(t)||(t=[t]),t.forEach(e,i||window)},_mailboxIdToCondition:function(t){return new SYNO.SDS.MailClient.Condition("mailbox",t)},_labelIdToCondition:function(t){return new SYNO.SDS.MailClient.Condition("label",t)},_getPageSize:function(t){return this.get("ThreadVault").getLastLimit(t)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.Control.View",{extend:"SYNO.SDS.MailClient.Control.Base",singleton:!0,config:{},to:function(t,e){var i=this.get("CardPanel");i.layout.activeItem.itemId===t&&i.layout.setActiveItem(e)},toMailApp:function(){this.get("ListPanel")&&(this.get("ListPanel").switchToMail(),this.syncCardPanel(),this.get("ToolbarActionObject").switchMailMode(),this._setSidebarMinSize(69),this.get("Window").switchToMail())},syncCardPanel:function(){this.isTwoCol()?this.toTwoCol():this.toThreeCol()},backToThread:function(){this.to("messagePanel","threadCardPanel")},toTwoCol:function(){this.get("CardPanel").switchToTwoColumn(),this.syncThreadCardPanel()},toThreeCol:function(){var t=this.get("CardPanel"),e=t.getActiveThread();t.switchToThreeColumn(),this.syncThreadCardPanel(),e&&this.ctrl("Mail").loadMessage(e.get("id"))},syncThreadCardPanel:function(){this.isInPriorityMailbox()?this.toPriorityMailbox():this.toNormalMailbox()},toPriorityMailbox:function(){this.isMessageMode()||this.get("ThreadCardPanel").switchToPriorityMailbox()},toNormalMailbox:function(){this.isMessageMode()||this.get("ThreadCardPanel").switchToNormalMailbox()},hideToast:function(){this.get("Window").hideToast()},expandLastMsg:function(){this.get("MessagePanel").getComponent("messageList").expandLastMsg()},updateDocumentTitle:function(){this.get("Switch").updateDocumentTitle()},_setSidebarMinSize:function(t){var e=this.get("Main");e.layout.west&&(e.layout.west.split.minSize=t)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.Cache",{extend:"Ext.util.Observable",requires:[],mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments),this.init()},init:function(){this.resetCacheTable()},update:function(t,e,i,n){this._updateCondKeyToCond(t);var a=t.toString();return this.updateByKey(a,e,i,n)},get:function(t,e,i){this._updateCondKeyToCond(t),this._updateLastLimit(t,i);var n=t.toString();return void 0===e&&void 0===i?this.getCachedData(n):this.getByKey(n,e,i)},has:function(t){this._updateCondKeyToCond(t);var e=t.toString();return!!this.table[e]},clear:function(t){var e=t.toString();return this.clearByKey(e)},clearAll:function(){this.resetCacheTable()},getCount:function(t){this._updateCondKeyToCond(t);var e=SYNO.SDS.MailClient.Array.isEmptyValue,i=t.toString(),n=this.getCachedData(i),a=n.findIndex(e);return-1!==a?a:n.length},getLastLimit:function(t){var e=t.toString();return void 0===this.lastLimit[e]&&(this.lastLimit[e]=25),this.lastLimit[e]},resetCacheTable:function(){this.table={},this.condKeyToCond={},this.lastLimit={},this.totalCount={}},getCachedData:function(t){return this.table[t]||(this.table[t]=[]),this.table[t]},getTotalCount:function(t){return void 0===this.totalCount[t]&&(this.totalCount[t]=-1),this.totalCount[t]},getConditions:function(){return Object.keys(this.table).map(function(t){return this._condKeyToCond(t)},this).filter(SYNO.SDS.MailClient.Array.hasValue)},forEachCond:function(t,e){Ext.iterate(this.table,function(i,n){var a=this._condKeyToCond(i);t.call(e||this,a,i)},this)},clearByKey:function(t){delete this.table[t],delete this.totalCount[t]},buildResp:function(t,e,i,n){var a,o=SYNO.SDS.MailClient.Array.isEmptyValue,s=Math.min(i+n,e),l=s-i,r={thread:t.slice(i,s),total:e};for(a=0;a<l;++a)if(o(r.thread[a]))return null;return r},getByKey:function(t,e,i){var n=this.getCachedData(t),a=this.getTotalCount(t),o=e+i,s=o>n.length&&n.length<a;return e<0?this.buildResp([],0,0,i):-1===a||s?null:this.buildResp(n,a,e,i)},getDataFromCondDataById:function(t,e){return t.find(function(t){return t.id===e},this)},getDataIdxFromCondDataById:function(t,e){return t.findIndex(function(t){return t.id===e},this)},updateByKey:function(t,e,i,n){var a,o=this.getCachedData(t);for(a=0;a<i.length;++a)o[a+e]=i[a];this.totalCount[t]=n},addThread:function(){},removeThreadFromStore:function(t,e){this.removeThread(t.condition.toString(),e)},removeThread:function(t,e){function i(t){return-1!==e.indexOf(t.id)}var n,a=this.getCachedData(t),o=[],s=[],l=0;for(Ext.isArray(e)||(e=[e]),o=a.filter(i),n=0;n<a.length;n++)void 0===a[n]?l++:i(a[n])||(s[l]=a[n],l++);this.table[t]=s,this.totalCount[t]-=o.length},getHiddenThread:function(t){var e=t.toString(),i=this.getCachedData(e),n=SYNO.SDS.MailClient.Model.ThreadStorePostProcessor,a=t.isSearch(),o=t.getLabelId(),s=t.getMailboxId();return i.filter(function(t){return n.isThreadDataHidden(t,s,o,a)})},clearAllHiddenThread:function(){Ext.iterate(this.table,function(t,e){var i=this._condKeyToCond(t);this.clearHiddenThread(i)},this)},clearHiddenThread:function(t){if(t){var e=t.toString(),i=this.getHiddenThread(t),n=i.map(function(t){return t.id});this.removeThread(e,n)}},debug:function(t){return Ext.isArray(t)||(t=[t]),t.map(function(t){return this.debugByKey(t.toString())},this)},debugByKey:function(t){return this.getCachedData(t).slice(0,10).map(function(t){var e=t.message[0].subject,i=t.message.length,n=SYNO.SDS.MailClient.Format.toTimeString(t.message[i-1].arrival_time);return String.format("{0} {1} ( {2} {3})",n,e,i,t.id)})},_updateCondKeyToCond:function(t){this.condKeyToCond[t.toString()]=t},_updateLastLimit:function(t,e){this.lastLimit[t.toString()]=e},_condKeyToCond:function(t){return this.condKeyToCond[t]}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.UIActorLib.BaseActor",{extend:"Ext.util.Observable",constructor:function(){this.callParent(arguments)},storeEditWrap:function(t,e,i,n){i=i||this;var a=t>3;a&&n.suspendEvents(),e.call(i,a),a&&(n.resumeEvents(),n.fireEvent("datachanged",n,!0))},removeEmptyThread:function(t){t.each(function(e){var i=e.get("message"),n=e.get("draft"),a=!i||0===i.length,o=!n||0===n.length;(a&&o||t.condition.isDraft()&&o)&&t.remove(e)},this)}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.DraftOperator",{extend:"SYNO.SDS.MailClient.UIActorLib.BaseActor",singleton:!0,addDraft:function(t,e){var i=e.data;t.draft.push(i)},editDraft:function(t,e){var i=e.data;t.draft.forEach(function(t){t.id===i.id&&Ext.apply(t,i)})},removeDraft:function(t,e){var i=e.data;t.draft=t.draft.filter(function(t){return-1===i.indexOf(t.id)})},handleDraftAdd:function(t,e){this.handleActionByFn(t,e,this.addDraft)},handleDraftEdit:function(t,e){this.handleActionByFn(t,e,this.editDraft)},handleDraftDelete:function(t,e){this.handleActionByFn(t,e,this.removeDraft),this.removeEmptyThread(t)},handleActionByFn:function(t,e,i){e.forEach(function(e){var n=t.getById(e.id);i.call(this,n.data,e),n.commit()},this)}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.GlobalLabelOperator",{extend:"SYNO.SDS.MailClient.UIActorLib.BaseActor",singleton:!0,handleLabelEdit:function(t,e,i,n,a,o){t.each(function(t){this.editLabel(t,e,i,n,a,o)},this)},handleLabelRemove:function(t,e){t.each(function(t){this.removeLabel(t,e)},this)},editLabel:function(t,e,i,n,a,o){this.editLabelData(t.data,e,i,n,a,o),t.commit()},removeLabel:function(t,e){this.removeLabelData(t.data,e),t.commit()},editLabelData:function(t,e,i,n,a,o){var s=SYNO.SDS.MailClient.Switch.getLabelStore().getById(e),l=t.label.find(function(t){return t.id===e});l&&s&&(l.name=i||l.name,l.text_color=n||l.text_color,l.background_color=a||l.background_color,Ext.isEmpty(i)&&!o||(l.full_name=s.get("full_name"),l.path=s.get("path")))},removeLabelData:function(t,e){var i=t.label.filter(function(t){return t.id!==e});t.label=i}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.LabelOperator",{extend:"Ext.util.Observable",requires:[],constructor:function(){this.labelUnreadCount={},this.threadLabelHash={}},adjustLabelInStore:function(t,e,i,n,a){var o=SYNO.SDS.MailClient.Switch,s=o.inLabel,l=this.isLabelIdInLabels(o.inLabelId,n);i.map(function(e){return t.getById(e)}).filter(this.hasValue).forEach(function(t){e.call(this,t,n)},this),!a&&s&&l&&t.fireEvent("datachanged",t,!0)},updateUnreadCount:function(){SYNO.SDS.MailClient.UIActorLib.Util.updateUnreadCount({},this.labelUnreadCount)},sortLabelName:function(t,e){var i=t.full_name.toLowerCase(),n=e.full_name.toLowerCase();return i===n?t.id>e.id?1:-1:i>n?1:-1},isUnreadMsg:function(t){var e=SYNO.SDS.MailClient.Define,i=t.mailbox_id===e.trashId||t.mailbox_id===e.junkId;return!t.read&&!i},isSameLabel:function(t,e){return t.id===e.id},hasValue:function(t){return!!t},without_label:function(t,e){return SYNO.SDS.MailClient.Array.without(t,e,this.isSameLabel)},intersection_label:function(t,e){return SYNO.SDS.MailClient.Array.intersection(t,e,this.isSameLabel)},isLabelIdInLabels:function(t,e){return e.some(function(e){return e.id===t})},adjustLabelUnreadCount:function(t,e,i){var n=t+"_"+e;this.threadLabelHash[n]||(this.threadLabelHash[n]=!0,this.labelUnreadCount.hasOwnProperty(e)||(this.labelUnreadCount[e]=0),this.labelUnreadCount[e]+=i)},addLabelToThreadData:function(t,e){var i=t.label,n=this.without_label(e,i),a=i.concat(n).sort(this.sortLabelName);t.label=a},addLabelToThread:function(t,e){var i=t.data.message.some(this.isUnreadMsg),n=SYNO.Util.copy(t.get("label")),a=t.get("id"),o=this.without_label(e,n),s=n.concat(o).sort(this.sortLabelName);i&&o.forEach(function(t){this.adjustLabelUnreadCount(a,t.id,1)},this),t.set("label",s)},removeLabelFromThreadData:function(t,e){var i=t.label,n=this.intersection_label(e,i),a=this.without_label(i,n).sort(this.sortLabelName);t.label=a},removeLabelFromThread:function(t,e){var i=t.data.message.some(this.isUnreadMsg),n=SYNO.Util.copy(t.get("label")),a=t.get("id"),o=this.intersection_label(e,n),s=this.without_label(n,o).sort(this.sortLabelName);i&&o.forEach(function(t){this.adjustLabelUnreadCount(a,t.id,-1)},this),t.set("label",s)}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.ThreadEditDataOperator",{extend:"Ext.util.Observable",execute:function(t,e,i){switch(e){case"message":this.setMessage(t,i);break;case"filtered_message":this.setFilteredMessage(t,i);break;case"add_message":this.addMessage(t,i);break;case"edit_message":this.editMessage(t,i);break;case"delete_message":this.deleteMessage(t,i);break;case"read_message":this.setMessageRead(t,i.id,i.value);break;case"read":this.setRead(t,i);break;case"star":this.setStar(t,i.id,i.value);break;case"set_mailbox":this.setMailbox(t,i.target_mailbox,i.operate_mailbox);break;case"delete_forever":this.deleteForever(t,i);break;case"reply_forward":this.markReplyForward(t,i.id,i.draftType)}},setMessage:function(t,e){var i=e.reduce(function(t,e){return e.read?t:t+1},0),n=e.some(function(t){return t.star});t.message=e,t.unread=i,t.star=n},setFilteredMessage:function(t,e){t.filtered_message=e},addMessage:function(t,e){t.message=t.message.concat(e)},editMessage:function(t,e){var i=t.message.slice();i.forEach(function(t,n){t.id===e.id&&(i[n]=e)}),t.message=i},deleteMessage:function(t,e){var i=t.message.filter(function(t,i){return t.id!==e.id});t.message=i},setMessageRead:function(t,e,i){this._setRead(t,i,function(t){return-1!==e.indexOf(t.id)})},setRead:function(t,e){this._setRead(t,e,function(t){return!0})},_setRead:function(t,e,i){var n=SYNO.SDS.MailClient.Array.deepCopy(t.message);n.forEach(function(t){i(t)&&(t.read=e)}),t.unread=n.filter(this._isUnread).length,t.message=n},setStar:function(t,e,i){function n(t){t.forEach(function(t){-1!==e.indexOf(t.id)&&(t.star=i)})}n(t.message),n(t.draft),t.star=i},setMailbox:function(t,e,i){function n(t){t.forEach(function(t){o.isMsgMovable(t,e,i,!0)&&(1===t.type?t.mailbox_id=s?e:a.draftsId:t.mailbox_id=e)})}var a=SYNO.SDS.MailClient.Define,o=SYNO.SDS.MailClient.MessageHouseLib.Util,s=e===a.trashId||e===a.junkId;n(t.message),n(t.draft)},deleteForever:function(t,e){function i(t){return t.filter(function(t){return t.mailbox_id!==e})}t.message=i(t.message),t.draft=i(t.draft)},markReplyForward:function(t,e,i){var n=SYNO.SDS.MailClient.Define.DraftType,a=i===n.REPLY,o=i===n.FORWARD;t.message.forEach(function(t){t.id===e&&(a&&(t.replied=!0),o&&(t.forwarded=!0))}),a&&(t.replied=!0),o&&(t.forwarded=!0)},_isRead:function(t){return t.read},_isUnread:function(t){return!t.read}}),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.CacheModifier",{
extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.UIActorLib.DraftOperator","SYNO.SDS.MailClient.UIActorLib.GlobalLabelOperator","SYNO.SDS.MailClient.UIActorLib.LabelOperator","SYNO.SDS.MailClient.UIActorLib.ThreadEditDataOperator"],mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{cacheInstance:null},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments),this.cache=this.config.cacheInstance,this.threadOperator=new SYNO.SDS.MailClient.UIActorLib.ThreadEditDataOperator,this.labelOperator=new SYNO.SDS.MailClient.UIActorLib.LabelOperator,this.DraftOperator=SYNO.SDS.MailClient.UIActorLib.DraftOperator,this.GlobalLabelOperator=SYNO.SDS.MailClient.UIActorLib.GlobalLabelOperator},handleThreadChange:function(t,e,i){switch(e){case"edit":this.editThreadByChangeList(t,i)}},handleDraftChange:function(t,e,i){switch(e){case"add":this.addDraftByChangeList(t,i);break;case"edit":this.editDraftByChangeList(t,i);break;case"delete":this.removeDraftByChangeList(t,i)}},handleGlobalLabelChange:function(t,e,i,n,a,o,s){switch(e){case"add":break;case"edit":this.editGlobalLabelByConditions(t,i,n,a,o,s);break;case"delete":this.removeGlobalLabelByConditions(t,i)}},editThreadByChangeList:function(t,e){this.processChangeItem(t,e,this.editThread)},addDraftByChangeList:function(t,e){this.processFilteredChangeItem(t,e,this.addDraft)},editDraftByChangeList:function(t,e){this.processFilteredChangeItem(t,e,this.editDraft)},removeDraftByChangeList:function(t,e){this.processFilteredChangeItem(t,e,this.removeDraft)},processChangeItem:function(t,e,i){t.forEach(function(t,n){var a=t.toString(),o=this.getCachedData(a);e.forEach(function(t,e){i.call(this,t,a,o,e,n)},this)},this)},processFilteredChangeItem:function(t,e,i){t.forEach(function(t,n){var a=t.toString(),o=this.getCachedData(a);this.getFilteredChangeList(t,o,e).forEach(function(e,n){i.call(this,e,t,o)},this)},this)},getFilteredChangeList:function(t,e,i){return i.filter(function(i){return e.find(function(e){return e.id===i.id||(!SYNO.SDS.MailClient.Settings.conversation_view&&t.isDraft()?Ext.isArray(i.data)&&i.data.indexOf(e.id)>-1:void 0)})})},addDraft:function(t,e,i){var n=t.id,a=this.getDataFromCondDataById(i,n);this.DraftOperator.addDraft(a,t)},editDraft:function(t,e,i){var n=t.id,a=this.getDataFromCondDataById(i,n);this.DraftOperator.editDraft(a,t)},removeDraft:function(t,e,i){var n,a=t.id;!SYNO.SDS.MailClient.Settings.conversation_view&&e.isDraft()&&(a=t.data[0]),(n=this.getDataFromCondDataById(i,a))&&this.DraftOperator.removeDraft(n,t)},addLabelByConditions:function(t,e,i){t.forEach(function(t){var n=t.toString();this.addLabel(n,e,i)},this)},removeLabelByConditions:function(t,e,i){t.forEach(function(t){var n=t.toString();this.removeLabel(n,e,i)},this)},addLabel:function(t,e,i){var n=this.getCachedData(t);this.getThreadsDataById(n,e).forEach(function(t){this.labelOperator.addLabelToThreadData(t,i)},this)},removeLabel:function(t,e,i){var n=this.getCachedData(t);this.getThreadsDataById(n,e).forEach(function(t){this.labelOperator.removeLabelFromThreadData(t,i)},this)},editGlobalLabelByConditions:function(t,e,i,n,a,o){t.forEach(function(t){var s=t.toString();this.editGlobalLabel(s,e,i,n,a,o)},this)},removeGlobalLabelByConditions:function(t,e){t.forEach(function(t){var i=t.toString();this.removeGlobalLabel(i,e)},this)},editGlobalLabel:function(t,e,i,n,a,o){this.getCachedData(t).forEach(function(t){this.GlobalLabelOperator.editLabelData(t,e,i,n,a,o)},this)},removeGlobalLabel:function(t,e){this.getCachedData(t).forEach(function(t){this.GlobalLabelOperator.removeLabelData(t,e)},this)},getThreadsDataById:function(t,e){return e.map(function(e){return this.getDataFromCondDataById(t,e)},this).filter(this.hasValue)},restoreDataToCondData:function(t,e){e=SYNO.SDS.MailClient.Array.deepCopy(e);var i=e.storeIdx;delete e.storeIdx,-1!==i&&t.splice(i,0,e)},editThread:function(t,e,i){var n,a=t.id,o=t.prop,s=this.getDataFromCondDataById(i,a);return s?o.all?(n=this.getDataIdxFromCondDataById(i,a),void(i[n]=o.all)):void Ext.iterate(o,function(t,e){this.threadOperator.execute(s,t,e)},this):void(o.all&&this.restoreDataToCondData(i,o.all))},getCachedData:function(t){return this.cache.getCachedData(t)},getDataFromCondDataById:function(t,e){return this.cache.getDataFromCondDataById(t,e)},getDataIdxFromCondDataById:function(t,e){return this.cache.getDataIdxFromCondDataById(t,e)},hasValue:function(t){return!!t}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.Fetcher",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.Model.ThreadProvider","SYNO.SDS.MailClient.UtilLib.Deferred"],singleton:!0,willTryToPreserveConnection:!1,constructor:function(t){this.callParent(arguments),this.Provider=SYNO.SDS.MailClient.Model.ThreadProvider,this.reqMap={},this.deferredAryMap={},this.offsetMap={},this.limitMap={}},get:function(t,e,i){var n,a,o,s,l,r=SYNO.SDS.MailClient.WebAPI,d=t.toString(),c=this.reqMap[d],h=c?this.offsetMap[d]:999999999,u=c?this.limitMap[d]:0,S=c?h+u:-1,m=e+i;return n=this._addToDeferredAry(d,e,i),this.willTryToPreserveConnection&&c&&e>=h&&m<=S?n:(c&&r.abort(c),o=Math.min(h,e),s=Math.max(S,m),l=s-o,this.offsetMap[d]=o,this.limitMap[d]=l,a=this.Provider.getThreadList(t,o,l),this.reqMap[d]=a.getAjaxId(),a.then(function(e){e.thread=SYNO.SDS.MailClient.Format.formatAddrsOfThreadsToNormal(e.thread),this._handleWebAPIResp(t,e)}.bind(this)).catch(function(t){return n.reject(t)}.bind(this)),n)},_handleWebAPIResp:function(t,e){var i=t.toString(),n=this.offsetMap[i],a=this.deferredAryMap[i];SYNO.SDS.MailClient.Switch.register("lastMatchedIds",e.matched_ids),SYNO.SDS.MailClient.Switch.register("lastSplitKeyword",e.split_keyword),a.forEach(function(t){var i,a=t[0],o=t[1],s=t[2],l=o-n,r=l+s;i=SYNO.SDS.MailClient.Array.deepCopy(e),i.thread=i.thread.slice(l,r),a.resolve(i)}.bind(this)),this._clearMap(i)},_clearMap:function(t){delete this.reqMap[t],delete this.offsetMap[t],delete this.limitMap[t],delete this.deferredAryMap[t]},_addToDeferredAry:function(t,e,i){this.deferredAryMap[t]||(this.deferredAryMap[t]=[]);var n=new SYNO.SDS.MailClient.UtilLib.Deferred;return this.deferredAryMap[t].push([n,e,i]),n}}),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.ThreadVault",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Model.ThreadProvider","SYNO.SDS.MailClient.ThreadVaultLib.Cache","SYNO.SDS.MailClient.ThreadVaultLib.CacheModifier","SYNO.SDS.MailClient.ThreadVaultLib.Fetcher","SYNO.SDS.MailClient.UtilLib.CallbackGuarder"],constructor:function(t){var e={};this.callParent([Ext.apply(e,t)]),this._guarder=new SYNO.SDS.MailClient.UtilLib.CallbackGuarder,this.initThreadVault()},initThreadVault:function(){window.tv=this,this.dirtyTable={},this.cache=new SYNO.SDS.MailClient.ThreadVaultLib.Cache,this.cacheModifier=new SYNO.SDS.MailClient.ThreadVaultLib.CacheModifier({config:{cacheInstance:this.cache}}),this.Util=SYNO.SDS.MailClient.ThreadVaultLib.ThreadVaultUtil,this.Fetcher=SYNO.SDS.MailClient.ThreadVaultLib.Fetcher,this.ThreadProvider=SYNO.SDS.MailClient.Model.ThreadProvider},get:function(t,e,i){var n=this._getFromCache(t,e,i);return!n||this.isDirty(t)||this.isNoCacheCondition(t)?this._getRefilledFromRemote(t,e,i):Promise.resolve(n)},getCount:function(t){return this.cache.getCount(t)},refetch:function(t){var e=this._getRefetchCacheCount(t);return this._fetchFromRemote(t,0,e)},refetchByCompound:function(t){var e,i;return t=Ext.isArray(t)?t:[t],e=t.map(function(t){return{condition:t,offset:0,limit:this._getRefetchCacheCount(t)}},this),i=this._fetchCallback.bind(this),this._fetchFromRemoteByCompound(e,i)},_getRefetchCacheCount:function(t){return Math.max(this.getCount(t),100)},_guard:function(t,e){return this._guarder.revoke(),this._guarder.guard(t,e||this)},prefetch:function(t){var e,i,n=SYNO.SDS.MailClient.Settings.conversations_per_page,a=Math.max(2*n,100);return t=t.filter(function(t){return!this.has(t)},this),e=t.map(function(t){return{condition:t,offset:0,limit:a}},this),i=this._guard(this._fetchCallback),this._fetchFromRemoteByCompound(e,i)},_fetchCallback:function(t,e,i){t&&(this.clearDirty(i.condition),this.updateCache(i.condition,i.offset,e))},clearHiddenThread:function(t){this.cache.clearHiddenThread(t)},clearAllHiddenThread:function(t){this.cache.clearAllHiddenThread()},_getFromCache:function(t,e,i){var n=this.cache.get(t,e,i);return this.processCacheResp(n)},_getRefilledFromRemote:function(t,e,i){var n=this.getCacheCount(t),a=Math.max(e-n,0),o=this.isNoCacheCondition(t),s=o?1:2,l=Math.floor(i*s),r=o?l:Math.max(l,100);return a=Math.min(a,500),this._fetchFromRemote(t,e-a,r+a).then(function(){return this._getFromCache(t,e,i)}.bind(this))},_getFromRemote:function(t,e,i){return this._fetchFromRemote(t,e,i).then(function(){return this._getFromCache(t,e,i)}.bind(this))},_fetchFromRemote:function(t,e,i){return this.Fetcher.get(t,e,i).then(function(i){this.clearDirty(t),this.updateCache(t,e,i)}.bind(this))},_fetchFromRemoteByCompound:function(t,e){var i;return i=t.map(function(t){return{condition:t.condition,offset:t.offset,limit:t.limit,callback:function(i,n){e(i,n,t)}}},this),this.ThreadProvider.getThreadLists(i)},getCacheCount:function(t){return this.isDirty(t)?0:this.cache.getCount(t)},has:function(t){return this.cache.has(t)},isNoCacheCondition:function(t){return t.isSearch()||t.isDraft()},markDirty:function(t){this.dirtyTable[t.toString()]=!0},markAllDirty:function(){this._getCachedConditions().forEach(function(t){this.markDirty(t)},this)},markClean:function(t){delete this.dirtyTable[t.toString()]},isDirty:function(t){return this.dirtyTable[t.toString()]},clearDirty:function(t){var e=t.toString();this.dirtyTable[e]&&(this.cache.clear(t),delete this.dirtyTable[t.toString()])},getLastLimit:function(t){return this.cache.getLastLimit(t)},clearAll:function(){this.cache.clearAll()},updateCache:function(t,e,i){this.cache.update(t,e,i.thread,i.total)},updateCacheByStore:function(t){var e=t.condition,i=t.totalLength,n=t.baseParams.offset,a=t.toJson();this.cache.update(e,n,a,i)},updateCacheByThreadChange:function(t,e,i){var n=this._getCachedConditions();this.cacheModifier.handleThreadChange(n,e,i),this.clearAllHiddenThread()},updateCacheByDraftChange:function(t,e,i){var n=this._getCachedConditions();this.cacheModifier.handleDraftChange(n,e,i),this.clearAllHiddenThread()},updateCacheByGlobalLabelChange:function(t,e,i,n,a,o,s){var l=this._getCachedConditions();this.cacheModifier.handleGlobalLabelChange(l,e,i,n,a,o,s)},updateCacheByApplyLabel:function(t,e,i){var n=this._getCachedConditions();this.cacheModifier.addLabelByConditions(n,e,i)},updateCacheByRemoveLabel:function(t,e,i){var n=this._getCachedConditions();this.cacheModifier.removeLabelByConditions(n,e,i)},processCacheResp:function(t){return SYNO.SDS.MailClient.Array.deepCopy(t)},_getCachedConditions:function(){return this.cache.getConditions()},debug:function(t){return t=t||SYNO.SDS.MailClient.Control.Mail.getCurrentConditions(),this.cache.debug(t)}}),Ext.define("SYNO.SDS.MailClient.Lib.ThreadVault",{extend:"SYNO.SDS.MailClient.ThreadVaultLib.ThreadVault",singleton:!0}),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.PreFetcher",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Lib.ThreadVault"],singleton:!0,constructor:function(){this.callParent(arguments),this.task=new Ext.util.DelayedTask(this.run,this),this.interval=100},prefetch:function(t){var e=this._getPrefetchConds();return t=t||5,0===e.length?(this._isRunning=!1,Promise.resolve()):(e=e.slice(0,t),SYNO.SDS.MailClient.Lib.ThreadVault.prefetch(e))},start:function(){this._isRunning=!0,this.run()},stop:function(){this._isRunning=!1},restart:function(){this.stop(),SYNO.SDS.MailClient.Lib.ThreadVault.clearAll(),this.start()},run:function(){return this._isRunning?this.prefetch().then(function(){this.task.delay(this.interval)}.bind(this)):Promise.resolve()},_getPrefetchConds:function(){var t=SYNO.SDS.MailClient.Control.Model.getAllCondition();return t.filter(function(t){return!SYNO.SDS.MailClient.Lib.ThreadVault.has(t)},this)}}),Ext.define("SYNO.SDS.MailClient.Control.Main",{extend:"SYNO.SDS.MailClient.Control.Base",requires:["SYNO.SDS.MailClient.Control.Contact","SYNO.SDS.MailClient.Control.Draft","SYNO.SDS.MailClient.Control.History","SYNO.SDS.MailClient.Control.Mail","SYNO.SDS.MailClient.Control.Model","SYNO.SDS.MailClient.Control.Selection","SYNO.SDS.MailClient.Control.Session","SYNO.SDS.MailClient.Control.Sidebar","SYNO.SDS.MailClient.Control.Thread","SYNO.SDS.MailClient.Control.Vault","SYNO.SDS.MailClient.Control.View","SYNO.SDS.MailClient.ThreadVaultLib.PreFetcher"],singleton:!0,config:{},initMailApp:function(){var t=SYNO.SDS.MailClient.UserSettingProperty;if(SYNO.SDS.MailClient.enableDebugLog=t.getEnableDebugLog(),SYNO.SDS.MailClient.enableThreadVault=t.getEnableThreadVault(),SYNO.SDS.MailClient.enableMailDelayedUpdate=t.getEnableMailDelayedUpdate(),SYNO.SDS.MailClient.enableFetchNewMailThread=t.getEnableFetchNewMailThread(),SYNO.SDS.MailClient.enableFetchOftenOpenedThread=t.getEnableFetchOftenOpenedThread(),SYNO.SDS.MailClient.disablePriorityMailboxUpdater=t.getDisablePriorityMailboxUpdater(),SYNO.SDS.MailClient.enableAdvancedRfcMsgIdGrouping=t.getEnableAdvancedRfcMsgIdGrouping(),window.ct=SYNO.SDS.MailClient.Control,window.syno_mc_flag=function(){(new SYNO.SDS.MailClient.Misc.Flags.Window).show()},this.isNormalMode())return this.setupNotificationPairedLink(),SYNO.SDS.MailClient.History.loadByURL()?Promise.resolve():this.reloadSidebar().then(function(){return this.toMailAppLandingPage()}.bind(this))},toMailAppLandingPage:function(){return this.toMailApp(),this.ctrl("Sidebar").openDefaultMailbox()},toMailApp:function(){this.get("Switch").currentStatus="mail",this.ctrl("View").toMailApp()},reloadApp:function(){return Promise.all([this.reloadSidebar(),this.reloadContent()])},reloadSidebar:function(){return this.ctrl("Sidebar").reloadMailSidebar()},reloadContent:function(){return this.ctrl("Mail").reloadMail()},setupNotificationPairedLink:function(){var t=window.location,e=t.origin+t.pathname;SYNO.Personal.Notification.Utils.setupBrowserPush("MailClient",e,!0).then(function(){}).catch(function(t){})}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.UIActorLib.ThreadEditRecordOperator",{extend:"SYNO.SDS.MailClient.UIActorLib.ThreadEditDataOperator",execute:function(t,e,i){switch(e){case"all":this.setAll(t,i);break;case"message":this.setMessage(t,i);break;case"filtered_message":this.setFilteredMessage(t,i);break;case"add_message":this.addMessage(t,i);break;case"edit_message":this.editMessage(t,i);break;case"delete_message":this.deleteMessage(t,i);break;case"read_message":this.setMessageRead(t,i.id,i.value);break;case"read":this.setRead(t,i);break;case"star":this.setStar(t,i.id,i.value);break;case"set_mailbox":this.setMailbox(t,i.target_mailbox,i.operate_mailbox);break;case"delete_forever":this.deleteForever(t,i);break;case"reply_forward":this.markReplyForward(t,i.id,i.draftType)}},setAll:function(t,e){delete t.storeIdx,t.data=e},setMessage:function(t,e){this.callParent([t.data,e])},setFilteredMessage:function(t,e){this.callParent([t.data,e])},addMessage:function(t,e){this.callParent([t.data,e])},editMessage:function(t,e){this.callParent([t.data,e])},deleteMessage:function(t,e){this.callParent([t.data,e])},setMessageRead:function(t,e,i){this.callParent([t.data,e,i])},setRead:function(t,e){this.callParent([t.data,e])},setStar:function(t,e,i){this.callParent([t.data,e,i])},setMailbox:function(t,e,i){this.callParent([t.data,e,i])},deleteForever:function(t,e){this.callParent([t.data,e])},markReplyForward:function(t,e,i){this.callParent([t.data,e,i])}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.Util",{extend:"Ext.util.Observable",singleton:!0,updateUnreadCount:function(t,e){t=t||{},e=e||{};var i,n,a=SYNO.SDS.MailClient.Switch.getMailboxStore(),o=SYNO.SDS.MailClient.Switch.getLabelStore(),s=SYNO.SDS.MailClient.Define,l=!1;for(i in t)if(t.hasOwnProperty(i)){if(-1<[s.trashId,s.draftsId,s.sentId].indexOf(parseInt(i,10)))continue;n=a.getById(i),n.data.additional.unread_count+=t[i],n.data.additional.unread_count<0&&(n.data.additional.unread_count=0),l=!0}for(i in e)if(e.hasOwnProperty(i)){if(!(n=o.getById(i)))return;n.data.additional.unread_count+=e[i],n.data.additional.unread_count<0&&(n.data.additional.unread_count=0),l=!0}l&&SYNO.SDS.MailClient.Control.Sidebar.updateMailSidebar()},increaseDraftUnreadCount:function(){this._modifyDraftUnreadCount(1)},decreaseDraftUnreadCount:function(){this._modifyDraftUnreadCount(-1)},_modifyDraftUnreadCount:function(t){var e=SYNO.SDS.MailClient.Switch.getMailboxStore(),i=SYNO.SDS.MailClient.Define,n=e.getById(i.draftsId);return n?n.data.additional.total_count+t<0?void SYNO.Debug.error("negative draft total_count"):(n.data.additional.total_count+=t,void SYNO.SDS.MailClient.Control.Sidebar.updateMailSidebar()):void SYNO.Debug.error("draft mailbox not found")}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.ThreadActor",{extend:"SYNO.SDS.MailClient.UIActorLib.BaseActor",requires:["SYNO.SDS.MailClient.UIActorLib.ThreadEditRecordOperator","SYNO.SDS.MailClient.UIActorLib.Util"],singleton:!0,constructor:function(){this.callParent(arguments),this.threadEditOperator=new SYNO.SDS.MailClient.UIActorLib.ThreadEditRecordOperator},_handleUnreadCountWhenSetMailbox:function(t,e,i,n,a,o){function s(t){t.forEach(function(t){if(!c.isMsgMovable(t,a,o,!0))return void(m=!0);r=1===t.type?u?a:d.draftsId:a,-1===i.indexOf(t.mailbox_id)&&i.push(t.mailbox_id),-1===n.indexOf(r)&&n.push(r)})}function l(t,i){t.forEach(function(t){e.hasOwnProperty(t.id)||(e[t.id]=0),i?e[t.id]+=1:e[t.id]-=1})}var r,d=SYNO.SDS.MailClient.Define,c=SYNO.SDS.MailClient.MessageHouseLib.Util,h=o===d.trashId||o===d.junkId,u=a===d.trashId||a===d.junkId,S=0!==t.get("filtered_message").length,m=!1;0!==t.get("unread")?(s(t.get("message")),s(t.get("draft")),u&&!m&&l(t.get("label"),!1),h&&!S&&l(t.get("label"),!0)):h&&!u&&function(t){t.forEach(function(t){t.read||(r=1===t.type?d.draftsId:a,-1===n.indexOf(r)&&n.push(r))})}(t.get("filtered_message"))},handleUnreadCount:function(t,e){var i={},n={},a=SYNO.SDS.MailClient.Define,o=SYNO.SDS.MailClient.Switch,s=o.inMailboxId===a.trashId||o.inMailboxId===a.junkId,l={};Ext.each(t,function(t,a){Ext.each(e,function(e,a,o){var r=t.getById(e.id);r&&!l[e.id]&&(Ext.iterate(e.prop,function(t,e,a){var o,l,d,c,h=[],u=[];if("read"===t||"read_message"===t){if((d="read_message"===t?e.value:e)!==r.get("unread")>0)return;if(!s)for(o=r.get("label"),l=0;l<o.length;++l)n.hasOwnProperty(o[l].id)||(n[o[l].id]=0),d&&0!==r.data.unread?n[o[l].id]-=1:d||0!==r.data.unread||(n[o[l].id]+=1);c=Ext.unique(r.get("message").map(function(t){return t.mailbox_id})),d?h=h.concat(c):u=u.concat(c)}else"set_mailbox"===t?this._handleUnreadCountWhenSetMailbox(r,n,h,u,e.target_mailbox,e.operate_mailbox):"delete_forever"===t&&0!==r.get("unread")&&h.push(e);var S=u.concat(h);for(l=0;l<S.length;++l)i.hasOwnProperty(S[l])||(i[S[l]]=0);for(l=0;l<h.length;++l)i[h[l]]-=1;for(l=0;l<u.length;++l)i[u[l]]+=1},this),l[e.id]=!0)},this)},this),SYNO.SDS.MailClient.UIActorLib.Util.updateUnreadCount(i,n)},handleThreadRestore:function(t,e){e=SYNO.SDS.MailClient.Array.deepCopy(e);var i=e.storeIdx;delete e.storeIdx,-1!==i&&(t.insert(i,new t.recordType(e,e.id)),t.totalLength+=1)},handleThreadEdit:function(t,e){t.suspendEvents(),e.forEach(function(e){var i,n=t.getById(e.id);if(!n)return i=SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore(),void(e.prop.all&&t===i&&this.handleThreadRestore(t,e.prop.all));Ext.iterate(e.prop,function(t,e){this.threadEditOperator.execute(n,t,e)},this)},this),t.resumeEvents(),t.fireEvent("datachanged",t,!0)},actRefresh:function(t,e){},actEdit:function(t,e){var i=Ext.isObject(e)?e.thread.length:e.length;this.handleUnreadCount(t,e),Ext.each(t,function(t,n){this.storeEditWrap(i,function(){this.handleThreadEdit(t,e);var i=SYNO.SDS.MailClient.Switch.getRegister("limit");t.getCount()>i&&t.remove(t.getRange(i))},this,t)},this)}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.DraftActor",{extend:"SYNO.SDS.MailClient.UIActorLib.BaseActor",requires:["SYNO.SDS.MailClient.UIActorLib.DraftOperator"],singleton:!0,filterNotInStoreItem:function(t,e){var i=Ext.isDefined(t.condition)&&t.condition.isDraft();return!SYNO.SDS.MailClient.Settings.conversation_view&&i?e.map(function(t){return{id:Ext.isArray(t.data)?t.data[0]:t.data.id,data:t.data}}).filter(function(e){return t.getById(e.id)}):e.filter(function(e){return t.getById(e.id)})},actAdd:function(t,e){Ext.each(t,function(t){var i=this.filterNotInStoreItem(t,e);SYNO.SDS.MailClient.UIActorLib.DraftOperator.handleDraftAdd(t,i)},this)},actEdit:function(t,e){Ext.each(t,function(t){var i=this.filterNotInStoreItem(t,e);SYNO.SDS.MailClient.UIActorLib.DraftOperator.handleDraftEdit(t,i)},this)},actDelete:function(t,e){Ext.each(t,function(t){var i=this.filterNotInStoreItem(t,e);SYNO.SDS.MailClient.UIActorLib.DraftOperator.handleDraftDelete(t,i)},this)}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.LabelActor",{extend:"SYNO.SDS.MailClient.UIActorLib.BaseActor",requires:["SYNO.SDS.MailClient.UIActorLib.LabelOperator","SYNO.SDS.MailClient.UIActorLib.Util"],singleton:!0,actApply:function(t,e,i){var n=new SYNO.SDS.MailClient.UIActorLib.LabelOperator;Ext.each(t,function(t,a){this.storeEditWrap(e.length,function(a){n.adjustLabelInStore(t,n.addLabelToThread,e,i,a)},this,t)},this),n.updateUnreadCount()},actRemove:function(t,e,i){var n=new SYNO.SDS.MailClient.UIActorLib.LabelOperator;Ext.each(t,function(t,a){this.storeEditWrap(e.length,function(a){n.adjustLabelInStore(t,n.removeLabelFromThread,e,i,a)},this,t)},this),n.updateUnreadCount()}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.GlobalLabelActor",{extend:"SYNO.SDS.MailClient.UIActorLib.BaseActor",requires:["SYNO.SDS.MailClient.UIActorLib.GlobalLabelOperator"],singleton:!0,actAdd:function(){},actEdit:function(t,e,i,n,a,o){Ext.each(t,function(t,s){this.storeEditWrap(length,function(){SYNO.SDS.MailClient.UIActorLib.GlobalLabelOperator.handleLabelEdit(t,e,i,n,a,o)},this,t)},this)},actDelete:function(t,e){Ext.each(t,function(t,i){this.storeEditWrap(length,function(){SYNO.SDS.MailClient.UIActorLib.GlobalLabelOperator.handleLabelRemove(t,e)},this,t)},this)}}),Ext.define("SYNO.SDS.MailClient.UIActorLib.UIActor",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.UIActorLib.ThreadActor","SYNO.SDS.MailClient.UIActorLib.DraftActor","SYNO.SDS.MailClient.UIActorLib.LabelActor","SYNO.SDS.MailClient.UIActorLib.GlobalLabelActor"],constructor:function(){this.ThreadActor=SYNO.SDS.MailClient.UIActorLib.ThreadActor,this.DraftActor=SYNO.SDS.MailClient.UIActorLib.DraftActor,this.LabelActor=SYNO.SDS.MailClient.UIActorLib.LabelActor,this.GlobalLabelActor=SYNO.SDS.MailClient.UIActorLib.GlobalLabelActor},actThreadRefresh:function(t,e){this.ThreadActor.actRefresh(t,e)},actThreadEdit:function(t,e){this.ThreadActor.actEdit(t,e)},actThreadChange:function(t,e,i){switch(e){case"refresh":this.actThreadRefresh(t,i);break;case"edit":this.actThreadEdit(t,i)}},actDraftAdd:function(t,e){this.DraftActor.actAdd(t,e)},actDraftEdit:function(t,e){this.DraftActor.actEdit(t,e)},actDraftDelete:function(t,e){this.DraftActor.actDelete(t,e)},actDraftChange:function(t,e,i){switch(e){case"add":this.actDraftAdd(t,i);break;case"edit":this.actDraftEdit(t,i);break;case"delete":this.actDraftDelete(t,i)}},actLabelApply:function(t,e,i){this.LabelActor.actApply(t,e,i)},actLabelRemove:function(t,e,i){this.LabelActor.actRemove(t,e,i)},actGlobalLabelAdd:function(t,e,i,n,a){this.GlobalLabelActor.actAdd(t,e,i,n,a)},actGlobalLabelEdit:function(t,e,i,n,a,o){this.GlobalLabelActor.actEdit(t,e,i,n,a,o)},actGlobalLabelDelete:function(t,e,i,n,a){this.GlobalLabelActor.actDelete(t,e,i,n,a)},actGlobalLabelChange:function(t,e,i,n,a,o,s){switch(e){case"add":this.actGlobalLabelAdd(t,i,n,a,o);break;case"edit":this.actGlobalLabelEdit(t,i,n,a,o,s);break;case"delete":this.actGlobalLabelDelete(t,i,n,a,o)}}}),Ext.define("SYNO.SDS.MailClient.Lib.UIActor",{extend:"SYNO.SDS.MailClient.UIActorLib.UIActor",singleton:!0}),Ext.define("SYNO.SDS.MailClient.Model.ContactStore",{extend:"SYNO.API.Store",constructor:function(t){var e={method:"POST",isNeedReload:!1,reader:new Ext.data.JsonReader({root:"contact",totalProperty:"total",fields:["id","addressbook_id","full_name","primary_mail","additional"]}),proxy:new SYNO.API.Proxy({api:"SYNO.Contacts.Contact",version:1,method:"list"}),baseParams:{api:"SYNO.Contacts.Contact",version:1,method:"list",offset:0,limit:-1,sort_by:"usage_frequency",sort_direction:"desc",additional:["extra_info"]}};this.callParent([Ext.apply(e,t)])},markDirty:function(){this.isNeedReload=!0},getContactJson:function(){return this.isNeedReload?this.getContactJsonFromRemote():Promise.resolve(this.getContactJsonFromCache())},getContactJsonFromCache:function(){return SYNO.SDS.MailClient.Format.contactStoreToJson(this)},getContactJsonFromRemote:function(){return new Promise(function(t,e){this.load({callback:function(i,n,a){a||e("loadContactStore failed"),this.isNeedReload=!1,t(this.getContactJsonFromCache())}})}.bind(this)).catch(function(t){})},promiseLoad:function(){return new Promise(function(t,e){this.load({callback:function(i,n,a){a||e("loadContactStore failed"),this.isNeedReload=!1,t()}})}.bind(this)).catch(function(t){})}}),Ext.define("SYNO.SDS.MailClient.Model.GroupStore",{extend:"SYNO.API.Store",constructor:function(t){var e={method:"POST",isNeedReload:!1,reader:new Ext.data.JsonReader({root:"data",totalProperty:"total",fields:["id","name","member","member_count","type"]})};this.callParent([Ext.apply(e,t)])},load:function(t){var e=SYNO.SDS.MailClient.Define.ContactsAddressbookType,i=SYNO.SDS.MailClient.Define.ContactsLabelType,n=[["listAddressbook",{hide_unaccepted:!0}],["listContactsLabel"],["listContactsOU",{apply_default:!0}]];SYNO.SDS.MailClient.OP.compound(n,{},function(n,a,o,s){if(!n)return void(t&&t.callback&&t.callback.call(t.scope||this,this.getRange(),o.compound[1],!1));var l={data:[]};this.isNeedReload=!1,a.result[0].success&&(a.result[0].data.addressbook.forEach(function(t){switch(t.type){case e.SUGGESTED:t.name=SYNO.SDS.MailClient._T("contact","suggested");break;case e.DEFAULT:t.name=SYNO.SDS.MailClient._T("contact","my_contacts");break;case e.DEFAULT_PUBLIC:t.name=SYNO.SDS.MailClient._T("contact","team_contact")}t.id="addressbook_"+t.id,t.type="addressbook"}),l.data=l.data.concat(a.result[0].data.addressbook)),a.result[1].success&&(a.result[1].data.label.forEach(function(t){switch(t.type){case i.STARRED:t.name=SYNO.SDS.MailClient._T("contact","starred")}t.id="label_"+t.id,t.type="label"}),l.data=l.data.concat(a.result[1].data.label)),a.result[2].success&&(a.result[2].data.group.forEach(function(t){t.id="ou_"+t.id,t.type="ou"}),l.data=l.data.concat(a.result[2].data.group)),this.loadData(l),t&&t.callback&&t.callback.call(t.scope||this,this.getRange(),o.compound[1],!0),SYNO.SDS.MailClient.Switch.updateContactByGroupData()},this)},promiseLoad:function(){return new Promise(function(t,e){this.load({callback:function(i,n,a){a||e("loadGroupStore failed"),t()}})}.bind(this))},markDirty:function(){this.isNeedReload=!0},getGroupJson:function(t){return this.isNeedReload?this.getGroupJsonFromRemote(t):Promise.resolve(this.getGroupJsonFromCache(t))},getGroupJsonFromCache:function(t){return SYNO.SDS.MailClient.Format.groupStoreToJson(this,t)},getGroupJsonFromRemote:function(t){return new Promise(function(e,i){this.load({callback:function(n,a,o){o||i("loadGroupStore failed"),this.isNeedReload=!1,e(this.getGroupJsonFromCache(t))}})}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.ColorPalette",{extend:"Ext.Container",xtype:"syno_mc_colorpalette",textColors:[],bgColors:[],rowLength:11,selected:[],defaultColor:null,constructor:function(t){this.textColors=SYNO.SDS.MailClient.Define.textColors,this.bgColors=SYNO.SDS.MailClient.Define.bgColors;var e,i=[];for(e=0;e<this.textColors.length;e++)i.push({xtype:"container",cls:"color-item",textColor:this.textColors[e],bgColor:this.bgColors[e],items:[{xtype:"container",cls:e<this.rowLength?"light":"dark",style:"background-color: #"+this.bgColors[e]+";"}]});var n={defaults:{select:function(){return this.addClass("color-selected"),this},deselect:function(){return this.removeClass("color-selected"),this},listeners:{scope:this,afterrender:function(t){t.el.on("click",function(e,i,n){this.select(t)},this)}}},items:i};this.callParent([Ext.apply(n,t)]),this.addEvents("select"),this.addClass("syno-mc-colorpalette"),null!==this.defaultColor&&this.select(this.items.get(this.defaultColor))},clearSelect:function(){var t;for(t=0;t<this.selected.length;++t)this.selected[t].deselect();this.selected=[]},select:function(t,e){-1<this.selected.indexOf(t)||(this.clearSelect(),this.selected=[t.select()],e||this.fireEvent("select",t.textColor,t.bgColor))},getSelectedNode:function(){if(this.selected.length)return{textColor:this.selected[0].textColor,bgColor:this.selected[0].bgColor}}}),Ext.define("SYNO.SDS.MailClient.ColorMenu",{extend:"SYNO.ux.Menu",requires:["SYNO.SDS.MailClient.ColorPalette"],constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={cls:"syno-mc-color-menu syno-mc-menu",items:[{xtype:"menutextitem",text:SYNO.SDS.MailClient._T("label","select_color")},{itemId:"ctn",xtype:"syno_mc_colorpalette",listeners:{scope:this,select:function(t,e){this.treeNode.fireEvent("colorchange",this.treeNode.id,void 0,t,e),this.hide()}}}]};return Ext.apply(e,t)},show:function(t,e,i,n){if(n){this.callParent([t,e,i]),this.treeNode=n;var a=this.getComponent("ctn");a.clearSelect(),a.items.each(function(t){if(t.bgColor===this.treeNode.attributes.background_color)return a.select(t,!0),!1},this);this.el.getBottom()>=Ext.getBody().getBottom()&&this.el.setTop(this.el.getTop()-25)}}}),Ext.define("SYNO.SDS.MailClient.LabelNodeUI",{extend:"Ext.tree.TreeNodeUI",requires:["SYNO.SDS.MailClient.ColorMenu"],renderElements:function(t,e,i,n){var a,o,s,l,r="";this.indentMarkup=t.parentNode?t.parentNode.ui.getChildIndent():"",this.isInteractiveNode=e.isInteractiveNode,e.count&&(r=e.count>9999?"9999+":e.count.toString()),l=['<li class="x-tree-node">','<div ext:tree-node-id="',t.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',e.cls,e.count&&this.isInteractiveNode?"unread ":"",this.isInteractiveNode?"interactive-label-node ":"",'" unselectable="on">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img alt="" src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow" />','<img alt="" src="',e.icon||this.emptyIcon,'" class="x-tree-node-icon',e.icon?" x-tree-node-inline-icon":"",e.iconCls?" "+e.iconCls:"",'" unselectable="on" />','<div class="color" style="background-color: #'+e.background_color+'"></div>','<a hidefocus="on" class="x-tree-node-anchor" tabIndex="1"><span unselectable="on">'+t.text+"</span></a>",this.isInteractiveNode?'<div class="count">'+r+"</div>":"","</div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join(""),!0!==n&&t.nextSibling&&(a=t.nextSibling.ui.getEl())?this.wrap=Ext.DomHelper.insertHtml("beforeBegin",a,l):this.wrap=Ext.DomHelper.insertHtml("beforeEnd",i,l),this.elNode=this.wrap.childNodes[0],this.ctNode=this.wrap.childNodes[1],s=0,o=this.elNode.childNodes,this.indentNode=o[s++],this.ecNode=o[s++],this.iconNode=o[s++],this.colorNode=o[s++],this.anchor=o[s++],this.textNode=this.anchor.firstChild,this.isInteractiveNode&&(this.countNode=o[s])},getDDHandles:function(){return this.isInteractiveNode?[this.iconNode,this.textNode,this.countNode,this.anchor,this.elNode]:[]},onClick:function(t){var e,i=Ext.fly(t.target);i&&(i.hasClass("color")&&this.isInteractiveNode?(e=this.node.getOwnerTree(),e.colorMenu||(e.colorMenu=new SYNO.SDS.MailClient.ColorMenu),e.colorMenu.show(t.target,"tl-tr",void 0,this.node)):this.callParent(arguments))}}),Ext.define("SYNO.SDS.MailClient.UserSettingProperty",{extend:"Object",singleton:!0,defaultSection:"SYNO.SDS.MailClient.Application",
requires:["SYNO.SDS.MailClient.ZipUtil"],getThreadWidth:function(){return this._get("threadWidth",360)},setThreadWidth:function(t){this._set("threadWidth",t)},getListWidth:function(){return this._get("listWidth",220)},setListWidth:function(t){this._set("listWidth",t)},getPGPDontRemind:function(){return this._get("PGP_dont_remind",!1)},setPGPDontRemind:function(t){this._set("PGP_dont_remind",t)},getEnableDebugLog:function(){return this._get("enableDebugLog",!1)},setEnableDebugLog:function(t){this._set("enableDebugLog",t)},getEnableThreadVault:function(){return this._get("enableThreadVault",!0)},setEnableThreadVault:function(t){this._set("enableThreadVault",t)},getEnableMailDelayedUpdate:function(){return this._get("enableMailDelayedUpdate",!0)},setEnableMailDelayedUpdate:function(t){this._set("enableMailDelayedUpdate",t)},getEnableFetchNewMailThread:function(){return this._get("enableFetchNewMailThread",!1)},setEnableFetchNewMailThread:function(t){this._set("enableFetchNewMailThread",t)},getEnableFetchOftenOpenedThread:function(){return this._get("enableFetchOftenOpenedThread",!0)},setEnableFetchOftenOpenedThread:function(t){this._set("enableFetchOftenOpenedThread",t)},getDisablePriorityMailboxUpdater:function(){return this._get("disablePriorityMailboxUpdater",!1)},setDisablePriorityMailboxUpdater:function(t){this._set("disablePriorityMailboxUpdater",t)},getEnableAdvancedRfcMsgIdGrouping:function(){return this._get("enableAdvancedRfcMsgIdGrouping",!0)},setEnableAdvancedRfcMsgIdGrouping:function(t){this._set("enableAdvancedRfcMsgIdGrouping",t)},getMailboxCollapseNode:function(){return this._get("mailboxCollapseNodeIds",[])},addMailboxCollapseNode:function(t){if(!Ext.isString(t)){var e=this.getMailboxCollapseNode();-1<e.indexOf(t)||(e.push(t),this._set("mailboxCollapseNodeIds",e))}},removeMailboxCollapseNode:function(t){var e=this.getMailboxCollapseNode(),i=e.indexOf(t);-1!==i&&(e.splice(i,1),this._set("mailboxCollapseNodeIds",e))},getLabelCollapseNode:function(){return this._get("labelCollapseNodeIds",[])},addLabelCollapseNode:function(t){var e=this.getLabelCollapseNode();e.indexOf(t)>-1||(e.push(t),this._set("labelCollapseNodeIds",e))},removeLabelCollapseNode:function(t){var e=this.getLabelCollapseNode(),i=e.indexOf(t);-1!==i&&(e.splice(i,1),this._set("labelCollapseNodeIds",e))},setPriorityMailboxSetting:function(t){this._zipAndSet("priorityMailboxSetting",t)},getPriorityMailboxSetting:function(){return this._getAndUnzip("priorityMailboxSetting",{})},setMailboxList:function(t){this._zipAndSet("mailboxList",t)},getMailboxList:function(){return this._getAndUnzip("mailboxList",{})},setLabelList:function(t){this._zipAndSet("labelList",t)},getLabelList:function(){return this._getAndUnzip("labelList",{})},setSettingInfo:function(t){this._zipAndSet("settingInfo",t)},getSettingInfo:function(){return this._getAndUnzip("settingInfo",{})},setSetting:function(t){var e=this.getSettingInfo();Ext.apply(e,t),this.setSettingInfo(e)},getNeedContactsTip:function(){return this._get("needContactsTip",!0)},setNeedContactsTip:function(t){this._set("needContactsTip",t)},getNeedMobileAppTip:function(){return!1!==this._get("needMobileTip",!0)&&this._get("needMobileTip",!0,this.defaultSection+".MobileTip")},setNeedMobileAppTip:function(t){this._set("needMobileTip",t,this.defaultSection+".MobileTip")},_get:function(t,e,i){var n=Ext.isDefined(i)?i:this.defaultSection,a=SYNO.SDS.UserSettings.getProperty(n,t);return void 0===a||null===a?e:a},_set:function(t,e,i){var n=Ext.isDefined(i)?i:this.defaultSection;SYNO.SDS.UserSettings.setProperty(n,t,e)},_getAndUnzip:function(t,e){var i=SYNO.SDS.UserSettings.getProperty(this.defaultSection,t);return void 0===i||null===i?e:JSON.parse(SYNO.SDS.MailClient.ZipUtil.unzipFromBase64(i))||e},_zipAndSet:function(t,e){e?this._set(t,SYNO.SDS.MailClient.ZipUtil.zipToBase64(JSON.stringify(e))||null):this._set(t)}}),Ext.define("SYNO.SDS.MailClient.Model.LabelStore",{extend:"SYNO.API.Store",requires:["SYNO.SDS.MailClient.LabelNodeUI","SYNO.SDS.MailClient.UserSettingProperty"],constructor:function(t){var e={method:"POST",isNeedReload:!1,proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Label",version:3,method:"list"}),baseParams:{additional:["unread_count"]},reader:new Ext.data.JsonReader({root:"label",totalProperty:"total",fields:["id","full_name","name","display_name","path","parent_id","background_color","text_color","additional"]}),listeners:{beforeload:function(t,e){this.setBaseParam("conversation_view",SYNO.SDS.MailClient.Settings.conversation_view)},load:function(t,e,i){t.data.each(function(t){var e=t.get("path").lastIndexOf("/"),i=t.get("path").substr(0,e),n=this.findExact("path",i);n<0?t.set("parent_id",0):t.set("parent_id",this.getAt(n).id),t.set("display_name",this._getDisplayName(t,134))},t),t.commitChanges()}}};this.callParent([Ext.apply(e,t)])},labelStoreToJson:function(t){var e=[];return t.each(function(t){e.push(SYNO.Util.copy(t.data))},this),e},toJson:function(){return this.labelStoreToJson(this)},isDirty:function(){return this.isNeedReload},markDirty:function(){this.isNeedReload=!0},getLabelJson:function(){return this.isNeedReload?this.getLabelJsonFromRemote():Promise.resolve(this.getLabelJsonFromCache())},getLabelJsonFromCache:function(){return this.toJson(this)},reloadLabelJson:function(){return this.markDirty(),this.getLabelJson()},getLabelJsonFromRemote:function(){return new Promise(function(t,e){this.load({callback:function(i,n,a){a||e("loadLabelStore failed"),SYNO.SDS.MailClient.UserSettingProperty.setLabelList({label:i.map(function(t){return t.json}),total:i.length}),this.isNeedReload=!1,t(this.getLabelJsonFromCache())}})}.bind(this))},parseLabelJsonToTreeNode:function(t,e,i){var n,a,o={},s=[];return t.forEach(function(t){n=o[t.parent_id],t.parent_id&&n?(n.leaf=!1,a=n.children):a=s,o[t.id]=this._createLabelNode(t,e,i),a.push(o[t.id])}.bind(this)),s},_createLabelNode:function(t,e,i){var n=SYNO.SDS.MailClient.UserSettingProperty.getLabelCollapseNode();return{uiProvider:SYNO.SDS.MailClient.LabelNodeUI,isInteractiveNode:e,id:t.id,name:t.name,parent_id:t.parent_id,text:Ext.util.Format.htmlEncode(t.name),qtip:t.name,text_color:t.text_color,background_color:t.background_color,count:t.additional.unread_count,data:t,children:[],leaf:!0,expanded:!i&&-1===n.indexOf(t.id)}},_getDisplayName:function(t,e,i){var n,a,o,s,l=document.createElement("canvas"),r=l.getContext("2d");if(r.font=i||"13px "+SYNO.SDS.MailClient.Format.getFontFamilyByLang(),!t)return"";if(n=t.get("full_name"),0===t.get("parent_id")||!e||r.measureText(n).width<e)return n;for(a=n.split("/"),s=Math.floor(a.length/2);s>0;s--)if(o=SYNO.SDS.MailClient.Array.deepCopy(a),o.splice(s,a.length-2*s,"..."),r.measureText(o.join("/")).width<e)return o.join("/");return".../"+t.get("name")}}),Ext.define("SYNO.SDS.MailClient.Model.MailboxStore",{extend:"SYNO.API.Store",requires:["SYNO.SDS.MailClient.UserSettingProperty"],constructor:function(t){var e={method:"POST",isNeedReload:!1,proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Mailbox",method:"list",version:5}),baseParams:{subscription:!1,additional:["unread_count","draft_total_count"]},reader:new Ext.data.JsonReader({root:"mailbox",totalProperty:"total",fields:["id","path","is_own","owner","my_permission","subscribed","additional"]}),listeners:{beforeload:function(t,e){this.setBaseParam("conversation_view",SYNO.SDS.MailClient.Settings.conversation_view)},load:function(t,e,i){t.data.each(function(t,e,i){var n=t.get("path").lastIndexOf("."),a=-1;if(t.set("type","mailbox"),n<0)t.set("parent_id",0),t.set("name",t.get("path"));else{var o=t.get("path").substr(0,n);a=this.findExact("path",o),a>=0&&t.set("parent_id",this.getAt(a).id),t.set("name",t.get("path").substr(n+1))}},t),t.commitChanges()}}};this.callParent([Ext.apply(e,t)])},mailboxStoreToJson:function(t){var e=[];return t.each(function(t){e.push(SYNO.Util.copy(t.data))},this),e},toJson:function(){return this.mailboxStoreToJson(this)},isDirty:function(){return this.isNeedReload},markDirty:function(){this.isNeedReload=!0},getMailboxJson:function(){return this.isNeedReload?this.getMailboxJsonFromRemote():Promise.resolve(this.getMailboxJsonFromCache())},getMailboxJsonFromCache:function(){return this.mailboxStoreToJson(this)},reloadMailboxJson:function(){return this.markDirty(),this.getMailboxJson()},getMailboxJsonFromRemote:function(){return new Promise(function(t,e){this.load({callback:function(i,n,a){a||e("loadMailboxStore failed"),SYNO.SDS.MailClient.UserSettingProperty.setMailboxList({mailbox:i.map(function(t){return t.json}),total:i.length}),this.isNeedReload=!1,t(this.getMailboxJsonFromCache())}})}.bind(this))},getMailboxByPath:function(t){var e={};return this.each(function(i){if(i.get("is_own")&&i.get("path")===t)return e=i,!1;if(!i.get("is_own")){var n=i.get("path"),a=SYNO.SDS.MailClient.Format.getAccountTextFromPath(n),o=SYNO.SDS.MailClient.Format.getAccountTextFromPath(t),s=n.substring(n.indexOf(".")+1);s=s.substring(s.indexOf(".")+1);var l=t.substring(t.indexOf(".")+1);if(l=l.substring(l.indexOf(".")+1),a.toLowerCase()===o.toLowerCase()&&s===l)return e=i,!1}},this),e},getMailboxIdsSharedToOthers:function(){var t=[];return this.each(function(e){var i=e.get("additional");i&&!Ext.isEmpty(i.permission)&&t.push(e.id)},this),t},isSubscribedSharedMailbox:function(){var t=!1;return this.each(function(e){!e.get("is_own")&&e.get("subscribed")&&(t=!0)},this),t}}),Ext.define("SYNO.SDS.MailClient.Model.Proxy",{extend:"SYNO.API.Proxy",mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{apiType:"listThread"},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments)},request:function(t,e,i,n,a,o,s){!1!==this.fireEvent("beforeload",this,i)?this.doRequest.apply(this,arguments):a.call(o||this,null,s,!1)},doRequest:function(t,e,i,n,a,o,s){var l,r=SYNO.SDS.MailClient.WebAPI;l=r.send(this.config.apiType,i),this.activeRequest[t]=l.getAjaxId();var d=function(){this.activeRequest[t]=void 0}.bind(this),c=function(t,e){this.fireEvent("loadexception",this,s,t,e),this.fireEvent("exception",this,"response",Ext.data.Api.actions.read,s,t,e)}.bind(this);l.then(function(t){var e=null;d();try{e=n.readRecords(t)}catch(i){return SYNO.Debug.error("Failed to read data",i),c(t,i),void a.call(o||this,e,s,!0)}this.fireEvent("load",this,t,s),a.call(o||this,e,s,!0)}.bind(this),function(t){d(),c(void 0,null),a.call(o||this,null,s,!1)}.bind(this))}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.Proxy",{extend:"SYNO.SDS.MailClient.Model.Proxy",config:{apiType:"listThread"},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments)},doRequest:function(t,e,i,n,a,o,s){if(!SYNO.SDS.MailClient.enableThreadVault)return SYNO.SDS.MailClient.ThreadVaultLib.Proxy.superclass.doRequest.apply(this,arguments);if(this.condition){var l=function(){}.bind(this),r=function(t,e){this.fireEvent("loadexception",this,s,t,e),this.fireEvent("exception",this,"response",Ext.data.Api.actions.read,s,t,e)}.bind(this);SYNO.SDS.MailClient.Lib.ThreadVault.get(this.condition,i.offset,i.limit).then(function(t){var e=null;l();try{e=n.readRecords(t)}catch(i){return SYNO.Debug.error("Failed to read data",i),r(t,i),void a.call(o||this,e,s,!0)}this.fireEvent("load",this,t,s),a.call(o||this,e,s,!0)}.bind(this),function(t){l(),r(void 0,t),a.call(o||this,null,s,!1)}.bind(this))}}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.MessageLib.WindowMaskUtil",{extend:"Ext.util.Observable",singleton:!0,showLoadingMask:function(){SYNO.SDS.MailClient.Window.getPanel("SYNO.SDS.MailClient.CardPanel").el.mask().addClass("syno-mc-transparent"),SYNO.SDS.MailClient.Switch.getRegister("showSearchingToast")?SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","searching"),[],!0):SYNO.SDS.MailClient.Window.showLoading()},hideLoadingMask:function(){SYNO.SDS.MailClient.Window.getPanel("SYNO.SDS.MailClient.CardPanel").el.unmask(),SYNO.SDS.MailClient.Switch.getRegister("showSearchingToast")?(SYNO.SDS.MailClient.Control.View.hideToast(),SYNO.SDS.MailClient.Switch.register("showSearchingToast",!1)):SYNO.SDS.MailClient.Window.hideLoading()}}),Ext.define("SYNO.SDS.MailClient.Model.BaseThreadProxy",{extend:"SYNO.SDS.MailClient.ThreadVaultLib.Proxy",requires:["SYNO.SDS.MailClient.MessageLib.WindowMaskUtil"],config:{},constructor:function(t){this.callParent(arguments),this.initProxy()},initProxy:function(){this.on({beforeload:this._onBeforeload,load:this._onLoad,exception:this._onException,scope:this})},_onBeforeload:function(t,e){this.abortExistingReadRequest(),0===SYNO.SDS.MailClient.Window.maskCnt&&SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.showLoadingMask()},_onLoad:function(t,e,i){SYNO.SDS.MailClient.Window.clearStatusBusy(),SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.hideLoadingMask()},_onException:function(t,e,i,n,a,o){SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.hideLoadingMask()},getActiveReadRequestId:function(){return this.activeRequest?this.activeRequest.read:null},abortExistingReadRequest:function(){var t=this.getActiveReadRequestId();t&&(Ext.Ajax.abort(t),this.activeRequest.read=void 0,SYNO.SDS.MailClient.Control.View.hideToast(),SYNO.SDS.MailClient.Switch.register("showSearchingToast",!1))}}),Ext.define("SYNO.SDS.MailClient.Model.BaseThreadReader",{extend:"Ext.data.JsonReader",constructor:function(t){var e={root:"thread",totalProperty:"total",fields:["id","star","label","message","draft","unread","replied","forwarded","last_modified",{name:"filtered_message",defaultValue:[]}]};this.callParent([Ext.apply(e,t)])}}),Ext.define("SYNO.SDS.MailClient.Model.BaseThreadStore",{extend:"SYNO.API.Store",requires:["SYNO.SDS.MailClient.Model.BaseThreadProxy","SYNO.SDS.MailClient.Model.BaseThreadReader","SYNO.SDS.MailClient.UtilLib.CallbackGuarder"],constructor:function(t){var e={method:"POST",baseParams:{condition:{},offset:0,limit:100},proxy:this.createThreadProxy(),reader:this.createThreadReader()};this.callParent([Ext.apply(e,t)]),this._guarder=new SYNO.SDS.MailClient.UtilLib.CallbackGuarder,this.initStore()},initStore:function(){this.addEvents("syncupdate"),SYNO.SDS.MailClient.MessageHouseLib.Prefetcher.monStore(this)},setCondition:function(t){this.condition=t,this.proxy.condition=t},setStoreConfig:function(t,e,i){var n=t.toWebAPIParams();this.setCondition(t),this.setBaseParam("condition",n),this.setBaseParam("limit",e),this.storeOptions({params:{condition:n,offset:void 0!==i?i:0,limit:e}})},_guard:function(t,e){return this._guarder.revoke(),this._guarder.guard(t,e||this)},createCallback:function(t,e,i){return"read"==t?this._guard(this.loadRecords):this._guard(function(n,a,o){this["on"+Ext.util.Format.capitalize(t)+"Records"](o,e,[].concat(n)),!0===o&&this.fireEvent("write",this,t,n,a,e),this.removeFromBatch(i,t,n)})},loadByCondition:function(t,e,i){return this.setBaseParam("limit",i),this.setCondition(t),this.setBaseParam("condition",t.toWebAPIParams()),new Promise(function(t,n){this.load({params:{offset:e,limit:i},scope:this,callback:function(e,i,a){a||n("loadByCondition failed"),t(e)}})}.bind(this))},loadByState:function(t){var e=t.condition,i=t.offset,n=t.limit;return this.loadByCondition(e,i,n)},loadByThreadIdShift:function(t,e){SYNO.Assert(1===e||-1===e,"idx should be 1 or -1");var i,n=this.getById(t),a=this.lastOptions.params.offset,o=this.baseParams.limit,s=this.getCount(),l=this.getTotalCount(),r=-1;if(!n)return Promise.resolve(null);if((i=this.indexOf(n)+e)<0)r=a-o;else{if(!(i>=s))return Promise.resolve(this.getAt(i).id);r=a+o}return r<0||r>=l?Promise.resolve(null):new Promise(function(t,i){SYNO.SDS.MailClient.Switch.register("offset",r),this.load({params:{offset:r},callback:function(i,n,a){var o=this.getAt(1===e?0:this.getCount()-1);t(o.id)}})}.bind(this))},reloadThread:function(t,e){this.reload({params:{offset:t,limit:e},keepScroll:!0,callback:function(t,e,i){i&&0===this.getTotalCount()&&(this.storeOptions({params:{offset:0}}),SYNO.SDS.MailClient.Switch.offsetChange(0,!0))}})},loadSingleThread:function(t){return SYNO.SDS.MailClient.WebAPI.getThread({id:[t]}).then(function(t){return t.thread.length?(this.suspendEvents(),this.loadData(t),this.resumeEvents(),t.thread[0].id):null}.bind(this),function(t){var e=SYNO.SDS.MailClient.Error.getErrorString(t);SYNO.SDS.MailClient.Window.getMsgBox().alert("",e)}.bind(this))},silentLoad:function(t,e){void 0===t&&(t=this.lastOptions.params.offset),void 0===e&&(e=this.lastOptions.params.limit),SYNO.SDS.MailClient.Lib.ThreadVault.get(this.condition,t,e).then(function(i){this.silentLoadData(i,t,e)}.bind(this))},silentLoadData:function(t,e,i){var n;this.fireEvent("syncupdate",t,e,i),this.clearData(),n=this.reader.readRecords(t),this.loadRecords(n,{add:!1,params:{offset:e,limit:i}},!0)},toJson:function(){var t=[];return this.each(function(e){t.push(SYNO.Util.copy(e.data))},this),t},hasThread:function(t){var e=!1;return this.each(function(i){if(t(i))return e=!0,!1},this),e},hasReadThread:function(){return this.hasThread(function(t){return 0===t.get("unread")})},getLastOffset:function(){return this.lastOptions?this.lastOptions.params.offset:this.baseParams.offset},getLastLimit:function(){return this.lastOptions?this.lastOptions.params.limit:this.baseParams.limit},createThreadProxy:function(){return new SYNO.SDS.MailClient.Model.BaseThreadProxy},createThreadReader:function(){return new SYNO.SDS.MailClient.Model.BaseThreadReader}}),Ext.define("SYNO.SDS.MailClient.Model.ThreadStorePostProcessor",{extend:"Ext.util.Observable",singleton:!0,filterMessagesNotInCurrentMailbox:function(t){var e,i=[],n=[],a=[],o=SYNO.SDS.MailClient.Switch,s=SYNO.SDS.MailClient.Define,l=SYNO.SDS.MailClient.MessageHouseLib.Util,r=s.draftsId===o.inMailboxId,d=o.inSearch||o.inLabel,c=o.inMailboxId;this.handleRequestingDrafts(t),t.each(function(t,e,i){var n,o=["message","draft"],h=r||d,u=0;a=[],t.data.filtered_message=[],o.forEach(function(e){n=t.get(e),n.forEach(function(t){l.shouldShowMsg(t)?t.read||void 0===t.mailbox_id||t.mailbox_id==s.draftsId||(u+=1):a.push(t),h=t.mailbox_id==c||h}),h?(t.data.filtered_message=a,a.forEach(function(t){n.remove(t)})):t.data.filtered_message=n.splice(0,n.length)}),t.data.unread=u},this),r?t.each(function(t,e,a){t.get("draft").length||-1!=i.indexOf(t)||(i.push(t),n.push(t.get("id")))}):o.inLabel?t.each(function(t,a,s){e=t.get("label").map(function(t){return t.id}),-1===e.indexOf(o.inLabelId)&&(i.push(t),n.push(t.get("id")))}):t.each(function(t,e,a){t.get("message").length||t.get("draft").length||-1!=i.indexOf(t)||(i.push(t),n.push(t.get("id")))}),i.length&&(t.remove(i),t.totalLength-=i.length)},handleRequestingDrafts:function(t){var e=SYNO.SDS.MailClient.Window.draftManager.getIdObj("send discard"),i=SYNO.SDS.MailClient.Window.draftManager.getIdObj("send");Ext.each(Object.keys(e),function(n){var a=t.getById(n);if(a){var o,s=a.get("draft").slice(),l=[];for(o=0;o<s.length;o++)-1!==e[n].indexOf(s[o].id)&&(i[n]&&-1!==i[n].indexOf(s[o].id)&&l.push(s[o]),s.splice(o--,1));a.get("draft").length!==s.length&&(a.data.draft=s);var r,d;if(l.length){for(r=a.get("message").slice(),o=0;o<l.length;o++)d=l[o],r.push(SYNO.SDS.MailClient.Format.draftDataToFakeMessage(d.thread_id,d.id,d,!0));a.data.message=r}}})},isThreadDataHidden:function(t,e,i,n){var a,o,s=SYNO.SDS.MailClient.Define,l=t.message,r=t.draft,d=s.trashId===e,c=s.junkId===e,h=s.starredId===e;return n?0===l.length&&0===r.length:!(!i||this.isThreadInLabel(t,i))||(e&&!h?(a=this.getMsgInMailbox(l,[e]),o=this.getMsgInMailbox(r,[e])):(a=l.slice(),o=r.slice()),d||c||(a=this.getMsgNotInMailbox(a,[s.trashId,s.junkId]),o=this.getMsgNotInMailbox(o,[s.trashId,s.junkId])),0===a.length&&0===o.length)},getMsgInMailbox:function(t,e){return t.filter(function(t){return this.isMsgInMailbox(t,e)},this)},getMsgNotInMailbox:function(t,e){return t.filter(function(t){return!this.isMsgInMailbox(t,e)},this)},isMsgInMailbox:function(t,e){return Ext.isArray(e)||(e=[e]),-1!==e.indexOf(t.mailbox_id)},isThreadInLabel:function(t,e){return t.label.map(function(t){return t.id},this).some(function(t){return t===e})}}),Ext.define("SYNO.SDS.MailClient.Model.PriorityThreadStore",{extend:"SYNO.SDS.MailClient.Model.BaseThreadStore",requires:["SYNO.SDS.MailClient.Model.ThreadStorePostProcessor"],constructor:function(t){this.callParent(arguments)},initStore:function(){this.callParent(arguments),this.on({load:function(){SYNO.SDS.MailClient.Switch.register("lastMatchedIds",[]),SYNO.SDS.MailClient.Switch.register("lastSplitKeyword","")},datachanged:function(){SYNO.SDS.MailClient.Model.ThreadStorePostProcessor.filterMessagesNotInCurrentMailbox(this)},scope:this})},resetData:function(t,e,i){this.loadData(t),this.setStoreConfig(e,i)}}),Ext.define("SYNO.SDS.MailClient.Model.SearchHistoryStore",{extend:"Ext.data.JsonStore",requires:[],constructor:function(t){var e={autoDestroy:!0,root:"history",fields:["id","content","count","last_time"]};this.callParent([Ext.apply(e,t)])},reloadStore:function(){return SYNO.SDS.MailClient.WebAPI.send("listSearchHistory").then(function(t){this.loadData(t)}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.Model.ThreadStore",{extend:"SYNO.SDS.MailClient.Model.BaseThreadStore",requires:["SYNO.SDS.MailClient.Model.ThreadStorePostProcessor"],constructor:function(t){this.callParent(arguments)},isLastOptionsSearching:function(){return this.lastOptions.params.condition.length>1},checkAndAbortExistingSearchingRequest:function(){this.proxy.getActiveReadRequestId()&&this.isLastOptionsSearching()&&this.proxy.abortExistingReadRequest()},applyPostProcessor:function(){SYNO.SDS.MailClient.Model.ThreadStorePostProcessor.filterMessagesNotInCurrentMailbox(this)},initStore:function(){this.callParent(arguments),this.on({datachanged:function(){this.applyPostProcessor()},scope:this})}}),Ext.define("SYNO.SDS.MailClient.Model.Main",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.Model.ContactStore","SYNO.SDS.MailClient.Model.DraftStore","SYNO.SDS.MailClient.Model.GroupStore","SYNO.SDS.MailClient.Model.LabelStore","SYNO.SDS.MailClient.Model.MailboxStore","SYNO.SDS.MailClient.Model.PriorityThreadStore","SYNO.SDS.MailClient.Model.SearchHistoryStore","SYNO.SDS.MailClient.Model.ThreadStore"],createPriorityThreadStore:function(t){return new SYNO.SDS.MailClient.Model.PriorityThreadStore({sectionIdx:t})},createThreadStore:function(){return new SYNO.SDS.MailClient.Model.ThreadStore}}),Ext.define("SYNO.SDS.MailClient.PriorityMailboxLib.Main",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition"],MailboxSectionTypeNum:1,LabelSectionTypeNum:2,StarSectionTypeNum:3,constructor:function(t){this.callParent([t]),this.addEvents("prioritydataload","prioritydatabeforeload")},init:function(){this.initStore()},getUnreadCountRelatedIds:function(){var t=[],e=[];return Ext.each(this.getSections(),function(i,n){i.type===this.MailboxSectionTypeNum?t.push(i.type_id):i.type===this.LabelSectionTypeNum&&e.push(i.type_id)},this),{mailboxIds:t,labelIds:e}},getUnreadCount:function(t){return this.unreadCount},setUnreadCount:function(t){this.unreadCount=t},getStoreCount:function(){return this.stores.reduce(function(t,e){return t+e.getCount()},0)},getStores:function(){return this.stores},getStoreByIdx:function(t){return this.getStores()[t]},getStoreBySection:function(t){var e=this.getSections(),i=e.indexOf(t);return this.getStoreByIdx(i)},getSections:function(){return this.Setting.section},getSectionByIdx:function(t){return this.getSections()[t]},getSetting:function(){return this.Setting},setSetting:function(t){this.Setting=t||{}},isEnablePriorityMailbox:function(){return this.Setting.enable_priority_mailbox},getBoundFns:function(t,e){return e.map(function(e){return t.bind.apply(t,[this].concat(e))},this)},promiseFns:function(t){return t.reduce(function(t,e){return t.then(e)},Promise.resolve())},promiseAllFns:function(t){return Promise.all(t.map(function(t){return t()}))},loadData:function(t){return SYNO.SDS.MailClient.enableThreadVault?this.loadDataByPromise(t):this.loadDataByCompound(t)},getPageSize:function(t){return this.getSectionByIdx(t).page_size},getOffset:function(t){var e=this.getStoreByIdx(t).lastOptions;return e&&e.params?e.params.offset:0},silentLoad:function(){var t=SYNO.SDS.MailClient.Lib.ThreadVault,e=this.getSections().map(function(e,i){if(e.type<=0)return Promise.resolve();var n=this.getSectionByIdx(i),a=this.getConditionBySectionIdx(i),o=this.getOffset(i);return t.get(a,o,n.page_size).then(function(t){this.getOffset(i)===o&&this.stores[i].silentLoadData(t,o,n.page_size)}.bind(this))},this);return Promise.all(e)},getSkipUpdateSection:function(){var t=SYNO.SDS.MailClient.Control.Mail;return t.isInPriorityMailbox()&&t.isThreeCol()&&t.isOpenEditor()?SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore().sectionIdx:-1},getLoadPromiseFns:function(){var t=SYNO.SDS.MailClient.Lib.ThreadVault;return this.skipSection=this.getSkipUpdateSection(),this.getSections().map(function(e,i){return e.type<=0||this.skipSection===i?function(){return Promise.resolve()}:function(){var e=this.getSectionByIdx(i),n=this.getConditionBySectionIdx(i);return t.get(n,0,e.page_size).then(function(t){SYNO.SDS.MailClient.Control.Mail.get("PriorityThreadPanel").sections[i].view.keepCheckedItem(),this.stores[i].resetData(t,n,e.page_size)}.bind(this))}.bind(this)},this)},loadDataByPromise:function(t){var e;return this.fireEvent("prioritydatabeforeload"),SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.showLoadingMask(),e=this.getLoadPromiseFns(),this.promiseAllFns(e).then(function(){this.fireEvent("viewchecked",t),SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.hideLoadingMask()}.bind(this),function(){SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.hideLoadingMask()})},loadDataByCompound:function(t){var e;return this.fireEvent("prioritydatabeforeload"),SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.showLoadingMask(),e=this.getSections().map(function(t,e){var i,n;if(this.skipSection=this.getSkipUpdateSection(),!(t.type<=0||this.skipSection===e))return i=this.getConditionBySectionIdx(e),n=this.getSectionByIdx(e),{condition:i,offset:0,limit:n.page_size,callback:function(t,a){t&&this.stores[e].resetData(a,i,n.page_size)}.bind(this)}},this).filter(function(t){return void 0!==t}),SYNO.SDS.MailClient.Model.ThreadProvider.getThreadLists(e).then(function(){this.fireEvent("viewchecked",t),SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.hideLoadingMask()}.bind(this)).catch(function(t){SYNO.Debug.error(t),SYNO.SDS.MailClient.MessageLib.WindowMaskUtil.hideLoadingMask()}.bind(this))},getConditions:function(){return this.getSections().map(this._sectionToCondition)},getConditionsHasMailboxId:function(t){return Ext.isArray(t)||(t=[t]),this.getConditions().filter(function(e){return t.some(function(t){return e.hasMailboxId(t)})})},getConditionsHasLabelId:function(t){return Ext.isArray(t)||(t=[t]),this.getConditions().filter(function(e){return t.some(function(t){return e.hasLabelId(t)})})},_sectionToCondition:function(t){var e=new SYNO.SDS.MailClient.Condition,i=SYNO.SDS.MailClient.PriorityMailboxLib.Main.prototype;switch(t.type){case i.MailboxSectionTypeNum:e.addCondition("mailbox",t.type_id);break;case i.LabelSectionTypeNum:e.addCondition("label",t.type_id);break;case i.StarSectionTypeNum:e.addCondition("mailbox",SYNO.SDS.MailClient.Define.starredId)}return 1===t.status&&e.addCondition("unread",!0),e},getConditionBySectionIdx:function(t){var e=this.getSectionByIdx(t);return this._sectionToCondition(e)},getConditionParamBySectionIdx:function(t){return this.getConditionBySectionIdx(t).toWebAPIParams()},getInMailboxIdBySectionIdx:function(t){var e=this.getSectionByIdx(t).type,i=this.getSectionByIdx(t).type_id;switch(e){case 1:return i;case 2:return 0;case 3:return SYNO.SDS.MailClient.Define.starredId;default:return 0}},createStore:function(t){var e=SYNO.SDS.MailClient.Model.Main.createPriorityThreadStore(t);return e.on({load:function(){this.fireEvent("prioritydataload",e.sectionIdx)},scope:this}),e},initStore:function(){this.stores=this.getSections().map(function(t,e){return this.createStore(e)},this)},getSectionLastOption:function(){var t=[];return Ext.each(this.getSections(),function(e,i){e.type>0&&t.push(this.stores[i].lastOptions.params)},this),t},findStoreByLastParams:function(t){var e,i=this.getSections();return Ext.each(this.stores,function(n,a){if(0===i[n.sectionIdx].type)return!1;var o=n.lastOptions.params;SYNO.SDS.MailClient.Tool.isSameThreadCondition(t.condition,o.condition)&&t.offset===o.offset&&t.limit===o.limit&&(e=n)},this),e},getSectionTitle:function(t){var e,i=this.getSectionByIdx(t),n="",a="",o=SYNO.SDS.MailClient.Switch.getMailboxStore(),s=SYNO.SDS.MailClient.Switch.getLabelStore();return this.StarSectionTypeNum==i.type?n=SYNO.SDS.MailClient._T("mailbox","starred"):this.LabelSectionTypeNum==i.type?(e=s.getById(i.type_id),n=e?e.get("name"):""):this.MailboxSectionTypeNum==i.type&&(e=o.getById(i.type_id),n=e?SYNO.SDS.MailClient.Format.getMailboxText(e.data,!0):""),a=1==i.status?SYNO.SDS.MailClient._T("thread","unread"):SYNO.SDS.MailClient._T("priority_mailbox","all"),n+": "+a},getMailboxSections:function(){return this.getSections().filter(function(t){return t.type===this.MailboxSectionTypeNum},this)},getLabelSections:function(){return this.getSections().filter(function(t){return t.type===this.LabelSectionTypeNum},this)},getUnreadSections:function(){return this.getSections().filter(function(t){return 1===t.status},this)},getConditionsOfUnreadSectionHavingReadThread:function(){return this.getUnreadSections().filter(function(t){return this.getStoreBySection(t).hasReadThread()},this).map(this._sectionToCondition)},handleDeletedMailbox:function(){var t,e=this.getMailboxSections();t=e.filter(function(t){return!SYNO.SDS.MailClient.Control.Model.isMailboxIdExist(t.type_id)}),t.forEach(function(t){t.type=0})},handleDeletedLabel:function(){var t,e=this.getLabelSections();t=e.filter(function(t){return!SYNO.SDS.MailClient.Control.Model.isLabelIdExist(t.type_id)}),t.forEach(function(t){t.type=0})},onLabelChange:function(t,e,i,n,a){var o=!1,s=!1;("delete"==t||"edit"==t&&Ext.isDefined(i))&&(Ext.each(this.getSections(),function(i,n){i.type==this.LabelSectionTypeNum&&i.type_id==e&&(o=!0,"delete"==t&&(i.type=0,s=!0))},this),SYNO.SDS.MailClient.Switch.inPriority&&o&&SYNO.SDS.MailClient.Control.Sidebar.updatePriorityMailboxSetting())},setDisplayingSectionIdx:function(t){this.displayingSectionIdx=t},getDisplayingSectionIdx:function(){return this.displayingSectionIdx},getDisplayingSection:function(){var t=this.getDisplayingSectionIdx();return Ext.isDefined(t)?this.getSectionByIdx(t):null},isDisplayingMailbox:function(){var t=this.getDisplayingSection();return!!t&&t.type===this.MailboxSectionTypeNum},getDisplayingMailboxId:function(){if(!this.isDisplayingMailbox())return null;var t=this.getDisplayingSection();return t?t.type_id:null},getStoreByThreadId:function(t){var e=null;return this.stores.forEach(function(i,n){if(i.getById(t))return e=i,!1},this),e}}),Ext.define("SYNO.SDS.MailClient.Lib.PriorityMailbox",{extend:"SYNO.SDS.MailClient.PriorityMailboxLib.Main",singleton:!0}),Ext.define("SYNO.SDS.MailClient.ThreadLib.ThreadControlOperator",{extend:"Ext.util.Observable",singleton:!0,requires:[],messageToTrash:function(t,e){this._modifyThread(this._getDiscardChangeList(t,e))},deleteForever:function(t,e){this._modifyThread(this._getDeleteForeverChangeList(t,e))},setMailbox:function(t,e,i){this._modifyThread(this._getSetMailboxChangeList(t,e,i))},markRead:function(t,e){this._modifyThread(this._getMarkReadChangeList(t,e))},markMessageRead:function(t,e){if(0!==t.length){var i=t.map(function(t){return this._getMarkMessageReadChangeListItem(e,t[0],t[1])},this);this._modifyThread(i)}},rollbackMarkRead:function(t,e){this._modifyThread(this._getMarkReadRestoreList(t,e))},rollbackMarkMessageRead:function(t,e){this.markMessageRead(t,!e)},setStar:function(t,e){var i=t.map(function(t){return this._getSetStarChangeListItem(e,t[0],t[1])
},this);this._modifyThread(i)},addLabel:function(t,e){this._applyLabel(t,e)},removeLabel:function(t,e){this._removeLabel(t,e)},undoSetMailbox:function(t){this._modifyThread(this._getUndoSetMailboxChangeList(t))},undoSingleSetMailbox:function(t,e){this._modifyThread(this._getUndoSingleSetMailboxChangeList(t,e))},undoLabelChange:function(t){this._modifyThread(this._getUndoLabelChangeChangeList(t))},undoRead:function(t){this._modifyThread(this._getUndoReadChangeList(t))},_modifyThread:function(t){SYNO.SDS.MailClient.Control.Thread.modifyThread("edit",t)},_applyLabel:function(t,e){SYNO.SDS.MailClient.Control.Thread.addLabel(t,e)},_removeLabel:function(t,e){var i=e.map(this._labelObjToId);SYNO.SDS.MailClient.Control.Thread.removeLabel(t,i)},_getDiscardChangeList:function(t,e){return e.map(function(e){var i=e.message.filter(function(e){return-1===t.indexOf(e.id)});return{id:e.id,prop:{message:i}}})},_getDeleteForeverChangeList:function(t,e){return t.map(function(t){return{id:t,prop:{delete_forever:e}}})},_getSetMailboxChangeList:function(t,e,i){return t.map(function(t){return{id:t,prop:{set_mailbox:{target_mailbox:e,operate_mailbox:i}}}})},_getMarkReadChangeList:function(t,e){return t.map(function(t){return{id:t,prop:{read:e}}})},_getMarkReadRestoreList:function(t,e){return t.map(function(t){return{id:t,prop:{read:!e}}})},_getMarkMessageReadChangeListItem:function(t,e,i){return{id:e,prop:{read_message:{id:i,value:t}}}},_getSetStarChangeListItem:function(t,e,i){return{id:e.id,prop:{star:{value:t?1:0,id:i}}}},_getUndoSetMailboxChangeList:function(t){return t.map(function(t){return{id:t.id,prop:{all:t}}})},_getUndoSingleSetMailboxChangeList:function(t,e){return t.map(function(t){var i=t.message;return i.length===e.length?{id:t.id,prop:{all:t}}:{id:t.id,prop:{message:i}}})},_getUndoLabelChangeChangeList:function(t){return t.map(function(t){return{id:t.id,prop:{all:t}}})},_getUndoReadChangeList:function(t){return t.map(function(t){return{id:t.id,prop:{message:t.message}}})},_labelObjToId:function(t){return t.id}}),Ext.define("SYNO.SDS.MailClient.ThreadLib.Toaster",{extend:"Ext.util.Observable",singleton:!0,requires:[],constructor:function(){this.WebAPI=SYNO.SDS.MailClient.WebAPI},show:function(t){this._show(t)},showDiscard:function(){this._show(SYNO.SDS.MailClient._T("notification","discard"))},showMessageToTrash:function(t){this._showWithUndo(t,SYNO.SDS.MailClient._T("notification","message_to_trash"))},showSetMailbox:function(t,e,i){this._showWithUndo(t,i||this._getSetMailboxNotification(e))},showDeleteForever:function(){this._show(this.getNotifyString("thread_delete"))},showMarkRead:function(t,e){var i=e?this.getNotifyString("conversations_mark_read"):this.getNotifyString("conversations_mark_unread");this._showWithUndo(t,i)},showThreadChangeLabel:function(t,e){this._showWithUndo(t,e.join("<br>"))},_show:function(t,e,i,n){SYNO.SDS.MailClient.Window.showToast(t,e,i,n)},_showWithUndo:function(t,e,i,n,a){var o=[[SYNO.SDS.MailClient._T("common","undo"),t]];this._show(e,o,n,a)},_getSetMailboxNotification:function(t){var e,i,n=SYNO.SDS.MailClient.Define,a=SYNO.SDS.MailClient.Switch.getMailboxStore();switch(t){case SYNO.SDS.MailClient.Settings.archive_mailbox:e=this.getNotifyString("achived");break;case n.trashId:e=this.getNotifyString("thread_to_trash");break;case n.junkId:e=this.getNotifyString("spam");break;case n.inboxId:i=a.getById(t).get("name"),e=String.format(this.getNotifyString("thread_move_to_mailbox"),Ext.util.Format.htmlEncode(i));break;default:i='"'+a.getById(t).get("name")+'"',e=String.format(this.getNotifyString("thread_move_to_mailbox"),Ext.util.Format.htmlEncode(i))}return e},getNotifyString:function(t){return SYNO.SDS.MailClient.Settings.conversation_view?SYNO.SDS.MailClient._T("notification",t):SYNO.SDS.MailClient._T("notification",SYNO.SDS.MailClient.Define.ConversationViewStringMap[t])}}),Ext.define("SYNO.SDS.MailClient.WebAPILib.AbortableWebAPI",{extend:"Ext.util.Observable",requires:[],constructor:function(t,e){this.callParent(arguments),this._promise=t,this._ajaxId=e},then:function(t,e){return this._promise.then(t,e)},catch:function(t){return this._promise.catch(t)},abort:function(){Ext.Ajax.abort(this._ajaxId)},getAjaxId:function(){return this._ajaxId}}),Ext.define("SYNO.SDS.MailClient.WebAPILib.BaseWebAPIConfig",{singleton:!0,data:{getPersonalProfile:{api:"SYNO.Personal.Profile",method:"get",version:1},getInfoMail:{api:"SYNO.MailClient.Info",method:"getinfo",version:2},getCompoundInfo:{api:"SYNO.MailClient.Info",method:"get_compound_info",version:2},getInfoSetting:{api:"SYNO.MailClient.Setting",method:"getinfo",version:1},getDownloadToken:{api:"SYNO.MailClient.Info",method:"get_download_token",version:1},getUsageLimit:{api:"SYNO.MailPlusServer.Client",method:"get_usage_limit",version:1},addMailbox:{api:"SYNO.MailClient.Mailbox",method:"create",version:6},setMailbox:{api:"SYNO.MailClient.Mailbox",method:"set",version:6},setSubscribeMailbox:{api:"SYNO.MailClient.Mailbox",method:"set_subscribed",version:6},deleteMailbox:{api:"SYNO.MailClient.Mailbox",method:"delete",version:6,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},listMailbox:{api:"SYNO.MailClient.Mailbox",method:"list",version:6,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},clearMessage:{api:"SYNO.MailClient.Mailbox",method:"clear_message",version:6},getThread:{api:"SYNO.MailClient.Thread",method:"get",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},listThread:{api:"SYNO.MailClient.Thread",method:"list",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},getMessageOffsetInThread:{api:"SYNO.MailClient.Thread",method:"get_message_offset",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},getMessageOffsetInThreadEx:{api:"SYNO.MailClient.Thread",method:"get_message_offset",version:10,build:function(t){return{msg_id:t,conversation_view:SYNO.SDS.MailClient.Settings.conversation_view}}},threadSetMailbox:{api:"SYNO.MailClient.Thread",method:"set_mailbox",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadSetMailboxEx:{api:"SYNO.MailClient.Thread",method:"set_mailbox",version:10,build:function(t){return{id:t[0],mailbox_id:t[1],operate_mailbox_id:t[2],conversation_view:SYNO.SDS.MailClient.Settings.conversation_view}}},threadDelete:{api:"SYNO.MailClient.Thread",method:"delete",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadDeleteEx:{api:"SYNO.MailClient.Thread",method:"delete",version:10,build:function(t){return{id:t[0],mailbox_id:t[1],conversation_view:SYNO.SDS.MailClient.Settings.conversation_view}}},threadAddLabel:{api:"SYNO.MailClient.Thread",method:"add_label",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadRemoveLabel:{api:"SYNO.MailClient.Thread",method:"remove_label",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadSetRead:{api:"SYNO.MailClient.Thread",method:"set_read",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadSetReadEx:{api:"SYNO.MailClient.Thread",method:"set_read",version:10,build:function(t){return{id:t[0],read:t[1],conversation_view:SYNO.SDS.MailClient.Settings.conversation_view}}},threadReportSpam:{api:"SYNO.MailClient.Thread",method:"report_spam",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadAddToSpamRule:{api:"SYNO.MailClient.Thread",method:"add_to_spam_rule",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},threadListExistSpamRule:{api:"SYNO.MailClient.Thread",method:"list_exist_spam_rule",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},smallBatchOp:{api:"SYNO.MailClient.Thread",method:"small_batch_op",version:10,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},listLabel:{api:"SYNO.MailClient.Label",method:"list",version:3,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},getLabel:{api:"SYNO.MailClient.Label",method:"get",version:3,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},addLabel:{api:"SYNO.MailClient.Label",method:"create",version:3},setLabel:{api:"SYNO.MailClient.Label",method:"set",version:3},deleteLabel:{api:"SYNO.MailClient.Label",method:"delete",version:3},listPGPKey:{api:"SYNO.MailClient.PGPKey",method:"list",version:1},addPGPKey:{api:"SYNO.MailClient.PGPKey",method:"create",version:1},setPGPKey:{api:"SYNO.MailClient.PGPKey",method:"set",version:1},deletePGPKey:{api:"SYNO.MailClient.PGPKey",method:"delete",version:1},getMessage:{api:"SYNO.MailClient.Message",method:"get",version:8},getMessageWithExtImg:{api:"SYNO.MailClient.Message",method:"get",version:8,build:function(t){return{id:t,additional:["blockquote","truncated"]}}},getMessageWithoutExtImg:{api:"SYNO.MailClient.Message",method:"get",version:8,build:function(t){return{id:t,additional:["blockquote","truncated","block_external_image"]}}},getMessageEx:{api:"SYNO.MailClient.Message",method:"get",version:8,build:function(t){return{id:t,additional:SYNO.SDS.MailClient.Settings.display_external_image?["blockquote","truncated"]:["blockquote","truncated","block_external_image"]}}},setStar:{api:"SYNO.MailClient.Message",method:"set_star",version:8},setStarEx:{api:"SYNO.MailClient.Message",method:"set_star",version:8,build:function(t){return{id:t[0],star:t[1]?1:0}}},messageSetMailbox:{api:"SYNO.MailClient.Message",method:"set_mailbox",version:8},messageSetMailboxEx:{api:"SYNO.MailClient.Message",method:"set_mailbox",version:8,build:function(t){return{id:t[0],mailbox_id:t[1]}}},messageSetRead:{api:"SYNO.MailClient.Message",method:"set_read",version:8},messageSetReadEx:{api:"SYNO.MailClient.Message",method:"set_read",version:8,build:function(t){return{id:t[0],read:t[1]}}},messageReportSpam:{api:"SYNO.MailClient.Message",method:"report_spam",version:8},messageAddToSpamRule:{api:"SYNO.MailClient.Message",method:"add_to_spam_rule",version:9},messageListExistSpamRule:{api:"SYNO.MailClient.Message",method:"list_exist_spam_rule",version:9},createDraft:{api:"SYNO.MailClient.Draft",method:"create",version:3},getDraft:{api:"SYNO.MailClient.Draft",method:"get",version:3},setDraft:{api:"SYNO.MailClient.Draft",method:"set",version:3},discardDraft:{api:"SYNO.MailClient.Draft",method:"delete",version:1},discardDraftEx:{api:"SYNO.MailClient.Draft",method:"delete",version:1,build:function(t){return{id:t}}},sendDraft:{api:"SYNO.MailClient.Draft",method:"send",version:3},listContact:{api:"SYNO.Contacts.Contact",method:"list",version:1},createContact:{api:"SYNO.Contacts.Contact",method:"create",version:1},updateContactUsageFrequency:{api:"SYNO.Contacts.Contact",method:"update_usage_frequency",version:1},listAddressbook:{api:"SYNO.Contacts.Addressbook",method:"list",version:1},listContactsLabel:{api:"SYNO.Contacts.Label",method:"list",version:1},listContactsOU:{api:"SYNO.Contacts.Contact",method:"list_group",version:1},labelAddMember:{api:"SYNO.Contacts.Label",method:"add_member",version:1},labelRemoveMember:{api:"SYNO.Contacts.Label",method:"remove_member",version:1},uploadSticker:{api:"SYNO.MailClient.Attachment",method:"upload_sticker",version:6},uploadDSM:{api:"SYNO.MailClient.Attachment",method:"upload_dsm",version:6},uploadUrl:{api:"SYNO.MailClient.Attachment",method:"upload_url",version:6},getAppTaskId:{api:"SYNO.MailClient.Attachment",method:"get_app_task_id",version:6},downloadDSM:{api:"SYNO.MailClient.Attachment",method:"download_dsm",version:6},downloadDSMAll:{api:"SYNO.MailClient.Attachment",method:"download_dsm_all",version:6},downloadInline:{api:"SYNO.MailClient.Attachment",method:"download_inline",version:6},listFilter:{api:"SYNO.MailClient.Filter",method:"list",version:3},addFilter:{api:"SYNO.MailClient.Filter",method:"create",version:3,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},setFilter:{api:"SYNO.MailClient.Filter",method:"set",version:3,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},deleteFilter:{api:"SYNO.MailClient.Filter",method:"delete",version:1},setFilterOrder:{api:"SYNO.MailClient.Filter",method:"setorder",version:1},setFilterEnabled:{api:"SYNO.MailClient.Filter",method:"set_enabled",version:1},addTask:{api:"SYNO.MailClient.Filter",method:"add_task",version:3,build:function(t){return Ext.apply(t,{conversation_view:SYNO.SDS.MailClient.Settings.conversation_view})}},cancelTask:{api:"SYNO.MailClient.Filter",method:"cancel_task",version:1},syncSetting:{api:"SYNO.MailClient.Setting",method:"sync",version:1},listSMTP:{api:"SYNO.MailClient.Setting.SMTP",method:"list",version:1},createSMTP:{api:"SYNO.MailClient.Setting.SMTP",method:"create",version:1},setSMTP:{api:"SYNO.MailClient.Setting.SMTP",method:"set",version:1},deleteSMTP:{api:"SYNO.MailClient.Setting.SMTP",method:"delete",version:1},setDefaultSMTP:{api:"SYNO.MailClient.Setting.SMTP",method:"set_default",version:1},getInfoPOP3:{api:"SYNO.MailClient.Setting.POP3",method:"getinfo",version:1},listPOP3:{api:"SYNO.MailClient.Setting.POP3",method:"list",version:1},createPOP3:{api:"SYNO.MailClient.Setting.POP3",method:"create",version:1},setPOP3:{api:"SYNO.MailClient.Setting.POP3",method:"set",version:1},deletePOP3:{api:"SYNO.MailClient.Setting.POP3",method:"delete",version:1},listCustomAutoReply:{api:"SYNO.MailClient.Setting.CustomAutoReply",method:"list",version:1},createCustomAutoReply:{api:"SYNO.MailClient.Setting.CustomAutoReply",method:"create",version:1},setCustomAutoReply:{api:"SYNO.MailClient.Setting.CustomAutoReply",method:"set",version:1},deleteCustomAutoReply:{api:"SYNO.MailClient.Setting.CustomAutoReply",method:"delete",version:1},getGeneral:{api:"SYNO.MailClient.Setting.General",method:"get",version:1},getPGP:{api:"SYNO.MailClient.Setting.PGP",method:"get",version:1},getSharingLink:{api:"SYNO.MailClient.Setting.SharingLink",method:"get",version:1},getPriorityMailbox:{api:"SYNO.MailClient.Setting.PriorityMailbox",method:"get",version:1},getManualConfig:{api:"SYNO.MailClient.Setting.ManualConfig",method:"get",version:1},listNotification:{api:"SYNO.MailClient.Setting.Notification",method:"list",version:1},createNote:{api:"SYNO.NoteStation.Note",method:"create",version:2},listSearchHistory:{api:"SYNO.MailClient.SearchHistory",method:"list",version:1},deleteSearchHistory:{api:"SYNO.MailClient.SearchHistory",method:"delete",version:1},listSpamRule:{api:"SYNO.MailClient.SpamRule",method:"list",version:1},addSpamRule:{api:"SYNO.MailClient.SpamRule",method:"create",version:1},setSpamRule:{api:"SYNO.MailClient.SpamRule",method:"set",version:1},setSpamRuleType:{api:"SYNO.MailClient.SpamRule",method:"set_type",version:1},deleteSpamRule:{api:"SYNO.MailClient.SpamRule",method:"delete",version:1},getQuotaInfo:{api:"SYNO.MailClient.Info",method:"get_quota_info",version:4}}}),Ext.define("SYNO.SDS.MailClient.WebAPILib.WebAPIConfigWithDefaultCB",{singleton:!0,data:{createContact:{api:"SYNO.Contacts.Contact",method:"create",version:1,hook:function(t,e,i,n){if(t){var a=SYNO.SDS.MailClient.Switch.getContactStore(),o=Ext.apply({full_name:i.full_name,primary_mail:i.mail[0].data,additional:{extra_info:{nick_name:i.nick_name,mail:i.mail.map(function(t){return t.data})}}},e);a.add(new a.recordType(o,e.id)),SYNO.SDS.MailClient.Switch.updateAutoCompleteMemProxy()}}}}}),Ext.define("SYNO.SDS.MailClient.WebAPILib.WebAPIConfig",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.WebAPILib.BaseWebAPIConfig","SYNO.SDS.MailClient.WebAPILib.WebAPIConfigWithDefaultCB"],constructor:function(){var t=SYNO.SDS.MailClient.WebAPILib.BaseWebAPIConfig,e=SYNO.SDS.MailClient.WebAPILib.WebAPIConfigWithDefaultCB;this.callParent(arguments),this.data=Ext.apply({},t.data),Ext.apply(this.data,e.data)}}),Ext.define("SYNO.SDS.MailClient.WebAPILib.BaseWebAPI",{extend:"Ext.Component",requires:["SYNO.SDS.MailClient.WebAPILib.AbortableWebAPI","SYNO.SDS.MailClient.WebAPILib.WebAPIConfig"],constructor:function(t){var e={using:"SYNO.SDS.MailClient.WebAPILib.WebAPIConfig"};this.callParent([Ext.apply(e,t)]),this.initWebAPI()},_send:function(t,e){if(Ext.isArray(t))return this.sendCompound.apply(this,arguments);var i=this.apiConfig.data[t];return this.doSend(this.instantiateWebAPIObj(i,e))},send:function(){var t=this._send.apply(this,arguments);return new SYNO.SDS.MailClient.WebAPILib.AbortableWebAPI(t,this.lastAjaxId)},sendCompound:function(t,e,i,n,a){return Ext.each(t,function(t){var e=t.apiType,i=this.apiConfig.data[e];this.pushQueue(e,i,t.params,t.callback,t.scope)},this),this.sendQueue(e,i,n,a)},abort:function(t){Ext.Ajax.abort(t),this.abortedMap[t.tId]=!0},getObjByStr:function(t){return t.split(".").reduce(function(t,e){return t[e]},window)},sendWebAPI:function(t){return this.lastAjaxId=this.callParent(arguments),this.lastAjaxId},initWebAPI:function(){this.apiConfig=this.getObjByStr(this.using),this.queue=[],this.abortedMap={},this.initInterface()},initInterface:function(){Ext.iterate(this.apiConfig.data,function(t,e){this[t]=this.buildWebAPIInterface(t,e)},this)},buildOldWebAPIInterface:function(t,e){return function(t,i,n){var a;Ext.isFunction(t)&&(n=i,i=t,t=void 0),a=this.instantiateWebAPIObj(e,t,i,n),this.sendWebAPI(a)}.bind(this)},buildWebAPIInterface:function(t,e){return function(t){var i=this.instantiateWebAPIObj(e,t);return this.doSend(i)}.bind(this)},onWebAPIFail:function(t,e,i,n){},onCompoundWebAPIHasFail:function(t,e,i,n,a){},doSend:function(t){return new Promise(function(e,i){var n,a=Ext.apply({},t);a.callback=function(a,o,s,l){n&&this.abortedMap[n.tId]||(t.callback(a,o,s,l),a?e(o):(this.onWebAPIFail(a,o,s,l),i(o)))}.bind(this),n=this.sendWebAPI(a)}.bind(this))},doSendEx:function(t){return new Promise(function(e,i){var n,a=Ext.apply({},t);a.callback=function(t,a,o,s){if(!this.abortedMap[n.tId]){var l={succ:t,resp:a,req:o,opt:s};t?e(l):(this.onWebAPIFail(t,a,o,s),i(l))}}.bind(this),n=this.sendWebAPI(a)}.bind(this))},doSendCompound:function(t,e,i,n){var a;return a={compound:Ext.apply({stopwhenerror:!1,params:e},i)},Ext.isArray(n)&&(a.encryption=n),this.doSendEx(a).then(function(i){var n,a=i.succ,o=i.resp,s=i.req,l=i.opt,r={};return r.has_fail=o.has_fail,r.result=o.result,r.length=t.length,r.api_type=[],Ext.each(t,function(t){r.api_type.push(t.apiType)},this),Ext.each(o.result,function(i,n){var a,o=e[n],s=t[n].apiType;o.callback.call(o.scope||window,i.success,i.data||i.error,o.params,l),a={succ:i.success,resp:i.data||i.error},Ext.isDefined(r[s])||(r[s]=a),r[n]=a},this),n={succ:a,resp:o,parsedResp:r,req:s,opt:l},o.has_fail&&this.onCompoundWebAPIHasFail(a,o,s,l,r),a?Promise.resolve(n):Promise.reject(n)}.bind(this))},pushQueue:function(t,e,i,n,a){this.queue.push({apiType:t,cfg:e,params:i,callback:n,scope:a})},sendQueue:function(t,e){var i,n=this.queue.slice();return this.queue=[],i=n.map(function(t){return this.instantiateWebAPIObj(t.cfg,t.params,t.callback,t.scope)},this),this.doSendCompound(n,i,t,e)},instantiateWebAPIObj:function(t,e,i,n){var a={};return Ext.copyTo(a,t,"api, method, version, params, encryption"),Ext.isFunction(t.build)?a.params=t.build(e):a.params=e,a.callback=function(e,a,o,s){Ext.isFunction(t.hook)&&t.hook(e,a,o,s),Ext.isFunction(i)&&i.call(n||window,e,a,o,s)},a}}),Ext.define("SYNO.SDS.MailClient.WebAPILib.WebAPI",{extend:"SYNO.SDS.MailClient.WebAPILib.BaseWebAPI",requires:[],constructor:function(){this.callParent(arguments),window.webapi=window.w=this},getErrorCodeByResp:function(t){return SYNO.SDS.MailClient.Error.getErrorCode(t)},showErrorMaskByResp:function(t){SYNO.SDS.MailClient.Window.el.mask(SYNO.SDS.MailClient.Error.getErrorString(t))},onWebAPIFail:function(t,e,i,n){this._handleError(e)},onCompoundWebAPIHasFail:function(t,e,i,n,a){t&&e.has_fail&&this._handleError(e)},_handleError:function(t){var e=this.getErrorCodeByResp(t);return SYNO.SDS.MailClient.Error.isPrivilegeErrorCode(e)?void SYNO.SDS.MailClient.Window.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t),function(){try{SYNO.SDS.Utils.Logout.action()}catch(t){}},this):SYNO.SDS.MailClient.Error.isFatalErrorCode(e)?void this.showErrorMaskByResp(t):void 0}}),Ext.define("SYNO.SDS.MailClient.WebAPI",{extend:"SYNO.SDS.MailClient.WebAPILib.WebAPI",singleton:!0}),Ext.define("SYNO.SDS.MailClient.ThreadLib.UndoAction",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.ThreadLib.Toaster","SYNO.SDS.MailClient.WebAPI"],constructor:function(){this.callParent(arguments),this.WebAPI=SYNO.SDS.MailClient.WebAPI,this.Toaster=SYNO.SDS.MailClient.ThreadLib.Toaster},showUndoMessageToTrash:function(t,e){this.Toaster.showMessageToTrash(this.undoSingleSetMailbox.bind(this,t,SYNO.SDS.MailClient.Define.trashId,e,{action:"normal"}))},showUndoMessageAddToBlacklist:function(t,e,i,n){this._showUndoAddToSpamRule(t,e,i,n,{addToBlacklist:!0})},showUndoMessageAddToWhitelist:function(t,e,i,n){this._showUndoAddToSpamRule(t,e,i,n,{addToBlacklist:!1})},showUndoSetMailbox:function(t,e,i,n){this.Toaster.showSetMailbox(this._undoSetMailbox.bind(this,t,e,i,n,{action:"normal"}),e)},showUndoReportSpam:function(t,e,i,n){this.Toaster.showSetMailbox(this._undoSetMailbox.bind(this,t,e,i,n,{action:"report_spam",isSpam:!1}),e)},showUndoReportNotSpam:function(t,e,i,n){this.Toaster.showSetMailbox(this._undoSetMailbox.bind(this,t,e,i,n,{action:"report_spam",isSpam:!0}),e)},showUndoAddToBlacklist:function(t,e,i,n,a){this._showUndoAddToSpamRule(t,e,i,a,{isThread:!0,addToBlacklist:!0,originalMailboxId:n})},showUndoAddToWhitelist:function(t,e,i,n,a){this._showUndoAddToSpamRule(t,e,i,a,{isThread:!0,addToBlacklist:!1,originalMailboxId:n})},_showUndoAddToSpamRule:function(t,e,i,n,a){var o=this._prepareUndoAddToSpamRuleFn(t,e,i,n,a),s=n.onlyUndoMailbox,l=n.notification;if(s)return o.undoMailboxFn(),void this.Toaster.show(l);this.Toaster.showSetMailbox(o.undoFn,e,l)},_prepareUndoAddToSpamRuleFn:function(t,e,i,n,a){var o=n.newSpamRuleIds,s=n.existDifferentTypeSpamRuleConditions,l=a.isThread,r=a.originalMailboxId,d=a.addToBlacklist,c={action:"spam_rule",isSpam:!d,newSpamRuleIds:o,existDifferentTypeSpamRuleConditions:s},h={action:"normal",isSilent:!0};return l?{undoFn:this._undoSetMailbox.bind(this,t,e,i,r,c),undoMailboxFn:this._undoSetMailbox.bind(this,t,e,i,r,h)}:{undoFn:this.undoSingleSetMailbox.bind(this,t,e,i,c),undoMailboxFn:this.undoSingleSetMailbox.bind(this,t,e,i,h)}},showUndoMarkRead:function(t,e){this.Toaster.showMarkRead(this.undoRead.bind(this,t,e),e)},showUndoThreadChangeLabel:function(t,e,i,n){this.Toaster.showThreadChangeLabel(this.undoLabelChange.bind(this,t,e,i),n)},undoRead:function(t,e){if(0!==t.length)return this.WebAPI.messageSetReadEx([t,!e]).then(this._showUndoneAndReload.bind(this)).catch(this._handleWebAPIError.bind(this))},_undoSetMailbox:function(t,e,i,n,a){var o=this._prepareUndoSetMailboxData(t,e,void 0,a),s=o.compound,l=o.affectedMailboxIds,r=a.isSilent;return SYNO.SDS.MailClient.Control.Vault.markMailboxDirty(l),this.WebAPI.send(s).then(function(t){if(SYNO.SDS.MailClient.Define.isMessageMode){r||this._showUndone();var e=new SYNO.SDS.MailClient.Condition("mailbox",n);return void SYNO.SDS.MailClient.Control.Mail.openThreadByCondition(i[0],e)}return r?this._reload():this._showUndoneAndReload()}.bind(this)).catch(this._handleWebAPIError.bind(this))},undoSingleSetMailbox:function(t,e,i,n){var a=this._prepareUndoSetMailboxData(t,e,function(t){return-1!==i.indexOf(t.id)},n),o=a.compound,s=a.affectedMailboxIds,l=n.isSilent;return SYNO.SDS.MailClient.Control.Vault.markMailboxDirty(s),this.WebAPI.send(o).then(function(t){return l?this._reload():this._showUndoneAndReload()}.bind(this)).catch(this._handleWebAPIError.bind(this))},_prepareUndoSetMailboxData:function(t,e,i,n){var a,o=[],s=[],l=SYNO.SDS.MailClient.Define.SpamRuleType,r=n.action,d=n.isSpam,c=n.newSpamRuleIds,h=n.existDifferentTypeSpamRuleConditions;return a=this._getMailboxUndoMap(t,function(t){if(!Ext.isFunction(i)||i(t))return t.mailbox_id!==e?t.mailbox_id:void 0}),Ext.iterate(a,function(t,e){switch(r){case"normal":o.push({apiType:"messageSetMailbox",params:{id:e,mailbox_id:parseInt(t,10)}});break;case"report_spam":o.push({apiType:"messageReportSpam",params:{id:e,mailbox_id:parseInt(t,10),is_spam:d}});break;case"spam_rule":o.push({apiType:"deleteSpamRule",params:{id:c}}),o.push({apiType:"setSpamRuleType",params:{condition:h,type:d?l.BLACK_LIST:l.WHITE_LIST}}),o.push({apiType:"messageReportSpam",params:{id:e,mailbox_id:parseInt(t,10),is_spam:d}});break;default:return Promise.reject("unknown action")}s.push(parseInt(t,10))}),{compound:o,affectedMailboxIds:s,undoMap:a}},_getMailboxUndoMap:function(t,e){function i(t){void 0!==(n=e(t))&&(a[n]||(a[n]=[]),a[n].push(t.id))}var n,a={};return t.forEach(function(t){t.message.forEach(i),t.filtered_message.forEach(i),t.draft.forEach(i)}),a},undoLabelChange:function(t,e,i){function n(t,e,i){Ext.isArray(i)||(i=[i]),i.forEach(function(i){t[i]||(t[i]=[]),t[i].push(e)})}function a(t,e){SYNO.SDS.MailClient.Control.Vault.markLabelDirty(t)}var o=SYNO.SDS.MailClient.Array,s=e.map(this._labelObjToId),l=i.map(this._labelObjToId),r={},d={},c=[];return t.forEach(function(t){var e=t.id,i=t.label.map(this._labelToId),a=o.intersection(i,l),c=o.without(s,i);n(r,e,a),n(d,e,c)},this),Ext.iterate(r,function(t,e){c.push({apiType:"threadAddLabel",params:{id:e,label_id:[parseInt(t,10)]}})}),Ext.iterate(d,function(t,e){c.push({apiType:"threadRemoveLabel",params:{id:e,label_id:[parseInt(t,10)]}})}),Ext.iterate(r,a),Ext.iterate(d,a),0===c.length?Promise.resolve():this.WebAPI.send(c).then(this._showUndoneAndReload.bind(this)).catch(this._handleWebAPIError.bind(this))},_showUndone:function(){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","action_undone"))},_showUndoneAndReload:function(){return this._showUndone(),SYNO.SDS.MailClient.Control.Main.reloadApp()},_reload:function(){return SYNO.SDS.MailClient.Control.Main.reloadApp()},_handleWebAPIError:function(t){var e=SYNO.SDS.MailClient.Error.getErrorString(t);SYNO.SDS.MailClient.Window.showToast(e)},_labelObjToId:function(t){return t.id},_labelToId:function(t){return t.id}}),Ext.define("SYNO.SDS.MailClient.ThreadLib.Action",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.ThreadLib.ThreadControlOperator","SYNO.SDS.MailClient.ThreadLib.Toaster","SYNO.SDS.MailClient.ThreadLib.UndoAction","SYNO.SDS.MailClient.WebAPI"],constructor:function(){this.callParent(arguments),this.WebAPI=SYNO.SDS.MailClient.WebAPI,this.Toaster=SYNO.SDS.MailClient.ThreadLib.Toaster,this.ThreadControlOperator=SYNO.SDS.MailClient.ThreadLib.ThreadControlOperator,this.UndoAction=SYNO.SDS.MailClient.ThreadLib.UndoAction},isThreadHasReadOnlyMsg:function(t){function e(t){return t.message.some(function(t){return SYNO.SDS.MailClient.Define.isReadOnlyMailbox(t.mailbox_id)})}return t.some(e)},isThreadModifiable:function(t){var e=SYNO.SDS.MailClient.Define,i=e.isInReadOnlyMailbox(),n=e.isInVirtaulOrLabel();return!(i||n&&this.isThreadHasReadOnlyMsg(t))},discard:function(t){var e=[],i=[];Ext.each(t,function(t,n,a){var o,s=t.draft,l=[],r=t.id;for(o=0;o<s.length;++o)e.push(s[o].id),l.push(s[o].id);SYNO.SDS.MailClient.Settings.conversation_view||s.length>0&&s[0].reply_to>0&&(r=s[0].reply_to),i.push({id:r,data:l})},this),this._discard(e,i)},_discard:function(t,e){var i=SYNO.SDS.MailClient.Control;return 0===t.length?Promise.resolve():(SYNO.SDS.MailClient.Control.Thread.deleteDraft(e),this.WebAPI.send("discardDraftEx",t).then(function(){return this.Toaster.showDiscard(),i.Mail.backToThread(),Promise.all([i.Mail.updateMail(),i.Sidebar.reloadMailboxList()])}.bind(this)).catch(this._handleWebAPIError.bind(this)))},messageToTrash:function(t,e){var i=SYNO.SDS.MailClient.Control,n=SYNO.SDS.MailClient.Define,a=this._getStore(),o=n.trashId,s={};return 0===t.length?Promise.resolve():(e=this._deepCopyAndFillStoreIdx(e,a),this.WebAPI.send("messageSetMailboxEx",[t,o]).then(function(){n.isMessageMode&&(s[o]=t,SYNO.SDS.MailClient.MessageHouseLib.Keeper.updateMailboxByMap(s)),i.Vault.markMailboxDirty(o),this.ThreadControlOperator.messageToTrash(t,e),this.UndoAction.showUndoMessageToTrash(e,t)}.bind(this)).catch(this._handleWebAPIError.bind(this)))},messageAddToSpamRule:function(t,e,i){var n=SYNO.SDS.MailClient.Define.SpamRuleType;return 0===t.length?Promise.resolve():this.WebAPI.send("messageListExistSpamRule",{type:i?n.WHITE_LIST:n.BLACK_LIST,id:t}).then(function(n){this._handleExistSpamRule(n.condition,i,function(n){this._messageAddToSpamRule(t,e,i,n)}.bind(this))}.bind(this)).catch(this._handleWebAPIError.bind(this))},_handleExistSpamRule:function(t,e,i){if(0!==t.length){var n=e?SYNO.SDS.MailClient._T("spam_rule","white_list"):SYNO.SDS.MailClient._T("spam_rule","black_list"),a=e?SYNO.SDS.MailClient._T("spam_rule","black_list"):SYNO.SDS.MailClient._T("spam_rule","white_list"),o=t.length<=3?t:t.slice(0,3).concat(["..."]),s=1===o.length?SYNO.SDS.MailClient._T("spam_rule","add_exist_address_dialog_desc"):SYNO.SDS.MailClient._T("spam_rule","add_exist_addresses_dialog_desc");SYNO.SDS.MailClient.Window.getMsgBox().confirm("",String.format(s,n,a,o.join(",<br />")),function(t){"yes"===t&&i(!0)},this)}else i(!1)},_messageAddToSpamRule:function(t,e,i,n){var a=this._getStore(),o=i?SYNO.SDS.MailClient.Define.junkId:SYNO.SDS.MailClient.Define.inboxId,s=SYNO.SDS.MailClient.Control;return e=this._deepCopyAndFillStoreIdx(e,a),this.WebAPI.send("messageAddToSpamRule",{id:t,is_blacklist:i,force:n}).then(function(n){var a=this._prepareUndoAddToSpamRuleData(n,i);e.forEach(function(t){t.message.forEach(function(t){s.Vault.markMailboxDirty(t.mailbox_id)}),t.filtered_message.forEach(function(t){s.Vault.markMailboxDirty(t.mailbox_id)})}),s.Vault.markMailboxDirty(o),SYNO.SDS.MailClient.Control.Main.reloadContent(),i?this.UndoAction.showUndoMessageAddToBlacklist(e,o,t,a):this.UndoAction.showUndoMessageAddToWhitelist(e,o,t,a)}.bind(this)).catch(function(t){604===SYNO.SDS.MailClient.Error.getErrorCode(t)?this._handleSpamRuleMaximumLimitError():this._handleWebAPIError(t)}.bind(this))},_handleSpamRuleMaximumLimitError:function(){SYNO.SDS.MailClient.Window.getMsgBox().alert("",String.format(SYNO.SDS.MailClient._T("spam_rule","maximum_limit_dialog_desc"),SYNO.SDS.MailClient.Define.spamRuleMaximumLimit)),SYNO.SDS.MailClient.Control.Main.reloadContent()},setMailbox:function(t,e,i){return this._setMailbox(t,e,{forAll:i,action:"normal"})},reportSpam:function(t){return this._setMailbox(t,SYNO.SDS.MailClient.Define.junkId,{forAll:!1,action:"report_spam",isSpam:!0})},reportNotSpam:function(t){return this._setMailbox(t,SYNO.SDS.MailClient.Define.inboxId,{forAll:!1,action:"report_spam",isSpam:!1})},addToBlackList:function(t){return this._addToSpamRule(t,SYNO.SDS.MailClient.Define.junkId,!0)},addToWhiteList:function(t){return this._addToSpamRule(t,SYNO.SDS.MailClient.Define.inboxId,!1)},_addToSpamRule:function(t,e,i){var n=SYNO.SDS.MailClient.Define.SpamRuleType;return this.WebAPI.send("threadListExistSpamRule",{type:i?n.WHITE_LIST:n.BLACK_LIST,id:this._getRecordIds(t)}).then(function(n){this._handleExistSpamRule(n.condition,i,function(n){this._setMailbox(t,e,{forAll:!1,action:"spam_rule",isSpam:i,force:n})}.bind(this))}.bind(this)).catch(this._handleWebAPIError.bind(this))},_getRecordIds:function(t){
return t.map(function(t){return t.id})},_getRecordData:function(t){return t.map(function(t){return t.data})},_setMailbox:function(t,e,i){var n,a,o,s=SYNO.SDS.MailClient.Control,l=SYNO.SDS.MailClient.Lib.PriorityMailbox,r=[],d=[],c=[];s.Mail.isInPriorityMailbox()?l.getSections().forEach(function(a,s){r=t.filter(function(t){return null!==t.store&&t.store.sectionIdx===s}),0!==r.length&&(c=this._getRecordIds(r),o=this._getRecordData(r),n=l.getInMailboxIdBySectionIdx(s),this._setMailboxImpl(c,e,o,n,i))}.bind(this)):(d=this._getRecordIds(t),a=this._getRecordData(t),n=s.Main.getInMailboxId(),this._setMailboxImpl(d,e,a,n,i))},_setMailboxImpl:function(t,e,i,n,a){var o,s,l=this._getStore(),r=t.length>=5,d=SYNO.SDS.MailClient.Define,c=SYNO.SDS.MailClient.Control,h=!1,u=!1,S=this.UndoAction,m=a.forAll,f=a.action,p=a.isSpam,g=a.force;if(m)return this.executeAllThreadAction([SYNO.SDS.MailClient.Format.makeAction("move_to",e)]);if(0===t.length)return Promise.resolve();switch(i=this._deepCopyAndFillStoreIdx(i,l),r&&!c.Mail.isInPriorityMailbox()&&SYNO.SDS.MailClient.Window.setStatusBusy(),d.isMessageMode||(this.ThreadControlOperator.setMailbox(t,e,n),c.Mail.isInPriorityMailbox()||(c.Vault.isInStock()?c.Mail.updateMailByToolbar():u=!0),c.Selection.get("ThreadCardPanel").clearSelections(),c.Mail.backToThread(),c.Vault.isInStock()?c.Mail.updateMail():h=!0),f){case"normal":o=this.WebAPI.send("threadSetMailboxEx",[t,e,n]),s=S.showUndoSetMailbox.bind(S);break;case"report_spam":o=this.WebAPI.send("threadReportSpam",{id:t,is_spam:p,operate_mailbox_id:n}),s=p?S.showUndoReportSpam.bind(S):S.showUndoReportNotSpam.bind(S);break;case"spam_rule":o=this.WebAPI.send("threadAddToSpamRule",{id:t,is_blacklist:p,force:g,operate_mailbox_id:n}),s=p?S.showUndoAddToBlacklist.bind(S):S.showUndoAddToWhitelist.bind(S);break;default:return Promise.reject("unknown action")}return o.then(function(a){if(u?c.Mail.updateMailByToolbar():h&&c.Mail.updateMail(),"spam_rule"!==f)s(i,e,t,n);else{var o=this._prepareUndoAddToSpamRuleData(a,p);s(i,e,t,n,o)}if(c.Vault.markMailboxDirty(e),d.isMessageMode){var l=new SYNO.SDS.MailClient.Condition("mailbox",e);SYNO.SDS.MailClient.Control.Mail.openThreadByCondition(t[0],l)}}.bind(this)).catch(function(t){604===SYNO.SDS.MailClient.Error.getErrorCode(t)?this._handleSpamRuleMaximumLimitError():this._handleWebAPIError(t)}.bind(this))},_prepareUndoAddToSpamRuleData:function(t,e){var i=t.new_spam_rule_id,n=t.new_spam_rule_condition,a=t.exist_same_type_spam_rule_condition,o=t.exist_different_type_spam_rule_condition,s=t.only_self_address,l=n.concat(o).concat(a);return{newSpamRuleIds:i,newSpamRuleConditions:n,existSameTypeSpamRuleConditions:a,existDifferentTypeSpamRuleConditions:o,onlySelfAddress:s,onlyUndoMailbox:s,notification:this._getAddToSpamRuleNotification(e,l,s)}},_getAddToSpamRuleNotification:function(t,e,i){var n,a,o=t?SYNO.SDS.MailClient._T("spam_rule","black_list"):SYNO.SDS.MailClient._T("spam_rule","white_list");return i?String.format(SYNO.SDS.MailClient._T("spam_rule","self_address_dialog_desc"),o):(n=this._truncateCondition(e,5),a=n.length>1?SYNO.SDS.MailClient._T("notification","add_to_spam_rule"):SYNO.SDS.MailClient._T("notification","add_to_spam_rule_singular"),String.format(a,o,n.join(",<br />")))},_truncateCondition:function(t,e){return t.length<=e?t:t.slice(0,e).concat(["..."])},deleteForever:function(t){SYNO.SDS.MailClient.Window.getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),function(e){"yes"===e&&this._deleteForever(t)},this)},_deleteForever:function(t){var e=SYNO.SDS.MailClient.Define,i=SYNO.SDS.MailClient.Switch,n=SYNO.SDS.MailClient.Control;return 0===t.length?Promise.resolve():this.WebAPI.send("threadDeleteEx",[t,i.inMailboxId]).then(function(){if(this.Toaster.showDeleteForever(),e.isMessageMode)return n.Mail.clearMessage();this.ThreadControlOperator.deleteForever(t,i.inMailboxId),n.Selection.clearSelect(),n.Mail.backToThread(),n.Mail.updateMail()}.bind(this)).catch(this._handleWebAPIError.bind(this))},markRead:function(t,e,i){var n=SYNO.SDS.MailClient.Control,a=n.Mail.getCurrentUnreadConditions(),o=n.Mail.isInPriorityMailbox(),s=[],l=[];return 0!==t.length||i?i?this.executeAllThreadAction([SYNO.SDS.MailClient.Format.makeAction("set_read",e)]):(t=SYNO.SDS.MailClient.Array.deepCopy(t),e||SYNO.SDS.MailClient.Control.Mail.backToThread(),t.forEach(function(t){var i=e?this._getIdsToRead(t):this._getIdsToUnread(t);s=s.concat(i),l.push([t.id,i])},this),this.ThreadControlOperator.markMessageRead(l,e),SYNO.SDS.MailClient.Control.Selection.updateToolbar(),this.WebAPI.send("messageSetReadEx",[s,e]).then(function(){o||n.Vault.markConditionDirty(a),this.UndoAction.showUndoMarkRead(s,e)}.bind(this)).catch(function(t){return this.ThreadControlOperator.rollbackMarkMessageRead(l,e),this._handleWebAPIError(t)}.bind(this))):Promise.resolve()},_getIdsToRead:function(t){return this._getMsgIdsByFn(t,function(t){return!t.read})},_getIdsToUnread:function(t){var e=t.message;return e.length>0?[e[e.length-1].id]:[]},doMarkRead:function(t,e){var i=SYNO.SDS.MailClient.Control,n=i.Mail.getCurrentUnreadConditions(),a=i.Mail.isInPriorityMailbox();return this.ThreadControlOperator.markRead(t,e),SYNO.SDS.MailClient.Control.Selection.updateToolbar(),this.WebAPI.send("threadSetReadEx",[t,e]).then(function(){a||i.Vault.markConditionDirty(n)}.bind(this)).catch(function(i){this.ThreadControlOperator.rollbackMarkRead(t,e)}.bind(this))},getLabelNotifyMsg:function(t,e){return e.length>5?String.format(SYNO.SDS.MailClient._T("notification",t+"_count"),e.length):String.format(SYNO.SDS.MailClient._T("notification",e.length>1?t+"s":t),e.map(this._labelObjToDisplayName).join(","))},threadChangeLabel:function(t,e,i,n,a){function o(t){t!==a&&SYNO.SDS.MailClient.Control.Vault.markLabelDirty(t)}var s,l,r,d,c=this._getStore(),h=t.map(function(t){return t.id},this),u=[],S=[];return n?(s=e.map(function(t){return SYNO.SDS.MailClient.Format.makeAction("set_label",t.id)}),l=i.map(function(t){return SYNO.SDS.MailClient.Format.makeAction("remove_label",t.id)}),this.executeAllThreadAction(s.concat(l))):0===h.length?Promise.resolve():(t=this._deepCopyAndFillStoreIdx(t,c),r=e.map(this._labelObjToId),d=i.map(this._labelObjToId),this.ThreadControlOperator.addLabel(h,e),e.length>0&&(u.push({apiType:"threadAddLabel",params:{id:h,label_id:r},callback:function(t,e){}.bind(this)}),S.push(this.getLabelNotifyMsg("apply_label",e))),this.ThreadControlOperator.removeLabel(h,i),i.length>0&&(u.push({apiType:"threadRemoveLabel",params:{id:h,label_id:d},callback:function(t,e){}.bind(this)}),S.push(this.getLabelNotifyMsg("remove_label",i))),SYNO.SDS.MailClient.Control.Selection.updateToolbar(),r.forEach(o),d.forEach(o),this.WebAPI.send(u).then(function(n){var a=n.succ,o=n.resp,s=n.parsedResp;if(!a||s.has_fail)return this._handleWebAPIError(o);this.UndoAction.showUndoThreadChangeLabel(t,e,i,S),SYNO.SDS.MailClient.Control.Mail.updateMail()}.bind(this)).catch(this._handleWebAPIError.bind(this)))},setStar:function(t,e,i){var n,a=[],o=[],s=SYNO.SDS.MailClient.Control;return i?this.executeAllThreadAction([SYNO.SDS.MailClient.Format.makeAction("set_star",e?"true":"false")]):0===t.length?Promise.resolve():(t.forEach(function(t){n=e?this._getIdsToStar(t):this._getIdsToUnstar(t),a=a.concat(n),o.push([t,n])},this),this.ThreadControlOperator.setStar(o,e),s.Selection.updateToolbar(),s.Vault.markMailboxDirty("starred"),this.WebAPI.send("setStarEx",[a,e]).catch(this._handleWebAPIError.bind(this)))},_getIdsToStar:function(t){var e=t.message,i=t.draft,n=[];return e.length>0?n.push(e[e.length-1].id):i.length&&n.push(i[i.length-1].id),n},_getIdsToUnstar:function(t){return this._getMsgIdsByFn(t,function(t){return t.star})},_getMsgIdsByFn:function(t,e){function i(t){return t.id}var n,a,o=t.message,s=t.draft;return n=o.filter(e).map(i),a=s.filter(e).map(i),[].concat(n,a)},addToTodoList:function(t){if(0!==t[0].message.length){var e,i,n=t[0].message,a=n[n.length-1].subject,o=n[n.length-1].rfc_message_id;return SYNO.Cal.Controller.TodoExternal.addMailToTodo({subject:a,app:"SYNO.SDS.MailClient.Application",msg_id:o}).then(function(t){return e=t.original_cal_id,i=t.evt_id,SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("calendar","add_to_todo_list_success")),SYNO.SDS.MailClient.AppLib.TodoPlugin.launch()}).then(function(){SYNO.Cal.Controller.TodoView.setViewType("by_list",e,i)}).catch(function(){SYNO.SDS.MailClient.Window.showToast(_T("error","error_error_system"))})}},executeAllThreadAction:function(t){return this._getStore().getTotalCount()<=SYNO.SDS.MailClient.Define.smallBatchOpLimit?this._sendSmallBatchOp(t):this._sendAddTask(t)},_sendSmallBatchOp:function(t){var e=SYNO.SDS.MailClient.Window,i=SYNO.SDS.MailClient.Control,n=function(t){return e.clearStatusBusy(),e.getMsgBox().alert("",SYNO.SDS.MailClient._T("error","batch_op_fail")),Promise.reject("executeAllThreadAction failed")};return e.setStatusBusy({text:SYNO.SDS.MailClient._T("common","apply_wait_msg")}),SYNO.SDS.MailClient.WebAPI.smallBatchOp({condition:this._getStore().lastOptions.params.condition,action:t}).then(function(t){e.clearStatusBusy(),i.Mail.reloadMail(),i.Sidebar.reloadMailboxList()}.bind(this)).catch(function(t){return n()}.bind(this))},_sendAddTask:function(t){var e=SYNO.SDS.MailClient.Window,i=this._getStore(),n=function(t){return e.clearStatusBusy(),e.getMsgBox().alert("",SYNO.SDS.MailClient._T("error","batch_op_fail")),Promise.reject("executeAllThreadAction failed")};return SYNO.SDS.MailClient.WebAPI.addTask({condition:i.lastOptions.params.condition,action:t}).then(function(t){if(!t.task_key)return n();var i={owner:e,msg:_T("common","msg_waiting"),progress:!0,progressText:"0/"+this._getStore().getTotalCount(),buttons:Ext.Msg.CANCEL,fn:function(){return SYNO.SDS.MailClient.WebAPI.cancelTask({task_key:t.task_key}).catch(function(t){SYNO.Debug.warn("cancel task failed",t)}.bind(this))}.bind(this)};e.getMsgBox().msg=i.msg,e.getMsgBox().show(i)}.bind(this)).catch(function(t){return n()}.bind(this))},_labelObjToId:function(t){return t.id},_labelObjToDisplayName:function(t){return'"'+Ext.util.Format.htmlEncode(t.name)+'"'},_handleWebAPIError:function(t){var e=SYNO.SDS.MailClient.Error.getErrorString(t);SYNO.SDS.MailClient.Window.showToast(e)},_getStore:function(){return SYNO.SDS.MailClient.Lib.Thread.store},_deepCopyAndFillStoreIdx:function(t,e){return t=SYNO.SDS.MailClient.Array.deepCopy(t),t.forEach(function(t){t.storeIdx=e.indexOfId(t.id)}),t}}),Ext.define("SYNO.SDS.MailClient.Lib.ThreadAction",{extend:"SYNO.SDS.MailClient.ThreadLib.Action",singleton:!0}),Ext.define("SYNO.SDS.MailClient.ThreadLib.Main",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Model.Main","SYNO.SDS.MailClient.Lib.PriorityMailbox","SYNO.SDS.MailClient.Lib.ThreadAction"],constructor:function(){this.callParent(arguments)},init:function(){this.WebAPI=SYNO.SDS.MailClient.WebAPI,this.PriorityMailbox=SYNO.SDS.MailClient.Lib.PriorityMailbox,this.PriorityMailbox.init(),this.store=SYNO.SDS.MailClient.Model.Main.createThreadStore(),this.currentStore=this.store,this.action=SYNO.SDS.MailClient.Lib.ThreadAction},findMatchStore:function(t){return SYNO.SDS.MailClient.Switch.inPriority?this.PriorityMailbox.findStoreByLastParams(t):this.store},getStoreToHandle:function(){var t=[];return SYNO.SDS.MailClient.Switch.inPriority?t=this.PriorityMailbox.getStores():t.push(this.store),t},getConditionToHandle:function(){return this.getStoreToHandle().map(function(t){return t.condition})},getAllRecords:function(){var t=this.getStoreToHandle(),e=[];return Ext.each(t,function(t,i){e=e.concat(t.getRange())},this),SYNO.SDS.MailClient.Format.getUniqueThreadRecord(e)},getAllUnreadOrStarredRecords:function(){return this.getAllRecords().filter(this.isUnreadOrStarredThread)},hasLessOrEqualToOneDraftOrThreadNotExisted:function(t){var e,i=this.getAllRecords();return!(e=i.filter(function(e){return e.id===t})[0])||e.data.draft&&e.data.draft.length<=1},setCurrentThreadStore:function(t){this.currentStore=-1==t?this.store:this.PriorityMailbox.getStoreByIdx(t)},getCurrentThreadStore:function(){return this.currentStore},isUnreadOrStarredThread:function(t){var e=SYNO.SDS.MailClient.ThreadLib.Main.prototype.isUnreadMsg;return t.data.star||t.data.message.some(e)},isUnreadMsg:function(t){var e=SYNO.SDS.MailClient.Define,i=t.mailbox_id===e.trashId||t.mailbox_id===e.junkId;return!t.read&&!i}}),Ext.define("SYNO.SDS.MailClient.Lib.Thread",{extend:"SYNO.SDS.MailClient.ThreadLib.Main",singleton:!0}),Ext.define("SYNO.SDS.MailClient.Main",{extend:"SYNO.ux.Panel",xtype:"mc_Main",constructor:function(t){this.callParent([this.fillConfig(t)]),SYNO.SDS.MailClient.Window.addPanel("SYNO.SDS.MailClient.Main",this),this.on("afterrender",this.regNavigateCmps,this),this.on("afterlayout",function(){SYNO.SDS.MailClient.Control.Main.initMailApp()},this,{single:!0})},fillConfig:function(t){var e=SYNO.SDS.MailClient.Define;this.threadDataHandler=SYNO.SDS.MailClient.Lib.Thread,this.threadDataHandler.init(),this.actionObject=SYNO.SDS.MailClient.ToolbarLib.ActionObject,this.actionObject.init();var i={};return e.isNormalMode?(this.mainCardPanel=new SYNO.SDS.MailClient.CardPanel,this.mainListPanel=new SYNO.SDS.MailClient.Sidebar.ListPanel({autoFlexcroll:!1}),i.items=[this.mainCardPanel,this.mainListPanel],e.launchParam.msg_id&&""===location.hash&&setTimeout(function(){SYNO.SDS.MailClient.Control.Sidebar.openMsgId(e.launchParam.msg_id)},1e3)):(SYNO.SDS.MailClient.Control.Sidebar.reloadMailSidebar(),this.mainCardPanel=new SYNO.SDS.MailClient.CardPanel({cls:"syno-mc-message-mode",listeners:{scope:this,afterrender:function(t){SYNO.SDS.MailClient.Control.View.toMailApp();var i=e.launchParam,n=SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition");i.t?setTimeout(function(){SYNO.SDS.MailClient.Control.Mail.openThreadByCondition(i.t,n)},1e3):i.msg_id&&""===location.hash&&setTimeout(function(){SYNO.SDS.MailClient.Control.Sidebar.openMsgId(e.launchParam.msg_id)},1e3)}}}),i.items=[this.mainCardPanel],i.boxMaxWidth=1200,i.boxMinWidth=800),i=Ext.apply(i,{border:!1,layout:"border",cls:"syno-mc-main-panel",bodyCssClass:"syno-mc-main-panel-body",monitorResize:!0,height:"auto"}),Ext.apply(i,t)},regNavigateCmps:function(){if(this.navigator=SYNO.SDS.MailClient.Window.navigator,this.navigator){var t=this.mainListPanel.mailList.mailboxList.treePanel,e=this.mainListPanel.mailList.othersMailboxList.treePanel,i=this.mainListPanel.mailList.labelList.treePanel,n=this.mainCardPanel.threadCardPanel.threadPanel.view,a=this.mainCardPanel.threadMessagePanel.threadCardPanel.threadPanel.view,o=this.mainCardPanel.messagePanel,s=this.mainCardPanel.threadMessagePanel.messagePanel,l=this.mainCardPanel.threadCardPanel.PriorityThreadPanel,r=this.mainCardPanel.threadMessagePanel.threadCardPanel.PriorityThreadPanel;this.navigator.regDefault(t),this.navigator.regUpDown(t,e),this.navigator.regUpDown(e,i),this.navigator.regLeftRight(t,n),this.navigator.regLeftRight(t,a),this.navigator.regLeftRight(i,n),this.navigator.regLeftRight(i,a),this.navigator.regLeftRight(n,o),this.navigator.regLeftRight(a,s),this.regPriorityNavigateCmps(l,!0),this.regPriorityNavigateCmps(r,!1)}},regPriorityNavigateCmps:function(t,e){var i=t.sections,n=this.mainListPanel.mailList.mailboxList.treePanel,a=this.mainListPanel.mailList.labelList.treePanel,o=this.mainCardPanel.messagePanel,s=this.mainCardPanel.threadMessagePanel.messagePanel;Ext.each(i,function(t,l){var r=e?"priorityColTwo":"priorityColThree";this.navigator.regGroup(r,t.view),t.view.navigationGroup=r,this.navigator.regLeftRight(n,t.view),this.navigator.regLeftRight(a,t.view),this.navigator.regLeftRight(t.view,e?o:s),Ext.each(i,function(e,i){i===l+1&&this.navigator.regUpDown(t.view,e.view)},this)},this)}}),Ext.define("SYNO.SDS.MailClient.PopOutWindowComposer",{extend:"SYNO.SDS.Window",requires:["SYNO.SDS.MailClient.Editor.EditorPanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on({scope:this,afterrender:function(){this.onWinResize(this.getWidth())},resize:function(t,e){this.onWinResize(e)},activate:function(){this.editor.onComposerUnmask()},deactivate:function(){this.editor.onComposerMask()}})},fillConfig:function(t){this.editor=new SYNO.SDS.MailClient.Editor.EditorPanel(Ext.apply({popoutWindow:this,level:SYNO.SDS.MailClient.Editor.LevelEnum.MAIN_WIN_POPOUT},t.editorConfig)),delete t.editorConfig;var e=Math.floor(.7*Ext.getBody().getWidth()),i=Math.floor(.9*(Ext.getBody().getHeight()-36)),n={owner:SYNO.SDS.MailClient.Window,cls:"syno-mc-composer-win syno-mc-modal-window",title:SYNO.SDS.MailClient._T("common","compose"),minWidth:600,minHeight:420,width:Math.max(Math.min(e,1150),600),height:Math.max(Math.min(i,800),420),layout:"fit",closable:!0,constrain:!0,minimizable:!0,maximizable:!1,buttonAlign:"left",fbar:new Ext.Toolbar({cls:"x-statusbar",items:[{itemId:"send",xtype:"syno_button",cls:"syno-mc-send",btnStyle:"blue",text:SYNO.SDS.MailClient._T("composer","send"),handler:this.editor.clickSend.createDelegate(this.editor,[])},{itemId:"includeAttachment",xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("composer","include_original_attachments"),hidden:!this.editor.draftObj||!this.editor.draftObj.refMsg||!this.editor.draftObj.refMsg.attachment.length||"forward"===this.editor.draftObj.replyType,listeners:{check:this.editor.checkIncludeAttachment.createDelegate(this.editor,[])}},"->",this.syncStatus=new SYNO.ux.DisplayField({cls:"sync-status"}),"-",{itemId:"discard",xtype:"syno_button",cls:"syno-mc-discard",iconCls:"syno-mc-print-icon",tooltip:SYNO.SDS.MailClient._T("composer","discard"),handler:this.editor.clickDiscard.createDelegate(this.editor,[])}]}),items:[this.editor]};return Ext.apply(n,t)},adjTopHeight:function(){this.editor&&this.editor.adjTopHeight()},afterRender:function(){this.callParent(arguments),this.alignTo(this.owner?this.owner.el:document.body,"c-c")},onDestroy:function(){this.callParent(arguments),this.animateTask&&this.animateTask.cancel()},show:function(){this.callParent(arguments),this.barItem.highlight(!0)},hide:function(){this.callParent(arguments),this.barItem.highlight(!1)},isAlwaysOnTop:function(){return!1},onWinResize:function(t){this.editor&&this.editor.adjTopWidth(t-this.body.getPadding("lr"))}}),Ext.define("SYNO.SDS.MailClient.PopOutWindowManager",{extend:"Ext.BoxComponent",requires:["SYNO.SDS.MailClient.PopOutWindowManagerItem"],singleton:!0,constructor:function(t){this.callParent([this.fillConfig(t)]),this.barItems=[],this.disableMask=new Ext.Container({cls:"syno-mc-popout-manager-bar-mask",renderTo:this.el})},fillConfig:function(t){var e={renderTo:Ext.getBody(),cls:"syno-mc-popoutwin-manager-bar"};return Ext.apply(e,t)},init:function(){this.mon(SYNO.SDS.MailClient.Window.el,"mousedown",this.onMainWinActivate,this),this.mon(SYNO.SDS.MailClient.Window,"deactivate",this.onMainWinDeactivate,this),this.mon(SYNO.SDS.MailClient.Switch,"cardwidthchange",this.onCardWidthChange,this)},onCardWidthChange:function(t){this.adjustItemDisplayOrder()},onMainWinActivate:function(t){this.hideComposer(),this.adjZIndex(SYNO.SDS.MailClient.Window)},onMainWinDeactivate:function(t){this.adjZIndex(t)},adjZIndex:function(t){var e=t.el.dom,i=e.currentStyle||window.getComputedStyle(e);this.el&&this.el.applyStyles("z-index: "+(parseInt(i.zIndex,10)+1))},hideComposer:function(){var t;for(t=0;t<this.barItems.length;t++)this.barItems[t].win.minimize()},disableComposer:function(){this.hideComposer(),this.disableMask.el.applyStyles("display: block;")},enableComposer:function(){this.disableMask.el.applyStyles("display: none;")},openComposerFromMailtoLink:function(t){this._openComposer(t,null,null,!0)},openComposer:function(t,e,i){this._openComposer(t,e,i,!1)},_openComposer:function(t,e,i,n){if(SYNO.SDS.MailClient.DraftLib.DraftManager.canOpenDraft()){Ext.isObject(t)?t instanceof Ext.data.Record||(t=this.getDraftRecord(t)):t=this.getDraftRecord();var a={isNew:!t||!t.get("id"),isMailtoLink:n,draftRec:t};e&&(a.draftObj=e),i&&(a.focusTarget=i);var o={editorConfig:a,listeners:{scope:this,close:this.onWinClose}},s=new SYNO.SDS.MailClient.PopOutWindowComposer(o);this.addItem(t,s),s.show(),s.adjTopHeight()}},getDraftRecord:function(t){return new Ext.data.Record(Ext.apply({subject:"",to:[],cc:[],bcc:[],body:"",attachment:[]},t))},onSwitchDraftChange:function(t,e){if("edit"===t||"delete"===t){var i,n,a,o;for(i=0;i<e.length;i++)for(n=0;n<this.barItems.length;n++)if(o=this.barItems[n],"edit"===t)e[i].data.id===o.win.editor.draftRec.get("id")&&o.updateText(e[i].data.subject);else for(a=0;a<e[i].data.length;a++)e[i].data[a]!==o.win.editor.draftRec.get("id")||o.win.editor.preventDelete||o.win.close()}},onWinClose:function(t){this.deleteItem(t.barItem)},getItem:function(t){var e,i;for(e=0;e<this.barItems.length;e++)if(i=this.barItems[e],i.win.editor.draftRec.get("id")===t)return i},addItem:function(t,e){var i=new SYNO.SDS.MailClient.PopOutWindowManagerItem({win:e,listeners:{scope:this,itemclick:this.toggleItem}});e.barItem=i,this.barItems.push(i),i.render(this.el),i.updateText(t.get("subject")),this.adjustItemDisplayOrder()},deleteItem:function(t){this.barItems.remove(t),t.destroy(),this.adjustItemDisplayOrder()},toggleItem:function(t){if(t.win.isVisible())return void t.win.hide();var e,i,n;for(e=0;e<this.barItems.length;e++)if(i=this.barItems[e].win,i.el.hasClass("active-win")){n=i;break}n&&Math.abs(t.win.x-n.x)<10&&Math.abs(t.win.y-n.y)<10&&(t.win.x+=30,t.win.y+=30,(t.win.x+t.win.getWidth()>Ext.getBody().getWidth()||t.win.y+t.win.getHeight()>Ext.getBody().getHeight())&&(t.win.x=10,t.win.y=10)),t.win.show(),t.updateAccessTime(),this.adjustItemDisplayOrder()},repositionTodoPlugin:function(){var t=SYNO.SDS.AppMgr.getByAppName("SYNO.Cal.Todo.Plugin.Instance")[0],e=t&&t.window;e&&e.el.setStyle("right",12+(this.chatPluginWidth?this.chatPluginWidth+8:0)+"px")},shiftForChatPlugin:function(t,e){this.chatPluginWidth=t?e:0,this.shiftForPlugins(),this.repositionTodoPlugin(),this.adjustItemDisplayOrder()},shiftForTodoPlugin:function(t,e){this.todoPluginWidth=t?e:0,this.shiftForPlugins(),this.adjustItemDisplayOrder()},shiftForPlugins:function(){this.el.setStyle("right",12+(this.chatPluginWidth?this.chatPluginWidth+8:0)+(this.todoPluginWidth?this.todoPluginWidth+8:0)+"px")},adjustItemDisplayOrder:function(){if(0!==this.barItems.length){var t=0,e=parseInt(this.el.getStyle("right"),10),i=Math.floor((window.innerWidth-6-e)/208),n=[],a=0;if(i>=this.barItems.length)for(t=0;t<this.barItems.length;t++)this.barItems[t].setVisible(!0);else{for(t=0;t<this.barItems.length;t++)n.push(this.barItems[t].accessTime);for(n.sort(function(t,e){return e-t}),a=n[i-1],t=0;t<this.barItems.length;t++)this.barItems[t].setVisible(this.barItems[t].accessTime>=a)}}}}),Ext.define("SYNO.SDS.MailClient.PopOutWindowManagerItem",{extend:"Ext.Container",requires:["SYNO.SDS.MailClient.PopOutWindowComposer"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("itemclick"),this.on("afterrender",function(){this.el.on("click",this.click,this)},this),this.highlight(this.win.isVisible()),this.updateAccessTime()},fillConfig:function(t){var e={cls:"syno-mc-popoutwin-manager-bar-item",items:[{itemId:"text",cls:"text",xtype:"container"},{itemId:"close",cls:"close-btn",xtype:"syno_button",scope:this,handler:this.clickClose}]};return Ext.apply(e,t)},updateText:function(t){t=t.trim()||"("+SYNO.SDS.MailClient._T("mail","empty_subject")+")";var e=this.getComponent("text");e.update(Ext.util.Format.htmlEncode(t)),e.el.dom.title=t},clickClose:function(){this.win.close()},click:function(){this.updateAccessTime(),this.fireEvent("itemclick",this)},highlight:function(t){this[t?"addClass":"removeClass"]("highlight")},updateAccessTime:function(){this.accessTime=(new Date).getTime()}}),Ext.define("SYNO.SDS.MailClient.PrintPage",{extend:"SYNO.ux.FleXcroll.DataView",constructor:function(t){var e=new Ext.data.JsonStore({fields:["id","arrival_time","attachment","bcc","body","cc","email","from","last_modified","mailbox_id","read","star","subject","thread_id","to","rfc_message_id","is_draft"],listeners:{scope:this,load:function(){var t,e,i,n,a,o=this.all.elements,s=this.store.getRange();if(SYNO.SDS.MailClient.Define.launchParam.ui)for(t=0;t<o.length;++t)for(n=Ext.fly(o[t]).select("[syno-mc-blockquote]"),e=0;e<n.getCount();++e)i=n.item(e).getAttribute("syno-mc-blockquote"),a=document.createElement("div"),a.innerHTML=s[t].get("body").blockquote[i],n.item(e).replaceWith(a);else for(t=0;t<o.length;++t){for(n=Ext.fly(o[t]).select("[syno-mc-blockquote]"),e=0;e<n.getCount();++e)a=Ext.fly(document.createElement("div")),a.addClass("syno-mc-blockquote-hidde").dom.innerHTML="[Quoted text hidden]",n.item(e).replaceWith(a.dom);for(n=Ext.fly(o[t]).select(".syno-mc-reply-content"),e=0;e<n.getCount();++e){a=Ext.fly(document.createElement("div")),a.addClass("syno-mc-blockquote-hidde").dom.innerHTML="[Quoted text hidden]",n.item(e).replaceWith(a.dom);break}}if(SYNO.SDS.MailClient.Define.launchParam.print){var l=this.el.select(".body img");this.imageCount=l.getCount(),this.imageLoaded=0,this.imageCount?l.each(function(t){t.on("load",function(){this.imageLoaded+=1,this.imageLoaded==this.imageCount&&window.print()},this,{single:!0})},this):window.print()}}}}),i=[];SYNO.SDS.MailClient.Define.launchParam.pm&&i.push({apiType:"getMessage",params:{id:SYNO.SDS.MailClient.Define.launchParam.pm,additional:["blockquote"]}}),SYNO.SDS.MailClient.Define.launchParam.pd&&i.push({apiType:"getDraft",params:{id:SYNO.SDS.MailClient.Define.launchParam.pd}}),SYNO.SDS.MailClient.WebAPI.send(i).then(function(t){SYNO.SDS.MailClient.Window.el.setStyle({position:"relative",height:"auto"});var e,i,n,a,o,s=t.resp.result,l=[];for(e=0;e<s.length;++e)for(n in s[e].data)if(s[e].data.hasOwnProperty(n)){for(a=s[e].data[n],i=0;i<a.length;++i)a[i]=SYNO.SDS.MailClient.Format.formatAddrsOfMsgToNormal(a[i]),a[i].is_draft="draft"==n,o||(o=a[i].subject.trim());l=l.concat(a)}o&&(document.title=o),this.store.loadData(l)}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this));var n={cls:"selectabletext",itemSelector:"div.item-wrap",itemSelectorCls:"item-wrap",border:!1,tpl:this.createTpl(),autoHeight:!0,autoFlexcroll:!1,store:e};this.callParent([Ext.apply(n,t)])},createTpl:function(){return new Ext.XTemplate('<tpl for=".">','<tpl if="xindex == 1">','<div class="title">','<span class="total">{[xcount]} messages</span>','<span class="nameaddr">',"{[this.getNameAddr()]}","</span>","</div>",'<div class="subject"><b>{subject:htmlEncode}</b></div>',"</tpl>",'<div class="sep-border"></div>','<div class="item-wrap">','<table class="from-time" width="100%"><tr>',"<td>{[this.getFrom(values.from)]}</td>",'<td align="right">{[SYNO.SDS.MailClient.Format.toFullTimeString(values.arrival_time)]}</td>',"</tr></table>",'<div class="to">','<tpl if="is_draft"><b>{[SYNO.SDS.MailClient._T("common", "draft")]}</b> </tpl>','<b>{[SYNO.SDS.MailClient._T("mail", "receiver")]}: </b>','<tpl for="to">{.:htmlEncode}','{[xindex < xcount ? ", " : ""]}',"</tpl>","</div>",'<tpl if="cc.length">','<div class="cc">','<b>{[SYNO.SDS.MailClient._T("mail", "copy")]}: </b>','<tpl for="cc">{.:htmlEncode}','{[xindex < xcount ? ", " : ""]}',"</tpl>","</div>","</tpl>",'<tpl if="bcc.length">','<div class="bcc">','<b>{[SYNO.SDS.MailClient._T("mail", "blind_copy")]}: </b>','<tpl for="bcc">{.:htmlEncode}','{[xindex < xcount ? ", " : ""]}',"</tpl>","</div>","</tpl>",'<div class="body reset">','<tpl if="body.html">',"{[this.composeHtml(values.body.html, values.body.style, values.rfc_message_id)]}","</tpl>",'<tpl if="!body.html">',"<pre>{values.body.plain:htmlEncode}</pre>","</tpl>","</div>",'<tpl if="attachment.length">','<div class="attachment">','<div class="total">{[String.format(SYNO.SDS.MailClient._T("mail", "attachments_count"), values.attachment.length)]}</div>','<tpl for="attachment">','<div><a target="_blank" href="{[SYNO.SDS.MailClient.Format.getAttachmentDownloadUrl(values)]}">{name:htmlEncode}</a><span>{[SYNO.SDS.MailClient.Format.getApproximateSizeFromByte(values.size, 0)[0]]}</span></div>','{[xcount < xindex ? "<br>" : ""]}',"</tpl>","</div>","</tpl>","</div>","</tpl>",'<div class="x-clear"></div>',{getNameAddr:function(){var t=SYNO.SDS.MailClient.Format.composeNameAddr(_S("user"),SYNO.SDS.MailClient.Format.composeAddrSpec(_S("user"),SYNO.SDS.MailClient.Info.smtp_hostname));return this.getFrom(t)},getFrom:function(t){var e=SYNO.SDS.MailClient.Format.addressWithDisplayNameRegExp,i=e.exec(t);return i&&i[1]?SYNO.SDS.MailClient.Format.toEmailSpan(t,"bold")+Ext.util.Format.htmlEncode(i[2]):SYNO.SDS.MailClient.Format.toEmailSpan(t,"bold")},composeHtml:function(t,e,i){var n,a;return Ext.isEmpty(e)||Ext.isEmpty(i)?t:(a=document.createElement("div"),a.setAttribute("syno-mc-class","syno-mc-"+i),a.innerHTML=t,n=document.createElement("style"),n.innerHTML=e,a.appendChild(n),a.outerHTML)}})},refresh:function(){this.callParent(arguments)}}),Ext.define("SYNO.SDS.MailClient.ReplySettingAddDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="createCustomAutoReply",this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:500};return Ext.apply(e,t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({itemId:"setting_panel",trackResetOnLoad:!0,items:[{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","mail_from"),emptyText:SYNO.SDS.MailClient._T("auto_reply","mail_from_hint"),name:"sender",maxlength:256,allowBlank:!1},{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),name:"subject",value:SYNO.SDS.MailClient._T("auto_reply","reply_subject"),maxlength:256,allowBlank:!1},{xtype:"syno_textarea",width:400,height:120,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","message"),name:"message",value:String.format(SYNO.SDS.MailClient._T("auto_reply","reply_msg"),"\r\n\r\n"),allowBlank:!1,listeners:{keydown:function(t,e,i){e.getKey()==e.ENTER&&e.stopPropagation()}}}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={};return e.sender=t.sender.trim(),e.subject=t.subject.trim(),e.message=t.message.trim(),!!(e.sender&&e.subject&&e.message)&&e},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.ReplySettingEditDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setCustomAutoReply";var e=t.targetInfo;if(!e)throw"no target";this.orgsender=e.sender,this.subject=e.subject,this.message=e.message,this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:500};return Ext.apply(e,t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({itemId:"setting_panel",trackResetOnLoad:!0,items:[{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","mail_from"),value:this.orgsender,emptyText:SYNO.SDS.MailClient._T("auto_reply","mail_from_hint"),name:"sender",maxlength:256,allowBlank:!1},{xtype:"syno_textfield",width:400,fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),name:"subject",value:this.subject,maxlength:256,allowBlank:!1},{xtype:"syno_textarea",width:400,height:120,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","message"),name:"message",value:this.message,allowBlank:!1,listeners:{keydown:function(t,e,i){e.getKey()==e.ENTER&&e.stopPropagation()}}}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={};return e.orgsender=this.orgsender,e.sender=t.sender.trim(),e.subject=t.subject.trim(),e.message=t.message.trim(),e},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.FilterAddEditDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.ConditionPanel","SYNO.SDS.MailClient.ActionPanel"],mode:"",
constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this.action_panel,"createfilter",this.onApplyDone,this),this.on("show",this.loadInfo,this)},fillConfig:function(t){var e={layout:"card",cls:"syno-mc-filter-win",padding:SYNO.SDS.MailClient.Format.isDSM6()?void 0:"16px 0 0 0",title:"add"==t.mode?_T("common","create"):_T("common","alt_edit"),width:618,height:462,minWidth:618,minHeight:462,useStatusBar:!1,closable:!0,activeItem:0,items:[this.condition_panel=new SYNO.SDS.MailClient.ConditionPanel({owner:this,itemId:"condition"}),this.action_panel=new SYNO.SDS.MailClient.ActionPanel({owner:this,itemId:"action"})]};return Ext.apply(e,t)},loadInfo:function(){"edit"===this.mode&&(this.condition_panel.loadTargetInfo(this.targetInfo.condition),this.action_panel.loadTargetInfo(this.targetInfo.action))},switchPanel:function(t){this.layout.setActiveItem(t)},onApplyDone:function(){this.fireEvent("apply"),this.close()},alertMessage:function(t,e,i){this.getMsgBox().alert("",t,e,i)}}),Ext.define("SYNO.SDS.MailClient.Setting.GridPanel",{extend:"SYNO.ux.GridPanel",emptyString:"",checkEmptyState:function(){this.callParent(arguments),this.store&&this.rendered&&this.emptyString&&(0===this.store.getCount()?this.mask(this.emptyString):this.unmask())},mask:function(t){this.view.el.mask(t,"syno-ux-grid-mask-info"),this.view.focusEl.set({tabIndex:-1}),this.view.setHeaderFocusTabbable(!1)},unmask:function(){this.view.el.unmask(),this.view.focusEl.set({tabIndex:0}),this.view.setHeaderFocusTabbable(!0)},renderCheckBox:function(t,e,i){var n="disabled"===t?"disabled":t?"checked":"unchecked",a="disabled"!==n&&"checked"===n,o=i?i.id+"_"+this.dataIndex:Ext.id(),s="disabled"===n?_T("common","disabled"):_JSLIBSTR("uicommon","enable_column_"+n),l="disabled"===n;return e=e||{},e.cellAttr=String.format('aria-label="{0} {1}" aria-checked="{2}" aria-disabled="{3}" role="checkbox"',Ext.util.Format.stripTags(this.orgHeader),s,a,l),String.format('<div class="syno-ux-grid-enable-column-{0}" id="{1}"></div>',n,o)}}),Ext.define("SYNO.SDS.MailClient.Setting.EditorGridPanel",{extend:"SYNO.ux.EditorGridPanel",emptyString:"",checkEmptyState:function(){this.callParent(arguments),this.store&&this.rendered&&this.emptyString&&(0===this.store.getCount()?this.mask(this.emptyString):this.unmask())},mask:function(t){this.view.el.mask(t||_T("common","loading"),"syno-ux-grid-mask-info"),this.view.focusEl.set({tabIndex:-1}),this.view.setHeaderFocusTabbable(!1)},unmask:function(){this.view.el.unmask(),this.view.focusEl.set({tabIndex:0}),this.view.setHeaderFocusTabbable(!0)}}),Ext.define("SYNO.SDS.MailClient.Setting.DDGridPanel",{extend:"SYNO.ux.DDGridPanel",emptyString:"",constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this,"rowmousedown",this.onRowMouseDown,this)},checkEmptyState:function(){this.callParent(arguments),this.store&&this.rendered&&this.emptyString&&(0===this.store.getCount()?this.mask(this.emptyString):this.unmask())},mask:function(t){this.view.el.mask(t,"syno-ux-grid-mask-info"),this.view.focusEl.set({tabIndex:-1}),this.view.setHeaderFocusTabbable(!1)},unmask:function(){this.view.el.unmask(),this.view.focusEl.set({tabIndex:0}),this.view.setHeaderFocusTabbable(!0)},onRowMouseDown:function(t,e,i){i.ctrlKey||i.shiftKey||t.getSelectionModel().selectRow(e)}}),Ext.define("SYNO.SDS.MailClient.Setting.List",{extend:"SYNO.ux.ModuleList",constructor:function(t){this.callParent([this.fillConfig(t)]),this.removeClass("syno-ux-modulelist"),this.addClass("syno-ux-treepanel")},fillConfig:function(t){var e={cls:"syno-mc-setting-list",listItems:this.getListItems()};return Ext.apply(e,t),e},getListItems:function(){return[{text:SYNO.SDS.MailClient._T("setting","general"),qtip:SYNO.SDS.MailClient._T("setting","general"),fn:"tab_general"},{text:SYNO.SDS.MailClient._T("setting","theme_setting"),qtip:SYNO.SDS.MailClient._T("setting","theme_setting"),fn:"tab_theme"},{text:SYNO.SDS.MailClient._T("setting","auto_reply_forward"),qtip:SYNO.SDS.MailClient._T("setting","auto_reply_forward"),fn:"tab_autoReply"},{text:SYNO.SDS.MailClient._T("common","mailbox"),qtip:SYNO.SDS.MailClient._T("common","mailbox"),fn:"tab_mailbox"},{text:SYNO.SDS.MailClient._T("common","shared_mailbox"),qtip:SYNO.SDS.MailClient._T("common","shared_mailbox"),fn:"tab_shared_mailbox"},{text:SYNO.SDS.MailClient._T("setting","filter"),qtip:SYNO.SDS.MailClient._T("setting","filter"),fn:"tab_filter"},{text:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),qtip:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),fn:"tab_priority_mailbox"},{text:SYNO.SDS.MailClient._T("setting","smtp_title"),qtip:SYNO.SDS.MailClient._T("setting","smtp_title"),fn:"tab_smtp"},{text:SYNO.SDS.MailClient._T("setting","pop3_title"),qtip:SYNO.SDS.MailClient._T("setting","pop3_title"),fn:"tab_pop3",hidden:!SYNO.SDS.MailClient.AdminSettings.POP3.enable_pop3},{text:SYNO.SDS.MailClient._T("pgp","open_pgp"),qtip:SYNO.SDS.MailClient._T("pgp","open_pgp"),fn:"tab_pgp",hidden:SYNO.SDS.MailClient.PGPSettings.pgp_disabled},{text:SYNO.SDS.MailClient._T("setting","notification_title"),qtip:SYNO.SDS.MailClient._T("setting","notification_title"),fn:"tab_notification"},{text:SYNO.SDS.MailClient._T("spam_rule","black_list_and_white_list"),qtip:SYNO.SDS.MailClient._T("spam_rule","black_list_and_white_list"),fn:"tab_spam_rule"},{text:SYNO.SDS.MailClient._T("lab","lab_title"),qtip:SYNO.SDS.MailClient._T("lab","lab_title"),fn:"tab_lab",hidden:!SYNO.SDS.MailClient.MailClientLab.enable_lab}]}}),Ext.define("SYNO.SDS.MailClient.Setting.Card",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.Setting.General","SYNO.SDS.MailClient.Setting.PGP.KeyMgrDialog","SYNO.SDS.MailClient.Setting.AutoReply","SYNO.SDS.MailClient.Setting.SMTP","SYNO.SDS.MailClient.Setting.POP3","SYNO.SDS.MailClient.Setting.Mailbox","SYNO.SDS.MailClient.Setting.SharedMailbox","SYNO.SDS.MailClient.Setting.Filter","SYNO.SDS.MailClient.Setting.PriorityMailbox","SYNO.SDS.MailClient.Setting.PGP.Main","SYNO.SDS.MailClient.Setting.SpamRule.Main","SYNO.SDS.MailClient.Setting.ThemeForm","SYNO.SDS.MailClient.Setting.Notification.Main","SYNO.SDS.MailClient.Setting.Lab"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addClass("syno-ux-formpanel")},fillConfig:function(t){var e=[this.general_panel=new SYNO.SDS.MailClient.Setting.General({itemId:"tab_general",smtpStore:this.getSMTPStore(),owner:this}),this.theme_panel=new SYNO.SDS.MailClient.Setting.ThemeForm({itemId:"tab_theme",owner:this}),this.auto_reply_panel=new SYNO.SDS.MailClient.Setting.AutoReply({itemId:"tab_autoReply",owner:this}),this.smtp_panel=new SYNO.SDS.MailClient.Setting.SMTP({itemId:"tab_smtp",smtpStore:this.getSMTPStore(),owner:this}),this.pop3_panel=new SYNO.SDS.MailClient.Setting.POP3({itemId:"tab_pop3",owner:this}),this.shared_mailbox_panel=new SYNO.SDS.MailClient.Setting.SharedMailbox({itemId:"tab_shared_mailbox",owner:this}),this.mailbox_panel=new SYNO.SDS.MailClient.Setting.Mailbox({itemId:"tab_mailbox",owner:this}),this.filter_panel=new SYNO.SDS.MailClient.Setting.Filter({itemId:"tab_filter",owner:this}),this.spam_rule_panel=new SYNO.SDS.MailClient.Setting.SpamRule.Main({itemId:"tab_spam_rule",owner:this}),this.priority_mailbox_panel=new SYNO.SDS.MailClient.Setting.PriorityMailbox({itemId:"tab_priority_mailbox",owner:this}),this.pgp_panel=new SYNO.SDS.MailClient.Setting.PGP.Main({itemId:"tab_pgp",owner:this}),this.notification_panel=new SYNO.SDS.MailClient.Setting.Notification.Main({itemId:"tab_notification",owner:this}),this.lab_panel=new SYNO.SDS.MailClient.Setting.Lab({itemId:"tab_lab",owner:this})],i={layout:"card",cls:"syno-mc-setting-card",activeItem:0,items:e,fbar:{xtype:"statusbar",defaultText:" ",statusAlign:"left",buttonAlign:"left",items:SYNO.SDS.MailClient.Format.orderButtonsByDSM({xtype:"syno_button",btnStyle:"blue",text:_T("common","apply"),scope:this,handler:this.applyHandler},{xtype:"syno_button",text:_T("common","cancel"),scope:this,handler:this.cancelHandler})}};return Ext.apply(i,t),i},getSMTPStore:function(){return this.smtpStore=this.smtpStore||new Ext.data.JsonStore({autoDestroy:!0,root:"smtp",idProperty:"id",fields:["id","display_name","mail","host_name","port","user_name","password","connection_type","signature"],data:SYNO.SDS.MailClient.SMTP,proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Setting.SMTP",method:"list",version:1,listeners:{load:function(t,e,i,n){SYNO.SDS.MailClient.SMTP=e}}}),listeners:{scope:this,beforeload:function(){this.setStatusBusy()},load:function(){this.clearStatusBusy()}}}),this.smtpStore},applyHandler:function(){this.applyAllForm()},cancelHandler:function(){this.isAnyFormDirty()?this.findWindow().getMsgBox().confirm("",_T("common","confirm_lostchange"),function(t){"yes"==t?(this.theme_panel.isDirty()&&this.theme_panel.resetPreview(),this.findWindow().close()):this.findWindow().list_panel.selectModule(this.getDirtyPanel())},this):this.findWindow().close()},getApiArray:function(t,e){var i=[];return this.items.each(function(n,a,o){n instanceof SYNO.SDS.Utils.FormPanel&&(!e||n.getForm().isDirty()||n.isDirty&&n.isDirty())&&(i=i.concat(n.getApiArray(t)))},this),SYNO.ux.Utils.uniqueApiArray(i)},getAllForms:function(){var t=[];return this.items.each(function(e,i,n){if(e.getForm){var a=e.getForm();t.push(a)}},this),t},loadAllForm:function(t){var e;if(!1===this.onBeforeRequest("get"))return!1;e=this.getApiArray("get"),e=this.processParams("get",e),this.sendAjaxRequest("get",e)},setActiveByForm:function(t,e){this.items.each(function(e,i,n){if(e.getForm&&e.getForm()===t)return this.findWindow().list_panel.selectModule(e.itemId),!1},this)},applyAllForm:function(t){var e,i=[],n={};return!1!==this.onBeforeRequest("set")&&(this.items.each(function(t,e,a){if(!(t instanceof SYNO.SDS.Utils.FormPanel))return void(Ext.isFunction(t.getExtraActions)&&(i=i.concat(t.getExtraActions())));var o=t.getForm(),s=Ext.isDefined(t.isDirty)&&t.isDirty();if(o.isDirty()||s){var l=o.getValues(!1,"set");Ext.apply(n,l)}},this),e=this.constructApplyParams(n),e=e.concat(i),0===e.length?void this.findWindow().close():(e=e.concat(this.getApiArray("get",!0)),e=this.processParams("set",e),e.push({api:"SYNO.MailClient.Setting.SMTP",method:"list",version:1}),void this.sendAjaxRequest("set",e)))},processParams:function(t,e){return this.items.each(function(i,n,a){if(i instanceof SYNO.SDS.Utils.FormPanel){var o=i.getForm();if("set"===t){var s=Ext.isDefined(i.isDirty)&&i.isDirty();if(!o.isDirty()&&!s)return}e=i.processParams(t,e)}},this),e},clearStatus:function(t){var e=this.getFooterToolbar();e&&Ext.isFunction(e.clearStatus)&&e.clearStatus(t)},resetAllForm:function(){var t=this.getAllForms();Ext.each(t,function(t,e,i){t.reset()},this)},isAnyFormDirty:function(){var t=this.getAllForms(),e=!1;return Ext.each(t,function(t,i,n){if(t.isDirty())return e=!0,!1},this),this.getComponent("tab_mailbox").isDirty()&&(e=!0),this.getComponent("tab_shared_mailbox").isDirty()&&(e=!0),this.theme_panel.isDirty()&&(e=!0),e},getDirtyPanel:function(){var t=this.getAllForms(),e="";return Ext.each(t,function(t,i,n){if(t.isDirty())return e=t.itemId,!1},this),this.getComponent("tab_mailbox").isDirty()&&(e="tab_mailbox"),this.getComponent("tab_shared_mailbox").isDirty()&&(e="tab_shared_mailbox"),this.theme_panel.isDirty()&&(e="tab_theme"),e},getAjaxCfg:function(t){return{}},getCompoundCfg:function(t){return{}},sendAjaxRequest:function(t,e){"get"===t?this.setStatusBusy():this.setStatusBusy({text:_T("common","saving")});var i=this.getAjaxCfg(t),n=this.getCompoundCfg(t),a=Ext.apply({params:{},compound:{stopwhenerror:!1,params:e},scope:this,callback:function(e,i,n){this.clearStatusBusy(),e?this.onApiSuccess(t,i,n):this.onApiFailure(t,i,n)}},i);a.compound=Ext.apply(a.compound,n),this.sendWebAPI(a)},onBeforeRequest:function(t){var e=!1;if(this.items.each(function(i,n,a){if(i instanceof SYNO.SDS.Utils.FormPanel)return i.onBeforeRequest(t)?void 0:(e=!0,!1)},this),e)return!1;if("get"===t)return!0;if(this.checkFormDirty&&!this.isAnyFormDirty()){var i=_T("error","nochange_subject");return this.setStatusError({text:i,clear:!0}),!1}var n=this.getAllForms(),a=!0;return Ext.each(n,function(t,e,i){if(!t.isValid())return a=!1,this.setStatusError({text:_T("common","forminvalid"),clear:!0}),this.setActiveByForm(t,e),!1},this),a},checkNeedRefresh:function(){var t=this.getComponent("tab_general");(t.hasConversationViewChange||t.blLangChanged)&&(SYNO.SDS.UserSettings.save(),SYNO.SDS.UserSettings.onSaveSuccess({callback:function(){this.findAppWindow().getMsgBox().confirm("",SYNO.SDS.MailClient._T("setting","refresh_confirm"),function(t){"yes"===t&&(window.onbeforeunload=null,SYNO.SDS.MailClient.Control.Mail.backToThread(),location.reload(!0))})},scope:this}))},handleSetSuccess:function(t){var e,i=this.getComponent("tab_general"),n=this.getComponent("tab_pgp"),a=this.getComponent("tab_theme"),o=this.getComponent("tab_priority_mailbox"),s=!1,l=!1;for(e=0;e<t.result.length;++e){if(i.webapi.api===t.result[e].api&&i.webapi.methods.get===t.result[e].method&&(t.result[e].data.split_pane_mode!==SYNO.SDS.MailClient.Settings.split_pane_mode&&(2===t.result[e].data.split_pane_mode?SYNO.SDS.MailClient.Control.View.toTwoCol():SYNO.SDS.MailClient.Control.View.toThreeCol()),t.result[e].data.archive_mailbox!==SYNO.SDS.MailClient.Settings.archive_mailbox&&(s=!0),SYNO.SDS.MailClient.UserSettingProperty.setSetting({general:t.result[e].data}),i.hasConversationViewChange&&(t.result[e].data.conversation_view=SYNO.SDS.MailClient.Settings.conversation_view),SYNO.SDS.MailClient.Switch.changeSettings(t.result[e].data),l=!0),o.webapi.api===t.result[e].api&&o.webapi.methods.get===t.result[e].method&&(t.result[e].data.enable_priority_mailbox!==SYNO.SDS.MailClient.Lib.PriorityMailbox.isEnablePriorityMailbox()&&(s=!0),SYNO.SDS.MailClient.Control.Sidebar.setPriorityMailboxSetting(t.result[e].data),SYNO.SDS.MailClient.UserSettingProperty.setPriorityMailboxSetting(t.result[e].data)),(s||"SYNO.MailClient.Mailbox"==t.result[e].api&&"set"==t.result[e].method)&&SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList(),n.webapi.api===t.result[e].api&&n.webapi.methods.get===t.result[e].method&&(SYNO.SDS.MailClient.PGPSettings=t.result[e].data,SYNO.SDS.MailClient.UserSettingProperty.setSetting({pgp:t.result[e].data})),"SYNO.MailClient.Setting.SMTP"==t.result[e].api&&"list"==t.result[e].method&&(SYNO.SDS.MailClient.SMTP=t.result[e].data),a.webapi.api===t.result[e].api&&a.webapi.methods.get===t.result[e].method){var r=SYNO.SDS.MailClient.UserSettingProperty.getSettingInfo().general;SYNO.SDS.MailClient.Settings.theme=t.result[e].data.theme,r.theme=t.result[e].data.theme,SYNO.SDS.MailClient.UserSettingProperty.setSetting({general:r}),SYNO.SDS.MailClient.AppLib.StyleLoader.loadCustomStyle()}"SYNO.MailClient.Setting.Lab"==t.result[e].api&&"get"==t.result[e].method&&(SYNO.SDS.MailClient.MailClientLab=t.result[e].data)}this.checkNeedRefresh(),l&&SYNO.SDS.MailClient.Control.Main.reloadContent()},onApiSuccess:function(t,e,i){var n=this.getComponent("tab_pgp"),a=this.getComponent("tab_lab");if("set"===t)return void(e.has_fail?this.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(e)}):(this.handleSetSuccess(e),this.setStatusOK(),this.findWindow().close()));"get"===t&&e.result.forEach(function(t){n.webapi.api===t.api&&n.webapi.methods.get===t.method&&(SYNO.SDS.MailClient.PGPSettings=t.data),a.webapi.api===t.api&&a.webapi.methods.get===t.method&&(SYNO.SDS.MailClient.MailClientLab=t.data)}),this.fireEvent("configload"),this.processReturnData(t,e,i)},processReturnData:function(t,e,i){this.items.each(function(n,a,o){if(n instanceof SYNO.SDS.Utils.FormPanel){var s=n.getForm();("set"!==t||s.isDirty())&&n.processReturnData(t,e,i)}},this)},onApiFailure:function(t,e,i){"get"===t?this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(e),function(){this.findWindow().close()},this):this.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(e)})},constructApplyParams:function(t){var e,i,n,a,o,s,l={},r=[];for(i in t)if(t.hasOwnProperty(i)){if(e=i.split("|"),4!=e.length)continue;n=i.substr(0,i.lastIndexOf("|")),a=i.substr(i.lastIndexOf("|")+1),o=t[i],l[n]||(l[n]={}),l[n][a]=o}for(n in l)if(l.hasOwnProperty(n)){e=n.split("|"),s={api:e[0],method:e[1],version:e[2]},s.params=SYNO.ux.Utils.getApiParams(s,this.getApiArray("set"));for(a in l[n])l[n].hasOwnProperty(a)&&(s.params[a]=l[n][a]);r.push(s)}return r},clearStatusBusy:function(t){this.clearStatus(t),this.unmaskAppWin()},setStatus:function(t){t=t||{};var e=this.getFooterToolbar();e&&Ext.isFunction(e.setStatus)&&e.setStatus(t)},maskAppWin:function(){var t=this.findWindow();t&&Ext.isDefined(t.maskForBusy)&&t.maskForBusy()},unmaskAppWin:function(){var t=this.findWindow();t&&Ext.isDefined(t.unmask)&&t.unmask()},setStatusBusy:function(t){t=t||{},Ext.applyIf(t,{text:_T("common","loading"),iconCls:"syno-ux-statusbar-loading"}),this.setStatus(t),this.maskAppWin()},setStatusOK:function(t){t=t||{},Ext.applyIf(t,{text:_T("common","setting_applied"),iconCls:"syno-ux-statusbar-success",clear:!0}),this.setStatus(t)},setStatusError:function(t){t=t||{},Ext.applyIf(t,{text:_T("common","error_system"),iconCls:"syno-ux-statusbar-error"}),this.setStatus(t)}}),Ext.define("SYNO.SDS.MailClient.Setting.Window",{extend:"SYNO.SDS.ModalWindow",requires:["SYNO.SDS.MailClient.Setting.Card","SYNO.SDS.MailClient.Setting.List"],activePage:"tab_general",constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this.list_panel.getSelectionModel(),"selectionchange",this.onListSelect,this),this.mon(this.card_panel,"configload",this.onConfigLoad,this)},fillConfig:function(t){var e={cls:"syno-mc-setting-win syno-mc-modal-window",title:_T("common","common_settings"),width:920,height:520,minWidth:600,minHeight:400,layout:"fit",fbar:!1,closable:!0,closeAction:"onCancel",items:[{xtype:"syno_panel",layout:"border",items:[this.list_panel=new SYNO.SDS.MailClient.Setting.List({region:"west",width:220,listeners:{scope:this,afterlayout:{buffer:80,single:!0,fn:function(t,e){t.selectModule(this.activePage),this.card_panel.loadAllForm(),SYNO.SDS.MailClient.WebAPI.getInfoPOP3({}).then(function(t){SYNO.SDS.MailClient.AdminSettings.POP3=t,this.list_panel.setModuleVisible("tab_pop3",t.enable_pop3)}.bind(this)).catch(function(t){}.bind(this))}}}}),this.card_panel=new SYNO.SDS.MailClient.Setting.Card({region:"center"})]}]};return Ext.apply(e,t),e},onListSelect:function(t,e){this.activePage=e.id,this.card_panel.getLayout().setActiveItem(e.id)},onConfigLoad:function(){this.list_panel.setModuleVisible("tab_pgp",!SYNO.SDS.MailClient.PGPSettings.pgp_disabled),this.list_panel.setModuleVisible("tab_lab",SYNO.SDS.MailClient.MailClientLab.enable_lab)},onOpen:function(t){this.callParent(arguments),t&&(this.activePage=t)},onCancel:function(){this.card_panel.cancelHandler()}}),Ext.define("SYNO.SDS.MailClient.POP3AddDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="createPOP3",this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:530};return Ext.apply(e,t)},stringNameValidator:function(t){return t.trim().length>0},fetchDaysValidator:function(t){var e=new Date;return!(t<1)&&!(parseInt(e.getTime()/1e3,10)-24*t*60*60<0)},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define,e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[-1,SYNO.SDS.MailClient._T("pop","custom_pop")],[0,SYNO.SDS.MailClient._T("pop","provider_yahoo")],[1,SYNO.SDS.MailClient._T("pop","provider_gmail")],[2,SYNO.SDS.MailClient._T("pop","provider_outlook")],[3,SYNO.SDS.MailClient._T("pop","provider_qq")]]});return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"mail",name:"mail",width:250,allowBlank:!1,validator:function(t){return SYNO.SDS.MailClient.Format.isAddrSpec(t)||_JSLIBSTR("extlang","emailText")},fieldLabel:SYNO.SDS.MailClient._T("pop","email_address")},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"server_provider",fieldLabel:SYNO.SDS.MailClient._T("pop","service_provider"),mode:"local",store:e,displayField:"display",valueField:"value",value:-1,listeners:{scope:this,select:function(t,e){if(-1<e.data.value){var i=this.serverProviderConfig(e.data.value);this.formPanel.getComponent("host_name").hide().setValue(i.host_name),this.formPanel.getComponent("port").hide().setValue(i.port),this.formPanel.getComponent("enable_ssl").hide().setValue(!0),this.formPanel.getComponent("verify_cert").hide().setValue(!0)}else this.formPanel.getComponent("host_name").show().setValue(""),this.formPanel.getComponent("port").show().setValue(110),this.formPanel.getComponent("enable_ssl").show().setValue(!1),this.formPanel.getComponent("verify_cert").show().setValue(!0)}}},{xtype:"syno_textfield",itemId:"host_name",name:"host_name",validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!1)},width:250,allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_server")},{xtype:"syno_textfield",itemId:"port",name:"port",width:250,allowBlank:!1,value:110,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_port"),vtype:"port"},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",validator:this.stringNameValidator,width:250,allowBlank:!1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",width:250,inputType:"password",fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"enable_ssl",name:"enable_ssl",width:400,boxLabel:SYNO.SDS.MailClient._T("pop","use_secure_connection"),scope:this,handler:function(t,e){if(!e)return this.formPanel.getComponent("verify_cert").disable(),void this.formPanel.getComponent("port").setValue(110);this.formPanel.getComponent("verify_cert").enable(),this.formPanel.getComponent("verify_cert").setValue(!0),this.formPanel.getComponent("port").setValue(995)}},{xtype:"syno_checkbox",itemId:"verify_cert",name:"verify_cert",disabled:!0,indent:1,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","verify_cert"),scope:this},{xtype:"syno_checkbox",itemId:"delete_after_fetch",name:"delete_after_fetch",width:400,boxLabel:SYNO.SDS.MailClient._T("pop","remove_original_copy"),scope:this},{xtype:"syno_compositefield",hideLabel:!0,width:450,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","select_mailbox"),width:180},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:SYNO.SDS.MailClient._T("mailbox","inbox"),value:SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t.inboxId).data.path,width:250,menuCfg:{width:250,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.junkId,t.draftsId,t.trashId,t.starredId]},listeners:{scope:this,change:function(t){var e=function(e,i,n){if(!n)return!1;Ext.getCmp(this.mailboxBtnId).value=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t).data.path};SYNO.SDS.MailClient.Switch.getMailboxStore().load({callback:e,scope:this})}}}]},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","select_fetch_days"),width:360},{xtype:"syno_compositefield",hideLabel:!0,indent:1,width:400,items:[{xtype:"syno_radio",checked:!0,inputValue:"recent",boxLabel:SYNO.SDS.MailClient._T("pop","fetch_recently"),name:"fetchmail_config",width:150,listeners:{scope:this,check:function(t,e){e?Ext.getCmp(this.fetchDaysId).enable():Ext.getCmp(this.fetchDaysId).disable()}}},{xtype:"syno_numberfield",id:this.fetchDaysId=Ext.id(),allowBlank:!1,width:200,value:7,validator:this.fetchDaysValidator},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","fetch_days")}]},{xtype:"syno_radio",itemId:"all_message",inputValue:"all",boxLabel:SYNO.SDS.MailClient._T("pop","fetch_all"),indent:1,name:"fetchmail_config"},{xtype:"syno_radio",itemId:"new_message",inputValue:"new",boxLabel:SYNO.SDS.MailClient._T("pop","fetch_only_new"),indent:1,name:"fetchmail_config"}]}),this.formPanel},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={},i=new Date;return e.mail=t.mail.trim(),e.server_provider=parseInt(t.server_provider,10),e.host_name=t.host_name.trim(),e.port=parseInt(t.port,10),e.user_name=t.user_name.trim(),e.password=t.password?t.password:"",e.enable_ssl="true"===t.enable_ssl,e.verify_cert="true"===t.verify_cert,e.delete_after_fetch="true"===t.delete_after_fetch,e.mailbox_path=Ext.getCmp(this.mailboxBtnId).value,this.getFormPanel().getComponent("new_message").getValue()?e.fetch_begin_date=parseInt(i.getTime()/1e3,10):this.getFormPanel().getComponent("all_message").getValue()?e.fetch_begin_date=-1:e.fetch_begin_date=parseInt(i.getTime()/1e3,10)-24*Ext.getCmp(this.fetchDaysId).getValue()*60*60,!!(e.mail&&e.host_name&&Ext.isNumber(e.port)&&e.user_name&&e.mailbox_path)&&e},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},serverProviderConfig:function(t){return[{host_name:"pop.mail.yahoo.com",port:995},{host_name:"pop.gmail.com",port:995},{host_name:"pop-mail.outlook.com",port:995},{host_name:"pop.qq.com",port:995}][t]}}),Ext.define("SYNO.SDS.MailClient.POP3EditDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setPOP3";var e=t.targetInfo;if(!e)throw"no target";this.info_id=e.id,this.is_localhost=0===this.info_id,this.mail=e.mail,this.server_provider=e.server_provider,this.host_name=e.host_name,this.port=e.port,this.user_name=e.user_name,this.password=Ext.isEmpty(this.user_name)?void 0:"\t\t\t\t\t\t\t\t",this.enable_ssl=e.enable_ssl,this.verify_cert=e.verify_cert,this.delete_after_fetch=e.delete_after_fetch,this.mailbox_path=e.mailbox_path,delete t.targetInfo,this.callParent([this.fillConfig(t)]),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:400};return Ext.apply(e,t)},stringNameValidator:function(t){return t.trim().length>0},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define,e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[-1,SYNO.SDS.MailClient._T("pop","custom_pop")],[0,SYNO.SDS.MailClient._T("pop","provider_yahoo")],[1,SYNO.SDS.MailClient._T("pop","provider_gmail")],[2,SYNO.SDS.MailClient._T("pop","provider_outlook")],[3,SYNO.SDS.MailClient._T("pop","provider_qq")]]});return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"mail",name:"mail",width:250,value:this.mail,allowBlank:!1,validator:function(t){return SYNO.SDS.MailClient.Format.isAddrSpec(t)||_JSLIBSTR("extlang","emailText")},fieldLabel:SYNO.SDS.MailClient._T("pop","email_address")},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"server_provider",fieldLabel:SYNO.SDS.MailClient._T("pop","service_provider"),mode:"local",store:e,displayField:"display",valueField:"value",value:this.server_provider,listeners:{scope:this,select:function(t,e){if(-1<e.data.value){var i=this.serverProviderConfig(e.data.value);this.formPanel.getComponent("host_name").hide().setValue(i.host_name),this.formPanel.getComponent("port").hide().setValue(i.port),this.formPanel.getComponent("enable_ssl").hide().setValue(!0),this.formPanel.getComponent("verify_cert").hide().setValue(!0)}else this.formPanel.getComponent("host_name").show().setValue(""),this.formPanel.getComponent("port").show().setValue(110),this.formPanel.getComponent("enable_ssl").show().setValue(!1),this.formPanel.getComponent("verify_cert").show().setValue(!1)},afterrender:function(t){-1<t.value&&(this.formPanel.getComponent("host_name").hide(),this.formPanel.getComponent("port").hide(),this.formPanel.getComponent("enable_ssl").hide(),this.formPanel.getComponent("verify_cert").hide())}}},{xtype:"syno_textfield",itemId:"host_name",name:"host_name",width:250,value:this.host_name,validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!1)},allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_server")},{xtype:"syno_textfield",itemId:"port",name:"port",value:this.port,width:250,allowBlank:!1,fieldLabel:SYNO.SDS.MailClient._T("pop","pop_port"),vtype:"port"},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",value:this.user_name,validator:this.stringNameValidator,width:250,allowBlank:!1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",value:this.password,width:250,inputType:"password",fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"enable_ssl",name:"enable_ssl",checked:this.enable_ssl,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","use_secure_connection"),scope:this,handler:function(t,e){if(!e)return this.formPanel.getComponent("verify_cert").disable(),void this.formPanel.getComponent("port").setValue(110);this.formPanel.getComponent("verify_cert").enable(),this.formPanel.getComponent("port").setValue(995)}},{xtype:"syno_checkbox",itemId:"verify_cert",name:"verify_cert",disabled:!this.enable_ssl,indent:1,checked:this.verify_cert,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","verify_cert"),scope:this},{xtype:"syno_checkbox",itemId:"delete_after_fetch",name:"delete_after_fetch",checked:this.delete_after_fetch,width:400,boxLabel:SYNO.SDS.MailClient._T("pop","remove_original_copy"),scope:this},{xtype:"syno_compositefield",hideLabel:!0,width:450,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("pop","select_mailbox"),width:180},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:Ext.util.Format.htmlEncode(t.isSystemMailboxName(this.mailbox_path)?t.getSystemMailboxNameString(this.mailbox_path):this.mailbox_path.split(".")[this.mailbox_path.split(".").length-1]),value:this.mailbox_path,width:250,menuCfg:{width:250,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.junkId,t.draftsId,t.trashId,t.starredId]},listeners:{scope:this,change:function(t){var e=function(e,i,n){if(!n)return!1;Ext.getCmp(this.mailboxBtnId).value=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t).data.path};SYNO.SDS.MailClient.Switch.getMailboxStore().load({callback:e,scope:this})}}}]}]}),this.formPanel},getParams:function(){var t,e=this.getFormPanel().getForm().getValues(),i={};return i.id=this.info_id,e.mail&&(t=e.mail.trim())&&t!=this.mail&&(i.mail=t),e.server_provider&&parseInt(e.server_provider,10)!=this.server_provider&&(i.server_provider=parseInt(e.server_provider,10)),e.host_name&&(t=e.host_name.trim())&&t!=this.host_name&&(i.host_name=t),e.port&&parseInt(e.port,10)!=this.port&&(i.port=parseInt(e.port,10)),e.user_name&&(t=e.user_name.trim())&&t!=this.user_name&&(i.user_name=t),e.password&&(t=e.password.trim())&&t!=this.password&&(i.password=t),e.enable_ssl&&(t="true"==e.enable_ssl)!=this.enable_ssl&&(i.enable_ssl=t),e.verify_cert&&(t="true"==e.verify_cert)!=this.verify_cert&&(i.verify_cert=t),e.delete_after_fetch&&(t="true"==e.delete_after_fetch)!=this.delete_after_fetch&&(i.delete_after_fetch=t),Ext.getCmp(this.mailboxBtnId).value&&Ext.getCmp(this.mailboxBtnId).value!=this.mailbox_path&&(i.mailbox_path=Ext.getCmp(this.mailboxBtnId).value),i},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()},serverProviderConfig:function(t){return[{host_name:"pop.mail.yahoo.com",port:995},{host_name:"pop.gmail.com",port:995},{host_name:"pop-mail.outlook.com",port:995},{host_name:"pop.qq.com",port:995}][t]}}),Ext.define("SYNO.SDS.MailClient.SectionEditDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",constructor:function(t){this.record=t.record,this.callParent([this.fillConfig(t)]),this.on("show",this.loadInfo,this)},fillConfig:function(t){var e={title:_T("common","alt_edit"),layout:"fit",width:540,height:365,cls:"syno-mc-section-edit-win",items:[this.getFormPanel()],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,disabled:_S("demo_mode"),
tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):"",handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})};return Ext.apply(e,t)},getFormPanel:function(){var t=SYNO.SDS.MailClient.Define,e=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("priority_mailbox","all")],[1,SYNO.SDS.MailClient._T("thread","unread")]]}),i=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[5,5],[10,10],[25,25],[50,50]]});return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({trackResetOnLoad:!0,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("priority_mailbox","section")+":"},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_radio",width:180,inputValue:1,boxLabel:SYNO.SDS.MailClient._T("common","mailbox"),indent:1,name:"type",checked:2!==this.record.get("type"),scope:this,handler:function(t,e){Ext.getCmp(this.mailboxBtnId).setDisabled(!e),Ext.getCmp(this.labelBtnId).setDisabled(e)}},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:SYNO.SDS.MailClient._T("filter","select_mailbox"),width:280,disabled:!0,menuCfg:{width:280,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,hideMailbox:[t.draftsId,t.sentId,t.trashId,t.junkId]},listeners:{scope:this,change:function(t){}}}]},{xtype:"syno_compositefield",hideLabel:!0,ctCls:"high-field",items:[{xtype:"syno_radio",width:180,inputValue:2,boxLabel:SYNO.SDS.MailClient._T("common","label"),indent:1,name:"type",checked:2==this.record.get("type"),scope:this,handler:function(t,e){Ext.getCmp(this.mailboxBtnId).setDisabled(e),Ext.getCmp(this.labelBtnId).setDisabled(!e)}},{xtype:"syno_mc_label_button",id:this.labelBtnId=Ext.id(),fieldLabel:SYNO.SDS.MailClient._T("common","label"),text:SYNO.SDS.MailClient._T("filter","select_label"),disabled:!0,width:280,menuCfg:{width:280,rootVisible:!1},listeners:{scope:this,change:function(t){}}}]},{xtype:"syno_combobox",cls:"syno-mc-combobox",ctCls:"high-field",listClass:"syno-ux-combobox-list syno-mc-combobox-list",width:280,name:"status",fieldLabel:SYNO.SDS.MailClient._T("priority_mailbox","display_status"),mode:"local",store:e,displayField:"display",valueField:"value",value:this.record.get("status")},{xtype:"syno_combobox",cls:"syno-mc-combobox",ctCls:"high-field",listClass:"syno-ux-combobox-list syno-mc-combobox-list",width:280,name:"page_size",fieldLabel:SYNO.SDS.MailClient._T("priority_mailbox","show_up_to"),mode:"local",store:i,displayField:"display",valueField:"value",value:this.record.get("page_size")},{xtype:"syno_checkbox",name:"hide_when_empty",boxLabel:SYNO.SDS.MailClient._T("priority_mailbox","hide_when_empty"),checked:this.record.get("hide_when_empty")}]}),this.formPanel},loadInfo:function(){var t=this.record.get("type");if(2==t){Ext.getCmp(this.mailboxBtnId).setDisabled(!0),Ext.getCmp(this.labelBtnId).setDisabled(!1);var e=SYNO.SDS.MailClient.Switch.getLabelStore().getById(this.record.get("type_id"));e&&Ext.getCmp(this.labelBtnId).setValue(e.get("id"),e.get("name"))}else if(Ext.getCmp(this.mailboxBtnId).setDisabled(!1),Ext.getCmp(this.labelBtnId).setDisabled(!0),1==t){var i=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(this.record.get("type_id"));i&&Ext.getCmp(this.mailboxBtnId).setValue(i.get("id"),SYNO.SDS.MailClient.Format.getMailboxText(i.data))}else 3==t&&Ext.getCmp(this.mailboxBtnId).setValue("starred",SYNO.SDS.MailClient._T("mailbox","starred"))},isDirty:function(){return this.getFormPanel().getForm().isDirty()},onApply:function(){var t=this.getFormPanel().getForm().getValues(),e=parseInt(t.type,10);if(1==e){if(!Ext.getCmp(this.mailboxBtnId).isValid())return!1}else if(!Ext.getCmp(this.labelBtnId).isValid())return!1;if(this.record.set("type",e),this.record.set("status",parseInt(t.status,10)),this.record.set("page_size",parseInt(t.page_size,10)),this.record.set("hide_when_empty","true"==t.hide_when_empty),1==this.record.get("type")){var i=Ext.getCmp(this.mailboxBtnId).getMailboxId();"starred"==i?(this.record.set("type_id",0),this.record.set("type",3)):this.record.set("type_id",i)}else 2==this.record.get("type")&&this.record.set("type_id",Ext.getCmp(this.labelBtnId).getLabelId());this.fireEvent("apply"),this.close()},onCancel:function(){if(!this.isDirty())return void this.close();var t=function(t){"yes"===t&&this.close()};this.owner.getMsgBox().confirm(this.title,_T("common","confirm_lostchange"),t,this)}}),Ext.define("SYNO.SDS.MailClient.SMTPAddDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"add",constructor:function(t){this.apiType="createSMTP",this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",this.onBindCheckbox,this,{single:!0}),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:435};return Ext.apply(e,t)},stringNameValidator:function(t){return t.trim().length>0},emailValidator:function(t){return this.stringNameValidator(t)&&SYNO.SDS.MailClient.Format.isAddrSpec(t)},isLocalhost:function(){var t=this.formPanel.getComponent("host_name").getValue();return t.trim().startsWith("127.")||"LOCALHOST"===t.trim().toUpperCase()},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"host_name",name:"host_name",validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!0)},width:250,allowBlank:!1,fieldLabel:_T("notification","alert_smtp")},{xtype:"syno_textfield",itemId:"port",name:"port",width:250,allowBlank:!1,value:25,fieldLabel:_T("notification","alert_port"),vtype:"port"},{xtype:"syno_checkbox",itemId:"enable_auth_checkbox",name:"auth",boxLabel:_T("notification","alert_smtp_need_auth")},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",validator:this.stringNameValidator,width:250,allowBlank:!1,indent:1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",width:250,inputType:"password",indent:1,fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"tls",name:"tls",width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_tls"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("ssl").setValue(!1),this.formPanel.getComponent("port").setValue(587)}},{xtype:"syno_checkbox",itemId:"ssl",name:"ssl",width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_ssl"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("tls").setValue(!1),this.formPanel.getComponent("port").setValue(465)}},{xtype:"syno_textfield",itemId:"mail",name:"mail",width:250,allowBlank:!1,validator:this.emailValidator.bind(this),fieldLabel:_T("notification","label_smtp_sender_mail")},{xtype:"syno_textfield",itemId:"display_name",name:"display_name",validator:this.stringNameValidator,width:250,fieldLabel:_T("notification","label_smtp_sender_name")}]}),this.formPanel},onBindCheckbox:function(){new SYNO.ux.Utils.EnableCheckGroup(this.getFormPanel().getForm(),"auth",["user_name","password"])},getParams:function(){var t=this.getFormPanel().getForm().getValues(),e={},i=0;return"true"===t.tls?i=1:"true"===t.ssl&&(i=2),e.display_name=t.display_name.trim(),e.mail=t.mail.trim(),e.host_name=t.host_name.trim(),e.port=parseInt(t.port,10),"true"===t.auth&&(e.user_name=t.user_name.trim(),e.password=t.password?t.password:""),e.connection_type=i,!!(e.display_name&&e.mail&&e.host_name&&Ext.isNumber(e.port))&&e},onApply:function(){if(this.isLocalhost()&&!1===this.formPanel.getComponent("enable_auth_checkbox").getValue())return void this.setStatusError({text:SYNO.SDS.MailClient._T("error","auth_is_required")});this.clearStatus(),this.callParent(arguments)},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.SMTPEditDialog",{extend:"SYNO.SDS.MailClient.AddEditWindow",mode:"edit",constructor:function(t){this.apiType="setSMTP";var e=t.targetInfo;if(!e)throw"no target";this.info_id=e.id,this.is_localhost=this.info_id<0,this.display_name=e.display_name,this.mail=e.mail,this.host_name=e.host_name,this.port=e.port,this.user_name=e.user_name,this.password=Ext.isEmpty(this.user_name)?void 0:"\t\t\t\t\t\t\t\t",this.connection_type=e.connection_type,delete t.targetInfo,this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",this.onBindCheckbox,this,{single:!0}),this.addEvents("apply")},fillConfig:function(t){var e={layout:"fit",height:435};return Ext.apply(e,t)},isLocalhost:function(){var t=this.formPanel.getComponent("host_name").getValue();return t.trim().startsWith("127.")||"LOCALHOST"===t.trim().toUpperCase()},stringNameValidator:function(t){return t.trim().length>0},emailValidator:function(t){return this.stringNameValidator(t)&&SYNO.SDS.MailClient.Format.isAddrSpec(t)},getFormPanel:function(){return this.formPanel=this.formPanel||new SYNO.ux.FormPanel({cls:"syno-mc-smtp-add-edit-form",border:!1,defaults:{width:250},items:[{xtype:"syno_textfield",itemId:"host_name",name:"host_name",width:250,value:this.host_name,disabled:this.is_localhost,validator:function(t){return SYNO.SDS.MailClient.Format.isValidIpOrHostname(t,!0)},allowBlank:!1,fieldLabel:_T("notification","alert_smtp")},{xtype:"syno_textfield",itemId:"port",name:"port",value:String(this.port),disabled:this.is_localhost,width:250,allowBlank:!1,fieldLabel:_T("notification","alert_port"),vtype:"port"},{xtype:"syno_checkbox",itemId:"enable_auth_checkbox",name:"auth",checked:!Ext.isEmpty(this.user_name),disabled:this.is_localhost,boxLabel:_T("notification","alert_smtp_need_auth")},{xtype:"syno_textfield",itemId:"user_name",name:"user_name",value:this.user_name,disabled:this.is_localhost,validator:this.stringNameValidator,width:250,allowBlank:!1,indent:1,fieldLabel:_T("notification","alert_smtp_user")},{xtype:"syno_textfield",itemId:"password",name:"password",value:this.password,disabled:this.is_localhost,width:250,inputType:"password",indent:1,fieldLabel:_T("notification","alert_smtp_pass")},{xtype:"syno_checkbox",itemId:"tls",name:"tls",checked:1===this.connection_type,disabled:this.is_localhost,width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_tls"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("ssl").setValue(!1),this.formPanel.getComponent("port").setValue(587)}},{xtype:"syno_checkbox",itemId:"ssl",name:"ssl",checked:2===this.connection_type,disabled:this.is_localhost,width:300,boxLabel:SYNO.SDS.MailClient._T("smtp","use_ssl"),scope:this,handler:function(t,e){if(!e)return void this.formPanel.getComponent("port").setValue(25);this.formPanel.getComponent("tls").setValue(!1),this.formPanel.getComponent("port").setValue(465)}},{xtype:"syno_textfield",itemId:"mail",name:"mail",value:this.mail,disabled:this.is_localhost,validator:this.emailValidator.bind(this),width:250,allowBlank:!1,fieldLabel:_T("notification","label_smtp_sender_mail")},{xtype:"syno_textfield",itemId:"display_name",name:"display_name",disabled:this.is_localhost&&SYNO.SDS.MailClient.AdminSettings.SMTP.disable_smtp_sender_name,value:this.display_name,validator:this.stringNameValidator,width:250,fieldLabel:_T("notification","label_smtp_sender_name")}]}),this.formPanel},onBindCheckbox:function(){if(!this.is_localhost){new SYNO.ux.Utils.EnableCheckGroup(this.getFormPanel().getForm(),"auth",["user_name","password"])}},getParams:function(){var t,e=this.getFormPanel().getForm().getValues(),i={},n=0;return"true"===e.tls?n=1:"true"===e.ssl&&(n=2),i.id=this.info_id,e.display_name&&(t=e.display_name.trim())&&t!=this.display_name&&(i.display_name=t),e.mail&&(t=e.mail.trim())&&t!=this.mail&&(i.mail=t),e.host_name&&(t=e.host_name.trim())&&t!=this.host_name&&(i.host_name=t),e.port&&parseInt(e.port,10)!=this.port&&(i.port=parseInt(e.port,10)),"true"===e.auth?(e.user_name&&(t=e.user_name.trim())&&t!=this.user_name&&(i.user_name=t),this.password!==e.password&&(i.password=e.password)):Ext.isEmpty(this.user_name)||this.is_localhost||(i.user_name="",i.password=""),n!=this.connection_type&&(i.connection_type=n),i},onApply:function(){if(0<this.info_id&&this.isLocalhost()&&!1===this.formPanel.getComponent("enable_auth_checkbox").getValue())return void this.setStatusError({text:SYNO.SDS.MailClient._T("error","auth_is_required")});this.clearStatus(),this.callParent(arguments)},isDirty:function(){return!!this.formPanel.getForm()&&this.formPanel.getForm().isDirty()}}),Ext.define("SYNO.SDS.MailClient.Setting.AutoReply",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.ReplyDialog"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",function(t,e){new SYNO.SDS.Utils.EnableCheckGroup(this.getForm(),"forward_enable",["forward_addr","keep_copy"]),new SYNO.SDS.Utils.EnableCheckGroup(this.getForm(),"reply_enable",["reply_time","subject","message","reply_begin_time","reply_end_time",this.btnCustomReply])},this,{single:!0})},fillConfig:function(t){var e=SYNO.SDS.MailClient.Format.isDSM6()?"syno_datefield":"syno_datetimefield";this.btnCustomReply=Ext.id();var i={webapi:{api:"SYNO.MailClient.Setting.ForwardReply",methods:{get:"get",set:"set"},version:"1"},items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("auto_reply","desc_auto_reply")},{xtype:"syno_checkbox",htmlEncode:!1,boxLabel:SYNO.SDS.MailClient._T("auto_reply","enable_forward")+String.format('<span class="syno-mc-white-tip" ext:qtip="{0}"></span>',String.format(SYNO.SDS.MailClient._T("setting","redirects_desc"),SYNO.SDS.MailClient.Info.max_redirects)),name:"forward_enable",listeners:{scope:this,check:function(t,e){e&&this.getForm().findField("keep_copy").setValue(!0)}}},{xtype:"syno_textfield",indent:1,width:320,fieldLabel:SYNO.SDS.MailClient._T("filter","forward_to"),name:"forward_addr",maxlength:256,allowBlank:!1,validator:SYNO.SDS.MailClient.Format.IsValidForwardAddress},{xtype:"syno_checkbox",indent:1,boxLabel:SYNO.SDS.MailClient._T("auto_reply","keep_copy"),name:"keep_copy"},{xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("auto_reply","enable_reply"),name:"reply_enable"},{xtype:"syno_compositefield",indent:1,name:"reply_time",items:[{xtype:e,name:"reply_begin_time",fieldLabel:SYNO.SDS.MailClient._T("auto_reply","reply_time"),isAllDay:!0,dateFormat:"m/d/Y",format:"m/d/Y",width:157,emptyText:_T("log","date_from"),listeners:{scope:this,select:function(t,e){this.getForm().findField("reply_end_time").setMinValue(e)}}},{xtype:e,name:"reply_end_time",isAllDay:!0,dateFormat:"m/d/Y",format:"m/d/Y",width:157,emptyText:_T("log","date_to"),listeners:{scope:this,select:function(t,e){this.getForm().findField("reply_begin_time").setMaxValue(e)}}}]},{xtype:"syno_textfield",indent:1,width:320,fieldLabel:SYNO.SDS.MailClient._T("mail","subject"),name:"subject",value:SYNO.SDS.MailClient._T("auto_reply","reply_subject"),maxlength:256,allowBlank:!1},{xtype:"syno_textarea",indent:1,width:320,height:120,fieldLabel:SYNO.SDS.MailClient._T("auto_reply","message"),name:"message",value:String.format(SYNO.SDS.MailClient._T("auto_reply","reply_msg"),"\r\n\r\n"),allowBlank:!1},{height:10,border:!1},{xtype:"syno_button",id:this.btnCustomReply,indent:1,text:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply"),handler:function(){new SYNO.SDS.MailClient.ReplyDialog({owner:this.findWindow()}).show()},scope:this}]};return Ext.apply(i,t),i},processReturnData:function(t,e,i){if(e.has_fail)return void this.callParent(arguments);var n;if(Ext.each(e.result,function(t){if(t.api===this.webapi.api)return n=t.data,!1},this),n.reply_begin_time){var a=new Date;a.setTime(1e3*n.reply_begin_time),n.reply_begin_time=a}else n.reply_begin_time="";if(n.reply_end_time){var o=new Date;o.setTime(1e3*n.reply_end_time),n.reply_end_time=o}else n.reply_end_time="";""===n.message&&delete n.message,""===n.subject&&delete n.subject,this.callParent(arguments)},processParams:function(t,e){if("set"!==t)return e;var i;return Ext.each(e,function(t){if(t.api===this.webapi.api&&"set"===t.method)return i=t.params,!1},this),i.reply_begin_time?i.reply_begin_time=Date.parse(i.reply_begin_time)/1e3:delete i.reply_begin_time,i.reply_end_time?i.reply_end_time=Date.parse(i.reply_end_time)/1e3+86399:delete i.reply_end_time,e}}),Ext.define("SYNO.SDS.MailClient.ReplyDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.ReplyPanel"],constructor:function(t){this.panel=new SYNO.SDS.MailClient.ReplyPanel;var e=Ext.apply(t,{title:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply"),height:500,width:650,resizable:!1,layout:"fit",items:this.panel,buttons:[{xtype:"syno_button",btnStyle:"blue",text:_T("common","alt_finish"),handler:this.close,scope:this}]});this.callParent([e]),this.on("show",function(){this.panel.getStore().load()},this)}}),Ext.define("SYNO.SDS.MailClient.ReplyPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.ReplySettingAddDialog","SYNO.SDS.MailClient.ReplySettingEditDialog"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("auto_reply","empty_auto_reply"),this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=function(t,e){var i=Ext.util.Format.htmlEncode(t);return e.attr='ext:qtip="'+Ext.util.Format.htmlEncode(i)+'"',i},i={itemId:"replyPanel",height:400,enableHdMenu:!1,enableColumnMove:!1,autoExpandColumn:"reply_msg_column",loadMask:!0,tbar:this.getTbarCfg(),store:this.getStore(),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=this.getTopToolbar(),i=t.getSelections();1===i.length?e.getComponent("edit").enable():e.getComponent("edit").disable();var n=0<i.length;Ext.each(i,function(t){if(0===t.get("id"))return n=!1,!1},this),n?e.getComponent("delete").enable():e.getComponent("delete").disable()}}}),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),cm:new Ext.grid.ColumnModel({columns:[{id:"reply_sender_column",dataIndex:"sender",width:100,header:SYNO.SDS.MailClient._T("auto_reply","mail_from"),align:"left",renderer:e},{id:"reply_subject_column",dataIndex:"subject",width:300,header:SYNO.SDS.MailClient._T("mail","subject"),align:"left",renderer:e},{id:"reply_msg_column",dataIndex:"message",width:300,header:SYNO.SDS.MailClient._T("auto_reply","message"),align:"left",renderer:e}],defaults:{sortable:!1,menuDisabled:!1}}),listeners:{scope:this,rowdblclick:function(){1===this.getSelectionModel().getSelections().length&&this.onEdit()}}};return Ext.apply(i,t),i},getStore:function(){return this.store=this.store||new SYNO.API.Store({proxy:new SYNO.API.Proxy({api:"SYNO.MailClient.Setting.CustomAutoReply",method:"list",version:1,listeners:{scope:this,beforeload:function(t,e){var i=t.activeRequest.read;if(i)return void Ext.Ajax.abort(i);this.findWindow().setStatusBusy()},load:function(){this.findWindow().clearStatusBusy()}}}),reader:new Ext.data.JsonReader({root:"custom_auto_reply",totalProperty:"total",fields:["sender","subject","message"]})}),this.store},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),scope:this,handler:this.onCreate},{itemId:"edit",text:_T("common","alt_edit"),disabled:!0,scope:this,handler:this.onEdit},{itemId:"delete",text:_T("common","delete"),disabled:!0,scope:this,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),function(t){"yes"===t&&this.onDelete()},this)}}]}},onCreate:function(){new SYNO.SDS.MailClient.ReplySettingAddDialog({title:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply")+" - "+_T("common","add"),height:325,width:650,owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()},onDelete:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e,i,n){t.push(e.get("sender"))},this),0!==t.length)return this.findWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteCustomAutoReply({sender_list:t}).then(function(t){this.findWindow().clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy()}.bind(this))},onEdit:function(){new SYNO.SDS.MailClient.ReplySettingEditDialog({title:SYNO.SDS.MailClient._T("auto_reply","customized_auto_reply")+" - "+_T("common","alt_edit"),height:300,width:650,owner:this.findWindow(),targetInfo:this.getSelectionModel().getSelected().data,listeners:{scope:this,apply:function(){this.store.reload()}}}).open()}}),Ext.define("SYNO.SDS.MailClient.Setting.Filter",{extend:"SYNO.SDS.MailClient.Setting.DDGridPanel",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.FilterAddEditDialog"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("setting","empty_filter"),this.callParent([this.fillConfig(t)]),this.mon(this.getSelectionModel(),"selectionchange",this.onRowSelectionChange,this)},fillConfig:function(t){var e={cls:"syno_mc_setting_filter_panel",autoExpandColumn:"name",enableColumnMove:!1,hideHeaders:!0,enableDragDrop:!0,tbar:this.getTbarCfg(),bbar:{buttonAlign:"left",height:"auto",items:[{xtype:"syno_displayfield",style:{whiteSpace:"pre-wrap"},value:SYNO.SDS.MailClient._T("filter","action_note")}]},store:this.getStore(),sm:new Ext.grid.RowSelectionModel,viewConfig:{ddGroup:"FilterDDGroup"},colModel:new Ext.grid.ColumnModel({columns:[{dataIndex:"name",align:"left",width:100,treeCol:!0,renderer:this.filterRenderer.createDelegate(this)}]}),listeners:{scope:this,afterDrop:this.setFilterOrder,activate:this.onPanelActivate,rowdblclick:this.editFilter}};return Ext.apply(e,t),e},onPanelActivate:function(t){this.store.load()},filterRenderer:function(t,e,i){var n,a,o="<div class='syno-mc-setting-filter {0}'><div>{1} <span>{2}</span></div><div>{3} <span>{4}</span></div></div>";return n=new SYNO.SDS.MailClient.Condition(i.get("condition")).toSyntaxString(),a=this.getDisplayAction(i.get("action")),Ext.isEmpty(a)&&(o="<div class='syno-mc-setting-filter {0}'><div>{1} <span>{2}</span></div><div>{3} <span style='color:red;'>{4}</span></div></div>",a=SYNO.SDS.MailClient._T("filter","can_not_apply")),String.format(o,i.get("enabled")?"":"disabled",SYNO.SDS.MailClient._T("filter","match")+": ",Ext.util.Format.htmlEncode(n),SYNO.SDS.MailClient._T("filter","do_action")+": ",a)},getDisplayAction:function(t){var e,i,n,a,o=[],s=SYNO.SDS.MailClient.Switch.getMailboxStore(),l=SYNO.SDS.MailClient.Switch.getLabelStore(),r=[];for(e=0;e<t.length;e++)i=this.getActionString(t[e].name),a=t[e].value,"set_label"!=t[e].name?("move_to"==t[e].name&&(n=s.getById(t[e].value),a=n?n.get("name"):""),"move_to"!=t[e].name&&"redirect"!=t[e].name||(i+=a?": ("+a+")":""),o.push(i)):(n=l.getById(t[e].value))&&r.push(n.get("name"));return r.length>0&&(i=this.getActionString("set_label")+": ("+r.join(", ")+")",o.push(i)),Ext.util.Format.htmlEncode(o.join(", "))},getActionString:function(t){switch(t){case"archive":return SYNO.SDS.MailClient._T("common","archive");case"set_read":return SYNO.SDS.MailClient._T("filter","mark_as_read");case"set_star":return SYNO.SDS.MailClient._T("filter","mark_as_star");case"set_label":return SYNO.SDS.MailClient._T("filter","apply_label");case"move_to":return SYNO.SDS.MailClient._T("filter","move_to");case"redirect":return SYNO.SDS.MailClient._T("filter","forward_to");case"trash":return _T("common","delete")}return""},onRowSelectionChange:function(t){this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection()),this.getTopToolbar().getComponent("edit").setDisabled(1!==t.getSelections().length),this.getTopToolbar().getComponent("btn_enable").setDisabled(!t.hasSelection());var e=this.getTopToolbar().getComponent("btn_enable").menu.getComponent("enable"),i=this.getTopToolbar().getComponent("btn_enable").menu.getComponent("disable"),n=!1,a=!1;e.enable(),i.enable(),t.getSelections().forEach(function(t){if(t.get("enabled")?n=!0:a=!0,n&&a)return!1},this),n||i.disable(),a||e.disable()},addFilter:function(){new SYNO.SDS.MailClient.FilterAddEditDialog({owner:this.findWindow(),mode:"add",listeners:{scope:this,apply:function(){this.store.reload()}}}).open()},editFilter:function(){new SYNO.SDS.MailClient.FilterAddEditDialog({owner:this.findWindow(),mode:"edit",targetInfo:this.getSelectionModel().getSelected().data,listeners:{scope:this,apply:function(){this.store.reload()}}}).open()},deleteFilter:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length)return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteFilter({id:t}).then(function(t){this.owner.clearStatusBusy(),this.store.reload()}.bind(this)).catch(function(t){this.owner.clearStatusBusy()}.bind(this))},setFilterOrder:function(){var t=[];if(this.getStore().each(function(e){t.push(e.get("id"))},this),0!==t.length)return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.setFilterOrder({id:t}).then(function(t){this.owner.clearStatusBusy(),this.store.reload()}.bind(this)).catch(function(t){this.owner.clearStatusBusy()}.bind(this))},setFilterEnable:function(t){var e=[],i=this.getSelectionModel().getSelections();if(Ext.each(i,function(t){e.push(t.get("id"))},this),0!==e.length)return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.setFilterEnabled({id:e,enabled:t}).then(function(t){this.owner.clearStatusBusy(),this.store.reload()}.bind(this)).catch(function(t){this.owner.clearStatusBusy()}.bind(this))},getStore:function(){return this.store=this.store||new SYNO.API.Store({method:"POST",reader:new Ext.data.JsonReader({root:"filter",totalProperty:"total",fields:["id","condition","action","enabled"]}),load:function(){return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listFilter").then(function(t){this.store.loadData(t)}.bind(this)).catch(function(t){this.owner.clearStatusBusy(),this.owner.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(t),clear:!0})}.bind(this))}.bind(this),listeners:{scope:this,load:function(t,e,i){this.owner.clearStatusBusy()}}}),this.store},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),handler:this.addFilter},{text:_T("common","alt_edit"),handler:this.editFilter,itemId:"edit",disabled:!0},{text:SYNO.SDS.MailClient._T("common","enable"),itemId:"btn_enable",disabled:!0,menu:[{text:SYNO.SDS.MailClient._T("common","enable"),handler:this.setFilterEnable.createDelegate(this,[!0]),itemId:"enable"},{text:SYNO.SDS.MailClient._T("common","disable"),handler:this.setFilterEnable.createDelegate(this,[!1]),itemId:"disable"}]},{text:_T("common","delete"),handler:this.deleteFilter,itemId:"delete",disabled:!0}]}}}),Ext.define("SYNO.SDS.MailClient.Setting.General",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.ComboBox"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("contentchange",this.updateTinyMCEMask,this)},fillConfig:function(t){function e(t){var e=[[0,t]],i=[3,7,14,30].map(function(t){return[t,String.format(SYNO.SDS.MailClient._T("setting","older_than_day"),t)]},this);return e.concat(i)}this.signature={};var i=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[25,25],[50,50],[100,100]]}),n=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("setting","set_immediately")],[1,"1 "+_T("common","time_second")],[3,"3 "+_T("common","time_seconds")],[10,"10 "+_T("common","time_seconds")]]}),a=new Ext.data.SimpleStore({autoDestroy:!0,fields:["id","value","display"],data:[[0,!0,SYNO.SDS.MailClient._T("setting","always_display")],[1,!1,SYNO.SDS.MailClient._T("setting","ask_before")]]}),o=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("thread","one_line_without_preview")],[1,SYNO.SDS.MailClient._T("thread","one_line_with_preview")],[2,SYNO.SDS.MailClient._T("thread","two_line")]]}),s=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("common","comfortable")],[1,SYNO.SDS.MailClient._T("common","cozy")],[2,SYNO.SDS.MailClient._T("common","compact")]]}),l=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:SYNO.SDS.Utils.getSupportedLanguageCodepage().concat([["utf8",SYNO.SDS.MailClient._T("common","unicode")]])}),r=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:[[0,SYNO.SDS.MailClient._T("setting","set_immediately")],[5,"5 "+_T("common","time_seconds")],[10,"10 "+_T("common","time_seconds")],[15,"15 "+_T("common","time_seconds")],[20,"20 "+_T("common","time_seconds")],[30,"30 "+_T("common","time_seconds")]]}),d=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:e(SYNO.SDS.MailClient._T("setting","dont_regular_delete"))}),c=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:e(SYNO.SDS.MailClient._T("setting","dont_regular_delete"))}),h=new Ext.data.SimpleStore({autoDestroy:!0,fields:["value","display"],data:e(SYNO.SDS.MailClient._T("setting","dont_regular_archive"))}),u=new Ext.data.SimpleStore({fields:["value","display"],data:[["def",_TT("SYNO.Application.Service.Instance","common","def_lang")]].concat(SYNO.SDS.Utils.getSupportedLanguage())}),S=this,m=SYNO.SDS.MailClient.Settings;this.prepareTinyMCE();var f={webapi:{api:"SYNO.MailClient.Setting.General",methods:{get:"get",set:"set"},version:"1"},listeners:{scope:this,flexcrollinitdone:function(){this.getContentTarget().dom.fleXdata.fixIEDispBug=Ext.emptyFn,this.addTinyMCE()},upload:function(t){this.onImageUpload(t)},activate:this.resetSignatureFieldSet,deactivate:this.recordSMTPSignature},fieldWidth:240,labelWidth:215,items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","general"),cls:"syno-mc-setting-general-panel",itemId:"general_fieldset",items:[{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"conversations_per_page",fieldLabel:SYNO.SDS.MailClient._T("setting","conversations_per_page"),mode:"local",store:i,displayField:"display",valueField:"value",value:m.conversations_per_page},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"display_external_image",fieldLabel:SYNO.SDS.MailClient._T("setting","external_image_display"),mode:"local",store:a,displayField:"display",valueField:"value",value:m.display_external_image},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","split_pane_mode")+":"},{xtype:"syno_radio",inputValue:2,boxLabel:SYNO.SDS.MailClient._T("common","no_split"),indent:1,name:"split_pane_mode",checked:2==m.split_pane_mode,scope:this,handler:function(t,e){this.setFieldDisabled("previewLayout",!e);var i=t.nextSibling();i&&"previewLayout"==i.itemId&&this.setFieldDisabled("displayDensity",!e||2===i.getValue())}},{xtype:"syno_combobox",itemId:"previewLayout",cls:"syno-mc-combobox",itemCls:"preview-layout-item-cls",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"preview_layout",mode:"local",hideLabel:!0,store:o,displayField:"display",valueField:"value",value:m.preview_layout,listeners:{scope:this,select:function(t,e,i,n){2==e.get("value")?this.setFieldDisabled("displayDensity",!0):this.setFieldDisabled("displayDensity",!1)}}},{xtype:"syno_radio",inputValue:3,indent:1,boxLabel:SYNO.SDS.MailClient._T("common","vertical_split"),name:"split_pane_mode",checked:3==m.split_pane_mode},{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","message_organization")+":"},{xtype:"syno_radio",inputValue:"on",indent:1,boxLabel:SYNO.SDS.MailClient._T("setting","by_conversation"),
name:"conversation_view",checked:m.conversation_view},{xtype:"syno_radio",inputValue:"off",indent:1,boxLabel:SYNO.SDS.MailClient._T("setting","by_message"),name:"conversation_view",checked:!m.conversation_view},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"user_lang",fieldLabel:_TT("SYNO.Application.Service.Instance","common","language"),displayField:"display",valueField:"value",value:this.getUserLang(),store:u},{xtype:"syno_combobox",itemId:"displayDensity",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"display_density",fieldLabel:SYNO.SDS.MailClient._T("setting","display_density"),mode:"local",store:s,displayField:"display",valueField:"value",value:m.display_density},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"mark_as_read_time",fieldLabel:SYNO.SDS.MailClient._T("setting","set_preview_readed"),mode:"local",store:n,displayField:"display",valueField:"value",value:m.mark_as_read_time},{xtype:"syno_combobox",cls:"syno-mc-combobox",listClass:"syno-ux-combobox-list syno-mc-combobox-list",name:"delay_send_time",fieldLabel:SYNO.SDS.MailClient._T("setting","delay_send_time"),mode:"local",store:r,displayField:"display",valueField:"value",value:m.delay_send_time},{xtype:"syno_compositefield",hideLabel:!0,items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","archive_mailbox")+":",width:215},{xtype:"syno_mc_mailbox_button",id:this.mailboxBtnId=Ext.id(),text:Ext.util.Format.htmlEncode(SYNO.SDS.MailClient.Switch.getMailboxStore().getById(m.archive_mailbox).data.name),value:SYNO.SDS.MailClient.Switch.getMailboxStore().getById(m.archive_mailbox).data.path,width:240,menuCfg:{width:240,hideManageBtn:!0,hideInbox:!0,rootVisible:!1,disableSharedToOthers:!0},listeners:{scope:this,change:function(t){this.getForm().findField("archive_mailbox").setValue(t)}}},{xtype:"hidden",name:"archive_mailbox",value:m.archive_mailbox}]},{xtype:"syno_checkbox",name:"enable_smtp_detecting",boxLabel:SYNO.SDS.MailClient._T("setting","enable_smtp_detecting"),checked:m.enable_smtp_detecting},{xtype:"syno_checkbox",name:"enable_shortcut",boxLabel:SYNO.SDS.MailClient._T("setting","enable_shortcut"),checked:m.enable_shortcut},{xtype:"syno_checkbox",name:"enable_floating_button",htmlEncode:!1,boxLabel:SYNO.SDS.MailClient._T("setting","enable_floating_button")+String.format('<span class="syno-mc-white-tip" ext:qtip="{0}"></span>',SYNO.SDS.MailClient._T("setting","floating_button_desc")),checked:m.enable_floating_button},{xtype:"syno_checkbox",name:"disable_show_mailbox",boxLabel:SYNO.SDS.MailClient._T("setting","disable_show_mailbox"),checked:m.disable_show_mailbox},{xtype:"syno_checkbox",name:"enlarge_image_cache_threshold",boxLabel:SYNO.SDS.MailClient._T("setting","enlarge_image_cache_threshold"),checked:m.enlarge_image_cache_threshold},{xtype:"syno_checkbox",name:"enable_upload_external_image",boxLabel:SYNO.SDS.MailClient._T("lab","enable_upload_external_image"),checked:m.enable_upload_external_image}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("common","lang_codepage"),items:[{xtype:"syno_displayfield",value:SYNO.SDS.MailClient._T("setting","download_compress_codepage_desc")},{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("common","lang_codepage"),hiddenName:"codepage",store:l,displayField:"display",valueField:"value",value:m.codepage,triggerAction:"all",editable:!1,mode:"local"}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("common","mailbox"),items:[{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("setting","trash_retaining_day"),hiddenName:"trash_retaining_day",store:d,displayField:"display",valueField:"value",value:m.trash_retaining_day,tpl:'<tpl for="."><div ext:qtip="{display}" class="x-combo-list-item">{display}</div></tpl>',mode:"local"},{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("setting","junk_retaining_day"),hiddenName:"junk_retaining_day",store:c,displayField:"display",valueField:"value",value:m.junk_retaining_day,tpl:'<tpl for="."><div ext:qtip="{display}" class="x-combo-list-item">{display}</div></tpl>',mode:"local"},{xtype:"syno_combobox",fieldLabel:SYNO.SDS.MailClient._T("setting","inbox_archiving_day"),hiddenName:"inbox_archiving_day",store:h,displayField:"display",valueField:"value",value:m.inbox_archiving_day,tpl:'<tpl for="."><div ext:qtip="{display}" class="x-combo-list-item">{display}</div></tpl>',mode:"local"},{xtype:"syno_checkbox",name:"clear_trash_on_logout",boxLabel:SYNO.SDS.MailClient._T("setting","clear_trash_on_logout"),checked:m.clear_trash_on_logout},{xtype:"syno_checkbox",name:"clear_junk_on_logout",boxLabel:SYNO.SDS.MailClient._T("setting","clear_junk_on_logout"),checked:m.clear_junk_on_logout}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","date_parser"),hidden:!SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application"),items:[{xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("setting","disable_date_parser"),name:"disable_date_highlight"}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","signature"),itemId:"signature_fieldset",items:[{xtype:"syno_checkbox",name:"enable_signature",boxLabel:SYNO.SDS.MailClient._T("setting","use_signature"),listeners:{scope:this,check:this.onEnableSignatureCheck}},{xtype:"syno_mc_combobox",name:"smtp_account",itemId:"smtp_account",hideLabel:!0,mode:"local",store:t.smtpStore,displayField:"mail",valueField:"id",disabled:!0,listeners:{scope:this,beforeselect:function(t,e,i){this.recordSMTPSignature();var n=this.signature[e.get("id")]?this.signature[e.get("id")]:e.get("signature");this.signature_tinymce.getEditor().setContent(n),this.readonly_tinymce.getEditor().setContent(n)}},isDirty:function(){return S.recordSMTPSignature(),!SYNO.SDS.MailClient.Tool.isEmptyObject(S.signature)}},{xtype:"container",itemId:"signature"},{xtype:"container",itemId:"signature_readonly",cls:"syno-mc-readonly-tinymce"}]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","default_text_style"),itemId:"font_style_fieldset",items:[{xtype:"hidden",name:"composer_fontname",value:""},{xtype:"hidden",name:"composer_fontsize",value:""},{xtype:"hidden",name:"composer_forecolor",value:""}]}]};return Ext.apply(f,t),f},updateScrollCls:function(){this.getEl()&&this.getEl().dom&&this.callParent(arguments)},prepareTinyMCE:function(){var t="SYNO.SDS.MailClient.Application",e=t+SYNO.SDS.Config.FnMap[t].config.version;this.ddupload=new SYNO.SDS.MailClient.Editor.DDUpload({skip_check_big_size_file:!0,owner:this});var i={plugins:["syno_mc_fontselect","syno_fontsizeselect","syno_mc_textcolor","syno_mc_autoresize"],toolbar:"syno_mc_fontselect syno_fontsizeselect forecolor removeformat",synoPostfix:e,statusbar:!1,menubar:!1,forced_root_block:"div",body_class:"mc-setting",content_css:"webman/3rdparty/MailClient/mc-tinymce.css",min_height:Ext.isModernIE?162:56,autoresize_min_height:Ext.isModernIE?162:56,autoresize_bottom_margin:0,autoresize_on_init:!1,owner:this,module:this},n={automatic_uploads:!1,images_dataimg_filter:Ext.emptyFn,paste_data_images:!0,skip_check_big_size_file:!0,paste_retain_style_properties:"border border-collapse border-spacing border-top border-left border-bottom border-right width vertical-align padding",paste_webkit_styles:"all",syno_word_keep_all_format:!0,plugins:["syno_mc_fontselect","syno_fontsizeselect","textcolor","hr","syno_mc_lists","syno_mc_link","syno_mc_autolink","syno_mc_autoresize","syno_mc_formupload","syno_mc_ddupload","syno_mc_image","syno_mc_pastelink","syno_mc_tab","syno_mc_indent_outdent"],toolbar:["syno_mc_fontselect syno_fontsizeselect forecolor backcolor bold italic underline removeformat | ","alignleft aligncenter alignright alignjustify numlist bullist syno_mc_outdent syno_mc_indent | ","syno_mc_link xxxtable syno_mc_image"].join(),synoPostfix:e,statusbar:!1,menubar:!1,convert_urls:!1,forced_root_block:"div",body_class:"mc-setting",content_css:"webman/3rdparty/MailClient/mc-tinymce.css",min_height:Ext.isModernIE?162:100,syno_mc_ddupload:{instance:this.ddupload},autoresize_min_height:Ext.isModernIE?162:100,autoresize_bottom_margin:12,autoresize_on_init:!1,is_signature:!0,owner:this,module:this};this.tinymce_ready_count=0,this.style_tinymce=new SYNO.ux.TinyMCE({owner:this,width:560,mceConfig:Ext.apply({},{min_height:34,autoresize_min_height:34},i),listeners:{scope:this,initialize:this.onTinyMCEInitialize}}),this.signature_tinymce=new SYNO.ux.TinyMCE({owner:this,width:560,mceConfig:Ext.apply({},n),listeners:{scope:this,initialize:this.onTinyMCEInitialize}}),this.readonly_tinymce=new SYNO.ux.TinyMCE({owner:this,width:560,mceConfig:Ext.apply({},{readonly:!0},n),listeners:{scope:this,initialize:this.onTinyMCEInitialize}})},getSenderUploadLimit:function(){return SYNO.SDS.MailClient.Define.SingleAttachmentSizeLimit},refreshInlineImage:function(){},addTinyMCE:function(){this.getComponent("font_style_fieldset").add(this.style_tinymce);var t=this.getComponent("signature_fieldset");t.getComponent("signature").add(this.signature_tinymce),t.getComponent("signature_readonly").add(this.readonly_tinymce),this.doLayout()},addFile:function(t,e,i){this.ddupload.addFile(t,e,i)},adjSignatureTinyMCESize:function(){this.getEditor().execCommand("mceAutoResize")},getEditor:function(){return this.signature_tinymce.editor},modifyResetStyle:function(t){var e=t.getContainer().querySelectorAll(".mce-btn.mce-last")[0];e&&(Ext.fly(e).addClass("syno-mc-default-text-style-reset"),e.childNodes[0].innerHTML=SYNO.SDS.MailClient._T("setting","default_text_style_reset"))},onEnableSignatureCheck:function(t,e){var i=this.smtpStore.getCount()>0;i||(e=!1),t.setDisabled(!i),this.tinymce_init_done&&(this.getComponent("signature_fieldset").getComponent("signature_readonly").setVisible(!e),this.getComponent("signature_fieldset").getComponent("signature").setVisible(e),this.getComponent("signature_fieldset").getComponent("smtp_account").setDisabled(!e),e?this.signature_tinymce.getEditor().getBody().focus():this.readonly_tinymce.getEditor().setContent(this.signature_tinymce.getEditor().getContent()))},resetSignatureFieldSet:function(){var t,e=this.smtpStore.getCount()>0,i=this.getComponent("signature_fieldset").getComponent("smtp_account");this.tinymce_init_done&&(e?(i.setValue(this.smtpStore.getAt(0).get("id")),t=this.signature[this.smtpStore.getAt(0).get("id")]?this.signature[this.smtpStore.getAt(0).get("id")]:this.smtpStore.getAt(0).get("signature"),this.signature_tinymce.getEditor().setContent(t)):(i.setValue(""),this.signature_tinymce.getEditor().setContent("")),this.onEnableSignatureCheck(this.getForm().findField("enable_signature"),this.getForm().findField("enable_signature").getValue()))},onTinyMCEInitialize:function(t,e){++this.tinymce_ready_count<3||(this.tinymce_init_done=!0,this.initStyleEditor(),this.initSignatureEditor())},initSignatureEditor:function(){var t,e,i=this.smtpStore.getCount()>0;for(t=0;t<this.smtpStore.getCount();++t)e=this.smtpStore.getAt(t),e.get("updated")||(this.signature_tinymce.getEditor().setContent(e.get("signature")),e.data.signature=this.signature_tinymce.getEditor().getContent(),e.data.updated=!0,e.commit());i&&(this.signature_tinymce.getEditor().setContent(this.smtpStore.getAt(0).get("signature")),this.readonly_tinymce.getEditor().setContent(this.smtpStore.getAt(0).get("signature"))),this.ddupload.renderTo(this.signature_tinymce.getEditor().getBody()),this.resetSignatureFieldSet()},onImageUpload:function(t){t.size>1048576&&this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("setting","img_too_large_msg")),this.updateImage(t,this.getEditor())},initStyleEditor:function(){var t=this.style_tinymce.getEditor();t.iframeElement.tabIndex=-1,this.modifyResetStyle(t),t.setContent(SYNO.SDS.MailClient._T("setting","default_text_style_preview_text"));var e=this;t.on("BeforeExecCommand",function(i){if(Ext.isObject(i)){var n,a,o=!0;switch(i.command){case"FontName":n="composer_fontname",a=i.value;break;case"FontSize":n="composer_fontsize",a=i.value;break;case"syno_mc_pre_forecolor":n="composer_forecolor",a=i.value.substr(1,6);break;case"RemoveFormat":e.getForm().findField("composer_fontname").setValue(""),e.getForm().findField("composer_fontsize").setValue(""),e.getForm().findField("composer_forecolor").setValue("");break;default:o=!1}a&&e.getForm().findField(n).setValue(a),o&&t.selection.select(t.getBody(),!0)}}),t.on("ExecCommand",function(i){Ext.isObject(i)&&-1!==["FontName","FontSize","syno_mc_post_forecolor","RemoveFormat"].indexOf(i.command)&&(t.selection.collapse(),e.findWindow().focus())}),this.updateTinyMCEStyle()},updateTinyMCEStyle:function(){if(Ext.isDefined(this.style_tinymce)&&this.style_tinymce.getEditor()&&this.style_tinymce.getEditor().initialized&&this.isReturned){var t,e=this.getForm(),i=this.style_tinymce.getEditor();t=e.findField("composer_fontname").getValue(),t&&i.execCommand("FontName",!1,t),t=e.findField("composer_fontsize").getValue(),t&&i.execCommand("FontSize",!1,t),t=e.findField("composer_forecolor").getValue(),t&&(t="#"+t,i.execCommand("syno_mc_pre_forecolor",!1,t),i.plugins.syno_mc_textcolor.applyFormat("forecolor",t),i.execCommand("syno_mc_post_forecolor",!1,t)),this.findWindow().focus(),this.fleXcrollTo(this.getComponent("general_fieldset").getEl())}},updateTinyMCEMask:function(){if(this.updateScroller(),this.style_tinymce.getEditor()&&this.style_tinymce.getEditor().initialized){var t=this.style_tinymce.getEditor();this.tinymceMask||(this.tinymceMask=Ext.fly(t.contentAreaContainer).createChild({tag:"div",style:"position: absolute; top: 0;"}),t.contentAreaContainer.style.position="relative"),this.tinymceMask.setSize(Ext.fly(t.contentAreaContainer).getSize())}},updateImage:function(t,e){if(t.inline&&!Ext.isEmpty(t.name)&&!Ext.isEmpty(t.ref)&&e){var i=this.findImageDom(t,e);i&&(this.updateImageAttribute(i,t),this.convertImageToDataUri(i))}},findImageDom:function(t,e){var i,n,a,o;for(n=String.format('img[data-ref="{0}"]',t.ref),o=e.getBody().querySelectorAll(n),i=0;i<o.length;++i)if(!o[i].getAttribute("cid")){a=o[i];break}return a},updateImageAttribute:function(t,e){var i={src:Ext.isString(e.source)?this.getDSImageUrl(e.source)+"&"+Math.random():URL.createObjectURL(e)};Ext.fly(t).set(i,!0),t.removeAttribute("data-temp"),t.removeAttribute("data-ref"),t.removeAttribute("data-synomc-uploading-img"),t.removeAttribute("data-mce-src")},convertImageToDataUri:function(t){this.getDataUri(t.src).then(function(e){t.src=e,Ext.fly(t).on("load",this.adjSignatureTinyMCESize.bind(this))}.bind(this)).catch(function(t){})},getDataUri:function(t){return new Promise(function(e,i){var n=new Image;n.crossOrigin="anonymous",n.onload=function(t){var i=document.createElement("canvas"),n=t.target,a=this.getEditor().getBody().clientWidth-20;n.naturalWidth>a?(i.width=a,i.height=n.naturalHeight*(a/n.naturalWidth)):(i.width=n.naturalWidth,i.height=n.naturalHeight),i.getContext("2d").drawImage(n,0,0,i.width,i.height),e(i.toDataURL("image/png"))}.bind(this),n.onerror=function(t){i(t)},n.src=t}.bind(this))},getDSImageUrl:function(t){var e=SYNO.API.currentManager.getBaseURL("SYNO.FileStation.Thumb","get",1);return e=Ext.urlAppend(e,Ext.urlEncode({size:"large",path:t}))},recordSMTPSignature:function(){var t=this.getForm().findField("smtp_account"),e=t.getStore().getById(parseInt(t.getValue(),10));if(this.signature_tinymce&&this.signature_tinymce.getEditor()){var i=this.signature_tinymce.getEditor().getContent();e&&e.get("signature")!==i&&(this.signature[e.get("id")]=i)}},processReturnData:function(t,e,i){var n=this.getForm();"get"==t&&Ext.each(e.result,function(t){if(t.api==this.webapi.api){if(3===t.data.split_pane_mode&&this.setFieldDisabled("previewLayout",!0),3!==t.data.split_pane_mode&&2!==t.data.preview_layout||this.setFieldDisabled("displayDensity",!0),t.data.conversation_view=t.data.conversation_view?"on":"off",t.data.codepage=t.data.codepage||_S("lang"),Ext.isDefined(t.data.archive_mailbox)){var e=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t.data.archive_mailbox);e&&Ext.getCmp(this.mailboxBtnId).setValue(e.get("id"),e.get("name"))}}else"SYNO.MailClient.Setting.SMTP"===t.api&&"getinfo"===t.method&&(SYNO.SDS.MailClient.AdminSettings.SMTP=t.data)},this),i&&Ext.isArray(i.compound)&&(n.loadRecords(e.result,i.compound),this.isReturned=!0,this.updateTinyMCEStyle())},processParams:function(t,e){if("set"!==t)return e.push({api:"SYNO.MailClient.Setting.SMTP",method:"getinfo",version:1}),e;if(this.blLangChanged=!1,this.hasConversationViewChange=!1,Ext.each(e,function(t){if(t.api==this.webapi.api&&"set"==t.method){Ext.isDefined(t.params.conversation_view)&&(t.params.conversation_view="on"==t.params.conversation_view,this.hasConversationViewChange=SYNO.SDS.MailClient.Settings.conversation_view!==t.params.conversation_view),Ext.isDefined(t.params.user_lang)&&(t.params.user_lang!=this.getUserLang()&&(SYNO.SDS.UserSettings.setProperty("Personal","lang",t.params.user_lang),this.blLangChanged=!0),delete t.params.user_lang);var e=Ext.getCmp(this.mailboxBtnId).getMailboxId();0!==e&&"starred"!==e&&(t.params.archive_mailbox=e)}},this),this.recordSMTPSignature(),!0===this.getForm().getValues().enable_signature){var i,n=this.getForm().findField("smtp_account").getStore();for(i in this.signature)this.signature.hasOwnProperty(i)&&n.getById(i)&&e.push({api:"SYNO.MailClient.Setting.SMTP",method:"set",version:"1",params:{id:parseInt(i,10),signature:this.signature[i]}})}return e},setFieldDisabled:function(t,e){var i=this.items.itemAt(0);e?i.getComponent(t).disable():i.getComponent(t).enable()},getUserLang:function(){return Ext.isDefined(SYNO.SDS.UserSettings.data.Personal)&&Ext.isDefined(SYNO.SDS.UserSettings.data.Personal.lang)?SYNO.SDS.UserSettings.data.Personal.lang:"def"}}),Ext.define("SYNO.SDS.MailClient.Setting.Mailbox",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",xtype:"mc_MailboxSettingGridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.Grid.TreeView"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("setting","empty_mailbox"),this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=new SYNO.ux.EnableColumn({header:_T("common","hide"),dataIndex:"hide",width:50,menuDisabled:!0,align:"center",listeners:{scope:this,click:this.onHideColumnClick},scope:this,renderer:function(t,e,i){return i.id===SYNO.SDS.MailClient.Define.inboxId?"":this.renderCheckBox(t,e,i)}}),i={cls:"mailbox-grid",autoExpandColumn:"name",enableColumnMove:!1,tbar:this.getTbarCfg(),store:this.getStore(),view:new SYNO.SDS.MailClient.Grid.TreeView({useArrows:!0,staticTree:!1}),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=SYNO.SDS.MailClient.Define,i=t.getSelections(),n=!0,a=!0,o=!0;Ext.each(i,function(t){if((t.node.attributes.isFakeNode||-1!==[e.draftsId,e.sentId,e.junkId,e.trashId].indexOf(t.id))&&(n=a=o=!1),t.id===SYNO.SDS.MailClient.Settings.archive_mailbox&&(o=a=!1),SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable&&!t.node.attributes.has_permission&&(o=!1),t.id===e.inboxId||t.node.findChild("id",SYNO.SDS.MailClient.Settings.archive_mailbox,!0))return a=!1,!1}),this.getTopToolbar().getComponent("add").setDisabled(!n),this.getTopToolbar().getComponent("delete").setDisabled(!(t.hasSelection()&&a)),this.getTopToolbar().getComponent("edit").setDisabled(1!==i.length||!a),this.getTopToolbar().getComponent("sharing").setDisabled(1!==i.length||!o)}}}),colModel:new Ext.grid.ColumnModel({columns:[{header:SYNO.SDS.MailClient._T("common","mailbox"),dataIndex:"name",align:"left",width:100,treeCol:!0,menuDisabled:!0,renderer:function(t,e,i){return t}},e]}),plugins:[e],listeners:{scope:this,activate:{fn:this.loadMailbox,single:!0}}};return Ext.apply(i,t),i},_hasMailboxSharedToOthers:function(){return this.store.findBy(function(t){return t.node.attributes&&t.node.attributes.has_permission})>-1},loadMailbox:function(){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(t){var e=SYNO.SDS.MailClient.Format.parseMailboxResp(t,null,null,null,!0);this.store.loadData(e),this.getTopToolbar().getComponent("sharing").setVisible(!SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable||this._hasMailboxSharedToOthers())}.bind(this))},getStore:function(){return this.store=this.store||new Ext.data.Store({autoDestroy:!0,method:"GET",idProperty:"id",totalProperty:"total",pruneModifiedRecords:!0,reader:new SYNO.ux.data.TreeReader({root:"",fields:[{name:"name",mapping:"text"},{name:"hide",convert:function(t,e){return!e.attributes.data.subscribed}}]})}),this.store},onHideColumnClick:function(t,e,i,n){var a,o,s=i,l=this.store.getAt(s);if(l.get("hide")){for(a=s+1;a<this.store.getCount();++a)if(o=this.store.getAt(a),o.depth>l.depth)o.set("hide",!0);else if(o.depth<=l.depth)break}else for(a=s-1;a>=0;--a)(o=this.store.getAt(a))&&o.depth<l.depth&&(o.set("hide",!1),l=o)},onChange:function(t,e,i,n,a){this.loadMailbox()},getExtraActions:function(){var t=[];return this.store.getModifiedRecords().forEach(function(e){Ext.isString(e.id)||t.push({api:"SYNO.MailClient.Mailbox",method:"set",params:{id:e.id,subscribed:!e.get("hide")},version:6})},this),t},isDirty:function(){return this.store.getModifiedRecords().length>0},onAddMailbox:function(){var t,e={},i=this.getSelectionModel().getSelections();e.id=1!=i.length?0:i[0].node.attributes.data.id,e.name=1!=i.length?SYNO.SDS.MailClient._T("common","mailbox"):i[0].get("name"),t=new SYNO.SDS.MailClient.AddMailbox({targetInfo:e,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.open()},onEditMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.EditMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onDeleteMailbox:function(){var t=this.getSelectionModel().getSelections(),e=[];this.owner.setStatusBusy({text:_T("common","msg_waiting")}),Ext.each(t,function(t,i,n){e.push(t.node.attributes.data.id)},this),SYNO.SDS.MailClient.Control.Sidebar.deleteMailbox(e).then(function(t){this.owner.clearStatusBusy(),this.loadMailbox()}.bind(this))},onSharingMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.SharingMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onMailboxActionDoneCb:function(t,e,i,n,a){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),handler:this.onAddMailbox,itemId:"add"},{text:_T("common","alt_edit"),handler:this.onEditMailbox,itemId:"edit",disabled:!0},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("mailbox","delete_confirm"),function(t){"yes"===t&&this.onDeleteMailbox()},this)}},{text:SYNO.SDS.MailClient._T("mailbox","sharing_and_permission"),itemId:"sharing",disabled:!0,handler:this.onSharingMailbox}]}}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.Main",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.Setting.Notification.SelectDialog","SYNO.Personal.Notification.SettingFormPanel","SYNO.SDS.MailClient.Grid.TreeView"],constructor:function(t){var e={cls:"syno-mc-setting-notification-panel",items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","general"),items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("setting","enable_extension_desc")},{xtype:"container",cls:"paired-link-container",items:{xtype:"box",cls:"paired-link",autoEl:{tag:"span",html:SYNO.SDS.MailClient._T("setting","enable_extension_link")},listeners:{afterrender:function(t){t.el.on("click",this.onClickPairedLink,this)},scope:this}}},{xtype:"syno_button",text:SYNO.SDS.MailClient._T("setting","select_mailbox_label"),handler:function(){new SYNO.SDS.MailClient.Setting.Notification.SelectDialog({owner:this.findWindow()}).open()},scope:this},this.notifySetting=new SYNO.Personal.Notification.SettingFormPanel({autoFlexcroll:!1,useGradient:!1,desktopHidden:!0,emailHidden:!0,mobileHidden:!0,browserHidden:!0,pkgName:"MailClient"})]},{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("setting","paired_device"),items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("setting","paired_device_desc")},{xtype:"syno_button",text:SYNO.SDS.MailClient._T("setting","device_list"),handler:function(){new SYNO.SDS.MailClient.Setting.Notification.PairDialog({owner:this.findWindow()}).open()},scope:this}]}]};this.callParent([Ext.apply(e,t)])},onClickPairedLink:function(){var t=window.location,e=t.origin+t.pathname;SYNO.Personal.Notification.Utils.enableBrowserPush("MailClient",e).catch(function(t){}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.SelectDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.Setting.Notification.SelectTabPanel"],constructor:function(t){var e={title:SYNO.SDS.MailClient._T("setting","select_mailbox_label"),width:500,height:500,closable:!0,closeAction:"onCancel",items:[this.selectPanel=new SYNO.SDS.MailClient.Setting.Notification.SelectTabPanel({owner:this})],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),listeners:{scope:this,afterrender:function(t,e){this.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listNotification").then(function(t){var e,i;e=t.config.filter(function(t){return"label"!==t.type}),i=t.config.filter(function(t){return"label"===t.type}),this.selectPanel.loadDataIntoStore(e,i)}.bind(this)).then(function(){this.clearStatusBusy()}.bind(this)).catch(function(t){SYNO.Debug.warn(t),this.owner.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("common","error_system")),this.close()}.bind(this))}}};this.callParent([Ext.apply(e,t)])},onApply:function(){var t=this.selectPanel.getModifiedConfigs();if(Ext.isEmpty(t))return void this.close();this.setStatusBusy(),this.sendWebAPI({api:"SYNO.MailClient.Setting.Notification",method:"set",version:1,params:{config:t},scope:this,callback:function(t,e){this.clearStatusBusy(),t?this.close():this.findWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("common","error_system"))}})},onCancel:function(){if(!this.isDirty())return void this.close();var t=function(t){"yes"===t&&this.close()};this.owner.getMsgBox().confirm(this.title,_T("common","confirm_lostchange"),t,this)},isDirty:function(){return 0<this.selectPanel.getModifiedConfigs().length}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.SelectTabPanel",{extend:"SYNO.ux.TabPanel",requires:["SYNO.SDS.MailClient.Setting.Notification.SelectGridPanel"],constructor:function(t){var e={height:400,activeTab:0,items:[new SYNO.SDS.MailClient.Setting.Notification.MailboxSelectGridPanel,new SYNO.SDS.MailClient.Setting.Notification.LabelSelectGridPanel,new SYNO.SDS.MailClient.Setting.Notification.OthersMailboxSelectGridPanel]};this.callParent([Ext.apply(e,t)])},loadDataIntoStore:function(t,e){return Promise.all([this.getItem("tab_mailbox").loadDataIntoStore(t),this.getItem("tab_label").loadDataIntoStore(e),this.getItem("tab_others_mailbox").loadDataIntoStore(t)])},getModifiedConfigs:function(){var t=[];return t=t.concat(this.getItem("tab_mailbox").getModifiedConfigs()),t=t.concat(this.getItem("tab_label").getModifiedConfigs()),t=t.concat(this.getItem("tab_others_mailbox").getModifiedConfigs())}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",constructor:function(t){var e=this,i=function(t){return t.node.attributes.isFakeNode||e.disableFirstLayerEnableColumn&&1===t.depth},n=new SYNO.ux.EnableColumn({header:SYNO.SDS.MailClient._T("setting","recieve_notification"),dataIndex:"select",width:80,menuDisabled:!0,align:"center",isIgnore:function(t,e){return i(e)},renderer:function(t,n,a){return i(a)?"":e.renderCheckBox.call(this,t,n,a)}}),a={cls:"mailbox-grid",type:null,id:null,title:"",colHeader:"",disableFirstLayerEnableColumn:!1,autoExpandColumn:"name",enableColumnMove:!1,store:this.getStore(),view:new SYNO.SDS.MailClient.Grid.TreeView({useArrows:!0,staticTree:!1,hideCollapseNodes:function(){for(var t,e,i,n=this.grid,a=n.store,o=n.view,s=0;s<a.getCount();)t=o.getRow(s),e=a.getAt(t.rowIndex).node,e&&!e.isLeaf()&&!1===e.expanded&&(i=Ext.fly(t).next(".x-tree-node-ct",!1))&&i.setStyle({display:"none"}),e&&e.attributes.isFakeNode&&Ext.fly(t).addClass("fake-node"),s++}}),sm:new Ext.grid.RowSelectionModel({singelSelect:!0}),colModel:new Ext.grid.ColumnModel({columns:[{header:this.colHeader,dataIndex:"name",align:"left",width:100,treeCol:!0,menuDisabled:!0,renderer:function(t,e,i){return t}},n]}),plugins:[n],listeners:{scope:this,viewready:function(){this.view.hideCollapseNodes(),this.view.updateScroller()}}};this.callParent([Ext.apply(a,t)])},createStore:function(){},loadDataIntoStore:function(){},getModifiedConfigs:function(){},fillSelectStatus:function(t,e){Ext.each(t,function(t){var i=e.findIndex(function(e){return e.id===t.id});-1!==i&&(t.select=e[i].enabled)},this)},getStore:function(){return this.store?this.store:(this.store=this.createStore(),this.store)},doCreateStore:function(t){return new Ext.data.Store({autoDestroy:!0,method:"GET",idProperty:"id",totalProperty:"total",pruneModifiedRecords:!0,reader:new SYNO.ux.data.TreeReader({root:"",fields:[{name:"name",mapping:t},{name:"select",convert:function(t,e){return e.attributes.data&&e.attributes.data.select}}]})})}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.MailboxSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",constructor:function(t){var e={type:"mailbox",id:"tab_mailbox",title:SYNO.SDS.MailClient._T("common","mailbox"),colHeader:SYNO.SDS.MailClient._T("common","mailbox")};this.callParent([Ext.apply(e,t)])},createStore:function(){return this.doCreateStore("text")},loadDataIntoStore:function(t){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(e){var i,n,a,o=SYNO.SDS.MailClient.Define,s=[o.draftsId,o.sentId,o.junkId,o.trashId];this.fillSelectStatus(e,t),i=SYNO.SDS.MailClient.Format.parseMailboxResp(e,null,!0,!0,!0).filter(function(t){return-1===s.indexOf(t.id)}),n=i.findIndex(function(t){return"starred"===t.id}),a=t.findIndex(function(t){return"star"===t.type}),-1!==n&&-1!==a&&(i[n].data.select=t[a].enabled),this.store.loadData(i)}.bind(this))},getModifiedConfigs:function(){var t=[];return Ext.each(this.store.getModifiedRecords(),function(e){if("starred"===e.id)return void t.push({enabled:e.data.select,id:0,type:"star"});t.push({enabled:e.data.select,id:e.id,type:"mailbox"})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.OthersMailboxSelectGridPanel",{extend:"SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",constructor:function(t){var e={type:"others_mailbox",id:"tab_others_mailbox",title:SYNO.SDS.MailClient._T("common","shared_mailbox"),colHeader:SYNO.SDS.MailClient._T("common","shared_mailbox"),disableFirstLayerEnableColumn:!0};this.callParent([Ext.apply(e,t)])},createStore:function(){return this.doCreateStore("text")},loadDataIntoStore:function(t){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(e){this.fillSelectStatus(e,t),this.store.loadData(SYNO.SDS.MailClient.Format.parseOthersMailboxResp(e,null,!0,!1,!0))}.bind(this))},getModifiedConfigs:function(){var t=[];return Ext.each(this.store.getModifiedRecords(),function(e){1!==e.depth&&t.push({enabled:e.data.select,id:e.id,type:"mailbox"})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.LabelSelectGridPanel",{
extend:"SYNO.SDS.MailClient.Setting.Notification.BaseSelectGridPanel",constructor:function(t){var e={type:"label",id:"tab_label",title:SYNO.SDS.MailClient._T("common","label"),colHeader:SYNO.SDS.MailClient._T("common","label")};this.callParent([Ext.apply(e,t)])},createStore:function(){return this.doCreateStore("name")},loadDataIntoStore:function(t){return SYNO.SDS.MailClient.Control.Model.getLabelJson().then(function(e){this.fillSelectStatus(e,t),this.store.loadData(SYNO.SDS.MailClient.Control.Model.parseLabelJsonToTreeNode(e,null,!0))}.bind(this))},getModifiedConfigs:function(){var t=[];return Ext.each(this.store.getModifiedRecords(),function(e){t.push({enabled:e.data.select,id:e.id,type:"label"})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.Notification.PairDialog",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.Personal.Notification.PairedInfo"],constructor:function(t){var e={title:SYNO.SDS.MailClient._T("setting","paired_device"),width:500,height:500,layout:"fit",items:[this.pairedGrid=new SYNO.Personal.Notification.PairedInfo({desktopHidden:!0,pkgName:"MailClient",tbar:{xtype:"syno_toolbar",items:[{text:_T("common","refresh"),handler:function(){this.refresh()},scope:this}]}})],buttons:[{text:_T("common","close"),scope:this,handler:this.close}]};this.callParent([Ext.apply(e,t)])},refresh:function(){this.pairedGrid.getBottomToolbar()?this.pairedGrid.getBottomToolbar().doRefresh():this.pairedGrid.loadData()},onShow:function(){this.pairedGrid.fireEvent("show");var t=this.pairedGrid.getBottomToolbar();t&&(t.items.itemAt(2).hide(),t.items.itemAt(3).hide(),t.items.itemAt(4).hide()),this.callParent(arguments)}}),Ext.define("SYNO.SDS.MailClient.Setting.PGP.Main",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.Setting.PGP.KeyMgrDialog"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this,"afterlayout",function(t,e){new SYNO.SDS.Utils.EnableCheckGroup(this.getForm(),"enable_pgp",[this.keyManagementBtnId,"default_enable_encrypt","default_enable_sign"])},this,{single:!0})},fillConfig:function(t){this.keyManagementBtnId=Ext.id();var e={webapi:{api:"SYNO.MailClient.Setting.PGP",methods:{get:"get",set:"set"},version:"1"},items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("pgp","open_pgp"),itemId:"PGP_fieldset",items:[{xtype:"syno_checkbox",name:"enable_pgp",boxLabel:SYNO.SDS.MailClient._T("pgp","enable_pgp")},{xtype:"syno_button",id:this.keyManagementBtnId,indent:1,name:"key_management",text:SYNO.SDS.MailClient._T("pgp","key_management"),style:"margin-bottom: 8px",handler:function(){new SYNO.SDS.MailClient.PGP.KeyMgrDialog({owner:this.findWindow()}).show()},scope:this},{xtype:"syno_checkbox",name:"default_enable_encrypt",indent:1,boxLabel:SYNO.SDS.MailClient._T("pgp","default_enable_encrypt")},{xtype:"syno_checkbox",name:"default_enable_sign",indent:1,boxLabel:SYNO.SDS.MailClient._T("pgp","default_enable_sign")}]}]};return Ext.apply(e,t)}}),Ext.define("SYNO.SDS.MailClient.Setting.POP3",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.POP3AddDialog","SYNO.SDS.MailClient.POP3EditDialog"],constructor:function(t){this.emptyString=SYNO.SDS.MailClient._T("setting","empty_pop3"),this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=SYNO.SDS.MailClient.Define,i={autoExpandColumn:"mail",enableColumnMove:!1,tbar:this.getTbarCfg(),store:this.getStore(),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=this.getTopToolbar(),i=t.getSelections();1===i.length?e.getComponent("edit").enable():e.getComponent("edit").disable();var n=0<i.length;Ext.each(i,function(t){if(0===t.get("id"))return n=!1,!1},this),n?e.getComponent("delete").enable():e.getComponent("delete").disable()}}}),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),colModel:new Ext.grid.ColumnModel({columns:[{header:SYNO.SDS.MailClient._T("pop","email_address"),dataIndex:"mail",align:"left",menuDisabled:!0,width:100},{header:SYNO.SDS.MailClient._T("common","mailbox"),dataIndex:"mailbox_path",align:"left",menuDisabled:!0,width:100,renderer:function(t){var i=e.isSystemMailboxName(t)?e.getSystemMailboxNameString(t):t.split(".")[t.split(".").length-1];return Ext.util.Format.htmlEncode(i)}},{header:SYNO.SDS.MailClient._T("pop","fetch_begin_date_title"),dataIndex:"fetch_begin_date",align:"left",menuDisabled:!0,width:200,renderer:function(t){if(-1===t)return SYNO.SDS.MailClient._T("pop","fetch_all");var e=new Date(1e3*t);return String.format(SYNO.SDS.MailClient._T("pop","fetch_begin_date"),e.format("m/d/Y"))}}]}),listeners:{scope:this,activate:function(){this.store.load()},rowdblclick:function(){1===this.getSelectionModel().getSelections().length&&this.onPOP3Edit()}}};return Ext.apply(i,t),i},getStore:function(){return this.store=this.store||new SYNO.API.Store({method:"POST",reader:new Ext.data.JsonReader({root:"pop3",totalProperty:"total",fields:["id","mail","server_provider","host_name","port","user_name","enable_ssl","verify_cert","delete_after_fetch","mailbox_path","fetch_begin_date"]}),load:function(){return this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("listPOP3").then(function(t){this.store.loadData(t)}.bind(this)).catch(function(t){this.owner.clearStatusBusy(),this.owner.setStatusError({text:SYNO.SDS.MailClient.Error.getErrorString(t),clear:!0})}.bind(this))}.bind(this),listeners:{scope:this,load:function(t,e,i){this.owner.clearStatusBusy()}}}),this.store},onPOP3Edit:function(){new SYNO.SDS.MailClient.POP3EditDialog({targetInfo:this.getSelectionModel().getSelected().data,owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),scope:this,handler:function(){new SYNO.SDS.MailClient.POP3AddDialog({owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()}},{itemId:"edit",text:_T("common","alt_edit"),disabled:!0,scope:this,handler:this.onPOP3Edit},{itemId:"delete",text:_T("common","delete"),disabled:!0,scope:this,handler:function(){var t=[],e=this.getSelectionModel().getSelections();Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length&&(this.owner.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deletePOP3({id:t}).then(function(t){this.owner.clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.owner.clearStatusBusy(),this.owner.setStatusError({text:SYNO.SDS.MailClient._T("api_error","pop_error"),clear:!0})}.bind(this)))}}]}}}),Ext.define("SYNO.SDS.MailClient.Setting.PriorityMailbox",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.SectionEditDialog"],constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={cls:"syno_mc_setting_pm_panel",webapi:{api:"SYNO.MailClient.Setting.PriorityMailbox",methods:{get:"get",set:"set"},version:"1"},items:[{xtype:"syno_fieldset",title:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),itemId:"pm_fieldset",items:[{xtype:"syno_displayfield",hideLabel:!0,value:SYNO.SDS.MailClient._T("priority_mailbox","setting_desc")},{xtype:"syno_checkbox",name:"enable_priority_mailbox",boxLabel:SYNO.SDS.MailClient._T("priority_mailbox","enable_priority_mailbox"),listeners:{scope:this,check:function(t,e){var i=this.getComponent("pm_fieldset").getComponent("section_grid");i&&(e?(i.removeClass("pm-disabled"),i.enable(),i.getView().dragZone.unlock()):(i.addClass("pm-disabled"),i.disable(),i.getView().dragZone.lock()))}}},{xtype:"syno_dd_gridpanel",itemId:"section_grid",autoExpandColumn:"desc",enableColumnMove:!1,hideHeaders:!0,enableDragDrop:!0,cls:"section-grid pm-disabled",width:460,store:this.getStore(),sm:new Ext.grid.RowSelectionModel,viewConfig:{ddGroup:"SectionDDGroup"},colModel:new Ext.grid.ColumnModel({columns:[{dataIndex:"desc",align:"left",width:100,renderer:this.sectionRenderer.createDelegate(this)},{dataIndex:"edit",align:"center",width:50,renderer:function(){return String.format('<a class="edit-link">{0}</a>',_T("common","alt_edit"))}},{dataIndex:"reset",align:"center",width:50,renderer:function(t,e,i){return String.format('<a class="reset-link {0}">{1}</a>',0===i.get("type")?"disabled":"",SYNO.SDS.MailClient._T("setting","default_text_style_reset"))}}]}),listeners:{scope:this,afterrender:function(t){t.getView().dragZone.lock()},cellclick:this.onGridCellClick,rowmousedown:this.onRowMouseDown,afterDrop:this.afterSectionDrop}},{xtype:"hidden",name:"section-hidden",value:""}]}]};return Ext.apply(e,t)},adjustSectionTitleText:function(t,e){var i=!1,n=Ext.DomHelper.createDom({tag:"div",cls:"syno-mc-modal-window",html:'<div class="syno-ux-gridpanel"><div></div></div>'}),a=Ext.fly(n);for(document.body.appendChild(n);170<Ext.util.TextMetrics.measure(a,t+(i?"...: ":": ")+e).width&&!(t.length-3<=0);)t=t.substr(0,t.length-3),i=!0;return document.body.removeChild(n),t+(i?"...":"")},sectionRenderer:function(t,e,i,n,a,o){var s="",l="";if(1==i.get("type")){var r=SYNO.SDS.MailClient.Switch.getMailboxStore(),d=r.getById(i.get("type_id"));d&&(s=SYNO.SDS.MailClient.Format.getMailboxText(d.data))}else if(2==i.get("type")){var c=SYNO.SDS.MailClient.Switch.getLabelStore(),h=c.getById(i.get("type_id"));h&&(s=Ext.util.Format.htmlEncode(h.get("name")))}else 3==i.get("type")&&(s=SYNO.SDS.MailClient._T("mailbox","starred"));return Ext.isEmpty(s)?'<div class="section empty">'+SYNO.SDS.MailClient._T("priority_mailbox","empty_section")+"</div>":(l=0===i.get("status")?SYNO.SDS.MailClient._T("pop","fetch_all"):SYNO.SDS.MailClient._T("thread","unread"),s=this.adjustSectionTitleText(s,l),String.format("<div class='section'>{0}: {1}</div>",s,l))},setSectionDirty:function(){this.getForm().findField("section-hidden").setValue("123456")},editSection:function(t){new SYNO.SDS.MailClient.SectionEditDialog({owner:this.findWindow(),record:this.store.getAt(t),listeners:{scope:this,apply:function(){this.getForm().findField("enable_priority_mailbox").getValue()&&this.getStore().getModifiedRecords().length>0&&this.setSectionDirty()}}}).open()},resetSection:function(t){var e=this.store.getAt(t);e.set("type",0),e.set("status",1),e.set("page_size",10),e.set("hide_when_empty",!1),e.set("type_id",0),this.setSectionDirty()},onGridCellClick:function(t,e,i,n){var a=n.getTarget("a",t.body,!0);a&&this.getForm().findField("enable_priority_mailbox").getValue()&&(a.hasClass("edit-link")?this.editSection(e):a.hasClass("reset-link")&&this.resetSection(e))},onRowMouseDown:function(t,e,i){i.ctrlKey||i.shiftKey||t.getSelectionModel().selectRow(e)},afterSectionDrop:function(){this.setSectionDirty()},onBeforeRequest:function(t){var e=!1;return"set"==t&&(this.getStore().each(function(t){if(0!==t.get("type"))return e=!0,!1},this),this.getForm().findField("enable_priority_mailbox").getValue()&&!e)?(this.owner.setStatusError({text:SYNO.SDS.MailClient._T("priority_mailbox","least_one_section"),clear:!0}),this.owner.setActiveByForm(this.getForm()),!1):this.callParent(arguments)},processReturnData:function(t,e,i){"get"==t&&Ext.each(e.result,function(t){t.api==this.webapi.api&&(this.store.loadData(t.data.section),this.getComponent("pm_fieldset").getComponent("section_grid").setDisabled(!t.data.enable_priority_mailbox))},this),this.callParent(arguments)},processParams:function(t,e){return"set"!==t?e:(Ext.each(e,function(t){if(t.api==this.webapi.api&&"set"==t.method&&(delete t.params["section-hidden"],t.params.enable_priority_mailbox&&this.getStore().getModifiedRecords().length>0)){var e=[];this.getStore().each(function(t){e.push(t.data)},this),t.params.section=e}},this),e)},getStore:function(){return this.store=this.store||new Ext.data.Store({autoDestroy:!0,pruneModifiedRecords:!0,reader:new Ext.data.JsonReader({fields:["type","status","type_id","page_size","hide_when_empty"]})}),this.store}}),Ext.define("SYNO.SDS.MailClient.Setting.SharedMailbox",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",xtype:"mc_OthersMailboxSettingGridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.Grid.TreeView"],enableColumnIdx:2,constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=new SYNO.ux.EnableColumn({header:SYNO.SDS.MailClient._T("common","subscribe"),dataIndex:"subscribed",menuDisabled:!0,align:"center",fixed:!0,listeners:{scope:this,click:this.onSubscribeColumnClick}}),i={cls:"mailbox-grid",tbar:this.getTbarCfg(),region:"center",autoExpandColumn:"name",enableColumnMove:!1,store:this.getStore(),view:new SYNO.SDS.MailClient.Grid.TreeView({useArrows:!0,staticTree:!1,hideCollapseNodes:function(){for(var t,e,i,n=this.grid,a=n.store,o=n.view,s=0;s<a.getCount();)t=o.getRow(s),e=a.getAt(t.rowIndex).node,e&&!e.isLeaf()&&!1===e.expanded&&(i=Ext.fly(t).next(".x-tree-node-ct",!1))&&i.setStyle({display:"none"}),s++}}),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=t.getSelections(),i=!0,n=!0,a=!0,o=!0,s=SYNO.SDS.MailClient.Define;Ext.each(e,function(t){if(s.isUserOrGroupNodeInMailboxList(t))return i=n=a=o=!1,!1;var e=s.getMailboxPermissionById(t.id),l=t.node.attributes.data.name,r=t.node.attributes.has_permission,d=t.get("parent_id");SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable&&!r&&(o=!1),i=i&&s.isMailboxAddable(e,l),n=n&&s.isMailboxDeletable(e,l),a=a&&s.isMailboxEditable(e,d),o=o&&s.isMailboxShareable(e)}),this.getTopToolbar().getComponent("add").setDisabled(1!==e.length||!i),this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection()||!n),this.getTopToolbar().getComponent("edit").setDisabled(1!==e.length||!a),this.getTopToolbar().getComponent("sharing").setDisabled(1!==e.length||!o)}}}),colModel:new Ext.grid.ColumnModel({defaultWidth:150,columns:[{header:SYNO.SDS.MailClient._T("common","mailbox"),dataIndex:"name",align:"left",treeCol:!0,menuDisabled:!0,resizable:!1,renderer:function(t,e,i){return t}},{header:SYNO.SDS.MailClient._T("mailbox","permission"),dataIndex:"my_permission",align:"left",fixed:!0},e]}),plugins:[e],listeners:{scope:this,afterrender:{fn:this.loadMailbox,single:!0},activate:{fn:this.handleMask},viewready:function(){this.view.hideCollapseNodes()}}};return Ext.apply(i,t),i},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),itemId:"add",handler:this.onAddMailbox,disabled:!0},{text:_T("common","alt_edit"),handler:this.onEditMailbox,itemId:"edit",disabled:!0},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:function(){this.findWindow().getMsgBox().confirm(SYNO.SDS.MailClient._T("common","remove_cfrmrmv"),SYNO.SDS.MailClient._T("mailbox","delete_confirm"),function(t){"yes"===t&&this.onDeleteMailbox()},this)}},{text:SYNO.SDS.MailClient._T("mailbox","sharing_and_permission"),itemId:"sharing",disabled:!0,handler:this.onSharingMailbox}]}},onAddMailbox:function(){var t,e={},i=this.getSelectionModel().getSelections();e.id=1!=i.length?0:i[0].node.attributes.data.id,e.name=1!=i.length?SYNO.SDS.MailClient._T("common","mailbox"):i[0].get("name"),t=new SYNO.SDS.MailClient.AddMailbox({targetInfo:e,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.open()},onEditMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.EditShareMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onDeleteMailbox:function(){var t=this.getSelectionModel().getSelections(),e=[];this.owner.setStatusBusy({text:_T("common","msg_waiting")}),Ext.each(t,function(t,i,n){e.push(t.node.attributes.data.id)},this),SYNO.SDS.MailClient.Control.Sidebar.deleteMailbox(e).then(function(t){this.owner.clearStatusBusy(),this.loadMailbox()}.bind(this))},onSharingMailbox:function(){var t,e=this.getSelectionModel().getSelections();1==e.length&&(t=new SYNO.SDS.MailClient.SharingMailbox({targetInfo:e[0].node.attributes.data,owner:this.findWindow(),listeners:{scope:this,apply:this.onMailboxActionDoneCb}}),t.show())},onMailboxActionDoneCb:function(t,e,i,n,a){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},_hasMailboxSharedToOthers:function(){return this.store.findBy(function(t){return t.node.attributes&&t.node.attributes.has_permission})>-1},loadMailbox:function(){return SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(t){var e=SYNO.SDS.MailClient.Format.parseOthersMailboxResp(t,null,null,null,!0),i=[];Ext.each(e,function(t,e,n){if(t.id<0)return!0;i.push(t)},this),this.store.loadData(i),this.checkUserGroupNodeStatus(),this.getTopToolbar().getComponent("sharing").setVisible(!SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable||this._hasMailboxSharedToOthers())}.bind(this))},handleMask:function(){0===this.store.getCount()?this.el.mask(SYNO.SDS.MailClient._T("setting","no_mailbox_share_to_you")):this.el.unmask()},getStore:function(){return this.store=this.store||new Ext.data.Store({autoDestroy:!0,method:"GET",idProperty:"id",totalProperty:"total",pruneModifiedRecords:!0,reader:new SYNO.ux.data.TreeReader({root:"",fields:[{name:"name",mapping:"text"},{name:"subscribed",convert:function(t,e){return!Ext.isString(e.id)&&e.attributes.data.subscribed}},{name:"parent_id",mapping:"parent_id"},{name:"my_permission",mapping:"my_permission",convert:function(t,e){var i=SYNO.SDS.MailClient.Define.MailboxPermission;return t===i.READ_ONLY?_T("nfs","nfs_read_only"):t===i.READ_WRITE?_T("nfs","nfs_read_write"):t===i.ADMIN?SYNO.SDS.MailClient._T("mailbox","admin"):""}}]}),listeners:{scope:this,load:this.handleMask}}),this.store},onSubscribeColumnClick:function(t,e,i,n){var a,o,s=i,l=this.store.getAt(s);if(Ext.isString(l.id)){for(a=s+1;a<this.store.getCount()&&(o=this.store.getAt(a),!(o.depth<=l.depth));++a)o.set("subscribed",l.get("subscribed"));return void this.checkEnableColumnHeaderStatus()}this.checkUserGroupNodeStatus()},checkUserGroupNodeStatus:function(){var t,e,i,n,a,o,s,l;for(i=0;i<this.store.getCount();++i)if(s=0,l=0,t=this.store.getAt(i),Ext.isString(t.id)){for(n=i+1;n<this.store.getCount()&&((e=this.store.getAt(n))&&!(e.depth<=t.depth));++n)!0===e.get("subscribed")?s++:l++;var r=n-i-1;a=r===s,o=r===l,a?t.set("subscribed",!0):o?t.set("subscribed",!1):t.set("subscribed","gray"),t.commit()}this.checkEnableColumnHeaderStatus()},checkEnableColumnHeaderStatus:function(){this.colModel.getColumnAt(this.enableColumnIdx).checkSelectAll(this.getStore())},onChange:function(t,e,i,n,a){this.loadMailbox()},isDirty:function(){return this.store.getModifiedRecords().length>0},getExtraActions:function(){var t=[];return this.store.getModifiedRecords().forEach(function(e){Ext.isString(e.id)||t.push({api:"SYNO.MailClient.Mailbox",method:"set",params:{id:e.id,subscribed:e.get("subscribed")},version:3})},this),t}}),Ext.define("SYNO.SDS.MailClient.Setting.SMTP",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",requires:["SYNO.SDS.MailClient.Setting.GridPanel","SYNO.SDS.MailClient.SMTPAddDialog","SYNO.SDS.MailClient.SMTPEditDialog"],constructor:function(t){this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e={autoExpandColumn:"host_name",enableColumnMove:!1,tbar:this.getTbarCfg(),store:t.smtpStore,sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){var e=this.getTopToolbar(),i=t.getSelections();1===i.length?e.getComponent("edit").enable():e.getComponent("edit").disable(),1===i.length&&i[0].id!=SYNO.SDS.MailClient.SMTP.smtp_default_id?e.getComponent("set_default").enable():e.getComponent("set_default").disable();var n=0<i.length;Ext.each(i,function(t){if(0>t.get("id"))return n=!1,!1},this),n?e.getComponent("delete").enable():e.getComponent("delete").disable()}}}),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),colModel:new Ext.grid.ColumnModel({columns:[{header:_T("notification","label_smtp_sender_mail"),dataIndex:"mail",align:"left",menuDisabled:!0,width:100},{header:SYNO.SDS.MailClient._T("smtp","set_default"),dataIndex:"id",align:"left",menuDisabled:!0,width:100,renderer:function(t,e,i){return t===SYNO.SDS.MailClient.SMTP.smtp_default_id?SYNO.SDS.MailClient._T("smtp","default"):""}}]}),listeners:{scope:this,rowdblclick:function(){1===this.getSelectionModel().getSelections().length&&this.onSMTPEdit()}}};return Ext.apply(e,t),e},onSMTPEdit:function(){new SYNO.SDS.MailClient.SMTPEditDialog({targetInfo:this.getSelectionModel().getSelected().data,owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()},onSMTPSetDefault:function(){if(this.getSelectionModel().hasSelection())return this.findWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.setDefaultSMTP({id:this.getSelectionModel().getSelected().data.id}).then(function(t){this.findWindow().clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy()}.bind(this))},getTbarCfg:function(){return{xtype:"syno_toolbar",defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),scope:this,handler:function(){new SYNO.SDS.MailClient.SMTPAddDialog({owner:this.findWindow(),listeners:{scope:this,apply:function(){this.getStore().load()}}}).open()}},{itemId:"edit",text:_T("common","alt_edit"),disabled:!0,scope:this,handler:this.onSMTPEdit},{itemId:"delete",text:_T("common","delete"),disabled:!0,scope:this,handler:function(){var t=[],e=this.getSelectionModel().getSelections();if(Ext.each(e,function(e){t.push(e.get("id"))},this),0!==t.length)return this.findWindow().setStatusBusy(),SYNO.SDS.MailClient.WebAPI.deleteSMTP({id:t}).then(function(t){this.findWindow().clearStatusBusy(),this.getStore().load()}.bind(this)).catch(function(t){this.findWindow().clearStatusBusy()}.bind(this))}},{itemId:"set_default",text:SYNO.SDS.MailClient._T("smtp","default"),disabled:!0,scope:this,handler:this.onSMTPSetDefault}]}}}),Ext.define("SYNO.SDS.MailClient.ColorField",{extend:"SYNO.ux.ColorField",xtype:"mc_colorfield",constructor:function(t){this.callParent(arguments),this.menu&&(this.menu.shadow=!1)}}),Ext.define("SYNO.SDS.MailClient.ImageDataView",{extend:"SYNO.SDS.Utils.DataView.LazyDataView",constructor:function(t){var e={cls:"view-thumbnails",itemSelector:"div.thumb-wrap",singleSelect:!0,tpl:new Ext.XTemplate('<tpl for=".">','<div class="thumb-wrap">','<div ext:qtip="{filename:qtipHtmlEncode}" class="thumb">','<div class="thumb-hover thumb-loading">','<img src="../scripts/ext-3/resources/images/default/s.gif" url="{preview}">',"</div>","<span>{displayname:htmlEncode}</span>","</div>","</div>","</tpl>",'<div class="x-clear"></div>')};this.imageLoader=new SYNO.SDS.Utils.ImageLoad,this.isRetina=SYNO.SDS.UIFeatures.IconSizeManager.getRetinaAndSynohdpackStatus(),this.callParent([Ext.apply(e,t)])},onUserResize:function(){this.el.dom&&this.callParent(arguments)},onLoadItem:function(t){var e,i=t.select("img");i.elements.length&&(e=i.elements[0])&&(e.src=e.getAttribute("url"),this.imageLoader.loadImg(e,{load:function(t){var e=Ext.fly(t).parent();e&&e.removeClass("thumb-loading")},error:function(t){var e=Ext.fly(t).parent();e&&e.removeClass("thumb-loading"),t.src=this.isRetina?"webman/modules/PhotoViewer/images/2x/no_thumbnail.png":"webman/modules/PhotoViewer/images/1x/no_thumbnail.png"}}))}}),Ext.define("SYNO.SDS.MailClient.BackgroundSelector",{extend:"SYNO.SDS.MailClient.ModalWindow",constructor:function(t){var e={cls:"syno-sds-image-selector",itemId:"backgroundSelector",width:616,height:444,layout:"card",title:SYNO.SDS.MailClient._T("common","select_image"),activeItem:"default_wallpaper",items:[{itemId:"default_wallpaper",xtype:"syno_panel",layout:"fit",border:!1,padding:"0 12px 0 20px",items:this.view=new SYNO.SDS.MailClient.ImageDataView({store:t.wallpaper_defaultstore,listeners:{scope:this,dblclick:this.onApply}})}],buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","choose"),btnStyle:"blue",scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):"",handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel})};this.addEvents("choose"),this.callParent([Ext.apply(e,t)])},onApply:function(){var t=this.view.getSelectedRecords();this.fireEvent("choose",this.view,t[0]),this.close()}}),Ext.define("SYNO.SDS.MailClient.Setting.ThemeForm",{extend:"SYNO.SDS.Utils.FormPanel",requires:["SYNO.SDS.MailClient.ThumbContainer"],themeDefaultSetting:{0:{color:"#ffffff",default_filename:"",image:!1,mask_opacity:20,position:1,theme:0,type:0},1:{color:"#ffffff",default_filename:"01.jpg",image:!0,mask_opacity:20,position:1,theme:1,type:0},2:{color:"#000000",default_filename:"04.jpg",image:!0,mask_opacity:20,position:1,theme:2,type:0}},constructor:function(t){var e={labelWidth:124,labelPad:16,height:440,cls:"syno-mc-theme",title:SYNO.SDS.MailClient._T("setting","theme_setting"),webapi:{api:"SYNO.MailClient.Theme",methods:{get:"getinfo",set:"set"},version:"1"},items:[this.getTplField(),this.getBackgroundField(),{fieldLabel:SYNO.SDS.MailClient._T("common","opacity"),width:168,xtype:"syno_sliderfield",name:"mask_opacity",listeners:{scope:this,valuechange:this.maskOpacityChange,buffer:50}},{xtype:"container",cls:"reset_default",items:{xtype:"box",autoEl:{tag:"span",html:SYNO.SDS.MailClient._T("setting","reset_default")},listeners:{scope:this,afterrender:function(t){t.el.on("click",function(){var t=this.tplDataView.getSelectedRecords()[0];this.resetToDefault(t.get("id"))},this)}}}}],listeners:{scope:this,change:this.onChange}};this.theme_setting={},this.db_theme_setting={},this.addEvents("change","apisuccess"),this.callParent([Ext.apply(e,t)]),this.on("afterrender",function(t){this.form=t.getForm(),this.backgroundImage=Ext.getCmp(this.thumbContainerId).getThumbImageCmp(),this.backgroundAdd=Ext.getCmp(this.thumbContainerId).getAddImageCmp(),this.backgroundPosition=this.form.findField("position"),this.backgroundColor=this.form.findField("color"),this.backgroundImage.el.on("click",this.onBackgroundClick,this),this.backgroundAdd.el.on("click",this.onBackgroundClick,this)},this,{buffer:100})},onChange:function(t,e){var i;if("all"!=t)if("image"===t)SYNO.SDS.MailClient.Window.el.setStyle("background-image",e?"url("+e.url+")":"none");else if("color"===t)"#"!==e[0]&&(e="#"+e),SYNO.SDS.MailClient.Window.el.setStyle("background-color",e);else if("position"===t){var n={};switch(e){case 0:n["background-position"]="50% 50%",n["background-repeat"]="no-repeat",n["background-size"]="auto";break;case 1:n["background-position"]="50% 50%",n["background-repeat"]="no-repeat",n["background-size"]="cover";break;case 2:n["background-position"]="50% 50%",n["background-repeat"]="no-repeat",n["background-size"]="contain";break;case 3:n["background-position"]="0 0",n["background-repeat"]="no-repeat",n["background-size"]="100%";break;case 4:n["background-position"]="0 0",n["background-repeat"]="repeat",n["background-size"]="auto"}SYNO.SDS.MailClient.Window.el.setStyle(n)}else"mask_opacity"===t?(SYNO.SDS.MailClient.Window.bwrap.setStyle("background",e),Ext.fly(SYNO.SDS.MailClient.Window.tl).setStyle("background",e)):"theme"===t&&SYNO.SDS.MailClient.AppLib.StyleLoader.loadThemeStyle(e);else for(i in e)e.hasOwnProperty(i)&&this.onChange(i,e[i])},processReturnData:function(t,e,i){var n=this.getForm();"get"==t&&Ext.each(e.result,function(t){if(t.api==this.webapi.api){var e=this.tplDataView.store.indexOfId(t.data.theme);-1!=e?this.tplDataView.select(e):this.tplDataView.select(0),this.db_theme_setting=Ext.apply({},t.data),t.data.color="#"+t.data.color.toUpperCase(),t.data.image&&t.data.default_filename?(e=this.getDefaultStore().find("filename",t.data.default_filename),-1!=e?this.setBackgroundImage(!0,this.getDefaultStore().getAt(e).get("preview")):this.setBackgroundImage(!1)):t.data.image||this.setBackgroundImage(!1)}},this),i&&Ext.isArray(i.compound)&&n.loadRecords(e.result,i.compound)},processParams:function(t,e){return"set"!==t?e:(Ext.each(e,function(t){t.api==this.webapi.api&&"set"==t.method&&(t.params.color=t.params.color.substr(t.params.color.indexOf("#")+1),Ext.copyTo(t.params,this.theme_setting,"image,type,default_filename,theme"))},this),e)},allIsDefault:function(t){var e=this.themeDefaultSetting[t],i=this.getForm().getValues();return!(i.mask_opacity!==e.mask_opacity||i.color.toLowerCase()!==e.color.toLowerCase()||i.hasOwnProperty("position")&&i.position!==e.position)&&!(Ext.isDefined(this.theme_setting.image)&&this.theme_setting.image!==e.image||Ext.isDefined(this.theme_setting.default_filename)&&this.theme_setting.default_filename!==e.default_filename||Ext.isDefined(this.theme_setting.type)&&this.theme_setting.type!==e.type)},resetToDefault:function(t){Ext.copyTo(this.theme_setting,this.themeDefaultSetting[t],"color,default_filename,image,mask_opacity,position,theme,type");var e,i=null,n=this.getDefaultStore().find("filename",this.theme_setting.default_filename);-1!=n&&(i=this.getDefaultStore().getAt(n).data,e=i.preview),this.setBackgroundImage(this.theme_setting.image,e),this.fireEvent("change","theme",t),this.backgroundPosition.setValue(this.theme_setting.position),this.fireEvent("change","position",this.theme_setting.position),this.backgroundColor.setValue(this.theme_setting.color.toUpperCase()),this.fireEvent("change","color",this.theme_setting.color),this.getForm().findField("mask_opacity").setValue(this.theme_setting.mask_opacity),this.fireEvent("change","mask_opacity",this.formatMaskOpacity(t,this.theme_setting.mask_opacity)),this.fireEvent("change","image",i)},isDirty:function(){var t=this.tplDataView.getSelectedRecords();if(0!==t.length){if(t[0].get("id")!==SYNO.SDS.MailClient.Settings.theme)return!0;var e,i=["type","image","default_filename"];for(e=0;e<i.length;++e)if(this.theme_setting.hasOwnProperty(i[e])&&this.theme_setting[i[e]]!==this.db_theme_setting[i[e]])return!0;return this.getForm().isDirty()}},reset:function(){this.callParent(arguments),this.theme_setting={}},afterRender:function(){this.callParent(arguments),this.loadForm()},applyForm:function(){this.checkFormDirty&&!this.isDirty()||this.callParent(arguments)},getTplField:function(){var t=SYNO.SDS.MailClient._T;return this.tplDataView=this.tplDataView||new Ext.DataView({fieldLabel:t("common","template"),labelWidth:124,overClass:"x-view-over",singleSelect:!0,itemSelector:"div.template-thumb",cls:"theme-tpl-dataview",store:new Ext.data.ArrayStore({autoDestroy:!0,fields:["id","name","string"],idIndex:0,data:[[0,"style",t("setting","standard_style")],[1,"light",t("setting","light_style")],[2,"dark",t("setting","dark_style")]]}),tabIndex:-1,tpl:new Ext.XTemplate('<tpl for=".">','<div class="template-item">','<div class="template-thumb template-{name}"></div>','<div class="template-text">{string}</div>',"</div>","</tpl>",'<div class="x-clear"></div>'),listeners:{scope:this,containerclick:this.onThumbContainerClick,click:this.onThumbClick}}),this.tplDataView},getBackgroundField:function(){var t=SYNO.SDS.MailClient._T,e=new Ext.data.ArrayStore({fields:["id","display"],data:[[0,t("common","center")],[1,t("common","fill")],[2,t("common","fit")],[3,t("common","stretch")],[4,t("common","tile")]]});return{fieldLabel:t("common","background"),layout:"column",border:!1,tabIndex:-1,cls:"syno-mc-image-upload",items:[{xtype:"syno_mc_thumb_container",id:this.thumbContainerId=Ext.id()},{xtype:"container",cls:"option-container",items:[{name:"position",xtype:"syno_combobox",tabIndex:-1,hideLabel:!0,forceSelection:!0,allowBlank:!1,displayField:"display",valueField:"id",width:160,store:e,listeners:{scope:this,select:this.positionSelect}},{name:"color",xtype:"mc_colorfield",tabIndex:-1,width:160,hideLabel:!0,onColorSelect:function(t,e){this.setValue("#"+e),this.fireEvent("colorselect",this,e)},listeners:{
scope:this,colorselect:this.colorSelected,change:this.colorSelected}},{xtype:"syno_button",tabIndex:-1,cls:"thumb-remove-btn",text:t("composer","remove"),handler:this.setBackgroundImage.createDelegate(this,[!1,""])}]}]}},onThumbContainerClick:function(){return!1},onThumbClick:function(t,e,i,n,a){var o=t.store.getAt(e),s=o.get("id"),l=Ext.isDefined(this.theme_setting.theme)?this.theme_setting.theme:this.db_theme_setting.theme;this.allIsDefault(l)?this.resetToDefault(s):(this.theme_setting.theme=s,this.fireEvent("change","theme",s),this.fireEvent("change","mask_opacity",this.formatMaskOpacity(s,Ext.isDefined(this.theme_setting.mask_opacity)?this.theme_setting.mask_opacity:this.db_theme_setting.mask_opacity)))},positionSelect:function(t,e,i){e.data.id!==this.theme_setting.position&&(this.theme_setting.position=e.data.id,this.fireEvent("change","position",e.data.id))},formatMaskOpacity:function(t,e){return 2==t?"rgba(0,0,0,"+e/100+")":"rgba(255,255,255,"+e/100+")"},maskOpacityChange:function(t,e){var i=Ext.isDefined(this.theme_setting.theme)?this.theme_setting.theme:SYNO.SDS.MailClient.Settings.theme;this.theme_setting.mask_opacity=e,this.fireEvent("change","mask_opacity",this.formatMaskOpacity(i,e))},colorSelected:function(t,e){this.fireEvent("change","color",e)},setBackgroundImage:function(t,e,i){!0===t||i?(this.backgroundImage.el.dom.src=e,this.backgroundImage.show(),this.backgroundAdd.hide(),i?(this.backgroundPosition.setDisabled(!0),this.backgroundColor.setDisabled(!0)):(this.backgroundPosition.setDisabled(!1),this.backgroundColor.setDisabled(!1)),this.theme_setting.image=!0):(this.backgroundImage.hide(),this.backgroundAdd.show(),this.backgroundPosition.setDisabled(!0),this.backgroundColor.setDisabled(!1),this.theme_setting.image=!1,this.fireEvent("change","image",null))},onBackgroundClick:function(){new SYNO.SDS.MailClient.BackgroundSelector({owner:this.findWindow(),wallpaper_defaultstore:this.getDefaultStore(),listeners:{scope:this,choose:this.backgroundSelected}}).show()},backgroundSelected:function(t,e){e&&(this.setBackgroundImage(!0,e.get("preview")),this.theme_setting.type=e.data.type,this.theme_setting.default_filename=e.data.filename,this.fireEvent("change","image",e.data))},getDefaultStore:function(){return this.defaultStore=this.defaultStore||new Ext.data.ArrayStore({fields:["type","filename","preview","url","displayname"],data:function(){var t,e,i,n=[],a=["01.jpg","02.jpg","03.jpg","04.jpg","05.jpg","06.jpg","07.jpg","08.png"],o=SYNO.SDS.UIFeatures.IconSizeManager.getRetinaAndSynohdpackStatus(),s=String.format("webman/3rdparty/MailClient/images/{0}x/_Wallpaper",o?2:1);for(t=0;t<8;t++)e=String.format("{0}/thumbnail_{1}.jpg",s,String.leftPad(t+1,2,"0")),i=String.format("{0}/{1}",s,a[t]),n.push([0,a[t],e,i,"Wallpaper "+(t+1)]);return n}()}),this.defaultStore},resetToDBConfig:function(){var t={};Ext.copyTo(t,this.db_theme_setting,"color,type,position,theme,default_filename");var e=null,i=this.getDefaultStore().find("filename",t.default_filename);-1!=i&&(e=this.getDefaultStore().getAt(i).data),this.fireEvent("change","image",e),this.fireEvent("change","mask_opacity",this.formatMaskOpacity(t.theme,this.db_theme_setting.mask_opacity)),this.fireEvent("change","all",t)},resetPreview:function(){this.resetToDBConfig()}}),Ext.define("SYNO.SDS.MailClient.SharingMailbox",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.ModalWindow","SYNO.SDS.MailClient.SharingMailboxGridPanel"],gridRowRemove:!1,constructor:function(t){this.mailboxId=t.targetInfo.id,this.callParent([this.fillConfig(t)]),this.on("show",function(){this.gridPanel.getStore().loadData(t.targetInfo.additional.permission)})},fillConfig:function(t){this.gridPanel=new SYNO.SDS.MailClient.SharingMailboxGridPanel({targetInfo:t.targetInfo,listeners:{scope:this,grid_row_removed:function(){this.gridRowRemove=!0}}});var e=t.targetInfo.name,i=SYNO.SDS.MailClient.Define;i.isSystemMailboxName(e)&&(e=i.getSystemMailboxNameString(e));var n={width:700,height:400,title:e+" - "+SYNO.SDS.MailClient._T("mailbox","sharing_and_permission"),resizable:!1,collapsible:!1,closable:!0,closeAction:"onCancel",layout:"fit",buttons:SYNO.SDS.MailClient.Format.orderButtonsByDSM({text:_T("common","ok"),btnStyle:"blue",scope:this,handler:this.onApply},{text:_T("common","cancel"),scope:this,handler:this.onCancel}),items:[this.gridPanel]};return Ext.apply(n,t)},isEnterFromTextFilter:function(t){var e=t.getTarget("","",!0).dom,i=this.gridPanel.getTopToolbar().getComponent("textFilter").getEl().dom;return e.isSameNode(i)},onApply:function(){if(!this.isEnterFromTextFilter(arguments[1])){if(!this.isGridPanelDirty())return void this.close();if(!this.isPermissionsValid())return void this.setStatusError({text:SYNO.SDS.MailClient._T("sharing","permission_error")});this.setStatusBusy(),SYNO.SDS.MailClient.WebAPI.send("setMailbox",this.getParams()).then(function(){this.clearStatusBusy(),this.fireEvent("apply"),this.close()}.bind(this)).catch(function(t){this.clearStatusBusy(),this.setStatusError({text:t.text?t.text:SYNO.SDS.MailClient.Error.getErrorString(t)}),SYNO.Debug.error(t)}.bind(this))}},onCancel:function(){this.isGridPanelDirty()?this.getMsgBox().confirm("",_T("common","confirm_lostchange"),function(t){"yes"===t&&this.close()},this):this.close()},getParams:function(){var t=[];return this.gridPanel.getStore().each(function(e){var i=this.getApiPermission(e);""!==i&&t.push({name:e.get("name"),is_user:e.get("is_user"),permission:i})},this),{id:this.mailboxId,permission:t}},getApiPermission:function(t){var e=SYNO.SDS.MailClient.Define.MailboxPermission,i="";return t.get("read")?i=e.READ_ONLY:t.get("write")?i=e.READ_WRITE:t.get("admin")&&(i=e.ADMIN),i},isGridPanelDirty:function(){return this.gridRowRemove||!Ext.isEmpty(this.gridPanel.getStore().modified)},isPermissionsValid:function(){var t=!0;return this.gridPanel.getStore().each(function(e){if(""===this.getApiPermission(e))return t=!1,!1},this),t}}),Ext.define("SYNO.SDS.MailClient.SharingMailboxGridPanel",{extend:"SYNO.ux.EditorGridPanel",requires:["SYNO.SDS.MailClient.EnableColumn","SYNO.SDS.MailClient.SelectServersUserWindow"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on("cellclick",this.onCellClick,this),this.on("headerclick",function(t,e,i){var n=t.getColumnModel(),a=n.getColumnId(e);this.onHeaderClick(n.getColumnById(a))},this)},fillConfig:function(t){var e,i,n,a,o=SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable;return e=new SYNO.SDS.MailClient.EnableColumn({header:_T("nfs","nfs_read_only"),dataIndex:"read",itemId:"read",width:50,menuDisabled:!0,align:"center",disabled:o}),i=new SYNO.SDS.MailClient.EnableColumn({header:_T("nfs","nfs_read_write"),dataIndex:"write",itemId:"write",width:50,menuDisabled:!0,align:"center",disabled:o}),n=new SYNO.SDS.MailClient.EnableColumn({header:SYNO.SDS.MailClient._T("mailbox","admin"),dataIndex:"admin",itemId:"admin",width:50,menuDisabled:!0,align:"center",disabled:o}),a={cls:"syno-mc-sharing-mailbox-grid",autoExpandColumn:"name",enableColumnMove:!1,enableHdMenu:!1,clicksToEdit:1,store:this.getStore(),tbar:this.createTbar(),bbar:{hidden:!o,height:"auto",items:[{xtype:"syno_displayfield",cls:"syno-mc-note",html:"<span>"+SYNO.SDS.MailClient._T("common","note")+":</span> "+SYNO.SDS.MailClient._T("mailbox","sharing_disabled_desc")}]},view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1,listeners:{scope:this,rowremoved:function(t,e,i){i.get("name")!=_S("user")&&this.fireEvent("grid_row_removed")}}}),colModel:new Ext.grid.ColumnModel({scope:this,columns:[{header:SYNO.SDS.MailClient._T("mailbox","user_or_group"),dataIndex:"name",align:"left",menuDisabled:!0,width:70,renderer:function(t,e,i,n,a,o){return i.get("is_user")?e.css+=" syno-mc-icon-combo-item-user":e.css+=" syno-mc-combo-item-group",e.attr+='ext:qtip="'+t+'"',t}},e,i,n]}),sm:new Ext.grid.RowSelectionModel({listeners:{scope:this,selectionchange:function(t){this.getTopToolbar().getComponent("delete").setDisabled(!t.hasSelection())}}}),plugins:[e,i,n]},Ext.apply(a,t),a},createTbar:function(){return new SYNO.ux.Toolbar({defaults:{scope:this,disabled:_S("demo_mode"),tooltip:_S("demo_mode")?_JSLIBSTR("uicommon","error_demo"):""},items:[{text:_T("common","add"),hidden:SYNO.SDS.MailClient.AdminSettings.SharedMailbox.disable,handler:this.onAddPermission},{text:_T("common","delete"),itemId:"delete",disabled:!0,handler:this.onDeletePermission},"->",this.getTextFilter(this.getStore())]})},getStore:function(){var t=SYNO.SDS.MailClient.Define.MailboxPermission,e=function(e,i){return i.permission===t.READ_ONLY},i=function(e,i){return i.permission===t.READ_WRITE},n=function(e,i){return i.permission===t.ADMIN};return this.store=this.store||new Ext.data.JsonStore({fields:[{name:"name"},{name:"is_user"},{name:"read",convert:e},{name:"write",convert:i},{name:"admin",convert:n}],listeners:{load:function(t,e,i){SYNO.SDS.MailClient.Format.removeUserFromStore(t,_S("user"))}}}),this.store},getTextFilter:function(t){return this.textFilter=this.textFilter||new SYNO.ux.TextFilter({itemId:"textFilter",store:t,localFilter:!0,localFilterField:["name"]}),this.textFilter},onAddPermission:function(){new SYNO.SDS.MailClient.SelectServersUserWindow({owner:this.findWindow(),targetInfo:this.targetInfo,listeners:{scope:this,selectdone:function(t,e){t.each(function(t){var e=this.store.findExact("name",t.name);-1!==e&&this.store.getAt(e).get("is_user")&&this.store.removeAt(e),this.store.add(new Ext.data.Record({name:t.name,is_user:!0,read:!0}))},this),e.each(function(t){var e=this.store.findExact("name",t.name);-1===e||this.store.getAt(e).get("is_user")||this.store.removeAt(e),this.store.add(new Ext.data.Record({name:t.name,is_user:!1,read:!0}))},this)}}}).open()},onDeletePermission:function(){var t=this.getSelectionModel().getSelections();Ext.each(t,function(t){this.getStore().remove(t)},this)},onHeaderClick:function(t){var e=this.getColumnModel().getColumnAt(1),i=this.getColumnModel().getColumnAt(2),n=this.getColumnModel().getColumnAt(3);t.box_el&&t.box_el.hasClass("syno-ux-cb-checked")&&("read"!==t.dataIndex&&(e.box_el.removeClass("syno-ux-cb-checked"),e.onSelectAll()),"write"!==t.dataIndex&&(i.box_el.removeClass("syno-ux-cb-checked"),i.onSelectAll()),"admin"!==t.dataIndex&&(n.box_el.removeClass("syno-ux-cb-checked"),n.onSelectAll()),t.box_el.addClass("syno-ux-cb-checked"))},onCellClick:function(t,e,i,n){var a=t.getStore().getAt(e),o=t.getColumnModel().getDataIndex(i),s=this.getColumnModel().getColumnAt(1),l=this.getColumnModel().getColumnAt(2),r=this.getColumnModel().getColumnAt(3);!0===a.get(o)&&function(e,i){"read"!==e&&(i.set("read",!1),s.checkSelectAll(t.getStore())),"write"!==e&&(i.set("write",!1),l.checkSelectAll(t.getStore())),"admin"!==e&&(i.set("admin",!1),r.checkSelectAll(t.getStore()))}(o,a)}}),Ext.define("SYNO.SDS.MailClient.Switch",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.Model.Main","SYNO.SDS.MailClient.SearchLib.SyntaxParser","SYNO.SDS.MailClient.Model.PagingMemoryProxy"],currentStatus:"mail",singleton:!0,constructor:function(t){this.current={offset:0,limit:100,showSearchingToast:!1,lastThreadCondition:new SYNO.SDS.MailClient.Condition,lastMatchedIds:[],lastSplitKeyword:""},this.mailboxStore=this.getMailboxStore(),this.labelStore=this.getLabelStore(),this.groupStore=this.getGroupStore(),this.searchHistoryStore=this.getSearchHistoryStore(),this.autoCompleteMemProxy=this.getAutoCompleteMemProxy(),this.autoCompleteData=[],this.callParent([t]),this.addEvents("externalSourceClickSync","editorcontentmousedown","cardwidthchange","settingchange","offsetchange","pgpkeychange"),this.inStar=this.inSearch=this.inLabel=this.inMailbox=!1},copy:function(t){this.current=SYNO.Util.copy(t.current),this.current.lastThreadCondition=new SYNO.SDS.MailClient.Condition(t.current.lastThreadCondition),Ext.copyTo(this,t,"inMailbox,inLabel,inSearch,inStar,inLabelId,inMailboxId")},register:function(t,e){Ext.isObject(t)?(Ext.apply(this.current,t),t.hasOwnProperty("lastThreadCondition")&&this.parseThreadConditionByObject(t.lastThreadCondition)):Ext.isString(t)&&(this.current[t]=e,"lastThreadCondition"===t&&this.parseThreadConditionByObject(e))},deleteRegister:function(t){Ext.isDefined(this.current[t])&&delete this.current[t]},parseThreadConditionByObject:function(t){var e=t.get();this.parseThreadCondition(e,!0)},parseThreadConditionInPriority:function(t){this.parseThreadCondition(t,!1)},parseThreadCondition:function(t,e){var i,n=SYNO.SDS.MailClient.SearchLib.SyntaxParser;for(this.inStar=this.inSearch=this.inLabel=this.inMailbox=!1,e&&(this.inPriority=!1),this.inMailboxId=0,this.syntaxMailboxes=[],i=0;i<t.length;++i)"mailbox"===t[i].name&&(this.inMailboxId=t[i].value),"keyword"===t[i].name&&(this.syntaxMailboxes=this.syntaxMailboxes.concat(n.getRelatedMailbox(t[i].value)));1===this.syntaxMailboxes.length&&0===this.inMailboxId&&(this.inMailboxId=SYNO.SDS.MailClient.Format.mailboxPathToId(this.syntaxMailboxes[0])),!Ext.isArray(t)||t.length>1?this.inSearch=!0:"mailbox"===t[0].name?this.inMailbox=!0:"priority"===t[0].name?this.inSearch=this.inPriority=!0:"starred"===t[0].name?this.inSearch=this.inStar=!0:"label"===t[0].name?(this.inLabel=!0,this.inLabelId=t[0].value):this.inSearch=!0},getRegister:function(t){return this.current[t]},getCurrentThreadStore:function(){return SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore()},getCurrentThreadRecord:function(t){return this.getCurrentThreadStore().getById(t)},loadMessageByIdxDiff:function(t,e){SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore().loadByThreadIdShift(t,e).then(function(t){t&&SYNO.SDS.MailClient.Control.Mail.loadMessage(t)})},editorContentMouseDown:function(t){this.fireEvent("editorcontentmousedown",t)},getMailboxStore:function(){return this.mailboxStore=this.mailboxStore||new SYNO.SDS.MailClient.Model.MailboxStore,this.mailboxStore},getLabelStore:function(){return this.labelStore=this.labelStore||new SYNO.SDS.MailClient.Model.LabelStore,this.labelStore},getGroupStore:function(){return this.groupStore=this.groupStore||new SYNO.SDS.MailClient.Model.GroupStore,this.groupStore},getSearchHistoryStore:function(){return this.searchHistoryStore=this.searchHistoryStore||new SYNO.SDS.MailClient.Model.SearchHistoryStore,this.searchHistoryStore},cardWidthChange:function(t,e){this.fireEvent("cardwidthchange",e)},changeSettings:function(t){var e=SYNO.SDS.MailClient.Define;SYNO.SDS.MailClient.Settings=t,e.isMessageMode&&(SYNO.SDS.MailClient.Settings.conversation_view=1===e.launchParam.cv),this.current.limit=t.conversations_per_page,this.fireEvent("settingchange",t)},getContactStore:function(){return this.contactStore=this.contactStore||this.createContactStore(),this.contactStore},createContactStore:function(){return new SYNO.SDS.MailClient.Model.ContactStore({listeners:{load:function(){this.updateContactByGroupData()},scope:this}})},updateContactByGroupData:function(){var t,e=SYNO.SDS.MailClient.Control.Model,i={};return e.getGroupJson().then(function(e){t=e}).then(e.getContactJson.bind(e)).then(function(e){this.contactByGroupData={},Ext.each(t,function(t){this.contactByGroupData[t.id]=[],"ou"===t.type&&(i[t.id]=t.member)},this),Ext.each(e,function(t){var e;Ext.isEmpty(t.additional.extra_info.mail)||(e="addressbook_"+t.addressbook_id,Ext.isDefined(this.contactByGroupData[e])&&this.contactByGroupData[e].push(t),t.additional.label.forEach(function(i){e="label_"+i.id,Ext.isDefined(this.contactByGroupData[e])&&this.contactByGroupData[e].push(t)},this),Object.keys(i).forEach(function(e){-1!==i[e].indexOf(t.id)&&this.contactByGroupData[e].push(t)},this))},this),this.updateAutoCompleteMemProxy()}.bind(this))},getContactByGroupData:function(t){return Ext.isEmpty(this.contactByGroupData)?[]:this.contactByGroupData[t]},hasEmailInContact:function(t){var e=t.toLowerCase();return this.contactStore.findBy(function(t,i){return!!(t.get("additional")&&t.get("additional").extra_info&&t.get("additional").extra_info.mail)&&t.get("additional").extra_info.mail.some(function(t){return t.toLowerCase()===e})})>-1},updateDocumentTitle:function(){var t,e,i=SYNO.SDS.MailClient,n=i.Define,a="",o="{0} - {1}",s=SYNO.SDS.MailClient._T("common","displayname");if(n.isComposeMode)a=i._T("common","compose");else if(n.isMessageMode||n.isPrintMode){if(!(t=SYNO.SDS.MailClient.Lib.Thread.store.getAt(0)))return;a=i.Format.templateSubjectFromMessageDraft(t.get("message"),t.get("draft"),!0)}else if(this.inStar)a=i._T("mailbox",n.starredId);else if(this.inPriority)a=i._T("priority_mailbox","priority_mailbox_title"),(e=SYNO.SDS.MailClient.Lib.PriorityMailbox.getUnreadCount())&&(o="{0} ("+e+") - {1}");else if(this.inSearch)a=i._T("search","search_result");else{if(!(t=this.inMailbox?this.mailboxStore.getById(this.inMailboxId):this.labelStore.getById(this.inLabelId)))return;a=n.getSystemMailboxNameString(t.data.name)||t.data.name,e=t.data.additional.hasOwnProperty("total_count")?t.data.additional.total_count:t.data.additional.unread_count,e&&(o="{0} ("+e+") - {1}")}document.title=String.format(o,a,s).trim()},offsetChange:function(t,e){this.current.offset=t,this.fireEvent("offsetchange",t,e)},PGPKeyChange:function(){this.fireEvent("pgpkeychange")},getAutoCompleteMemProxy:function(){return this.autoCompleteMemProxy=this.autoCompleteMemProxy||new SYNO.SDS.MailClient.Model.PagingMemoryProxy(this.getAutoCompleteData()),this.autoCompleteMemProxy},updateAutoCompleteMemProxy:function(){this.getAutoCompleteMemProxy().setData(this.getAutoCompleteData())},getAutoCompleteData:function(){var t={},e=[];return this.getContactStore().each(function(i){if(Ext.isEmpty(i.data.additional.extra_info.mail))return!0;i.data.additional.extra_info.mail.forEach(function(n,a,o){var s,l,r,d={};s=SYNO.SDS.MailClient.Format.composeNameAddr(i.data.full_name,n),t.hasOwnProperty(s)||(d.id="contact_"+s+"_"+(i.data.primary_mail==n?"p":"np"),d.type="contact",l=i.data.additional.extra_info.nick_name?String.format("{0} ({1})",i.data.full_name,i.data.additional.extra_info.nick_name):i.data.full_name,r=SYNO.SDS.MailClient.Format.composeNameAddr(l,n),d.mail_for_search=n,d.address_value=s,t[s]=!0,d.name_with_nickname=l,d.search_field=r,d.combobox_display=r,d.combobox_display_encode=Ext.util.Format.htmlEncode(d.combobox_display),d.address_encode=Ext.util.Format.htmlEncode(d.address_value),d.address_display=SYNO.SDS.MailClient.Editor.SuperBoxSelect.toAddressDisplay(d.address_encode),e.push(d))},this)},this),Ext.each(this.getGroupStore().getRange(),function(t){var i={};i.id=t.data.id,i.type=t.data.type,i.search_field=t.data.name,i.combobox_display=i.search_field,i.combobox_display_encode=Ext.util.Format.htmlEncode(i.combobox_display),i.members=SYNO.SDS.MailClient.Switch.getContactByGroupData(t.id),i.members.length>0&&e.push(i)},this),{contact:e}}}),Ext.define("SYNO.SDS.MailClient.Array",{extend:"Ext.util.Observable",singleton:!0,deepCopy:function(t,e){var i,n,a,o;if(!t||"object"!=typeof t)return t;if("[object Array]"===Object.prototype.toString.call(t)){for(i=[],o=0;o<t.length;++o)i[o]=this.deepCopy(t[o]);return i}if(!Ext.isObject(t))return t;for(i={},e=e||[],n=Object.keys(t),a=n.length,o=0;o<a;++o)-1===e.indexOf(n[o])&&(i[n[o]]=this.deepCopy(t[n[o]]));return i},unique:function(t){return this.uniqueBy(t)},uniqueBy:function(t,e){var i={};return e||(e=function(e){return t.indexOf(e)}),t.filter(function(t){var n=e(t);return!i.hasOwnProperty(n)&&(i[n]=!0)})},contain:function(t,e,i){return t.some(function(t){return i?i(e,t):e===t})},without:function(t,e,i){return t.filter(function(t){return!SYNO.SDS.MailClient.Array.contain(e,t,i)})},intersection:function(t,e,i){return t.filter(function(t){return SYNO.SDS.MailClient.Array.contain(e,t,i)})},hasValue:function(t){return!!t},isEmptyValue:function(t){return!t}}),function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.blobUtil=t()}}(function(){return function t(e,i,n){function a(s,l){if(!i[s]){if(!e[s]){var r="function"==typeof require&&require;if(!l&&r)return r(s,!0);if(o)return o(s,!0);var d=new Error("Cannot find module '"+s+"'");throw d.code="MODULE_NOT_FOUND",d}var c=i[s]={exports:{}};e[s][0].call(c.exports,function(t){var i=e[s][1][t];return a(i||t)},c,c.exports,t,e,i,n)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<n.length;s++)a(n[s]);return a}({1:[function(t,e,i){(function(t){function i(t){for(var e=0;e<t.length;e++){var i=t[e];if(i.buffer instanceof ArrayBuffer){var n=i.buffer;if(i.byteLength!==n.byteLength){var a=new Uint8Array(i.byteLength);a.set(new Uint8Array(n,i.byteOffset,i.byteLength)),n=a.buffer}t[e]=n}}}function n(t,e){e=e||{};var n=new o;i(t);for(var a=0;a<t.length;a++)n.append(t[a]);return e.type?n.getBlob(e.type):n.getBlob()}function a(t,e){return i(t),new Blob(t,e||{})}var o=t.BlobBuilder||t.WebKitBlobBuilder||t.MSBlobBuilder||t.MozBlobBuilder,s=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),l=s&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),r=o&&o.prototype.append&&o.prototype.getBlob;e.exports=function(){return s?l?t.Blob:a:r?n:void 0}()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],2:[function(t,e,i){(function(t){"use strict";function i(){c=!0;for(var t,e,i=h.length;i;){for(e=h,h=[],t=-1;++t<i;)e[t]();i=h.length}c=!1}function n(t){1!==h.push(t)||c||a()}var a,o=t.MutationObserver||t.WebKitMutationObserver;if(o){var s=0,l=new o(i),r=t.document.createTextNode("");l.observe(r,{characterData:!0}),a=function(){r.data=s=++s%2}}else if(t.setImmediate||void 0===t.MessageChannel)a="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){i(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},t.document.documentElement.appendChild(e)}:function(){setTimeout(i,0)};else{var d=new t.MessageChannel;d.port1.onmessage=i,a=function(){d.port2.postMessage(0)}}var c,h=[];e.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],3:[function(t,e,i){"use strict";function n(){}function a(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=b,this.queue=[],this.outcome=void 0,t!==n&&r(this,t)}function o(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function s(t,e,i){m(function(){var n;try{n=e(i)}catch(e){return f.reject(t,e)}n===t?f.reject(t,new TypeError("Cannot resolve promise with itself")):f.resolve(t,n)})}function l(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function r(t,e){function i(e){o||(o=!0,f.reject(t,e))}function n(e){o||(o=!0,f.resolve(t,e))}function a(){e(n,i)}var o=!1,s=d(a);"error"===s.status&&i(s.value)}function d(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}function c(t){return t instanceof this?t:f.resolve(new this(n),t)}function h(t){var e=new this(n);return f.reject(e,t)}function u(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,a=!1;if(!i)return this.resolve([]);for(var o=new Array(i),s=0,l=-1,r=new this(n);++l<i;)!function(t,n){function l(t){o[n]=t,++s!==i||a||(a=!0,f.resolve(r,o))}e.resolve(t).then(l,function(t){a||(a=!0,f.reject(r,t))})}(t[l],l);return r}function S(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,a=!1;if(!i)return this.resolve([]);for(var o=-1,s=new this(n);++o<i;)!function(t){e.resolve(t).then(function(t){a||(a=!0,f.resolve(s,t))},function(t){a||(a=!0,f.reject(s,t))})}(t[o]);return s}var m=t(2),f={},p=["REJECTED"],g=["FULFILLED"],b=["PENDING"];e.exports=a,a.prototype.catch=function(t){return this.then(null,t)},a.prototype.then=function(t,e){if("function"!=typeof t&&this.state===g||"function"!=typeof e&&this.state===p)return this;var i=new this.constructor(n);if(this.state!==b){s(i,this.state===g?t:e,this.outcome)}else this.queue.push(new o(i,t,e));return i},o.prototype.callFulfilled=function(t){f.resolve(this.promise,t)},o.prototype.otherCallFulfilled=function(t){s(this.promise,this.onFulfilled,t)},o.prototype.callRejected=function(t){f.reject(this.promise,t)},o.prototype.otherCallRejected=function(t){s(this.promise,this.onRejected,t)},f.resolve=function(t,e){var i=d(l,e);if("error"===i.status)return f.reject(t,i.value);var n=i.value;if(n)r(t,n);else{t.state=g,t.outcome=e;for(var a=-1,o=t.queue.length;++a<o;)t.queue[a].callFulfilled(e)}return t},f.reject=function(t,e){t.state=p,t.outcome=e;for(var i=-1,n=t.queue.length;++i<n;)t.queue[i].callRejected(e);return t},a.resolve=c,a.reject=h,a.all=u,a.race=S},{2:2}],4:[function(t,e,i){e.exports="function"==typeof Promise?Promise:t(3)},{3:3}],5:[function(t,e,i){"use strict";function n(t){for(var e=t.length,i=new ArrayBuffer(e),n=new Uint8Array(i),a=-1;++a<e;)n[a]=t.charCodeAt(a);return i}function a(t){for(var e="",i=new Uint8Array(t),n=i.byteLength,a=-1;++a<n;)e+=String.fromCharCode(i[a]);return e}function o(t,e){return new _(function(i,n){var a=new Image;e&&(a.crossOrigin=e),a.onload=function(){i(a)},a.onerror=n,a.src=t})}function s(t){var e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height,0,0,t.width,t.height),e}function l(t,e){return e=e||{},"string"==typeof e&&(e={type:e}),new x(t,e)}function r(t){return(window.URL||window.webkitURL).createObjectURL(t)}function d(t){return(window.URL||window.webkitURL).revokeObjectURL(t)}function c(t){return new _(function(e,i){var n=new FileReader,o="function"==typeof n.readAsBinaryString;n.onloadend=function(t){var i=t.target.result||"";if(o)return e(i);e(a(i))},n.onerror=i,o?n.readAsBinaryString(t):n.readAsArrayBuffer(t)})}function h(t,e){return _.resolve().then(function(){var i=[n(atob(t))];return e?l(i,{type:e}):l(i)})}function u(t,e){return _.resolve().then(function(){return h(btoa(t),e)})}function S(t){return c(t).then(function(t){return btoa(t)})}function m(t){return _.resolve().then(function(){var e=t.match(/data:([^;]+)/)[1],i=t.replace(/^[^,]+,/,"");return l([n(atob(i))],{type:e})})}function f(t){return S(t).then(function(e){return"data:"+t.type+";base64,"+e})}function p(t,e,i,n){return e=e||"image/png",o(t,i).then(function(t){return s(t)}).then(function(t){return t.toDataURL(e,n)})}function g(t,e,i){return _.resolve().then(function(){return"function"==typeof t.toBlob?new _(function(n){t.toBlob(n,e,i)}):m(t.toDataURL(e,i))})}function b(t,e,i,n){return e=e||"image/png",o(t,i).then(function(t){return s(t)}).then(function(t){return g(t,e,n)})}function C(t,e){return _.resolve().then(function(){return l([t],e)})}function y(t){return new _(function(e,i){var n=new FileReader;n.onloadend=function(t){var i=t.target.result||new ArrayBuffer(0);e(i)},n.onerror=i,n.readAsArrayBuffer(t)})}var x=t(1),_=t(4);e.exports={createBlob:l,createObjectURL:r,revokeObjectURL:d,imgSrcToBlob:b,imgSrcToDataURL:p,canvasToBlob:g,dataURLToBlob:m,blobToDataURL:f,blobToBase64String:S,base64StringToBlob:h,binaryStringToBlob:u,blobToBinaryString:c,arrayBufferToBlob:C,blobToArrayBuffer:y}},{1:1,4:4}]},{},[5])(5)}),function(){/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20160520
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
var t=t||function(t){"use strict";if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var e=t.document,i=function(){return t.URL||t.webkitURL||t},n=e.createElementNS("http://www.w3.org/1999/xhtml","a"),a="download"in n,o=function(t){var e=new MouseEvent("click");t.dispatchEvent(e)},s=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),l=t.webkitRequestFileSystem,r=t.requestFileSystem||l||t.mozRequestFileSystem,d=function(e){(t.setImmediate||t.setTimeout)(function(){throw e},0)},c=0,h=function(t){var e=function(){"string"==typeof t?i().revokeObjectURL(t):t.remove()};setTimeout(e,4e4)},u=function(t,e,i){e=[].concat(e);for(var n=e.length;n--;){var a=t["on"+e[n]];if("function"==typeof a)try{a.call(t,i||t)}catch(t){d(t)}}},S=function(t){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type)?new Blob(["",t],{type:t.type}):t},m=function(e,d,m){m||(e=S(e));var f,p,g,b=this,C=e.type,y=!1,x=function(){u(b,"writestart progress write writeend".split(" "))},_=function(){if(p&&s&&"undefined"!=typeof FileReader){var n=new FileReader;return n.onloadend=function(){var t=n.result;p.location.href="data:attachment/file"+t.slice(t.search(/[,;]/)),b.readyState=b.DONE,x()},n.readAsDataURL(e),void(b.readyState=b.INIT)}if(!y&&f||(f=i().createObjectURL(e)),p)p.location.href=f;else{void 0===t.open(f,"_blank")&&s&&(t.location.href=f)}b.readyState=b.DONE,x(),h(f)},M=function(t){return function(){if(b.readyState!==b.DONE)return t.apply(this,arguments)}},D={create:!0,exclusive:!1};return b.readyState=b.INIT,d||(d="download"),a?(f=i().createObjectURL(e),void setTimeout(function(){n.href=f,n.download=d,o(n),x(),h(f),b.readyState=b.DONE})):(t.chrome&&C&&"application/octet-stream"!==C&&(g=e.slice||e.webkitSlice,e=g.call(e,0,e.size,"application/octet-stream"),y=!0),l&&"download"!==d&&(d+=".download"),("application/octet-stream"===C||l)&&(p=t),r?(c+=e.size,void r(t.TEMPORARY,c,M(function(t){t.root.getDirectory("saved",D,M(function(t){var i=function(){t.getFile(d,D,M(function(t){t.createWriter(M(function(i){i.onwriteend=function(e){p.location.href=t.toURL(),b.readyState=b.DONE,u(b,"writeend",e),h(t)},i.onerror=function(){var t=i.error;t.code!==t.ABORT_ERR&&_()},"writestart progress write abort".split(" ").forEach(function(t){i["on"+t]=b["on"+t]}),i.write(e),b.abort=function(){i.abort(),b.readyState=b.DONE},b.readyState=b.WRITING}),_)}),_)};t.getFile(d,{create:!1},M(function(t){t.remove(),i()}),M(function(t){t.code===t.NOT_FOUND_ERR?i():_()}))}),_)}),_)):void _())},f=m.prototype,p=function(t,e,i){return new m(t,e,i)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(t,e,i){return i||(t=S(t)),navigator.msSaveOrOpenBlob(t,e||"download")}:(f.abort=function(){var t=this;t.readyState=t.DONE,u(t,"abort")},f.readyState=f.INIT=0,f.WRITING=1,f.DONE=2,f.error=f.onwritestart=f.onprogress=f.onwrite=f.onabort=f.onerror=f.onwriteend=null,p)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);Ext.define("SYNO.SDS.MailClient.FileOP",{singleton:!0,saveAs:t,getBlobByUrl:function(t){return new Promise(function(e,i){var n,a,o=new XMLHttpRequest;o.open("GET",t,!0),o.responseType="arraybuffer",o.onload=function(){200!==this.status&&i("xhr status is not 200: "+this.status),n=o.getResponseHeader("Content-Type"),a=new Blob([this.response],{type:n}),e(a)},o.send()})},readArrayBufferFromBlob:function(t){return new Promise(function(e,i){var n=new FileReader;n.onload=function(t){e(t)},n.readAsArrayBuffer(t)})},saveTextToFile:function(t,e){var i=new Blob([t],{type:"text/plain"});return this.saveAs(i,e)},saveBinaryToFile:function(t,e){var i=new Blob([t],{type:"application/octet-stream"});return this.saveAs(i,e)}})}(),Ext.define("SYNO.SDS.MailClient.Format",{singleton:!0,addressWithDisplayNameRegExp:/(.*?)(\s*<([^<|^>]*?@[^<|^>]*?)>)$/,escapeRE:function(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},htmlToPlain:function(t,e){var i=document.createElement("div");i.innerHTML=t;var n=i.textContent||i.innerText||"";return e?n.substr(0,500).trim().replace(/(\r\n|\n|\r)/gm," ").replace(/\s\s+/gm," ").replace(/\s*</,"<").replace(/>\s*/,">"):n},toFullTimeString:function(t){var e=new Date(1e3*t),i=e.getFullYear(),n=e.getMonth()+1,a=e.getDay(),o=e.getDate(),s=_T("login","mon_"+n),l=_T("login","weekday_"+a);return String.format(_T("login","date_format_with_year"),s,o,l,i)+" "+String.format("{0}:{1}:{2}",e.format("H"),e.format("i"),e.format("s"))},toTimeString:function(t,e){var i=new Date(1e3*t),n=new Date,a=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(n.getFullYear(),0,1),s=(n.getTime()-i.getTime())/1e3,l="";e&&(s<60?l="0 minute ago":s<3600?l=Math.floor(s/60)+" minutes ago":s<86400?l=Math.floor(s/3600)+" hours ago":s<1209600&&(l=Math.floor(s/86400)+" days ago"));var r;return r=i.getTime()>a.getTime()?Ext.util.Format.date(i,"H:i"):i.getTime()>o.getTime()?Ext.util.Format.date(i,"M d"):Ext.util.Format.date(i,"m/d/y"),l?r+" ("+l+")":r},isAddrSpec:function(t,e){var i=/^([^\s]+@[^\s]+)$/,n=i.exec(t);return!(!n||!SYNO.SDS.MailPlusServer.EaiAddrValidator(n[1]))&&(!e||n)},isNonEAIAddrSpec:function(t,e){var i=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,n=i.exec(t);return!!n&&(!e||n)},isDomainSpec:function(t){var e=/^(\S+)$/,i=e.exec(t);return!!i&&SYNO.SDS.MailPlusServer.EaiDomainValidator(i[1])},isNameAddr:function(t){return!!this.matchNameAddr(t)},getMailByNameAddr:function(t){var e=this.matchNameAddr(t);return e?e[2]:null},getMailByNameAddrOrAddr:function(t){var e=this.getMailByNameAddr(t);return!e&&this.isAddrSpec(t)&&(e=t),e},matchNameAddr:function(t){var e=this._matchNameAddrRE(t);return e&&this.isAddrSpec(e[2])?e:null},_matchNameAddrRE:function(t){return/^(.*?)(?:\s*)<([^<>]*@[^<>]*)>$/.exec(t)},isValidEmail:function(t){return this.isNameAddr(t)||this.isAddrSpec(t)},IsValidForwardAddress:function(t){var e,i,n=SYNO.SDS.MailClient.Info.max_redirects,a=SYNO.SDS.MailClient.SMTP.smtp.filter(function(t){return t.id<0});return e=t.split(",").map(function(t){return t.trim().toLowerCase()}),i=a.map(function(t){return t.mail.toLowerCase()}),e.length>n?String.format(SYNO.SDS.MailClient._T("setting","exceed_max_redirects"),n):e.every(function(t){return SYNO.SDS.MailClient.Format.isValidEmail(t.trim())})?!i.some(function(t){return-1!==e.indexOf(t)})||SYNO.SDS.MailClient._T("setting","autoforward_has_self_address"):Ext.form.VTypes.emailText},isValidIpOrHostname:function(t,e){var i=SYNO.SDS.MailPlusServer.Punycode.Converter.toASCII(t);return!(!e&&SYNO.SDS.MailClient.Format.isBasicLocalHost(i))&&Ext.form.VTypes.iporhostname(i)},isBasicLocalHost:function(t){if(!Ext.form.VTypes.ip(t))return"localhost"===t.toLowerCase();return!!t.match(/^(127\..*|::1|0:0:0:0:0:0:0:1)$/)},strippedUser:function(t){var e;return-1!==(e=t.indexOf("@"))?t.substr(0,e):-1!==(e=t.indexOf("\\"))&&t.length>e+1?t.substr(e+1):t},composeAddrSpec:function(t,e){return Ext.isString(t)&&Ext.isString(e)?String.format("{0}@{1}",this.strippedUser(t),e):""},composeNameAddr:function(t,e){return Ext.isString(t)&&Ext.isString(e)?String.format("{0} <{1}>",t,e):""},toEmail:function(t){return this.isNameAddr(t)?this.matchNameAddr(t)[2]:this.isAddrSpec(t)?t:""},toEmailSpan:function(t,e,i){return this._toEmailSpan(t,e,i)},toEmailSpanShowSelf:function(t,e,i){return this._toEmailSpan(t,e,!1,!0,i)},_toEmailSpan:function(t,e,i,n,a){var o=this.addressWithDisplayNameRegExp,s=o.exec(t),l=Ext.util.Format.htmlEncode;if(s&&s[1]){var r=s[1],d=r.concat(s[2]);return n&&this.isSMTPMail(s[3])?r=SYNO.SDS.MailClient._T("mail","self"):a&&-1<r.indexOf(" ")&&(r=r.substr(0,r.indexOf(" "))),String.format('<span {0} email="{1}" displayname="{3}">{2}</span>',e?'class="'+e+'"':"",l(s[3]),l(i?d:r),l(s[1]))}var c="",h=s?s[3]:t.trim();return c=n&&this.isSMTPMail(h)?SYNO.SDS.MailClient._T("mail","self"):-1!==h.indexOf(" ")?h.substr(0,h.indexOf(" ")):-1!==h.indexOf("@")?h.substr(0,h.indexOf("@")):h,String.format('<span {0} email="{1}" displyname="{3}">{2}</span>',e?'class="'+e+'"':"",l(t),l(i?t:c),l(h))},isSMTPMail:function(t){var e=SYNO.SDS.MailClient.Format.toEmail(t).toLowerCase();return SYNO.SDS.MailClient.ComposerLib.Config.getSMTPMail().some(function(t){return t.toLowerCase()===e})},getFromInfo:function(t){var e,i={displayName:"",email:"",innerEmail:"",isInContact:!1};return Ext.isString(t)?(e=t.match(/((?:[^ ]| )+) (<([^>]*)>)$/))?(i.displayName=e[1],i.email=e[2],i.innerEmail=e[3],i.isInContact=SYNO.SDS.MailClient.Switch.hasEmailInContact(i.innerEmail),i):(i.email=t,i):i},isDisplayNameMalicious:function(t,e){for(var i,n=SYNO.SDS.MailClient.Format,a="[^"+n.escapeRE('\\,;<>@@:/{}[]()".')+"\\s]+",o="[^"+n.escapeRE("!\"#$%&'()*+,./:;<=>?@@[\\]^_`{|}~\,;<>:/{}()。$*+?|!#%&=﹍~︵︶︷︸﹤﹥﹛﹜﹙﹚﹢")+"\\s]+",s=a+"(\\."+a+")*[@@]"+o+"(\\."+o+")+",l=new RegExp(s,"g"),r=[];i=l.exec(t);)r.push(i[0]);return r.some(function(t){return t!==e},this)},templateSenderFromMessageDraft:function(t,e){return this._templateContactFromMessageDraft(t,e,!1)},templateReceiverFromMessageDraft:function(t,e){return this._templateContactFromMessageDraft(t,e,!0)},_templateContactFromMessageDraft:function(t,e,i){function n(t){var e,i=0,n=o,a=SYNO.SDS.MailClient.Format.toEmail(t).toLowerCase();e=c.map(function(t){return t.email}),i=e.indexOf(a),0===i&&n!==c[i].isRead&&(i=e.indexOf(a,1)),i>0&&(n=c[i].isRead&&o,c.splice(i,1)),0!==i&&c.push({email:a,address:t,isRead:n})}var a,o,s,l=i?SYNO.SDS.MailClient._T("mail","receiver")+": ":"",r=[],d=[],c=[];for(a=0;a<t.length;a++)i&&t[a].mailbox_id!==SYNO.SDS.MailClient.Define.sentId||(o=t[a].read,(s=i?t[a].recipients:[t[a].from])&&s.forEach(n));return c.forEach(function(t){var e,i;e=SYNO.SDS.MailClient.Format.toEmailSpanShowSelf(t.address,t.isRead?"":"item-unread"),i=SYNO.SDS.MailClient.Format.toEmailSpanShowSelf(t.address,t.isRead?"":"item-unread",!0),r.push(e),d.push(i)}),r.length>3&&0===e.length?l+=d[0]+" .. "+d[d.length-2]+", "+d[d.length-1]:r.length>3?l+=d[0]+" .. "+d[d.length-1]:r.length>1?l+=d.join(", "):1===r.length&&(l+=r[0]),t.length>1&&(l+=' <span class="count">('+t.length+")</span>"),r.length&&e.length&&(l+=", "),e.length>1?l+='<span class="draft">'+SYNO.SDS.MailClient._T("common","draft")+'</span> <span class="count">('+e.length+")</span>":1==e.length&&(l+='<span class="draft">'+SYNO.SDS.MailClient._T("mailbox","draft")+"</span>"),l},templateSubjectFromMessageDraft:function(t,e,i){var n="",a="";t.length&&(n=t[0].subject),e.length&&(a=e[e.length-1].subject);var o=n||(a||"("+SYNO.SDS.MailClient._T("mail","empty_subject")+")");return i?o:Ext.util.Format.htmlEncode(o)},templateBodyPreviewFromMessageDraft:function(t,e){var i="";return t.length?i=Ext.isDefined(t[t.length-1].body_preview)?t[t.length-1].body_preview:this.htmlToPlain(t[t.length-1].body.html,!0):e.length&&(i=Ext.isDefined(e[e.length-1].body_preview)?e[e.length-1].body_preview:this.htmlToPlain(e[e.length-1].body.html,!0)),Ext.util.Format.htmlEncode(i)},templateTimeString:function(t,e){var i;return i=t.length?t[t.length-1].modified_time?t[t.length-1].modified_time:t[t.length-1].arrival_time:0,e?SYNO.SDS.MailClient.Format.toFullTimeString(i):SYNO.SDS.MailClient.Format.toTimeString(i)},templateAttachment:function(t,e){var i,n,a,o=[t,e],s=[];for(i=0;i<o.length;++i)for(n=0;n<o[i].length;++n)if(o[i][n].attachment.length)for(a=0;a<o[i][n].attachment.length;a++)Ext.isString(o[i][n].attachment[a])?s.push(o[i][n].attachment[a]):s.push(o[i][n].attachment[a].name);return s.length?'<div class="attachment" title="'+Ext.util.Format.htmlEncode(s.join(", "))+'"></div>':""},templateNotShareIcon:function(t){if(t.isCopyBeforeSend)return"";var e=SYNO.SDS.MailClient.Control.Main,i=e.getInMailboxId(),n=e.isInPriorityMailbox(),a=SYNO.SDS.MailClient.Lib.PriorityMailbox;if(this.isMailboxNeedShowNotShared(i))return i===t.mailbox_id?"":'<div class="not-shared-icon" ext:qtip="'+SYNO.SDS.MailClient._T("composer","not_share_message")+'"></div>';if(n&&a.isDisplayingMailbox()){var o=a.getDisplayingMailboxId();if(this.isMailboxNeedShowNotShared(o))return o===t.mailbox_id?"":'<div class="not-shared-icon" ext:qtip="'+SYNO.SDS.MailClient._T("composer","not_share_message")+'"></div>'}return""},getApproximateSizeFromByte:function(t,e){var i,n,a=["Byte(s)","KB","MB","GB","TB","PB","EB","ZB","YB"],o=1024,s=e<0?0:e;return Ext.isNumber(t)?0===t?["0 Byte",0]:(i=Math.floor(Math.log(t)/Math.log(o)),n=parseFloat((t/Math.pow(o,i)).toFixed(s)),[Ext.util.Format.htmlEncode(n+" "+a[i]),n*Math.pow(o,i)]):["",0]},isMailboxNeedShowNotShared:function(t){var e=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t);if(Ext.isEmpty(e))return!1;var i=e.data.is_own&&!Ext.isEmpty(e.data.additional.permission),n=!e.data.is_own;return i||n},isMailboxNeedCopyTo:function(t){var e=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t);if(Ext.isEmpty(e))return!1;var i=SYNO.SDS.MailClient.Define.MailboxPermission,n=e.data.is_own&&!Ext.isEmpty(e.data.additional.permission),a=!e.data.is_own&&(e.data.my_permission===i.ADMIN||e.data.my_permission===i.READ_WRITE);return n||a},isSharedMailbox:function(t){var e,i,n=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t);return!Ext.isEmpty(n)&&(e=n.data.is_own&&!Ext.isEmpty(n.data.additional.permission),i=!n.data.is_own,e||i)},makeAction:function(t,e){var i={};return i.name=t,i.value=e.toString(),i},contactStoreToJson:function(t){var e=[];return t.each(function(t){e.push(SYNO.Util.copy(t.data))},this),e},groupStoreToJson:function(t,e){var i=[];return e=e||"all",t.each(function(t){"all"!==e&&t.get("type")!==e||i.push(SYNO.Util.copy(t.data))},this),i},_generateFakeMailboxes:function(t){function e(t,i,n,a){var o=t.substring(0,t.lastIndexOf(".")),s=t.substring(t.lastIndexOf(".")+1);Ext.isEmpty(o)||n.hasOwnProperty(o)||e(o,i,n,a),n.hasOwnProperty(t)||(n[t]=t,a.push({id:t,type:"mailbox",name:Ext.util.Format.htmlEncode(s),parent_id:o,subscribed:i,path:t,qtip:SYNO.SDS.MailClient._T("mailbox","not_exist"),additional:{unread_count:0}}))}var i={},n=[];return t.sort(function(t,e){return t.path.toLowerCase()<e.path.toLowerCase()?-1:1}),Ext.each(t,function(t){t.is_own&&(i[t.path]=t.path,e(t.path,t.subscribed,i,n))},this),n},parseMailboxResp:function(t,e,i,n,a){var o,s,l,r=SYNO.SDS.MailClient.Define,d=new Ext.util.MixedCollection,c=[],h={};return d.addAll(t),d.addAll(this._generateFakeMailboxes(t)),i&&d.add({id:"starred",type:"star",name:SYNO.SDS.MailClient._T("mailbox","starred"),parent_id:0,subscribed:!0,path:"starred",qtip:SYNO.SDS.MailClient._T("mailbox","starred"),additional:{unread_count:0}}),e&&SYNO.SDS.MailClient.Lib.PriorityMailbox.isEnablePriorityMailbox()&&d.add({id:"priority",type:"star",name:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),parent_id:0,subscribed:!0,path:"priority",qtip:SYNO.SDS.MailClient._T("priority_mailbox","priority_mailbox_title"),additional:{unread_count:0}}),d.sort("asc",function(t,e){function i(t){return t.id<0||"priority"===t.id||"starred"===t.id}function n(t){return i(t)?r.getSystemMailboxPathById(t.id):t.path.toLowerCase()}var a=SYNO.SDS.MailClient.Define.SystemMailboxName.indexOf(n(t)),o=SYNO.SDS.MailClient.Define.SystemMailboxName.indexOf(n(e));return i(t)&&i(e)?a-o:i(t)||i(e)?i(t)?-1:i(e)?1:0:t.path.toLowerCase()<e.path.toLowerCase()?-1:1}),d.each(function(t,i,r){if(("star"===t.type||Ext.isString(t.id)||t.is_own)&&(!n||t.subscribed)){if(l=t.path.substring(0,t.path.lastIndexOf(".")),Ext.isEmpty(l))o=c;else{if(!(s=h[l]))return;s.leaf=!1,o=s.children}h[t.path]=this._createMailboxNode(t,e,a),o.push(h[t.path])}},this),this.arrangeArchiveMailbox(h,c)},parseOthersMailboxResp:function(t,e,i,n,a){var o,s=[],l={},r={},d=[],c="",h=new Ext.util.MixedCollection;return h.addAll(t),h.sort("asc",function(t,e){return t.path.toLowerCase()<e.path.toLowerCase()?-1:1}),h.each(function(t,h,u){t.is_own||i&&!t.subscribed||n&&SYNO.SDS.MailClient.Define.isReadOnlyMailbox(t.id)||(c=t.owner,""===c||r.hasOwnProperty(c)||(r[c]=c,d=s,l[c]=d[d.push(this._createAccountNode(c))-1]),(o=t.parent_id?l[t.parent_id]||l[c]:l[c])&&(o.leaf=!1,d=o.children,l[t.id]=d[d.push(this._createMailboxNode(t,e,a))-1]))},this),this.arrangeArchiveMailbox(l,s)},_createMailboxNode:function(t,e,i){var n=SYNO.SDS.MailClient.UserSettingProperty.getMailboxCollapseNode(),a=t.additional.permission&&t.additional.permission.findIndex(function(t){return t.name!==_S("user")})>-1,o="mailbox"===t.type&&Ext.isString(t.id);return{nodoType:"async",uiProvider:e||Ext.tree.TreeNodeUI,type:"mailbox",isFakeNode:o,cls:o?"fake-node":"",id:t.id,text:this.getMailboxText(t),data:t,count:t.id===SYNO.SDS.MailClient.Define.draftsId?t.additional.total_count:t.additional.unread_count,hide:!t.subscribed,children:[],has_permission:a,qtip:o?SYNO.SDS.MailClient._T("mailbox","not_exist"):this.getMailboxText(t,!0),parent_id:t.parent_id,my_permission:t.my_permission,leaf:!0,expanded:!i&&-1===n.indexOf(t.id),listeners:o?{beforeclick:function(t,e){return t.isLeaf()||t.toggle(),!1}}:{}}},_createAccountNode:function(t){return{nodoType:"async",uiProvider:Ext.tree.TreeNodeUI,type:"account",id:t,text:t,hide:!1,children:[],qtip:t,leaf:!0,listeners:{beforeclick:function(t,e){return t.isLeaf()||t.toggle(),!1}},expanded:!0}},getMailboxText:function(t,e){var i=SYNO.SDS.MailClient.Define,n=["archived","archive"];if(SYNO.SDS.MailClient.Define.isSystemMailboxName(t.name))switch(t.id){case i.draftsId:return i.getSystemMailboxNameString("Drafts");case i.sentId:return i.getSystemMailboxNameString("Sent");default:return i.getSystemMailboxNameString(t.name)}return t.id===SYNO.SDS.MailClient.Settings.archive_mailbox?-1!==n.indexOf(t.path.toLowerCase())?i.getSystemMailboxNameString("Archived"):i.getSystemMailboxNameString("Archived")+" - "+Ext.util.Format.htmlEncode(t.name):e?t.name:Ext.util.Format.htmlEncode(t.name)},mailboxPathToId:function(t){var e,i=SYNO.SDS.MailClient.Switch,n=SYNO.SDS.MailClient.Define,a=SYNO.SDS.MailClient.SearchLib.SyntaxParser,o=0;return n.isSystemMailboxName(t)?o=n.getSystemMailboxIdByPath(t):(e=i.getMailboxStore().getMailboxByPath(a.getRealMailboxPath(t)),SYNO.SDS.MailClient.Tool.isEmptyObject(e)||(o=e.get("id"))),o},arrangeArchiveMailbox:function(t,e){for(var i=SYNO.SDS.MailClient.Settings.archive_mailbox,n=-1,a=-1;t[i]&&0!==t[i].data.parent_id;)i=t[i].data.parent_id;if(Ext.each(e,function(t,e){if(t.id===i?n=e:t.id===SYNO.SDS.MailClient.Define.trashId&&(a=e),-1!==n&&-1!==a)return!1},this),-1!==n&&-1!==a){var o=e[n];e.splice(n,1),e.splice(a+1,0,o)}return e},isPGPAvailable:function(t){var e=[];return t.additional&&t.additional.contact_detail&&t.additional.contact_detail.mail&&(e=t.additional.contact_detail.mail.map(function(t){return t.data},this)),SYNO.SDS.MailClient.PGP.Encryption.isPGPAvailable(e)},getCustomLogoDownloadUrl:function(){var t=SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Setting.CustomLogo","download",1),e=SYNO.SDS.MailClient.AdminSettings.CustomLogo.version;return t=Ext.urlAppend(t,Ext.urlEncode({v:e||(new Date).getTime()}))},getAttachmentTempUrl:function(t){var e=SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Attachment","download",6,!1,t.name);return e=Ext.urlAppend(e,Ext.urlEncode({type:"original",uid:SYNO.SDS.MailClient.Info.uid,content_id:'"'+t.cid+'"',md5:'"'+t.md5+'"',download_token:SYNO.SDS.MailClient.Info.download_token}))},_getAttachmentDownloadUrl:function(t,e,i){var n=SYNO.API.currentManager.getBaseURL("SYNO.MailClient.Attachment","download",6,e,t.name),a={id:t.id};return t.md5&&(a.md5=t.md5),i&&(a.uid=t.uid,a.file_hash=t.file_hash,a.download_token=SYNO.SDS.MailClient.Info.download_token),Ext.urlAppend(n,Ext.urlEncode(SYNO.API.EncodeParams(a)))},getAttachmentDownloadUrl:function(t,e){return this._getAttachmentDownloadUrl(t,e,!1)},getAttachmentDownloadUrlWithFileHash:function(t,e){return this._getAttachmentDownloadUrl(t,e,!0)},attachmentToPreviewAttachment:function(t){var e,i=[];for(e=0;e<t.length;++e)i.push(t[e].name);return i},fullMessageToPreviewMessage:function(t){return{arrival_time:t.arrival_time,attachment:this.attachmentToPreviewAttachment(t.attachment),body_preview:this.htmlToPlain(t.body.html,!0),email:t.email,from:t.from,id:t.id,last_modified:t.last_modified,mailbox_id:t.mailbox_id,read:t.read,rfc_message_id:t.rfc_message_id,star:t.star,subject:t.subject,thread_id:t.thread_id,type:t.type}},draftDataToFakeMessage:function(t,e,i,n,a,o){var s=Math.round(new Date/1e3),l=SYNO.SDS.MailClient._T("notification","sending"),r=[].concat(i.attachment);i.temp_attachment&&(r=r.concat(i.temp_attachment.filter(function(t){return!t.inline&&!Ext.isNumber(t)}))),o&&(r=r.concat(o.filter(function(t){return!t.inline})));var d={message_status:SYNO.SDS.MailClient.Define.MessageStat.FROM_DRAFT,arrival_time:s,attachment:r,body_preview:l,email:SYNO.SDS.MailClient.Format.toEmail(i.from),from:i.from,id:e,last_modified:s,mailbox_id:SYNO.SDS.MailClient.Define.sentId,read:!0,rfc_message_id:"",star:0,subject:i.subject,thread_id:t,type:2};return Ext.isEmpty(a)||Ext.apply(d,{isCopyBeforeSend:a}),n||Ext.apply(d,{bcc:i.bcc||[],body:{html:i.body,html2:'<div class="sending-hint"><div class="icon"></div><div class="text">'+l+"</div></div>",plain:l,truncated:!1},cc:i.cc||[],operation_ids:[e],to:i.to||[]}),d},getTinyMCEDefaultStyle:function(t){var e=SYNO.SDS.MailClient.Settings,i=[];return e.composer_fontname&&i.push("font-family: "+e.composer_fontname),e.composer_fontsize&&i.push("font-size: "+e.composer_fontsize),e.composer_forecolor&&i.push("color: #"+e.composer_forecolor),t?i.length?{style:i.join("; ")+";"}:{}:i.length?i.join("; ")+";":""},toAttachmentName:function(t){return(Ext.isString(t.name)?t.name:t)||"noname.eml"},getLink:function(t){var e=t.match(/^(https?:\/\/|ftp:\/\/|www\.|(?:mailto:)?[A-Z0-9._%+\-]+@)(.+)$/i);if(e)return"www."==e[1]?e[1]="http://www.":/@$/.test(e[1])&&!/^mailto:/.test(e[1])&&(e[1]="mailto:"+e[1]),e[1]+e[2]},getUniqueThreadRecord:function(t){var e={},i=[];return Ext.each(t,function(t,n){e[t.get("id")]||i.push(t),e[t.get("id")]=!0},this),i},getUIStringByPermission:function(t){var e=SYNO.SDS.MailClient.Define.MailboxPermission;return t===e.READ_ONLY?_T("nfs","nfs_read_only"):t===e.READ_WRITE?_T("nfs","nfs_read_write"):t===e.ADMIN?SYNO.SDS.MailClient._T("mailbox","admin"):""},getAccountTextFromPath:function(t){var e=t.substring(t.indexOf(".")+1);return e=e.substring(0,e.indexOf("."))},removeUserFromStore:function(t,e){Ext.each(t.getRange(),function(i){var n=i.get("name");this.strippedUser(n)===this.strippedUser(e)&&t.remove(i)},this)},removeURLParameter:function(t,e){var i;return t=decodeURI(t).split("?"),i=1==t.length?"":t[1],i=i.replace(new RegExp("&?"+e+"=[\\w]*","g"),""),i=i.replace(/^&/,""),encodeURI(t[0]+(i.length?"?"+i:""))},quote:function(t){return'"'+t.replace(/\\|"/g,function(t){return"\\"+t})+'"'},unquote:function(t){var e=t[0];return'"'!==e?t:t.substring(1,t.length-1).replace(/\\\\/g,"\\").replace(/\\"/g,e)},rfc822AddrToNormalAddr:function(t){var e,i,n,a,o=SYNO.SDS.MailClient.Format,s=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]*$/;return(e=t.lastIndexOf("<"))<0?t:(n=t.substr(0,e).trim(),a=t.substr(e),i=s.exec(n),i||(n=o.unquote(n)),n+" "+a)},rfc822AddrsToNormalAddrs:function(t){return t.map(this.rfc822AddrToNormalAddr)},normalAddrToRFC822Addr:function(t){var e,i,n,a,o=SYNO.SDS.MailClient.Format,s=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]*$/;return(e=t.lastIndexOf("<"))<0?t:(n=t.substr(0,e).trim(),a=t.substr(e),i=s.exec(n),i||(n=o.quote(n)),n+" "+a)},normalAddrsToRFC822Addrs:function(t){return t.map(this.normalAddrToRFC822Addr)},formatAddrsOfMsgToNormal:function(t){var e=SYNO.SDS.MailClient.Array.deepCopy(t);return e.from&&(e.from=this.rfc822AddrToNormalAddr(e.from)),e.to&&(e.to=this.rfc822AddrsToNormalAddrs(e.to)),e.cc&&(e.cc=this.rfc822AddrsToNormalAddrs(e.cc)),e.bcc&&(e.bcc=this.rfc822AddrsToNormalAddrs(e.bcc)),e.rfc_reply_to&&(e.rfc_reply_to=this.rfc822AddrsToNormalAddrs(e.rfc_reply_to)),e.recipients&&(e.recipients=this.rfc822AddrsToNormalAddrs(e.recipients)),e},formatAddrsOfMsgsToNormal:function(t){return t.forEach(function(e,i){t[i]=this.formatAddrsOfMsgToNormal(e)},this),t},formatAddrsOfThreadsToNormal:function(t){return t.forEach(function(e,i){t[i].draft=this.formatAddrsOfMsgsToNormal(e.draft),t[i].message=this.formatAddrsOfMsgsToNormal(e.message)},this),t},formatAddrsOfMsgToRFC822:function(t){var e=SYNO.SDS.MailClient.Array.deepCopy(t);return e.from&&(e.from=this.normalAddrToRFC822Addr(e.from)),e.to&&(e.to=this.normalAddrsToRFC822Addrs(e.to)),e.cc&&(e.cc=this.normalAddrsToRFC822Addrs(e.cc)),e.bcc&&(e.bcc=this.normalAddrsToRFC822Addrs(e.bcc)),e.rfc_reply_to&&(e.rfc_reply_to=this.normalAddrsToRFC822Addrs(e.rfc_reply_to)),e.recipients&&(e.recipients=this.normalAddrsToRFC822Addrs(e.recipients)),e},formatAddrsOfMsgsToRFC822:function(t){return t.forEach(function(e,i){t[i]=this.formatAddrsOfMsgToRFC822(e)},this),t},isDSM6:function(){return"6"===_S("majorversion")},orderButtonsByDSM:function(t,e){return this.isDSM6()?[t,e]:[e,t]},getFontFamilyByLang:function(){switch(_S("lang")){case"cht":return"Arial, Verdana, Microsoft JhengHei, sans-serif";case"chs":return"Arial, Verdana, Microsoft YaHei, sans-serif";case"jpn":return"Arial, Verdana, Meiryo, sans-serif"}return"Arial, Verdana, sans-serif"}}),Ext.define("SYNO.SDS.MailClient.ImageLoader",{extend:"Ext.util.Observable",singleton:!0,concurrency:5,constructor:function(){this.queue=[],this.runningCount=0},preload:function(t){Ext.isArray(t)||(t=[t]),Ext.each(t,function(t){this.doPreload(t)},this)},doPreload:function(t){var e=Ext.DomHelper.createDom({tag:"img","data-tmpsrc":t});e.onload=function(t,e){this.onImgLoad(t,e)}.bind(this,e,t),e.onerror=function(t,e){this.onImgError(t,e)}.bind(this,e,t),this.queue.push(e),this.tick()},onImgLoad:function(t,e){--this.runningCount,this.tick()},onImgError:function(t,e){--this.runningCount,this.tick()},tick:function(){for(;this.runningCount<this.concurrency&&this.queue.length>0;)++this.runningCount,this.next()},next:function(){var t=this.queue.shift();t.src=t.dataset.tmpsrc}}),Ext.define("SYNO.SDS.MailClient.OPDefaultCb",{statics:{createContact:function(t,e,i,n){if(t&&!Ext.isEmpty(i.mail[0])){var a=SYNO.SDS.MailClient.Switch.getContactStore(),o=Ext.apply({full_name:i.full_name,primary_mail:i.mail[0].data,additional:{extra_info:{nick_name:i.nick_name,mail:i.mail.map(function(t){return t.data})}}},e);a.add(new a.recordType(o,e.id)),SYNO.SDS.MailClient.Switch.updateAutoCompleteMemProxy()}}}}),Ext.define("SYNO.SDS.MailClient.OP",function(){var t={listContact:["SYNO.Contacts.Contact","list",1],createContact:["SYNO.Contacts.Contact","create",1,!0],updateContactUsageFrequency:["SYNO.Contacts.Contact","update_usage_frequency",1,!0],listAddressbook:["SYNO.Contacts.Addressbook","list",1],listContactsLabel:["SYNO.Contacts.Label","list",1],listContactsOU:["SYNO.Contacts.Contact","list_group",1],labelAddMember:["SYNO.Contacts.Label","add_member",1],labelRemoveMember:["SYNO.Contacts.Label","remove_member",1],getAppTaskId:["SYNO.MailClient.Attachment","get_app_task_id",6]},e=function(t,e,i,n,a,o){return SYNO.API.Request({api:t,method:e,version:i,params:n,callback:a,scope:o})},i={mailKey:"SYNO.MailClient",addrKey:"SYNO.Contacts",singleton:!0,beforeRequest:function(t,e,i){if(e.params&&e.params.api){var n,a,o=[];if(0===e.params.api.indexOf(this.mailKey)||0===e.params.api.indexOf(this.addrKey))o.push(e.params.api);else{if(!e.params.compound)return;for(a=Ext.decode(e.params.compound),n=0;n<a.length;++n)0!==a[n].api.indexOf(this.mailKey)&&0!==a[n].api.indexOf(this.addrKey)||o.push(a[n].api)}}},requestComplete:function(t,e,i,n){if(i.params&&i.params.api){var a,o,s=[];if(0===i.params.api.indexOf(this.mailKey)||0===i.params.api.indexOf(this.addrKey))s.push(i.params.api);else{if(!i.params.compound)return;for(o=Ext.decode(i.params.compound),a=0;a<o.length;++a)0!==o[a].api.indexOf(this.mailKey)&&0!==o[a].api.indexOf(this.addrKey)||s.push(o[a].api)}}},html5UploadBaseOP:function(t,e,i,n,a,o,s){return SYNO.API.Request({timeout:18e5,api:t,method:e,version:i,html5upload:!0,uploadData:n,progress:o,callback:a,scope:s})},html5UploadFile:function(t,e,i,n,a){var o=new window.FormData;return Ext.iterate(t,function(t,e,i){"[object Blob]"===e.toString()?o.append(t,e,e.name):o.append(t,e)}),a?this.html5UploadBaseOP("SYNO.MailClient.Attachment","upload_big_size",6,o,e,i,n):this.html5UploadBaseOP("SYNO.MailClient.Attachment","upload",6,o,e,i,n)},compound:function(e,i,n,a){if(Ext.isArray(e)){var o={};i&&(o=Ext.apply({},i));var s=[],l={};Ext.each(e,function(e,i,n){var a=e[0],o=e[1],r=e[2],d=e[3],c=e[4];s.push({api:t[a][0],method:t[a][1],version:t[a][2],params:o}),l[t[a][0]+"."+t[a][1]+"."+i]={scope:d,cb:r,apiKey:a,useDefault:c}});var r=a||this;return o.params=s,SYNO.API.Request({compound:o,callback:function(e,i,a,o){var s,r,d,c,h,u=0;if(e){if(i.has_fail){var S=[105,402,405,406],m=SYNO.SDS.MailClient.Error.getErrorCode(i);if(-1<S.indexOf(m))return void SYNO.SDS.MailClient.Window.el.mask(SYNO.SDS.MailClient.Error.getErrorString(i))}for(u=0;u<i.result.length;++u)s=i.result[u],r=l[s.api+"."+s.method+"."+u],d=r.scope||this,c=r.apiKey,h=Ext.isBoolean(r.useDefault)?r.useDefault:t[c][3],h&&SYNO.SDS.MailClient.OPDefaultCb.hasOwnProperty(c)&&SYNO.SDS.MailClient.OPDefaultCb[c].call(this,s.success,s.success?s.data:s.error,a.compound[u],o),Ext.isFunction(r.cb)&&r.cb.call(d,s.success,s.success?s.data:s.error,a.compound[u],o)}Ext.isFunction(n)&&n.call(this,e,i,a,o)},scope:r})}}};return Ext.iterate(t,function(t,n,a){i[t]=function(i,a,o,s){var l=Ext.isBoolean(s)?s:n[3];return e(n[0],n[1],n[2],i,function(e,i,n,o){if(!e){var s=[105,402,405,406],r=SYNO.SDS.MailClient.Error.getErrorCode(i);if(-1<s.indexOf(r))return void SYNO.SDS.MailClient.Window.el.mask(SYNO.SDS.MailClient.Error.getErrorString(i))}l&&SYNO.SDS.MailClient.OPDefaultCb.hasOwnProperty(t)&&SYNO.SDS.MailClient.OPDefaultCb[t].apply(this,arguments),Ext.isFunction(a)&&a.apply(this,arguments)},o)},i[t+"Promise"]=function(e,n,a,o){return new Promise(function(n,s){i[t](e,function(t,e,i,a){t?n(e):s(e)},a||window,o)})}},this),Ext.Ajax.on("beforerequest",i.beforeRequest,this),Ext.Ajax.on("requestcomplete",i.requestComplete,this),Ext.Ajax.on("requestexception",i.requestComplete,this),i}),Ext.define("SYNO.SDS.MailClient.Polyfill",{extend:"Ext.util.Observable",singleton:!0,constructor:function(){this.fixElementMatches(),this.fixArrayFindIndex()},fixElementMatches:function(){Element.prototype.matches||(Element.prototype.matches=Element.prototype.matchesSelector||Element.prototype.mozMatchesSelector||Element.prototype.msMatchesSelector||Element.prototype.oMatchesSelector||Element.prototype.webkitMatchesSelector||function(t){for(var e=(this.document||this.ownerDocument).querySelectorAll(t),i=e.length;--i>=0&&e.item(i)!==this;);return i>-1})},fixArrayFindIndex:function(){Array.prototype.findIndex||Object.defineProperty(Array.prototype,"findIndex",{value:function(t){if(null===this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var n=arguments[1],a=0;a<i;){var o=e[a];if(t.call(n,o,a,e))return a;a++}return-1}})}}),Ext.define("SYNO.SDS.MailClient.TextHighlighterBase",{extend:"Ext.Component",mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{ignoringList:["SCRIPT","STYLE","TEXTAREA"],ignoringCls:"skip-highlight",highlightMatcher:function(t,e){return this.defaultHighlightMatcher(t,e)},highlightContainer:{tag:"span",cls:"highlight",style:"background: #FA0;"},highlightContainerDataset:{},bindingEl:void 0,listeners:{click:function(t,e,i){},highlightclick:function(t,e,i){}}},basicHighlightMatcher:function(t,e){return t.toLowerCase().indexOf(e.toLowerCase())},latinHighlightMatcher:function(t,e){var i=this.escapeRE(e),n=String.format("(^|[^{0}])({1})($|[^{2}])","A-Za-zÀ-ÖØ-öø-ɏЁёА-я",i,"A-Za-zÀ-ÖØ-öø-ɏЁёА-я"),a=new RegExp(n,"i"),o=a.exec(t);if(o)return o.index+o[1].length},defaultHighlightMatcher:function(t,e){
return/^[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u0401\u0451\u0410-\u044F]+$/.test(e)?this.latinHighlightMatcher(t,e):this.basicHighlightMatcher(t,e)},constructor:function(t){var e;this.config=this.constructConfig(t),e="."+this.config.highlightContainer.cls.split(" ").join("."),this.config.highlightSelector=this.config.highlightContainer.tag+e,this.callParent(arguments),this.config.bindingEl&&this.bind(this.config.bindingEl)},bind:function(t){var e;this.config.listeners&&(e={click:function(t,e,i,n){var a=this.config.listeners,o=a.click||Ext.emptyFn,s=a.highlightclick||Ext.emptyFn;e.matches(this.config.highlightSelector)?s.call(a.scope||window,t,e,i,n):o.call(a.scope||window,t,e,i,n)},scope:this},this.mon(t,e))},escapeRE:function(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isTextNode:function(t){return 3===t.nodeType},isElementNode:function(t){return 1===t.nodeType},isIgnoringTag:function(t){return-1!==this.config.ignoringList.indexOf(t.tagName)},isHighlightableNode:function(t){return this.isElementNode(t)&&t.hasChildNodes()&&!this.isIgnoringTag(t)},hasCls:function(t,e){return(" "+t.className+" ").indexOf(" "+e+" ")>-1},getNodes:function(t,e){return Ext.DomQuery.jsSelect(t,e)},extractFirstChild:function(t){var e=t.parentNode;return e.replaceChild(t.firstChild,t),e},createTextNode:function(t){return document.createTextNode(t)},createColoredNode:function(t){var e=Ext.DomHelper.createDom(this.config.highlightContainer),i=this.config.highlightContainerDataset;return e.appendChild(t.cloneNode(!0)),Ext.iterate(i,function(t,i){e.dataset[t]=i},this),e},getMatchedInfo:function(t,e){var i=this.config.highlightMatcher.call(this,t.nodeValue,e);return-1===i||void 0===i?null:{from:i,len:e.length}},highlightTextNode:function(t,e,i){var n,a;n=t.splitText(e),n.splitText(i),a=this.createColoredNode(n),n.parentNode.replaceChild(a,n)},doHighlight:function(t,e){var i,n,a=this.hasCls(t,this.config.highlightContainer.cls),o=this.hasCls(t,this.config.ignoringCls),s=!1;if(a||o)return!1;if(this.isTextNode(t))(i=this.getMatchedInfo(t,e))&&(this.highlightTextNode(t,i.from,i.len),s=!0);else if(this.isHighlightableNode(t))for(n=0;n<t.childNodes.length;++n)this.doHighlight(t.childNodes[n],e)&&++n;return s},highlightByNode:function(t,e){e=Ext.isArray(e)?e:[e],e.forEach(function(e){this.doHighlight(e,t)},this)},highlightBySelector:function(t,e,i){var n=this.getNodes(e||"body",i);this.highlightByNode(t,n)},highlight:function(t,e,i){""!==t&&(void 0===e&&(e="body"),Ext.isString(e)?this.highlightBySelector(t,e,i):this.highlightByNode(t,e))},mergeTextNode:function(t){var e,i,n=t.nextSibling,a=t.parentNode;return!(null===n||!this.isTextNode(n))&&(e=t.nodeValue+n.nodeValue,i=this.createTextNode(e),a.insertBefore(i,t),a.removeChild(t),a.removeChild(n),!0)},mergeUnhighlightedNode:function(t){var e,i,n=t.childNodes;for(i=0;i<t.childNodes.length;++i)e=n[i],this.isElementNode(e)?this.mergeUnhighlightedNode(e):this.isTextNode(e)&&this.mergeTextNode(e)&&--i},unhighlight:function(t,e){this.getNodes(t||this.config.highlightSelector,e).forEach(function(t){t=this.extractFirstChild(t),this.mergeUnhighlightedNode(t)},this)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.TextHighlighter",{extend:"SYNO.SDS.MailClient.TextHighlighterBase",singleton:!0,config:{ignoringCls:"syno-mc-skip-highlight",highlightMatcher:function(t,e){return this.defaultHighlightMatcher(t,e)},highlightContainer:{tag:"span",cls:"syno-mc-highlight",style:"background: rgba(255,245,0,0.7);"}}}),Ext.define("SYNO.SDS.MailClient.Button",{extend:"SYNO.ux.Button",xtype:"syno_mc_button",constructor:function(t){this.notChangeTemplate=t.notChangeTemplate,this.callParent(arguments),this.addClass("syno-mc-button")},onRender:function(t,e){this.menu&&!this.notChangeTemplate?this.template=new Ext.Template('<span id="{4}" cellspacing="0" class="x-btn {3}">','<button type="{0}"></button><em class="{2} x-unselectable" unselectable="on"></em>',"</span>"):this.template=new Ext.Template('<span id="{4}" cellspacing="0" class="x-btn {3}">','<em class="{2} x-unselectable" unselectable="on">','<button type="{0}"></button></em>',"</span>"),SYNO.ux.Button.superclass.onRender.call(this,t,e),SYNO.ux.Utils.setFormItemIndent(this)}}),Ext.define("SYNO.SDS.MailClient.GhostButton",{extend:"SYNO.SDS.MailClient.Button",xtype:"syno_mc_ghost_button",constructor:function(t){this.callParent(arguments),this.text=t.text||t.initialConfig.text||t.initialConfig.tooltip,this.iconCls&&delete this.iconCls,this.addClass("syno-mc-ghost-button")}}),Ext.define("SYNO.SDS.MailClient.GhostSplitButton",{extend:"SYNO.SDS.MailClient.SplitButton",xtype:"syno_mc_ghost_split_button",constructor:function(t){this.callParent(arguments),this.text=t.text||t.initialConfig.text||t.initialConfig.tooltip,this.iconCls&&delete this.iconCls,this.addClass("syno-mc-ghost-button")}}),Ext.define("SYNO.SDS.MailClient.Lib.Factory",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.Button","SYNO.SDS.MailClient.GhostButton","SYNO.SDS.MailClient.SplitButton","SYNO.SDS.MailClient.GhostSplitButton"],create:function(t,e){},createActionButton:function(t,e){return new(0,{Button:SYNO.SDS.MailClient.Button,GhostButton:SYNO.SDS.MailClient.GhostButton,SplitButton:SYNO.SDS.MailClient.SplitButton,GhostSplitButton:SYNO.SDS.MailClient.GhostSplitButton}[t])(SYNO.SDS.MailClient.ToolbarLib.ActionObject[e])},createActionButtons:function(t,e){return e.map(function(e){return this.createActionButton(t,e)}.bind(this))},createActionButtonsByInfo:function(t){return t.map(function(t){return this.createActionButton(t.type,t.actionId)}.bind(this))}}),Ext.define("SYNO.SDS.MailClient.Lib.Logger",{extend:"Ext.util.Observable",singleton:!0,requires:[],constructor:function(){this.callParent(arguments),this.data=[]},error:function(){var t,e="";for(t=0;t<arguments.length;++t)e+=arguments[t]+" ";this._add("error",e)},show:function(){this.data.forEach(function(t){var e=t[1];SYNO.Debug.error(e)},this)},_add:function(t,e){"error"===t&&(SYNO.SDS.MailClient.PushServerLib.Main.error(e),SYNO.SDS.MailClient.enableDebugLog&&SYNO.Debug.error(e)),this.data.push([t,e,new Date])}}),Ext.define("SYNO.SDS.MailClient.AppLib.ChatPlugin",{extend:"Ext.util.Observable",requires:[],singleton:!0,init:function(){if(SYNO.SDS.AppUtil.isValidApp("SYNO.SDS.Chat.Application")&&SYNO.SDS.MailClient.Define.isNormalMode){var t={style:{right:"12px",bottom:"4px"}};this.popOutWinManager=SYNO.SDS.MailClient.Window.popOutWinManager,SYNO.SDS.AppLaunch("SYNO.SDS.Chat.Integration.Application",t,null,this._afterInit,this)}},_afterInit:function(){var t=Ext.getCmp(SYNO.SDS.MailClient.Window.package_header_id),e=new SYNO.SDS.Chat.Integration.Main.PluginButton,i=SYNO.SDS.Chat.AppUtils.getAppWin();this._fixCompatibleApp(),t.items.get(3).insert(2,e),t.doLayout(),i.on("show",this.fixPos,this),i.on("expand",this.fixPos,this),i.on("collapse",this.fixPos,this),i.on("hide",function(){this.popOutWinManager.shiftForChatPlugin(!1)},this)},_fixCompatibleApp:function(){var t=SYNO.SDS.MailClient.AppLib.Util.getAppVersion("SYNO.SDS.Chat.Integration.Application");Ext.isNumber(t)&&t<11900&&(SYNO.SDS.Chat.Integration.Main.MessageBox.prototype.getButtons=function(){var t=SYNO.SDS.MessageBoxV5.prototype.getButtons.apply(this,arguments);return Ext.each(t,function(t){Ext.isFunction(t.addClass)&&t.addClass("syno-plugin")}),t})},fixPos:function(){var t=SYNO.SDS.Chat.AppUtils.getAppWin().getWidth();this.popOutWinManager.shiftForChatPlugin(!0,t)}}),Ext.define("SYNO.SDS.MailClient.AppLib.ContactsTip",{extend:"Ext.Container",constructor:function(t){var e={html:this.getHtml()};this.callParent([Ext.apply(e,t)])},getHtml:function(){return'<div class="syno-mc-tip-mask" id="contacts-tip-mask"><div class="syno-mc-tip-container" id="contacts-tip-container"><div class="syno-mc-tip-menu" id="contacts-tip-menu"><div class="tip-content"><div class="title">'+SYNO.SDS.MailClient._T("contact","contacts_tip_title")+'</div><div class="desc">'+SYNO.SDS.MailClient._T("contact","contacts_tip_desc")+'</div></div><div class="tip-image"></div></div><div class="syno-mc-tip-triangle" id="contacts-tip-triangle"></div></div></div>'},afterRender:function(){this.callParent(arguments),this.mon(SYNO.SDS.MailClient.Window,"resize",function(){this._alignItems(!1)},this),this.mon(this.el,"click",this._doDestroy,this),this._alignItems(!0)},_alignItems:function(t){var e=Ext.get("app-launcher-container"),i=Ext.get("contacts-tip-container"),n=Ext.get("contacts-tip-menu");Ext.get("contacts-tip-triangle").alignTo(n,"b-tr",[-59,0]),t?(i.alignTo(e,"tr-b",[59,-74]),this._animateMenu()):i.alignTo(e,"tr-b",[59,6])},_animateMenu:function(){Ext.get("contacts-tip-mask").setStyle("background","rgba(0, 0, 0, 0.5)"),Ext.get("contacts-tip-container").animate({opacity:{to:1,from:0},top:{to:45,unit:"px"}},.4,null,"cubic-bezier(0.33, 0, 0, 1.1)","run")},_doDestroy:function(){SYNO.SDS.MailClient.UserSettingProperty.setNeedContactsTip(!1),Ext.get("contacts-tip-container").addClass("x-hide-display"),Ext.get("contacts-tip-mask").setStyle("background","rgba(0, 0, 0, 0)"),setTimeout(function(){this.destroy()}.bind(this),400)}}),Ext.define("SYNO.SDS.MailClient.AppLib.MobileAppTip",{extend:"SYNO.ux.Panel",constructor:function(t){this.checkboxId=Ext.id();var e={cls:"mobile-tip",hieght:212,padding:8,floating:!0,shadow:!1,items:[{xtype:"container",html:this._getHtml()},{xtype:"syno_panel",cls:"check-ct",items:[{xtype:"syno_checkbox",cls:"check",boxLabel:SYNO.SDS.MailClient._T("common","tip_dont_show_again"),id:this.checkboxId}]}]};this.callParent([Ext.apply(e,t)])},_getHtml:function(){return'<div class="close"></div><div class="app-info"><div class="icon"></div><div class="desc"><div class="text">'+SYNO.SDS.MailClient._T("common","mobile_app_tip")+'</div><div class="link"><a target=#>'+SYNO.SDS.MailClient._T("common","mobile_app_tip_link")+"</a></div></div></div>"},afterRender:function(){this.callParent(arguments);var t=this.el.child(".close"),e=this.el.child(".link");this.mon(SYNO.SDS.MailClient.Window,"resize",function(){this._alignItems()},this),t.on("click",this._onTipClose,this),e.on("click",this._onLinkClick,this),this._alignItems()},_alignItems:function(){this.el.alignTo(Ext.getBody(),"br",[0-this.getWidth()-20,0-this.getHeight()-20])},_onLinkClick:function(){new SYNO.SDS.MailClient.AppLib.MobileAppTipWindow({owner:SYNO.SDS.MailClient.Window}).open()},_onTipClose:function(){Ext.getCmp(this.checkboxId).getValue()&&SYNO.SDS.MailClient.UserSettingProperty.setNeedMobileAppTip(!1),this.destroy()}}),Ext.define("SYNO.SDS.MailClient.AppLib.MobileAppTipWindow",{extend:"SYNO.SDS.ModalWindow",constructor:function(t){var e={layout:"fit",height:377,width:526,resizable:!1,collapsible:!1,draggable:!1,closable:!0,cls:"mobile-tip-win",items:[{xtype:"container",cls:"wrap",html:this._getHtml()}]};this.callParent([Ext.apply(e,t)])},_getHtml:function(){var t=SYNO.SDS.MailClient._T("common","mobile_app_download")+String.format(SYNO.SDS.MailClient._T("common","mobile_app_download_web"),"https://archive.synology.com/download/Mobile/Android-DSmail");return'<div class="qr"></div><div class="title">'+SYNO.SDS.MailClient._T("common","mobile_app")+'</div><div class="desc">'+t+"</div>"}}),Ext.define("SYNO.SDS.MailClient.AppLib.DownloadTokenRunner",{extend:"Ext.util.TaskRunner",requires:["SYNO.SDS.MailClient.WebAPI"],singleton:!0,constructor:function(){this.callParent(arguments)},startTask:function(t){this.start({interval:t,run:function(){return SYNO.SDS.MailClient.WebAPI.send("getDownloadToken").then(function(t){t&&(SYNO.SDS.MailClient.Info.download_token=t.download_token,SYNO.SDS.MailClient.Control.Main.get("MessagePanel").refreshInlineImage(),this.refreshEditorImages())}.bind(this)).catch(function(t){SYNO.Debug.error(t)})}.bind(this)})},refreshEditorImages:function(){window.tinymce.editors.forEach(function(t){t.owner.refreshInlineImage()})}}),Ext.define("SYNO.SDS.MailClient.AppLib.Html5Uploader",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.UtilLib.Deferred","SYNO.SDS.MailClient.WebAPILib.AbortableWebAPI","SYNO.SDS.MailClient.WebAPI"],singleton:!0,upload:function(t,e){var i=this._buildFormData(t);return this._upload("SYNO.MailClient.Attachment","upload",6,i,e)},uploadBigSize:function(t,e){var i=this._buildFormData(t);return this._upload("SYNO.MailClient.Attachment","upload_big_size",6,i,e)},_buildFormData:function(t){var e=new window.FormData;return Ext.iterate(t,function(t,i,n){"[object Blob]"===i.toString()?e.append(t,i,i.name):e.append(t,i)}),e},_upload:function(t,e,i,n,a){var o,s=new SYNO.SDS.MailClient.UtilLib.Deferred;return o=SYNO.API.Request({timeout:18e5,api:t,method:e,version:i,html5upload:!0,uploadData:n,progress:a,callback:function(t,e,i,n){t?s.resolve(e):s.reject(e)}}),new SYNO.SDS.MailClient.WebAPILib.AbortableWebAPI(s,o)}}),Ext.define("SYNO.SDS.MailClient.AppLib.IdleDetector",{extend:"Ext.util.Observable",requires:[],singleton:!0,constructor:function(){this.callParent(arguments),this.idleInterval=1e4,this.addEvents("idle","active")},init:function(){this._monWindow(),this._initIdleTask()},_monWindow:function(){Ext.EventManager.addListener(window,"keyup",this._onWindowKeyUp,this),Ext.EventManager.addListener(window,"click",this._onWindowClick,this),Ext.EventManager.addListener(window,"mousemove",this._onWindowMouseMove,this),Ext.EventManager.addListener(window,"mousewheel",this._onWindowMouseWheel,this)},_munWindow:function(){Ext.EventManager.removeListener(window,"keyup",this._onWindowKeyUp,this),Ext.EventManager.removeListener(window,"click",this._onWindowClick,this),Ext.EventManager.removeListener(window,"mousemove",this._onWindowMouseMove,this),Ext.EventManager.removeListener(window,"mousewheel",this._onWindowMouseWheel,this)},_initIdleTask:function(){this.idleTask=new Ext.util.DelayedTask(function(){this._toIdleMode()}.bind(this)),this.idleTask.delay(this.idleInterval)},_onWindowKeyUp:function(){this._onUserMove()},_onWindowClick:function(){this._onUserMove()},_onWindowMouseMove:function(){this._onUserMove()},_onWindowMouseWheel:function(){this._onUserMove()},_onUserMove:function(){this._toActiveMode()},_toIdleMode:function(){this.isIdle()||(this.setIsIdle(!0),this.fireEvent("idle"))},_toActiveMode:function(){this.idleTask.delay(this.idleInterval),this.isIdle()&&(this.setIsIdle(!1),this.fireEvent("active"))},isIdle:function(){return this.__isIdle},setIsIdle:function(t){this.__isIdle=t}}),Ext.define("SYNO.SDS.MailClient.AppLib.Initiator",{extend:"Ext.Component",requires:["SYNO.SDS.MailClient.WebAPI","SYNO.SDS.MailClient.UserSettingProperty"],singleton:!0,getAppInfo:function(){var t=SYNO.SDS.MailClient.UserSettingProperty,e=t.getSettingInfo(),i=[];return i.push({apiType:"getInfoMail"}),SYNO.SDS.MailClient.Tool.isEmptyObject(e)&&i.push({apiType:"getInfoSetting"}),SYNO.SDS.MailClient.WebAPI.send(i,{mode:"parallel"}).then(function(i){return i.resp.result.forEach(function(i){if("SYNO.MailClient.Info"===i.api){if(!i.success)return void(410===SYNO.SDS.MailClient.Error.getErrorCode(i.error)&&this.waitForDatabaseReady());SYNO.SDS.MailClient.Info=SYNO.Util.copy(i.data)}if("SYNO.MailClient.Setting"===i.api){if(!i.success)return;t.setSettingInfo(i.data),e=SYNO.Util.copy(i.data)}}.bind(this)),this._applySettings(e),i}.bind(this)).catch(function(t){SYNO.Debug.error(t)})},getMailboxAndLabelInfo:function(){var t=SYNO.SDS.MailClient.UserSettingProperty,e=t.getPriorityMailboxSetting(),i=t.getMailboxList(),n=t.getLabelList(),a=[];return SYNO.SDS.MailClient.Tool.isEmptyObject(e)&&a.push({apiType:"getPriorityMailbox"}),SYNO.SDS.MailClient.Tool.isEmptyObject(i)&&a.push({apiType:"listMailbox",params:{subscription:!1,additional:["unread_count","draft_total_count"]}}),SYNO.SDS.MailClient.Tool.isEmptyObject(n)&&a.push({apiType:"listLabel",params:{additional:["unread_count"]}}),SYNO.SDS.MailClient.WebAPI.send(a,{mode:"parallel"}).then(function(a){a.resp.result.forEach(function(a){a.success&&("SYNO.MailClient.Setting.PriorityMailbox"===a.api&&(t.setPriorityMailboxSetting(a.data),e=SYNO.Util.copy(a.data)),"SYNO.MailClient.Mailbox"===a.api&&(t.setMailboxList(a.data),i=SYNO.Util.copy(a.data)),"SYNO.MailClient.Label"===a.api&&(t.setLabelList(a.data),n=SYNO.Util.copy(a.data)))}),SYNO.SDS.MailClient.Lib.PriorityMailbox.setSetting(e),SYNO.SDS.MailClient.Switch.getMailboxStore().loadData(i),SYNO.SDS.MailClient.Switch.getLabelStore().loadData(n)}.bind(this))},getAppData:function(){return SYNO.SDS.MailClient.WebAPI.send("getCompoundInfo").then(function(t){Ext.apply(SYNO.SDS.MailClient.Info,t.info),SYNO.SDS.MailClient.SMTP=t.smtp||{},SYNO.SDS.MailClient.PGPKey=t.pgp||{},SYNO.SDS.MailClient.PGP.Encryption.loadFromWebAPIResp(t.pgp),SYNO.SDS.MailClient.MailClientLab=t.mailclient_lab||{}})},getOtherAppData:function(){var t;return t=[{apiType:"getPersonalProfile",callback:function(t,e){t&&(SYNO.SDS.MailClient.PersonalProfile=e)}},{apiType:"listSearchHistory",callback:function(t,e){t&&SYNO.SDS.MailClient.Switch.getSearchHistoryStore().loadData(e)}},{apiType:"getUsageLimit",callback:function(t,e){t&&(SYNO.SDS.MailClient.Info.usage_limits=e.limit_list,SYNO.SDS.MailClient.Error.updateAPIErrorStringMap())},scope:this}],SYNO.SDS.MailClient.WebAPI.send(t,{mode:"parallel"})},getContact:function(){return Promise.all([SYNO.SDS.MailClient.Switch.getContactStore().promiseLoad(),SYNO.SDS.MailClient.Switch.getGroupStore().promiseLoad()]).then(function(){SYNO.SDS.MailClient.Switch.updateContactByGroupData()}).catch(function(t){SYNO.Debug.error(t)})},syncAA:function(){return SYNO.SDS.MailClient.WebAPI.send("syncSetting")},refreshCachedSetting:function(){return SYNO.SDS.MailClient.WebAPI.send("getInfoSetting").then(function(t){var e=SYNO.SDS.MailClient.UserSettingProperty,i=SYNO.SDS.MailClient.Control,n=e.getSettingInfo();SYNO.SDS.MailClient.Tool.isEqualObject(t,n)||(this._applySettings(t),t.general.split_pane_mode!==n.general.split_pane_mode&&i.View.syncCardPanel(),t.general.archive_mailbox!==n.general.archive_mailbox&&i.Sidebar.updateMailboxList(!0),t.general.theme!==n.general.theme&&SYNO.SDS.MailClient.AppLib.StyleLoader.loadThemeStyle(t.general.theme),i.Main.reloadContent(),e.setSettingInfo(t))}.bind(this))},refreshCachedData:function(){var t=[{apiType:"getPriorityMailbox"},{apiType:"listMailbox",params:{subscription:!1,additional:["unread_count","draft_total_count"]}},{apiType:"listLabel",params:{additional:["unread_count"]}}];return SYNO.SDS.MailClient.WebAPI.send(t,{mode:"parallel"}).then(function(t){this._processResp(t.resp.result)}.bind(this))},_processResp:function(t){var e=SYNO.SDS.MailClient.UserSettingProperty,i=SYNO.SDS.MailClient.Control,n=e.getPriorityMailboxSetting(),a=e.getMailboxList(),o=e.getLabelList();t.forEach(function(t){t.success&&("SYNO.MailClient.Setting.PriorityMailbox"===t.api&&(SYNO.SDS.MailClient.Tool.isEqualObject(t.data,n)||(e.setPriorityMailboxSetting(t.data),i.Sidebar.setPriorityMailboxSetting(t.data),t.data.enable_priority_mailbox!==n.enable_priority_mailbox&&i.Sidebar.updateMailboxList(!0))),"SYNO.MailClient.Mailbox"===t.api&&(SYNO.SDS.MailClient.Tool.isEqualObject(t.data,a)||(e.setMailboxList(t.data),SYNO.SDS.MailClient.Switch.getMailboxStore().loadData(t.data),i.Vault.markMailboxDirty(this._getDirtyIds(a.mailbox,t.data.mailbox)),i.Sidebar.updateMailboxList())),"SYNO.MailClient.Label"===t.api&&(SYNO.SDS.MailClient.Tool.isEqualObject(t.data,o)||(e.setLabelList(t.data),SYNO.SDS.MailClient.Switch.getLabelStore().loadData(t.data),i.Vault.markLabelDirty(this._getDirtyIds(o.label,t.data.label)),i.Sidebar.updateLabelList())))}.bind(this))},_applySettings:function(t){SYNO.SDS.MailClient.Tool.isEmptyObject(t)||(SYNO.SDS.MailClient.AdminSettings={},Ext.apply(SYNO.SDS.MailClient.AdminSettings,t.manual_config),Ext.apply(SYNO.SDS.MailClient.AdminSettings,{POP3:t.pop3,SharedMailbox:t.shared_mailbox,SharingLink:t.sharing_link,CustomLogo:t.custom_logo}),SYNO.SDS.MailClient.Switch.changeSettings(t.general),SYNO.SDS.MailClient.PGPSettings=t.pgp,SYNO.SDS.MailClient.AdminSettings.CustomLogo.is_custom?SYNO.SDS.MailClient.AppLib.StyleLoader.setLogo(SYNO.SDS.MailClient.Format.getCustomLogoDownloadUrl()):SYNO.SDS.MailClient.AppLib.StyleLoader.setLogo())},_getDirtyIds:function(t,e){var i=function(t){return t.id},n=t.map(i),a=e.map(i);return SYNO.SDS.MailClient.Array.without(a,n)},waitForDatabaseReady:function(){this._pollingTask=this._pollingTask||this.addTask({interval:6e3,scope:this,run:function(){SYNO.SDS.MailClient.WebAPI.send("getInfoMail").then(function(t){location.reload(!0)}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this))}}),this._pollingTask.start(!1)}}),Ext.define("SYNO.SDS.MailClient.AppLib.StyleLoader",{extend:"Ext.util.Observable",requires:[],singleton:!0,constructor:function(){this.callParent(arguments),this.styleVersion=null},load:function(){SYNO.SDS.MailClient.Define.isNormalMode&&(SYNO.SDS.MailClient.Format.isDSM6()&&this.loadDefaultDSMThemeStyle(),0!==SYNO.SDS.MailClient.Settings.theme&&this.loadThemeStyle(SYNO.SDS.MailClient.Settings.theme,!0),this.loadCustomStyle())},loadDefaultDSMThemeStyle:function(){this.loadStyle("default-dsm-theme","webman/3rdparty/MailClient/default-dsm-theme.css"+this.styleVersion,"mailclient")},loadThemeStyle:function(t,e){var i,n;switch(t){case 1:i="light";break;case 2:i="dark";break;default:i="style"}n="webman/3rdparty/MailClient/"+i+".css"+this.styleVersion,this.displayTheme=i,this.loadStyle("mailclient-temp",n).then(function(t){t.purgeAllListeners(),Ext.util.CSS.removeStyleSheet("mailclient"),t.dom.id="mailclient",e&&this._addRemovedStyleDetect()}.bind(this))},loadCustomStyle:function(){var t=document.getElementById("mailclient-custom"),e=t?"mailclient-custom-temp":"mailclient-custom",i=Ext.urlAppend("mailplus/custom.css","",!0);this.loadStyle(e,i).then(function(e){t&&(e.purgeAllListeners(),Ext.util.CSS.removeStyleSheet("mailclient-custom-temp"),e.dom.id="mailclient-custom")})},loadStyle:function(t,e,i){var n,a=document.getElementsByTagName("head")[0],o=document.createElement("link");o.id=t,o.rel="stylesheet",o.type="text/css",o.href=e;var s=document.getElementById(i);return s?a.insertBefore(o,s):a.appendChild(o),n=Ext.get(o),new Promise(function(t,e){n.on("load",function(){t(n)},{single:!0})})},findAndMarkMailClientStyleSheet:function(){var t,e,i=/MailClient\/style.css(.*?)$/,n=document.getElementsByTagName("head")[0],a=n.querySelectorAll('link[rel="stylesheet"]');for(t=0;t<a.length;++t)(e=i.exec(a[t].href))&&(a[t].id="mailclient",this.styleVersion=e[1])},_checkAndDeleteOldStyle:function(t){t.forEach(function(t){t.addedNodes.forEach(function(t){var e=/MailClient\/style.css(.*?)$/;"style"!==this.displayTheme&&"text/css"===t.type&&t.href&&e.exec(t.href)&&t.parentNode.removeChild(t)},this)},this)},_addRemovedStyleDetect:function(){new MutationObserver(this._checkAndDeleteOldStyle.bind(this)).observe(document.head,{childList:!0})},setLogo:function(t){SYNO.SDS.MailClient.Define.isNormalMode&&SYNO.SDS.MailClient.Control.Main.get("Window").setLogo(t)}}),Ext.define("SYNO.SDS.MailClient.AppLib.TodoPlugin",{extend:"Ext.util.Observable",requires:[],singleton:!0,appName:"SYNO.Cal.Todo.Plugin.Instance",launch:function(){if(this.isValid())return new Promise(function(t,e){SYNO.SDS.AppLaunch(this.appName,{from_syno_app_url:{app:"SYNO.SDS.MailClient.Application"}},null,function(){this._afterLaunch(),t()},this)}.bind(this))},_afterLaunch:function(){var t=SYNO.SDS.AppMgr.getByAppName(this.appName)[0].window;this._fixCompatibleApp(),t.el.setPositioning({top:"auto",left:"auto",bottom:"4px"}),SYNO.SDS.MailClient.Window.popOutWinManager.repositionTodoPlugin(),this.fixPos(),t.on("show",this.fixPos,this),t.on("expand",this.fixPos,this),t.on("collapse",this.fixPos,this),t.on("hide",this.fixPos,this)},_fixCompatibleApp:function(){var t=SYNO.SDS.MailClient.AppLib.Util.getAppVersion(this.appName);Ext.isNumber(t)&&t<10900&&(SYNO.Cal.Component.Todo.DateTime.Picker.prototype.minDate=Date.parseDate("1970-01-01","Y-m-d"),SYNO.Cal.Component.Todo.DateTime.Picker.prototype.maxDate=(new Date).add(Date.YEAR,100),SYNO.Cal.Component.Todo.DateTime.Field.prototype.isAllDay=!1)},isValid:function(){return SYNO.SDS.AppUtil.isValidApp("SYNO.Cal.Application")&&SYNO.SDS.MailClient.Define.isNormalMode},fixPos:function(){var t=SYNO.SDS.AppMgr.getByAppName(this.appName)[0].window;SYNO.SDS.MailClient.Window.popOutWinManager.shiftForTodoPlugin(t.isVisible(),t.getWidth())}}),Ext.define("SYNO.SDS.MailClient.AppLib.Util",{singleton:!0,getAppVersion:function(t){var e,i;if((e=SYNO.SDS.Config.FnMap[t])&&e.config&&Ext.isString(e.config.version)&&(i=e.config.version.match(/(.*)-(.*)/),Ext.isArray(i)&&i.length>2))return parseInt(i[2],10)}}),Ext.define("SYNO.SDS.MailClient.AppLib.VisibleDetector",{extend:"Ext.util.Observable",requires:[],singleton:!0,constructor:function(){this.callParent(arguments),this.checkInterval=1e3,this.addEvents("visible","invisible")},init:function(){this.initCheckTask()},initCheckTask:function(){this.checkTask=new Ext.util.DelayedTask(function(){var t=this.isWindowVisible();if(this.checkTask.delay(this.checkInterval),void 0===this.lastVisible)return void(this.lastVisible=t);t!==this.lastVisible&&(this.lastVisible=t,this.lastVisible?this.fireEvent("visible"):this.fireEvent("invisible"))}.bind(this)),this.checkTask.delay(this.checkInterval)},isWindowVisible:function(){return!this.isWindowHidden()},isWindowHidden:function(){var t=["webkit","moz","ms","o"];if("hidden"in document)return document.hidden;for(var e=0;e<t.length;e++)if(t[e]+"Hidden"in document)return document[t[e]+"Hidden"];return!1}}),Ext.define("SYNO.SDS.MailClient.AppLib.WindowOpener",{extend:"Ext.util.Observable",requires:[],singleton:!0,constructor:function(){this.callParent(arguments),this._calendarUrl=location.protocol+"//"+location.host,this.fetchAppURL()},openCalendar:function(t,e){this._openNewWindow(this.getCalendarUrl(),"SYNO.Cal.Application",t,e)},_openNewWindow:function(t,e,i,n){var a,o=n||"",s={launchParam:Ext.urlEncode(i)};a=Ext.urlAppend(t,Ext.urlEncode(s),!1)+o,window.open(a,"_blank","")},getCalendarUrl:function(){return this._calendarUrl},setCalendarUrl:function(t){this._calendarUrl=t},fetchAppURL:function(){return this._fetchApplicationInfo().then(this._parseApplicationInfo.bind(this))},_fetchApplicationInfo:function(){return new Promise(function(t,e){SYNO.API.Request({params:{is_app_portal:!!_S("rewriteApp")},api:"SYNO.Personal.Application.Info",method:"get",version:1,callback:function(i,n,a,o){!i||n&&n.has_fail?e(n):t(n)},scope:this})})},_parseApplicationInfo:function(t){t.applications.forEach(function(t){t.appname.indexOf("SYNO.Cal.Application")>-1&&!0!==_S("sharing")&&"SYNO.Cal.Application"!==_S("standaloneAppName")&&this.setCalendarUrl(t.launch_url)},this)}}),Ext.define("SYNO.SDS.MailClient.AppLib.Main",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.AppLib.ChatPlugin","SYNO.SDS.MailClient.AppLib.ContactsTip","SYNO.SDS.MailClient.AppLib.MobileAppTip","SYNO.SDS.MailClient.AppLib.DownloadTokenRunner","SYNO.SDS.MailClient.AppLib.Html5Uploader","SYNO.SDS.MailClient.AppLib.IdleDetector","SYNO.SDS.MailClient.AppLib.Initiator","SYNO.SDS.MailClient.AppLib.StyleLoader","SYNO.SDS.MailClient.AppLib.TodoPlugin","SYNO.SDS.MailClient.AppLib.Util","SYNO.SDS.MailClient.AppLib.VisibleDetector","SYNO.SDS.MailClient.AppLib.WindowOpener","SYNO.SDS.MailClient.UserSettingProperty"],singleton:!0}),Ext.define("SYNO.SDS.MailClient.PushServerLib.BackendSocket",{extend:"Ext.util.Observable",requires:["SYNOMailClientSocketIO"],mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{events:["index_done","filter_task","mailbox_index_done","read_change","smtp_change","contact_change","db_upgrade_done"]},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments),this.initEvents(),this.registerWindowEvent()},initEvents:function(){this.addEvents.apply(this,this.config.events)},createSocket:function(){var t=location.pathname.substr(0,location.pathname.lastIndexOf("/")+1)+"/MailClient/socket.io";_S("sharing")&&(t=t.replace("/sharing/","/")),this.socket=new SYNOMailClientSocketIO(location.protocol+"//"+location.host,{path:t,query:Ext.urlEncode({SynoToken:_S("SynoToken"),client:"browser",version_ui:SYNO.SDS.Config.FnMap["SYNO.SDS.MailClient.Application"].config.version}),reconnection:!0,reconnectionDelay:5e3,reconnectionDelayMax:15e3,randomizationFactor:.5}),this.bindSocket()},bindSocket:function(){var t=this.socket,e=this.onDisconnect.bind(this);this.config.events.forEach(function(t){var e=function(e){SYNO.Debug("[socket]",t,e),this.fireEvent(t,e)}.bind(this);this.socket.on(t,e)},this),t.on("connect",this.onConnect.bind(this)),t.on("disconnect",e),t.on("reconnect",this.onReconnect.bind(this)),t.on("reconnect_error",this.onReconnectError.bind(this)),t.on("reconnect_attempt",this.onReconnectAttempt.bind(this)),t.on("error",this.onError.bind(this)),window.addEventListener("beforeunload",function(){t.off("disconnect",e)})},info:function(t){this._log("info",t)},error:function(t){this._log("error",t)},_log:function(t,e){this.socket.emit("client."+t,e)},onConnect:function(){SYNO.SDS.MailClient.Control.View.hideToast(),SYNO.Debug("mail connect")},onDisconnect:function(){this._showOfflineToast(),SYNO.Debug.warn("mail disconnected, now="+new Date)},onReconnect:function(){SYNO.Debug.info("mail reconnect"),this.fireEvent("socket_reconnect")},onReconnectError:function(){this._showOfflineToast(),SYNO.Debug.warn("mail reconnect_error, now="+new Date)},onReconnectAttempt:function(){this._showReconnectingToast(),SYNO.Debug.info("mail reconnect attempt")},onError:function(t){SYNO.Debug.warn("socket error",t);try{t=JSON.parse(t)}catch(t){}t.code&&this.fireEvent("socket_error",t)},onReconnectFailed:function(){SYNO.Debug.error("mail reconnect failed")},getSocketId:function(){return this.socket.id},reconnect:function(){this.socket&&(this.socket.disconnect(),this.socket.connect())},registerWindowEvent:function(){var t=function(){!1===navigator.onLine?(SYNO.Debug("offline, now="+new Date),this._showOfflineToast(),setTimeout(function(){!1===navigator.onLine&&this.reconnect()}.bind(this),1e4)):this.socket.connected&&(SYNO.Debug("online"),SYNO.SDS.MailClient.Control.View.hideToast())}.bind(this);window.addEventListener("offline",t),window.addEventListener("online",t)},isOffline:function(){return!navigator.onLine||!this.socket.connected},_showOfflineToast:function(){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("common","no_internet"),[[SYNO.SDS.MailClient._T("common","reconnect"),function(){this.reconnect(),this._showReconnectingToast()},this]],!0)},_showReconnectingToast:function(){SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("common","no_internet_reconnecting"),[],!0)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.PushServerLib.IndexCollector",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Array"],constructor:function(t,e){this.callParent(arguments),this.indexDoneFn=t,this.delayTime=e,this.init()},init:function(){this.clear(),this.handleIndexDoneDelayTask=new Ext.util.DelayedTask(this._handleIndexDone,this)},_handleIndexDone:function(){this.indexDoneFn(this.collect())},add:function(t){t.mailbox_id&&this.mailbox_ids.push(t.mailbox_id),t.mailbox_ids&&(this.mailbox_ids=this.mailbox_ids.concat(t.mailbox_ids)),this.label_ids=this.label_ids.concat(t.label_ids),this.ids=this.ids.concat(t.ids),this.starred=this.starred||t.starred,this.handleIndexDoneDelayTask.delay(this.delayTime)},remove:function(t){var e=SYNO.SDS.MailClient.Array.without;this.mailbox_ids=e(this.mailbox_ids,t.mailbox_ids),this.label_ids=e(this.label_ids,t.label_ids),this.ids=e(this.ids,t.ids),this.starred=this.starred&&!t.starred},collect:function(){var t={mailbox_ids:Ext.unique(this.mailbox_ids),label_ids:Ext.unique(this.label_ids),ids:Ext.unique(this.ids),starred:this.starred};return this.clear(),t},clear:function(){this.mailbox_ids=[],this.label_ids=[],this.ids=[],this.starred=0}}),
Ext.define("SYNO.SDS.MailClient.PushServerLib.ReadChangeCollector",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Array"],constructor:function(t,e){this.callParent(arguments),this.doneFn=t,this.delayTime=e,this.init()},init:function(){this.clear(),this.handleDoneDelayTask=new Ext.util.DelayedTask(this._handleDone,this)},_handleDone:function(){this.doneFn(this.collect())},add:function(t){this.changes=this.changes.concat(t),this.handleDoneDelayTask.delay(this.delayTime)},remove:function(t){throw"not implemented yet"},collect:function(){var t=this.changes;return this.clear(),t},clear:function(){this.changes=[]}}),Ext.define("SYNO.SDS.MailClient.PushServerLib.Updater",{extend:"Ext.util.Observable",requires:[],mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],config:{},constructor:function(t){this.config=this.constructConfig(t),this.callParent(arguments),this.Vault=SYNO.SDS.MailClient.Control.Vault},onMailboxIndexDone:function(){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},update:function(t,e,i,n){return this._update(t,e,i,n)},immediatelyUpdate:function(t,e,i,n){return this._update(t,e,i,n,!0)},_update:function(t,e,i,n,a){return SYNO.SDS.MailClient.Control.Mail.checkNewMsg(n),SYNO.SDS.MailClient.Control.Sidebar.reloadMailSidebar(),this._updateThread(t,e,i,n,a)},_updateThread:function(t,e,i,n,a){var o=SYNO.SDS.MailClient.Control.Mail,s=SYNO.SDS.MailClient.disablePriorityMailboxUpdater,l=a||!SYNO.SDS.MailClient.enableMailDelayedUpdate;return SYNO.SDS.MailClient.Control.Vault.markDirty(t,e,i),this._refetch(t,e,i).then(function(){return o.isDisplayingAnyOf(t,e,i)?s&&o.isInPriorityMailbox()?Promise.resolve():l?o.updateMail():(o.setIsViewDirty(!0),Promise.resolve()):Promise.resolve()}.bind(this))},_refetch:function(t,e,i){return SYNO.SDS.MailClient.enableFetchNewMailThread?SYNO.SDS.MailClient.Control.Vault.refetchAll(t,e,i):SYNO.SDS.MailClient.Control.Vault.refetchDisplayingAndOftenOpened(t,e,i)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.PushServerLib.Main",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.Define","SYNO.SDS.MailClient.AppLib.IdleDetector","SYNO.SDS.MailClient.AppLib.VisibleDetector","SYNO.SDS.MailClient.PushServerLib.BackendSocket","SYNO.SDS.MailClient.PushServerLib.IndexCollector","SYNO.SDS.MailClient.PushServerLib.ReadChangeCollector","SYNO.SDS.MailClient.PushServerLib.Updater"],constructor:function(){this.callParent(arguments),this.IdleDetector=SYNO.SDS.MailClient.AppLib.IdleDetector,this.VisibleDetector=SYNO.SDS.MailClient.AppLib.VisibleDetector,this.backendSocket=new SYNO.SDS.MailClient.PushServerLib.BackendSocket,this.updater=new SYNO.SDS.MailClient.PushServerLib.Updater,this.indexCollector=new SYNO.SDS.MailClient.PushServerLib.IndexCollector(this.onIndexCollectorDone.bind(this),2e3),this.indexCollectorForWebAPI=new SYNO.SDS.MailClient.PushServerLib.IndexCollector(this.onIndexCollectorForWebAPIDone.bind(this),6e4),this.readChangeCollector=new SYNO.SDS.MailClient.PushServerLib.ReadChangeCollector(this.onReadChangeCollectorDone.bind(this),1e3),SYNO.SDS.MailClient.Define.isComposeMode||SYNO.SDS.MailClient.Define.isMessageMode||(this.backendSocket.on("index_done",this.onIndexDone,this),this.backendSocket.on("filter_task",this.onFilterTask,this),this.backendSocket.on("mailbox_index_done",this.onMailboxIndexDone,this,{buffer:1e3}),this.backendSocket.on("read_change",this.onReadChange,this),this.backendSocket.on("socket_reconnect",this.onSocketReconnect,this)),this.backendSocket.on("smtp_change",this.onSMTPChange,this),this.backendSocket.on("socket_error",this.onSocketError,this),this.backendSocket.on("contact_change",this.onContactChange,this),this.backendSocket.on("db_upgrade_done",this.onDbUpgradeDone,this),Ext.EventManager.addListener(window,"mousewheel",this.onMouseWheel,this),this.lastReloadTime=0},onIndexDone:function(t){var e=SYNO.SDS.MailClient.Settings.conversation_view?t.thread_view_info:t.message_view_info;t.is_from_webapi?this.indexCollectorForWebAPI.add(e):(this.indexCollectorForWebAPI.remove(e),this.indexCollector.add(e))},onIndexCollectorDone:function(t){this._handleIndexDone(t)},onIndexCollectorForWebAPIDone:function(t){this._handleIndexDone(t)},_handleIndexDone:function(t){this.IdleDetector.isIdle()&&!this.isDisableThreadUpdate()?this.updater.immediatelyUpdate(t.mailbox_ids,t.label_ids,t.starred,t.ids):this.updater.update(t.mailbox_ids,t.label_ids,t.starred,t.ids),SYNO.SDS.MailClient.WebAPI.send("getQuotaInfo").then(function(t){SYNO.SDS.MailClient.Info.quota_info=t,SYNO.SDS.MailClient.Control.Sidebar.updateQuotaInfo()}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this))},onMailboxIndexDone:function(t){this.updater.onMailboxIndexDone(t.mailbox_id)},onSocketReconnect:function(){SYNO.SDS.MailClient.Define.isPrintMode||(SYNO.SDS.MailClient.Lib.ThreadVault.markAllDirty(),SYNO.SDS.MailClient.Control.Sidebar.reloadMailSidebar(),this._reloadCurrentView())},onSocketError:function(t){var e,i,n,a=SYNO.SDS.WindowMgr.front;a.el.hasClass("syno-mc-composer-win")||(a=SYNO.SDS.MailClient.Window),e=Ext.getBody().mask(),i=a.getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t),this._reloadApp,this),n=e.dom.currentStyle||window.getComputedStyle(e.dom),i.el.setStyle("z-index",parseInt(n.zIndex,10)+2)},onVanishedMsg:function(t){var e=SYNO.SDS.MailClient.Control,i=t.mailbox_ids,n=t.label_ids,a=t.starred;e.Vault.markDirty(t.mailbox_ids,t.label_ids,t.starred),e.Sidebar.reloadMailSidebar(),e.Mail.isDisplayingAnyOf(i,n,a)&&e.Mail.silentReloadMail()},onReadChange:function(t){this.readChangeCollector.add(t.change)},onReadChangeCollectorDone:function(t){var e=SYNO.SDS.MailClient.ThreadLib.ThreadControlOperator,i=SYNO.SDS.MailClient.Settings.conversation_view,n={},a={},o=[],s=[];t.forEach(function(t,e){var o=i?t.thread_id:t.id,s=t.read?n:a,l=t.read?a:n;Ext.isArray(s[o])?s[o].push(t.id):s[o]=[t.id],l.hasOwnProperty(o)&&l[o].remove(t.id)}),Object.keys(n).forEach(function(t){Ext.isEmpty(n[t])||o.push([parseInt(t,10),n[t]])}),Object.keys(a).forEach(function(t){Ext.isEmpty(a[t])||s.push([parseInt(t,10),a[t]])}),e.markMessageRead(o,!0),e.markMessageRead(s,!1)},onSMTPChange:function(t){return SYNO.SDS.MailClient.WebAPI.send("listSMTP").then(function(t){SYNO.SDS.MailClient.SMTP=t}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this))},onContactChange:function(t){Promise.all([SYNO.SDS.MailClient.Switch.getContactStore().promiseLoad(),SYNO.SDS.MailClient.Switch.getGroupStore().promiseLoad()]).then(function(){SYNO.SDS.MailClient.Switch.updateContactByGroupData()}).catch(function(t){SYNO.Debug.error(t)})},onDbUpgradeDone:function(t){location.reload(!0)},_reloadCurrentView:function(){var t=+new Date;t-this.lastReloadTime>6e5&&(this.lastReloadTime=t,SYNO.SDS.MailClient.Control.Mail.silentReloadMail())},_reloadApp:function(){var t,e,i=window.tinymce.editors,n=[];for(t=0;t<i.length;t++)(e=i[t].owner)instanceof SYNO.SDS.MailClient.Editor.EditorPanel&&n.push(e.draftObj.save());return Promise.all(n).catch(function(t){SYNO.Debug.error(t)}).then(function(){location.reload(!0)})},onFilterTask:function(t){if(!SYNO.SDS.MailClient.Define.isMessageMode){var e=SYNO.SDS.MailClient.Settings.conversation_view?t.thread_view_info:t.message_view_info,i=Math.floor(Date.now()/1e3),n=SYNO.SDS.MailClient.Window;if(t.progress<0)return n.updateTaskIndicator(!1),void this.updater.immediatelyUpdate(e.mailbox_ids,e.label_ids,e.starred,[]);if(t.progress==t.total)return n.getMsgBox().isVisible()?(n.updateDialogProgress(t.progress,t.total),new Ext.util.DelayedTask(n.getMsgBox().hide,this).delay(500)):t.mailbox_delete_task?n.showToast(SYNO.SDS.MailClient._T("common","delete_mailbox_failed")):n.showToast(SYNO.SDS.MailClient._T("common","background_task_complete")),n.updateTaskIndicator(!1),void this.updater.immediatelyUpdate(e.mailbox_ids,e.label_ids,e.starred,[]).then(function(){var t=SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition"),e=SYNO.SDS.MailClient.Control.Mail.isInMessageView();t.isSearch()&&!e&&SYNO.SDS.MailClient.Control.Mail.search(t)}.bind(this));n.getMsgBox().isVisible()?n.updateDialogProgress(t.progress,t.total):n.updateTaskIndicator(!0,t.progress,t.total),(!Ext.isDefined(this.last_update_time)||i-this.last_update_time>5||t.progress===t.total)&&(this.updater.update(e.mailbox_ids,e.label_ids,e.starred,[]),this.last_update_time=i)}},info:function(t){this.backendSocket.info(t)},error:function(t){this.backendSocket.error(t)},monDetector:function(){this.IdleDetector.on({idle:this.onIdle,active:this.onActive,scope:this}),this.VisibleDetector.on({visible:this.onVisible,invisible:this.onInvisible,scope:this})},onIdle:function(){this.updateMailIfViewIsDirty()},onActive:function(){this.updateMailIfViewIsDirty()},onVisible:function(){this.updateMailIfViewIsDirty()},onInvisible:function(){this.updateMailIfViewIsDirty()},onMouseWheel:function(){this.updateMailIfViewIsDirty()},updateMailIfViewIsDirty:function(){if(SYNO.SDS.MailClient.enableMailDelayedUpdate){if(this.isDisableThreadUpdate())return;SYNO.SDS.MailClient.Control.Mail.updateMailIfViewIsDirty(!0)}},isDisableThreadUpdate:function(){var t=SYNO.SDS.MailClient.Control.Mail;return t.isInPriorityMailbox()&&t.isInMessageView()},isOffline:function(){return this.backendSocket.isOffline()},login:function(){this.backendSocket.createSocket()}}),Ext.define("SYNO.SDS.MailClient.Misc.Flags.Panel",{extend:"SYNO.SDS.Utils.FormPanel",constructor:function(t){var e=this.getCheckboxConfig(),i={height:400,items:[{xtype:"syno_displayfield",hideLabel:!0,value:"Custom Flags (refresh MailPlus page to apply those changes)"},{xtype:"syno_displayfield",fieldLabel:"thread vault memory",value:Math.floor(Ext.encode(SYNO.SDS.MailClient.Lib.ThreadVault).length/1024)+" KB"},{xtype:"syno_displayfield",fieldLabel:"message cache memory",value:Math.floor(Ext.encode(SYNO.SDS.MailClient.MessageLib.MsgCache).length/1024)+" KB"}].concat(e)};this.callParent([Ext.apply(i,t)])},getFlagsConfig:function(){return[["Enable debug log","enableDebugLog"],["Use thread vault","enableThreadVault"],["Don't update thread view immediately (to prevent thread view jumping)","enableMailDelayedUpdate"],["Fetch new mail threads for me","enableFetchNewMailThread"],["Fetch often opened mailbox/label for me (this is a subset of previous option)","enableFetchOftenOpenedThread"],["Don't auto update thread list in Priority Mailbox","disablePriorityMailboxUpdater"],["Enable advanced RFC Msg ID grouping (try not merging msgs with the same msg id)","enableAdvancedRfcMsgIdGrouping"]]},getFlags:function(){return this.getFlagsConfig().map(function(t){return t[1]})},resetToDefault:function(){this.getFlags().forEach(function(t){this._setUserSetting(t,void 0),this.getComponent(t).setValue(this._getUserSetting(t))},this)},getCheckboxConfig:function(){var t;return t=this.getFlagsConfig(),t.map(function(t){var e=t[0],i=t[1];return{xtype:"syno_checkbox",itemId:i,boxLabel:e,value:!0,handler:function(t,e){this._setUserSetting(i,e)}.bind(this),listeners:{afterrender:function(t){t.setValue(this._getUserSetting(i))}.bind(this)}}},this)},_getUserSetting:function(t){var e=this._getGetterName(t);return SYNO.SDS.MailClient.UserSettingProperty[e]()},_setUserSetting:function(t,e){var i=this._getSetterName(t);SYNO.SDS.MailClient.UserSettingProperty[i](e),SYNO.SDS.MailClient[t]=e},_capitalizeFirstLetter:function(t){return t.charAt(0).toUpperCase()+t.slice(1)},_getGetterName:function(t){return"get"+this._capitalizeFirstLetter(t)},_getSetterName:function(t){return"set"+this._capitalizeFirstLetter(t)},onApply:Ext.emptyFn}),Ext.define("SYNO.SDS.MailClient.Misc.Flags.Window",{extend:"SYNO.SDS.MailClient.ModalWindow",requires:["SYNO.SDS.MailClient.Misc.Flags.Panel"],constructor:function(t){this.flagsPanel=new SYNO.SDS.MailClient.Misc.Flags.Panel;var e={title:"Flags",items:this.flagsPanel,width:520,height:480,buttons:[{text:_T("common","reset"),scope:this,handler:this.onReset},{text:_T("common","ok"),btnStyle:"blue",scope:this,handler:this.onApply}]};this.callParent([Ext.apply(e,t)])},onReset:function(){this.flagsPanel.resetToDefault()},onApply:function(){this.close()}}),Ext.define("SYNO.SDS.MailClient.SearchScopeMenu",{extend:"SYNO.ux.Menu",constructor:function(t){var e={cls:"search-scope-menu",width:196,maxHeight:321,autoFlexcroll:!0,defaultType:"menucheckitem",defaults:{htmlEncode:!1},items:[{itemId:"all",text:SYNO.SDS.MailClient._T("search","all_mailboxes")}],listeners:{scope:this,beforeshow:this._onBeforeShow}};Ext.apply(e,t),this.callParent([e])},_getMenuItemTpl:function(){return this.encodedTpl||(this.encodedTpl=Ext.menu.Item.prototype.encodedTpl=new Ext.XTemplate('<a class="x-menu-list-item" hidefocus="true" unselectable="on" href="{href}" role="menuitem"','<tpl if="hrefTarget">',' target="{hrefTarget}"',"</tpl>",">",'<div id="{id}" class="{cls} x-unselectable" ext:qtip="{text}">','<img alt="{altText}" src="{icon}" class="x-menu-item-icon {iconCls}"/>','<span class="x-menu-item-text" ext:qtip="{text}">{text}</span>',"</div>","</a>"),this.menuItemTpl=this.encodedTpl),this.menuItemTpl},_onBeforeShow:function(t){this._regenItemList()},_addMenuItem:function(t,e,i,n){this.addItem({itemId:t,text:e,mailboxId:i,checked:n,itemTpl:this._getMenuItemTpl()})},_regenItemList:function(){var t=SYNO.SDS.MailClient.SearchLib.SyntaxParser;this.removeAll(!0),SYNO.SDS.MailClient.Control.Model.getMailboxJson().then(function(e){this._addMenuItem("all",SYNO.SDS.MailClient._T("search","all_mailboxes"),0,0===this.owner.getMailboxId()),this.addSeparator(),SYNO.SDS.MailClient.Format.parseMailboxResp(e,null,!0,!0,!0).forEach(function(t,e,i){this._addMenuItem(t.data.path,t.text,t.data.id,this.owner.getMailboxId()===t.data.id),t.data.id===SYNO.SDS.MailClient.Settings.archive_mailbox&&this.addSeparator()},this);var i=SYNO.SDS.MailClient.Format.parseOthersMailboxResp(e,null,!0,!1,!0);Ext.isEmpty(i)||this.addSeparator(),i.forEach(function(e,i,n){e.children.forEach(function(e,i,n){this._addMenuItem(e.data.path,t.getDisplayMailboxPath(SYNO.SDS.MailClient.Switch.getMailboxStore().getById(e.data.id)),e.data.id,this.owner.getMailboxId()===e.data.id)},this)},this),this.items.each(function(t){t.el.dom.qtip=t.text},this)}.bind(this)).catch(function(t){SYNO.Debug.error(t)})}}),Ext.define("SYNO.SDS.MailClient.SearchScopeButton",{extend:"SYNO.ux.Button",mailboxId:0,requires:["SYNO.SDS.MailClient.SearchScopeMenu"],constructor:function(t){var e={cls:"search-scope-btn",text:SYNO.SDS.MailClient._T("search","all"),hidden:!0,menu:new SYNO.SDS.MailClient.SearchScopeMenu({owner:this,defaultOffsets:[0,1]})};Ext.apply(e,t),this.callParent([e]),this.addEvents("change","menuitemclick"),this.mon(this.menu,"itemclick",this._onMenuItemClick,this)},_onMenuItemClick:function(t){this._setValue(t.mailboxId,t.text),this.fireEvent("menuitemclick",this.currentElementId)},getMailboxId:function(){return this.mailboxId},setValue:function(t){var e;return"starred"===t?void this._setValue(t,SYNO.SDS.MailClient._T("mailbox","starred")):0===t?void this._reset():(e=SYNO.SDS.MailClient.Switch.getMailboxStore().getById(t),void(e?this._setValue(t,SYNO.SDS.MailClient.Format.getMailboxText(e.data)):this._reset()))},_setValue:function(t,e){this.mailboxId=t,0===t&&(e=SYNO.SDS.MailClient._T("search","all")),this.setText(e),this.setTooltip(e)},_reset:function(){this._setValue(0,SYNO.SDS.MailClient._T("search","all"))}}),Ext.define("SYNO.SDS.MailClient.FilterPanel",{extend:"SYNO.ux.Panel",requires:["SYNO.SDS.MailClient.ActionPanel","SYNO.SDS.MailClient.ConditionPanel"],hasMsgBox:!1,constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this.action_panel,"createfilter",this.resetAll,this),this.mon(this.condition_panel,"reset",this._onConditionReset,this),this.mon(this.condition_panel,"mailboxchange",this._onMailboxChange,this),this.addEvents("reset","mailboxchange")},fillConfig:function(t){var e={width:618,height:474,layout:"card",cls:"syno-mc-advanced-search-panel syno-mc-modal-window",floating:!0,border:!1,useGradient:!1,autoFlexcroll:!1,activeItem:0,items:[this.condition_panel=new SYNO.SDS.MailClient.ConditionPanel({owner:this,itemId:"condition"}),this.action_panel=new SYNO.SDS.MailClient.ActionPanel({owner:this,itemId:"action"})],listeners:{scope:this,beforehide:this._saveAdvanceCondition}};return Ext.apply(e,t),e},hasDropDown:function(){return this.condition_panel.hasDropDown()||this.action_panel.hasDropDown()||this.hasMsgBox},switchPanel:function(t){this.layout.setActiveItem(t)},resetAll:function(){this.action_panel.resetPanel(),this.condition_panel.resetPanel(),this.switchPanel("condition"),this.hide()},_onConditionReset:function(t){this.action_panel.resetPanel(),this.fireEvent("reset",t)},_onMailboxChange:function(t,e){this.fireEvent("mailboxchange",t)},setConditions:function(t,e){this.condition_panel.setConditions(t,e)},_saveAdvanceCondition:function(){this.isVisible()&&(this.conditions=this.condition_panel.getConditions(!0))},alertMessage:function(t,e,i){this.hasMsgBox=!0,SYNO.SDS.MailClient.Window.getMsgBox().alert("",t,function(){this.hasMsgBox=!1,e&&e.call(i)},this)}}),Ext.define("SYNO.SDS.MailClient.MailboxButton",{extend:"SYNO.SDS.MailClient.TreeMenuButton",requires:["SYNO.SDS.MailClient.Search.SearchMailboxMenu"],xtype:"syno_mc_mailbox_button",htmlEncode:!1,constructor:function(t){var e,i={};t.hasOwnProperty("menuCfg")&&(i=t.menuCfg,delete t.menuCfg),e={text:t.text||SYNO.SDS.MailClient._T("search","all_mailboxes"),currentElementId:t.currentMailboxId||0,menu:new SYNO.SDS.MailClient.Search.SearchMailboxMenu(Ext.apply({ownerBtn:this},i))},Ext.apply(e,t),this.callParent([e])},getMailboxId:function(){return this.getCurrentElementId()},getMailBoxName:function(){return this.getCurrentElementName()}}),Ext.define("SYNO.SDS.MailClient.SearchLib.SyntaxParser",{extend:"Object",singleton:!0,requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.SearchLib.PegjsParser"],constructor:function(){this.parser=SYNO.SDS.MailClient.SearchLib.PegjsParser},parse:function(t){try{return this.parser.parse(this._preProcess(t))}catch(t){return!1}},tokenlize:function(t){return t.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)},_preProcess:function(t){var e=this.tokenlize(t);return e?(e=e.map(function(t){return'"'===t[0]?t:(t=t.replace(/(in:|label:|from:|to:|subject:|larger:|smaller:|before:|after:|filename:)/g,function(e){return e.length===t.length?t:e+" "}),-1===t.indexOf(' "')&&(t=t.replace(/\(/g," ( "),t=t.replace(/\)/g," ) "),t=t.replace(/ -/g," NOT ")),0===t.indexOf("-")&&(t=t.replace(/^-/," NOT ")),t)}),e.join(" ")):""},_traverse:function(t,e,i){var n=!1;e=e||Ext.emptyFn;var a=function(t,o,s){if(t&&!n)return t.operator&&("UnaryExpression"===t.type?-1===t.operator.indexOf(":")?a(t.left,o,!0):o||a(t.left,t.operator,s):(a(t.left,o,s),a(t.right,o,s))),!1===e.call(i,t,o,s)?void(n=!0):void 0};a(t.expression,"")},toCondition:function(t){var e=this.parse(t),i=new SYNO.SDS.MailClient.Condition,n=!0,a=["from:","to:","subject:"];return e?(this._traverse(e,function(t,e,o){if(t.operator){if("OR"===t.operator||"NOT"===t.operator&&""!==e&&-1===a.indexOf(e))return n=!1,!1}else this._addNodeToCondition(i,e,o,t)},this),n?i:new SYNO.SDS.MailClient.Condition("keyword",t)):new SYNO.SDS.MailClient.Condition("keyword",t)},getRelatedMailbox:function(t){var e=this.parse(t),i=[];if(!e)return i;var n=function(t,e){t.operator||"in:"!==e||i.push(t.value)};return this._traverse(e,n,this),i},getDisplayMailboxPath:function(t){var e=t.get("path"),i=[];return t.get("is_own")?e.replace(/\./g,"/"):(i=e.split("."),i[0]="~",i[1]=i[1].replace(/\//g,"."),i.join("/"))},getRealMailboxPath:function(t){var e=[];return 0===t.indexOf("~/")&&(e=t.split("/"),e.length>=3&&"~"==e[0])?(e[0]="synology_internal_shared_namespace",e[1]=e[1].replace(/\./g,"/"),e.join(".")):t.replace(/\//g,".")},_addNodeToCondition:function(t,e,i,n){var a=n.value;switch(-1!=n.value.indexOf(" ")&&(a='"'+a+'"'),e){case"in:":t.addCondition("mailbox",this.getRealMailboxPath(n.value));break;case"label:":t.addCondition("label",n.value);break;case"from:":t.addCondition("from",a,i);break;case"to:":t.addCondition("to",a,i);break;case"subject:":t.addCondition("subject",a,i);break;case"larger:":t.addCondition("larger",1048576*parseInt(n.value,10));break;case"smaller:":t.addCondition("smaller",1048576*parseInt(n.value,10));break;case"before:":Date.parseDate(n.value,"Y/m/d")&&t.addCondition("before",n.value);break;case"after:":Date.parseDate(n.value,"Y/m/d")&&t.addCondition("after",n.value);break;case"filename:":t.addCondition("keyword","filename:"+a);break;default:Ext.isEmpty(e)&&("is:starred"===n.value?t.addCondition("starred",!0):"has:attachment"===n.value?t.addCondition("has_attachment",!0):"is:unread"===n.value?t.addCondition("unread",!0):t.addCondition("keyword",a,i))}}}),Ext.define("SYNO.SDS.MailClient.Switch",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.Model.Main","SYNO.SDS.MailClient.SearchLib.SyntaxParser","SYNO.SDS.MailClient.Model.PagingMemoryProxy"],currentStatus:"mail",singleton:!0,constructor:function(t){this.current={offset:0,limit:100,showSearchingToast:!1,lastThreadCondition:new SYNO.SDS.MailClient.Condition,lastMatchedIds:[],lastSplitKeyword:""},this.mailboxStore=this.getMailboxStore(),this.labelStore=this.getLabelStore(),this.groupStore=this.getGroupStore(),this.searchHistoryStore=this.getSearchHistoryStore(),this.autoCompleteMemProxy=this.getAutoCompleteMemProxy(),this.autoCompleteData=[],this.callParent([t]),this.addEvents("externalSourceClickSync","editorcontentmousedown","cardwidthchange","settingchange","offsetchange","pgpkeychange"),this.inStar=this.inSearch=this.inLabel=this.inMailbox=!1},copy:function(t){this.current=SYNO.Util.copy(t.current),this.current.lastThreadCondition=new SYNO.SDS.MailClient.Condition(t.current.lastThreadCondition),Ext.copyTo(this,t,"inMailbox,inLabel,inSearch,inStar,inLabelId,inMailboxId")},register:function(t,e){Ext.isObject(t)?(Ext.apply(this.current,t),t.hasOwnProperty("lastThreadCondition")&&this.parseThreadConditionByObject(t.lastThreadCondition)):Ext.isString(t)&&(this.current[t]=e,"lastThreadCondition"===t&&this.parseThreadConditionByObject(e))},deleteRegister:function(t){Ext.isDefined(this.current[t])&&delete this.current[t]},parseThreadConditionByObject:function(t){var e=t.get();this.parseThreadCondition(e,!0)},parseThreadConditionInPriority:function(t){this.parseThreadCondition(t,!1)},parseThreadCondition:function(t,e){var i,n=SYNO.SDS.MailClient.SearchLib.SyntaxParser;for(this.inStar=this.inSearch=this.inLabel=this.inMailbox=!1,e&&(this.inPriority=!1),this.inMailboxId=0,this.syntaxMailboxes=[],i=0;i<t.length;++i)"mailbox"===t[i].name&&(this.inMailboxId=t[i].value),"keyword"===t[i].name&&(this.syntaxMailboxes=this.syntaxMailboxes.concat(n.getRelatedMailbox(t[i].value)));1===this.syntaxMailboxes.length&&0===this.inMailboxId&&(this.inMailboxId=SYNO.SDS.MailClient.Format.mailboxPathToId(this.syntaxMailboxes[0])),!Ext.isArray(t)||t.length>1?this.inSearch=!0:"mailbox"===t[0].name?this.inMailbox=!0:"priority"===t[0].name?this.inSearch=this.inPriority=!0:"starred"===t[0].name?this.inSearch=this.inStar=!0:"label"===t[0].name?(this.inLabel=!0,this.inLabelId=t[0].value):this.inSearch=!0},getRegister:function(t){return this.current[t]},getCurrentThreadStore:function(){return SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore()},getCurrentThreadRecord:function(t){return this.getCurrentThreadStore().getById(t)},loadMessageByIdxDiff:function(t,e){SYNO.SDS.MailClient.Lib.Thread.getCurrentThreadStore().loadByThreadIdShift(t,e).then(function(t){t&&SYNO.SDS.MailClient.Control.Mail.loadMessage(t)})},editorContentMouseDown:function(t){this.fireEvent("editorcontentmousedown",t)},getMailboxStore:function(){return this.mailboxStore=this.mailboxStore||new SYNO.SDS.MailClient.Model.MailboxStore,this.mailboxStore},getLabelStore:function(){return this.labelStore=this.labelStore||new SYNO.SDS.MailClient.Model.LabelStore,this.labelStore},getGroupStore:function(){return this.groupStore=this.groupStore||new SYNO.SDS.MailClient.Model.GroupStore,this.groupStore},getSearchHistoryStore:function(){return this.searchHistoryStore=this.searchHistoryStore||new SYNO.SDS.MailClient.Model.SearchHistoryStore,this.searchHistoryStore},cardWidthChange:function(t,e){this.fireEvent("cardwidthchange",e)},changeSettings:function(t){var e=SYNO.SDS.MailClient.Define;SYNO.SDS.MailClient.Settings=t,e.isMessageMode&&(SYNO.SDS.MailClient.Settings.conversation_view=1===e.launchParam.cv),this.current.limit=t.conversations_per_page,this.fireEvent("settingchange",t)},getContactStore:function(){return this.contactStore=this.contactStore||this.createContactStore(),this.contactStore},createContactStore:function(){return new SYNO.SDS.MailClient.Model.ContactStore({listeners:{load:function(){this.updateContactByGroupData()},scope:this}})},updateContactByGroupData:function(){var t,e=SYNO.SDS.MailClient.Control.Model,i={};return e.getGroupJson().then(function(e){t=e}).then(e.getContactJson.bind(e)).then(function(e){this.contactByGroupData={},Ext.each(t,function(t){this.contactByGroupData[t.id]=[],"ou"===t.type&&(i[t.id]=t.member)},this),Ext.each(e,function(t){var e;Ext.isEmpty(t.additional.extra_info.mail)||(e="addressbook_"+t.addressbook_id,Ext.isDefined(this.contactByGroupData[e])&&this.contactByGroupData[e].push(t),t.additional.label.forEach(function(i){e="label_"+i.id,Ext.isDefined(this.contactByGroupData[e])&&this.contactByGroupData[e].push(t)},this),Object.keys(i).forEach(function(e){-1!==i[e].indexOf(t.id)&&this.contactByGroupData[e].push(t)},this))},this),this.updateAutoCompleteMemProxy()}.bind(this))},getContactByGroupData:function(t){return Ext.isEmpty(this.contactByGroupData)?[]:this.contactByGroupData[t]},hasEmailInContact:function(t){var e=t.toLowerCase();return this.contactStore.findBy(function(t,i){return!!(t.get("additional")&&t.get("additional").extra_info&&t.get("additional").extra_info.mail)&&t.get("additional").extra_info.mail.some(function(t){return t.toLowerCase()===e})})>-1},updateDocumentTitle:function(){var t,e,i=SYNO.SDS.MailClient,n=i.Define,a="",o="{0} - {1}",s=SYNO.SDS.MailClient._T("common","displayname");if(n.isComposeMode)a=i._T("common","compose");else if(n.isMessageMode||n.isPrintMode){if(!(t=SYNO.SDS.MailClient.Lib.Thread.store.getAt(0)))return;a=i.Format.templateSubjectFromMessageDraft(t.get("message"),t.get("draft"),!0)}else if(this.inStar)a=i._T("mailbox",n.starredId);else if(this.inPriority)a=i._T("priority_mailbox","priority_mailbox_title"),(e=SYNO.SDS.MailClient.Lib.PriorityMailbox.getUnreadCount())&&(o="{0} ("+e+") - {1}");else if(this.inSearch)a=i._T("search","search_result");else{if(!(t=this.inMailbox?this.mailboxStore.getById(this.inMailboxId):this.labelStore.getById(this.inLabelId)))return;a=n.getSystemMailboxNameString(t.data.name)||t.data.name,e=t.data.additional.hasOwnProperty("total_count")?t.data.additional.total_count:t.data.additional.unread_count,e&&(o="{0} ("+e+") - {1}")}document.title=String.format(o,a,s).trim()},offsetChange:function(t,e){this.current.offset=t,this.fireEvent("offsetchange",t,e)},PGPKeyChange:function(){this.fireEvent("pgpkeychange")},getAutoCompleteMemProxy:function(){return this.autoCompleteMemProxy=this.autoCompleteMemProxy||new SYNO.SDS.MailClient.Model.PagingMemoryProxy(this.getAutoCompleteData()),this.autoCompleteMemProxy},updateAutoCompleteMemProxy:function(){this.getAutoCompleteMemProxy().setData(this.getAutoCompleteData())},getAutoCompleteData:function(){var t={},e=[];return this.getContactStore().each(function(i){if(Ext.isEmpty(i.data.additional.extra_info.mail))return!0;i.data.additional.extra_info.mail.forEach(function(n,a,o){var s,l,r,d={};s=SYNO.SDS.MailClient.Format.composeNameAddr(i.data.full_name,n),t.hasOwnProperty(s)||(d.id="contact_"+s+"_"+(i.data.primary_mail==n?"p":"np"),d.type="contact",l=i.data.additional.extra_info.nick_name?String.format("{0} ({1})",i.data.full_name,i.data.additional.extra_info.nick_name):i.data.full_name,r=SYNO.SDS.MailClient.Format.composeNameAddr(l,n),d.mail_for_search=n,d.address_value=s,t[s]=!0,d.name_with_nickname=l,d.search_field=r,d.combobox_display=r,d.combobox_display_encode=Ext.util.Format.htmlEncode(d.combobox_display),d.address_encode=Ext.util.Format.htmlEncode(d.address_value),d.address_display=SYNO.SDS.MailClient.Editor.SuperBoxSelect.toAddressDisplay(d.address_encode),e.push(d))},this)},this),Ext.each(this.getGroupStore().getRange(),function(t){var i={};i.id=t.data.id,i.type=t.data.type,i.search_field=t.data.name,i.combobox_display=i.search_field,i.combobox_display_encode=Ext.util.Format.htmlEncode(i.combobox_display),i.members=SYNO.SDS.MailClient.Switch.getContactByGroupData(t.id),i.members.length>0&&e.push(i)},this),{contact:e}}}),Ext.define("SYNO.SDS.MailClient.SearchLib.SearchAdvisor",{extend:"Object",requires:["SYNO.SDS.MailClient.Switch"],singleton:!0,constructor:function(){this.callParent(arguments),this._initStore()},_initStore:function(){this.historyStore=SYNO.SDS.MailClient.Switch.getSearchHistoryStore(),this.addressStroe=new Ext.data.JsonStore({autoDestroy:!0,fields:["id","value","name","search_value"]}),this.mailboxStore=new Ext.data.JsonStore({autoDestroy:!0,fields:["id","path","is_own"]}),this.labelStore=new Ext.data.JsonStore({autoDestroy:!0,fields:["id","name"]}),this.syntaxStore=new Ext.data.ArrayStore({fields:["value"],data:[["from:"],["to:"],["subject:"],["in:"],["label:"],["larger:"],["smaller:"],["before:"],["after:"],["filename:"],["has:attachment"],["is:unread"],["is:starred"]]})},updateAddressStroe:function(){var t=[];SYNO.SDS.MailClient.Switch.getContactStore().each(function(e){if(Ext.isEmpty(e.data.additional.extra_info.mail))return!0;e.data.additional.extra_info.mail.forEach(function(i,n,a){var o="contact_"+i,s=e.data.additional.extra_info.nick_name?String.format("{0} ({1})",e.data.full_name,e.data.additional.extra_info.nick_name):e.data.full_name,l=SYNO.SDS.MailClient.Format.composeNameAddr(s,i);t.push({id:o,name:s,value:i,search_value:l})},this)},this),this.addressStroe.loadData(t)},updateMailboxStore:function(){var t=[],e=SYNO.SDS.MailClient.SearchLib.SyntaxParser;SYNO.SDS.MailClient.Switch.getMailboxStore().each(function(i){t.push({id:i.get("id"),path:e.getDisplayMailboxPath(i),is_own:i.get("is_own")})},this),this.mailboxStore.loadData(t)},updateLabelStore:function(){var t=[];SYNO.SDS.MailClient.Switch.getLabelStore().each(function(e){t.push({id:e.get("id"),name:e.get("full_name")})},this),this.labelStore.loadData(t)},_parseDisplayPart:function(t,e,i){var n=Ext.isString(i)?i:"display",a={},o=e.toLowerCase().indexOf(t.toLowerCase());return a[n]="",a[n+"_match"]="",a[n+"_last"]="",o<0||Ext.isEmpty(t.trim())?(a[n]=e,a):(a[n]=e.substring(0,o),a[n+"_match"]=e.substr(o,t.length),a[n+"_last"]=e.substring(o+t.length),a)},_getHistoryQueryData:function(t){var e=[],i=Ext.isEmpty(t.trim())?5:2;return this.historyStore.filter("content",t.trim(),!0),this.historyStore.getRange(0,i-1).forEach(function(i,n,a){var o={id:"history_"+i.get("id"),value:i.get("content"),display:i.get("content"),type:"history",original_id:i.get("id")};Ext.apply(o,this._parseDisplayPart(t,i.get("content"))),e.push(o)},this),e},_getAddressSyntaxHint:function(t,e){return"from:"==t.syntax||"to:"==t.syntax?t.syntax:e===SYNO.SDS.MailClient.Define.sentId?"to:":"from:"},_getAddressQueryData:function(t,e,i){var n=[];return!1===e||"from:"!=e.syntax&&"to:"!=e.syntax||(t=e.query),this.addressStroe.filter("search_value",t.trim(),!0),this.addressStroe.getRange(0,1).forEach(function(a,o,s){var l={id:a.get("id"),value:a.get("value"),display:a.get("search_value"),type:"address",hint:this._getAddressSyntaxHint(e,i)};Ext.apply(l,this._parseDisplayPart(t,a.get("name"))),Ext.apply(l,this._parseDisplayPart(t,a.get("value"),"hint_value")),n.push(l)},this),n},_getMailboxQueryData:function(t){var e,i=[],n=SYNO.SDS.MailClient.Define,a=SYNO.SDS.MailClient.Format;return!1===t||"in:"!=t.syntax?[]:(e=t.query,this.mailboxStore.filter("path",e,!0),
this.mailboxStore.getRange(0,0).forEach(function(t,o,s){var l=t.get("path"),r=n.isSystemMailboxName(l)&&"enu"!==_S("lang")?" - "+n.getSystemMailboxNameString(l):"",d={id:"mailbox_"+t.get("id"),value:l.search(/\s|"|\(|\)/g)>=0?a.quote(l):l,display:l+r,type:"mailbox"};Ext.apply(d,this._parseDisplayPart(e,d.display)),i.push(d)},this),i)},_getLabelQueryData:function(t){var e,i=[],n=SYNO.SDS.MailClient.Format;return!1===t||"label:"!=t.syntax?[]:(e=t.query,this.labelStore.filter("name",e,!0),this.labelStore.getRange(0,0).forEach(function(t,a,o){var s=t.get("name"),l={id:"label_"+t.get("id"),value:s.search(/\s|"|\(|\)/g)>=0?n.quote(s):s,display:s,type:"label"};Ext.apply(l,this._parseDisplayPart(e,t.get("name"))),i.push(l)},this),i)},_getSyntaxQueryData:function(t){var e=[];return this.syntaxStore.filter("value",t.trim()),this.syntaxStore.getRange(0,0).forEach(function(i,n,a){if(t.trim()!=i.get("value")){var o={id:"syntax_"+i.get("id"),value:i.get("value"),display:i.get("value"),type:"syntax"};Ext.apply(o,this._parseDisplayPart(t,i.get("value"))),e.push(o)}},this),e},get:function(t,e,i){var n,a,o=this._getHistoryQueryData(t);return Ext.isEmpty(t.trim())||(n=this._getSyntaxQueryData(t),a="in:"===e.syntax?this._getMailboxQueryData(e):"label:"===e.syntax?this._getLabelQueryData(e):this._getAddressQueryData(t,e,i),o.length&&a.length&&(a[0].is_first=!0),(o.length||a.length)&&n.length&&(n[0].is_first=!0),o=o.concat(a,n)),o}}),Ext.define("SYNO.SDS.MailClient.Search.MailSearchField",{extend:"SYNO.ux.ComboBox",xtype:"mc_MailSearchField",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.MailClient.FilterPanel","SYNO.SDS.MailClient.MailboxButton","SYNO.SDS.MailClient.SearchLib.SearchAdvisor"],constructor:function(t){this.SearchAdvisor=SYNO.SDS.MailClient.SearchLib.SearchAdvisor,this.callParent([this.fillConfig(t)]),this.addClass("syno-mc-searchfield"),this.mon(SYNO.SDS.MailClient.Switch,"editorcontentmousedown",function(){this.searchPanel&&!this.searchPanel.hasDropDown()&&this.searchPanel.hide()},this),SYNO.SDS.MailClient.Window.regShortCut(this,SYNO.SDS.MailClient.KeyNavigator.ShortCut.SEARCH),this.on("afterrender",this.onSearchFieldAfterRender,this),this.mon(SYNO.SDS.MailClient.Window.el,"mousedown",this.onDocMouseDown,this)},fillConfig:function(t){this.store=new Ext.data.JsonStore({autoDestroy:!0,fields:["id","value","display","display_match","display_last","type","original_id","is_first","hint","hint_value","hint_value_match","hint_value_last"]});var e={store:this.store,cls:"syno-mc-history-combo",editable:!0,lazyInit:!1,enableKeyEvents:!0,autoSelect:!1,hideTrigger:!1,typeAhead:!0,displayField:"display",tpl:this.getTpl(),minChars:0,typeAheadDelay:10,emptyText:null,width:618,minListWidth:618,listeners:{scope:this,focus:this._onSearchFieldFocus,resize:this.onSearchFieldResize,beforequery:this.onSearchFieldBeforeQuery,select:this.onSearchFieldSelect,collapse:this.onListCollapse,keydown:this.onSearchFieldKeyDown,destroy:this.onSearchFieldDestroy}};return Ext.apply(e,t),e},onRender:function(t,e){this.callParent(arguments),this.wrap.addClass("syno-mc-history-combo-wrap"),this.typeAhead&&(this.hintInput=this.el.insertSibling({tag:"input",cls:"typeahead-hint",autocomplete:Ext.isChrome?"false":"off"},"before")),this.searchIcon=this.wrap.createChild({tag:"span",cls:"syno-mc-search-icon",children:[{tag:"span",cls:"icon"}]},this.el),this.listAlign=["tl-bl?",[0-this.searchIcon.getWidth(),0]],Ext.isGecko&&this.el.dom.addEventListener("input",this.onSearchFieldInput.bind(this))},_onSearchFieldFocus:function(){this.onSearchFieldClick(),this.focusSearchField()},focusSearchField:function(){this.setWidth(618),this.owner.setFocus()},blurSearchField:function(){this.setWidth(618),this.owner.setBlur()},onSearchFieldResize:function(t,e){var i=this.getTriggerWidth()+41;Ext.isNumber(e)&&this.el.setWidth(e-i),this.el.getWidth()&&this.wrap.setWidth(this.el.getWidth()+i),this.hintInput.setWidth(this.el.getWidth())},onListCollapse:function(t){this.clearHintText()},onMouseover:function(){this.callParent(arguments),this.wrap.addClass("syno-mc-history-combo-wrap-hover")},onMouseout:function(){this.callParent(arguments),this.wrap.removeClass("syno-mc-history-combo-wrap-hover")},onTriggerClick:function(){this.showSearchPanel()},applyEmptyText:function(){this.callParent(arguments),this.el.hasClass(this.emptyClass)&&this.clearHintText()},getLastSyntaxQuery:function(t){var e,i,n,a,o={syntax:"",query:""},s=["from:","to:","in:","label:"];return!Ext.isEmpty(t.trim())&&" "!==t.charAt(t.length-1)&&(!!(e=SYNO.SDS.MailClient.SearchLib.SyntaxParser.tokenlize(t.trim()))&&(i=e.pop(),-1!==s.indexOf(i)?(o.syntax=i,o):(a=s.some(function(t,e){if(0===i.search(t))return o.syntax=t,o.query=i.substr(t.length),!0},this),a?o:!(!e.length||(n=e.pop(),-1===s.indexOf(n)))&&(o.syntax=n,o.query=i,o))))},onTypeAhead:function(){var t,e,i,n=this.getRawValue(),a="",o=SYNO.SDS.MailClient.Define;Ext.isEmpty(n.trim())||(i=this.getLastSyntaxQuery(n),i&&"in:"===i.syntax&&this.scopeBtn.getMailboxId()!==o.starredId&&this.scopeBtn.setValue(0),this.store.getCount()>0&&(t=this.store.getAt(0).get("value"),e=this.store.getAt(0).get("type"),0===t.indexOf(n)&&"mailbox"!==e&&"label"!==e?a=t:i&&0===t.indexOf(i.query)&&"history"!==e&&"syntax"!==e&&(a=n.substring(0,n.lastIndexOf(i.query))+t)),this.setHintText(a))},onViewClick:function(t){if(4==arguments.length&&arguments[3].getTarget(".btn-del"))return void this.onHistoryDelete(this.view.getSelectedIndexes()[0]);this.callParent(arguments),Ext.isEmpty(this.view.getSelectedIndexes())&&this.doSearch()},onSearchFieldAfterRender:function(t){this.mon(SYNO.SDS.MailClient.Switch.getContactStore(),"datachanged",function(){this.SearchAdvisor.updateAddressStroe()},this),this.mon(SYNO.SDS.MailClient.Switch.getMailboxStore(),"datachanged",function(){this.SearchAdvisor.updateMailboxStore()},this),this.mon(SYNO.SDS.MailClient.Switch.getLabelStore(),"datachanged",function(){this.SearchAdvisor.updateLabelStore()},this),this.el.on("click",this.onSearchFieldClick,this),this.list.addClass("syno-mc-history-combo-list"),this.keyNav.tab=function(){return!0}},onSearchFieldBeforeQuery:function(t){this.updateStore(t.query),t.forceAll=!0},updateStore:function(t){var e=this.getLastSyntaxQuery(t);this.store.loadData(this.SearchAdvisor.get(t,e,this.scopeBtn.getMailboxId()))},onLoad:function(){this.hasFocus&&(this.store.getCount()>0||this.listEmptyText?(this.expand(),this.restrictHeight(),this.lastQuery==this.allQuery?(this.editable,!1===this.autoSelect||this.selectByValue(this.value,!0)||this.select(0,!0)):!1!==this.autoSelect&&this.selectNext()):this.collapse(),this.typeAhead&&this.taTask.delay(this.typeAheadDelay))},updateConditionAfterThreadStoreLoad:function(t,e){this.mon(t,"load",function(){var t=new SYNO.SDS.MailClient.Condition(t);this.updateByCondition(t)},this,{single:!0})},updateHistoryAfterThreadStoreLoad:function(t,e){this.mon(t,"load",function(){SYNO.SDS.MailClient.Switch.getSearchHistoryStore().reloadStore()},this,{single:!0})},updateByCondition:function(t){var e=t.toSyntaxString(),i=t.getMailboxId(),n=t.hasStar();this.setValue(Ext.isEmpty(e.trim())?"":e.trim()+" "),i!==SYNO.SDS.MailClient.Define.inboxId||t.isSearch()||(i=0),!i&&n&&(i="starred"),this.scopeBtn.setValue(i),t.isSearch()?this.focusSearchField():this.blurSearchField()},onSearchFieldClick:function(t,e,i){if(!SYNO.SDS.MailClient.Info.fts_enabled)return void this.showSearchPanel(!0);this.doQuery(this.getRawValue(),!0)},onKeyUp:function(t){var e=t.getKey();!1===this.editable||!0===this.readOnly||e!=t.BACKSPACE&&e!=t.DELETE&&t.isSpecialKey()||(this.lastKey=e,this.dqTask.delay(this.queryDelay)),Ext.form.ComboBox.superclass.onKeyUp.call(this,t)},onSearchFieldKeyDown:function(t,e){var i=this.el.dom.selectionStart>=this.getRawValue().length;Ext.EventObject.RIGHT==e.getKey()&&i&&this.getHintText().length>this.getRawValue().length&&this.setRawValue(this.getHintText()),this.checkDisableTypeahead(),Ext.EventObject.ENTER!==e.getKey()||this.isExpanded()||(this.doSearchByEnterTask||(this.doSearchByEnterTask=new Ext.util.DelayedTask(this.doSearch,this)),this.doSearchByEnterTask.delay(200))},onSearchFieldInput:function(){this.dqTask.delay(this.queryDelay)},processValueOnSelect:function(t,e){var i=e.get("value"),n=this.getRawValue().trim(),a=e.get("type");return t&&"history"!==a&&"syntax"!==a?n.substring(0,n.lastIndexOf(t.query))+i:i},onSelect:function(t,e){var i=this.getLastSyntaxQuery(this.getRawValue()),n=this.processValueOnSelect(i,t),a="address"===t.get("type");!1!==this.fireEvent("beforeselect",this,t,e)&&(this.inKeyMode||this.setRawValue(a&&!i?t.get("hint")+n:n),this.collapse(),this.fireEvent("select",this,t,e)),this.clearHintText()},onSearchFieldSelect:function(t,e,i){var n=SYNO.SDS.MailClient.SearchLib.SyntaxParser,a=SYNO.SDS.MailClient.Define;"syntax"!==e.get("type")&&("history"===e.get("type")&&n.getRelatedMailbox(e.get("value")).length>0&&this.scopeBtn.getMailboxId()!==a.starredId&&this.scopeBtn.setValue(0),this.doSearch())},doSearch:function(){var t,e=this.getRawValue().trim();Ext.isEmpty(e)||(this.searchPanel&&this.searchPanel.resetAll(),this.clearHintText(),t=new SYNO.SDS.MailClient.Condition({mailbox:this.scopeBtn.getMailboxId(),keyword:e}),SYNO.SDS.MailClient.Control.Mail.search(t))},onHistoryDelete:function(t){var e=this.store.getAt(t),i=e.get("original_id"),n=SYNO.SDS.MailClient.Switch.getSearchHistoryStore();n.remove(n.getById(i)),this.updateStore(this.getRawValue()),SYNO.SDS.MailClient.WebAPI.send("deleteSearchHistory",{id:[i]})},onSearchFieldDestroy:function(t){this.searchPanel&&Ext.destroy(this.searchPanel)},onDocMouseDown:function(t){!this.searchPanel||t.within(this.searchPanel.getEl())||t.within(this.searchIcon)||this.searchPanel.hasDropDown()||t.getTarget(".syno-mc-modal-window")||t.getTarget(".ext-el-mask")||this.searchPanel.hide();var e=SYNO.SDS.MailClient.Switch.getRegister("lastThreadCondition");e instanceof SYNO.SDS.MailClient.Condition&&(t.getTarget(".search-ct")||this.searchPanel&&t.within(this.searchPanel.getEl())||e.isSearch()||this.blurSearchField())},getSearchPanel:function(){return this.searchPanel||(this.searchPanel=new SYNO.SDS.MailClient.FilterPanel({renderTo:SYNO.SDS.MailClient.Window.getEl(),shadow:!1,hidden:!0}),this.mon(this.searchPanel,"reset",this.onConditionReset,this),this.mon(this.searchPanel,"mailboxchange",this._onSearchPanelMailboxChange,this)),this.searchPanel},showSearchPanel:function(t){if(!0!==this.disabled){var e,i=this.getSearchPanel();if(i.isVisible()&&!t)return void i.hide();this.collapse(),this.focusSearchField(),e=SYNO.SDS.MailClient.SearchLib.SyntaxParser.toCondition(this.getRawValue()).toWebAPIParams(),i.setConditions(this.scopeBtn.mailboxId,e),i.getEl().alignTo(this.searchIcon,"tl-bl?",[0,1]),i.show()}},setHintText:function(t){this.checkDisableTypeahead()||(this.hintInput.dom.value=t)},getHintText:function(){return this.hintInput.dom.value},clearHintText:function(){this.setHintText("")},_onSearchPanelMailboxChange:function(t){this.scopeBtn.setValue(t)},onConditionReset:function(t){t||this.reset()},onShortCut:function(t){if(SYNO.SDS.MailClient.KeyNavigator.ShortCut.SEARCH===t)return this.focus(),!0},checkDisableTypeahead:function(){return this.el.dom.scrollWidth>this.getWidth()&&(this.hintInput.dom.value="",!0)},select:function(t,e){if(this.callParent(arguments),this.inKeyMode){t<0&&this.setValue(this.keepText);var i,n=this.store.getAt(t),a=this.getLastSyntaxQuery(this.keepText);n&&(i=n.get("value"),"history"===n.get("type")||"syntax"===n.get("type")||!1===a&&"address"===n.get("type")?("address"===n.get("type")&&(i=n.get("hint")+i),this.setValue(i)):!1!==a&&this.setValue(this.keepText.substring(0,this.keepText.lastIndexOf(a.query))+i)),this.clearHintText()}},selectNext:function(){-1==this.selectedIndex&&(this.keepText=this.getRawValue());var t=this.store.getCount();t>0&&(-1==this.selectedIndex?this.select(0):this.selectedIndex==t-1?this.select(-1):this.select(this.selectedIndex+1))},selectPrev:function(){-1==this.selectedIndex&&(this.keepText=this.getRawValue());var t=this.store.getCount();t>0&&(-1==this.selectedIndex?this.select(t-1):0===this.selectedIndex?this.select(-1):this.select(this.selectedIndex-1))},getTpl:function(){return new Ext.XTemplate('<tpl for=".">','<tpl if="is_first">','<div class="item-sep"></div>',"</tpl>",'<div class="x-combo-list-item {[values.cls || ""]} {values.type}" role="option" aria-label="{[Ext.util.Format.htmlEncode(Ext.util.Format.stripTags(values.display))]}" id="{[Ext.id()]}">',"<tpl if=\"type !== 'address'\">",'<span class="item-icon {type}"></span>',"<span>","{values.display:htmlEncode}",'<span class="match">{values.display_match:htmlEncode}</span>',"{values.display_last:htmlEncode}","</span>","<tpl if=\"type == 'history'\">",'<span class="btn-del"></span>',"</tpl>","</tpl>","<tpl if=\"type == 'address'\">",'<span class="item-icon {type}"></span>','<span class="text-wrap">','<span class="text">',"{values.display:htmlEncode}",'<span class="match">{values.display_match:htmlEncode}</span>',"{values.display_last:htmlEncode}","</span>",'<span class="syntax">',"{values.hint}","{values.hint_value:htmlEncode}",'<span class="match">{values.hint_value_match:htmlEncode}</span>',"{values.hint_value_last:htmlEncode}","</span>","</span>","</tpl>","</div>","</tpl>")}}),Ext.define("SYNO.SDS.MailClient.Search.SearchField",{extend:"Ext.Container",requires:["SYNO.SDS.MailClient.SearchScopeButton","SYNO.SDS.MailClient.Search.MailSearchField"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.mon(this.scopeBtn,"menuitemclick",this._onScopeBtnMenuClick,this)},fillConfig:function(t){var e={cls:"search-ct",items:[{xtype:"container",cls:"search-scope-ct",items:[this.scopeBtn=new SYNO.SDS.MailClient.SearchScopeButton({})]},this.mailSearchField=new SYNO.SDS.MailClient.Search.MailSearchField({itemId:"mailSearchfield",height:32,owner:this,scopeBtn:this.scopeBtn})],listeners:{scope:this}};return Ext.apply(e,t),e},setFocus:function(){this.addClass("search-mode"),this.scopeBtn.show()},setBlur:function(){this.removeClass("search-mode"),this.scopeBtn.hide()},_onScopeBtnMenuClick:function(){this.mailSearchField.doSearch()}}),Ext.define("SYNO.SDS.MailClient.AppWindow",{extend:"SYNO.SDS.AppWindow",requires:["SYNO.SDS.MailClient.Condition","SYNO.SDS.AppLauncher.Panel","SYNO.SDS.MailClient.Search.SearchField","SYNO.SDS.MailClient.Setting.Window"],constructor:function(t){t=t||{},t.cls||(t.cls=""),t.cls+=" syno-mc-win",this.callParent([t]),this.on("afterlayout",function(){this.maximized&&!SYNO.SDS.MailClient.Define.isPrintMode&&this.setSize(this.container.getSize())},this)},setTitle:Ext.emptyFn,createPackageHeader:function(){new Ext.Container({renderTo:this.header,cls:"syno-mc-window-toolbar",id:this.package_header_id=Ext.id(),items:[{xtype:"container",cls:"logo-ct",items:[{id:this.defaultLogoId=Ext.id(),xtype:"container",cls:"logo"},{id:this.customLogoId=Ext.id(),xtype:"box",cls:"custom-logo",hidden:!0,autoEl:{tag:"img"}}],listeners:{scope:this,afterrender:function(t){this.defaultLogo=Ext.getCmp(this.defaultLogoId),this.customLogo=Ext.getCmp(this.customLogoId),t.el.on("click",this.onClickLogo,this)}}},this.searchField=new SYNO.SDS.MailClient.Search.SearchField({activeItem:0,itemId:"search"}),{xtype:"container",cls:"task_indicator",items:[{xtype:"container",id:this.task_indicator_id=Ext.id(),cls:"text",hidden:!0,html:SYNO.SDS.MailClient._T("common","task_running_desc")}]},{xtype:"container",cls:"action-ct",items:[{xtype:"syno_mc_button",iconCls:"todo-button",tooltip:SYNO.SDS.MailClient._T("calendar","launch_todo_list_plugin"),hidden:!SYNO.SDS.MailClient.Define.isSupportTodoPlugin(),enableToggle:!0,handler:function(t){var e=SYNO.SDS.AppMgr.getByAppName("SYNO.Cal.Todo.Plugin.Instance")[0];Ext.isDefined(e)&&e.window.isVisible()?e.window.hide():SYNO.SDS.MailClient.AppLib.TodoPlugin.launch()}},{xtype:"syno_mc_button",iconCls:"app-launcher",id:"app-launcher-container",tooltip:_TT("SYNO.Application.Service.Instance","common","menu_tip"),enableToggle:!0,handler:function(t){Ext.isEmpty(this.panel)&&(this.panel=new SYNO.SDS.AppLauncher.Panel({width:378,height:214,padding:"15px",defaultAnchor:"t",defaultAlignPos:"tr-tr?",defaultOffsets:[-12,42],animate:!1})),t.pressed&&(this.panel.show(),this.mon(this.panel,"hide",function(){t.pressed&&t.toggle()},this,{single:!0}))}},{xtype:"syno_mc_button",cls:"account-button",text:_S("user"),menu:[{text:SYNO.SDS.MailClient._T("common","common_settings"),cls:"syno-mc-account-settings",hidden:!SYNO.SDS.MailClient.Define.isNormalMode,handler:function(){new SYNO.SDS.MailClient.Setting.Window({owner:SYNO.SDS.MailClient.Window}).open()}},{text:SYNO.SDS.MailClient._T("common","help"),hidden:!this.showHelp,scope:this,handler:this.onClickHelp},{text:SYNO.SDS.MailClient._T("common","common_about"),scope:this,handler:function(){this.showAboutWindow()}},{text:_T("common","logout"),handler:function(){SYNO.SDS.StatusNotifier.fireEvent("logout");var t=[];if(SYNO.SDS.MailClient.Settings.clear_trash_on_logout&&t.push({apiType:"addTask",params:{condition:new SYNO.SDS.MailClient.Condition("mailbox",SYNO.SDS.MailClient.Define.trashId).toWebAPIParams(),action:[SYNO.SDS.MailClient.Format.makeAction("delete","")]}}),SYNO.SDS.MailClient.Settings.clear_junk_on_logout&&t.push({apiType:"addTask",params:{condition:new SYNO.SDS.MailClient.Condition("mailbox",SYNO.SDS.MailClient.Define.junkId).toWebAPIParams(),action:[SYNO.SDS.MailClient.Format.makeAction("delete","")]}}),t.length)SYNO.SDS.MailClient.WebAPI.send(t).catch(function(t){SYNO.Debug.error(t)}.bind(this)).then(function(){window.onbeforeunload=SYNO.SDS.onBasicBeforeUnload;try{SYNO.SDS.Utils.Logout.action()}catch(t){}});else{window.onbeforeunload=SYNO.SDS.onBasicBeforeUnload;try{SYNO.SDS.Utils.Logout.action()}catch(t){}}}}]}]}]})},afterRender:function(){SYNO.SDS.AppWindow.superclass.afterRender.apply(this,arguments),this.header&&SYNO.SDS.MailClient.Define.isNormalMode&&(this.header.update(""),this.createPackageHeader()),_S("standalone")&&this.alignTo(document.body,"c-c")},onClickLogo:function(){var t=SYNO.SDS.MailClient.Control;t.Main.toMailAppLandingPage().then(function(){t.Main.reloadApp()}.bind(this))},setLogo:function(t){t?(this.customLogo.el.dom.src=t,this.defaultLogo.hide(),this.customLogo.show()):(this.customLogo.hide(),this.defaultLogo.show())},getMsgBox:function(t){if(!this.msgBox||this.msgBox.isDestroyed){var e=t&&t.owner||this;e=e.isDestroyed?null:e;var i={owner:e,onShow:function(){SYNO.SDS.MessageBoxV5.superclass.onShow.apply(this,arguments),e&&e.popOutWinManager.disableComposer()},onHide:function(){e&&e.popOutWinManager.enableComposer(),SYNO.SDS.MessageBoxV5.superclass.onHide.apply(this,arguments)}};this.isV5Style()?this.msgBox=new SYNO.SDS.MessageBoxV5(i):this.msgBox=new SYNO.SDS.MessageBox(i),this.msgBox.addClass("syno-mc-messagebox")}return this.msgBox.getWrapper(t)}}),Ext.define("SYNO.SDS.MailClient.ComposePage",{extend:"SYNO.ux.Panel",xtype:"mc_ComposePage",constructor:function(t){var e=SYNO.SDS.MailClient.Define;this.callParent([this.fillConfig(t)]),SYNO.SDS.MailClient.Switch.updateDocumentTitle(),this._renderEditor({subject:"",to:e.launchParam.to||e.launchParam.zip_to||[],cc:[],bcc:[],body:"",attachment:[]})},fillConfig:function(t){var e={boxMaxWidth:1200,boxMinWidth:800,layout:"fit",cls:"syno-mc-main-panel",bodyCssClass:"syno-mc-main-panel-body"};return Ext.apply(e,t)},removeEditor:function(){this.remove(this.editorPanel,!0),delete this.editorPanel},resumeEditor:function(t,e,i){Ext.apply(t,{id:e,thread_id:i}),this._renderEditor(t)},_renderEditor:function(t){SYNO.SDS.MailClient.DraftLib.DraftManager.canOpenDraft()&&(this.editorPanel=new SYNO.SDS.MailClient.Editor.EditorPanel({level:SYNO.SDS.MailClient.Editor.LevelEnum.NEW_WIN,newWinEditor:this,draftRec:new Ext.data.Record(t),border:!0,isNew:!t.hasOwnProperty("id")}),this.add(this.editorPanel),this.doLayout())}}),Ext.define("SYNO.SDS.MailClient.ComposerLib.Config",{extend:"Ext.util.Observable",singleton:!0,requires:[],getSMTPData:function(){return SYNO.SDS.MailClient.SMTP.smtp.map(function(t){var e=SYNO.SDS.MailClient.Format.composeNameAddr(t.display_name,t.mail);return{id:t.id,address:e,mail:t.mail,encode:Ext.util.Format.htmlEncode(e),signature:t.signature}})},getSMTPMail:function(){return this.getSMTPData().map(function(t){return t.mail})},getSMTPAddr:function(){return this.getSMTPData().map(function(t){return t.address})},isEnableSMTPDetecting:function(){return SYNO.SDS.MailClient.Settings.enable_smtp_detecting},getDefaultFromAddr:function(){var t=this.getSMTPData(),e=t[0];return Ext.each(t,function(t){t.id===SYNO.SDS.MailClient.SMTP.smtp_default_id&&(e=t.address)}),e}}),function(t){if(function(){try{var t=new URL("b","http://a");return t.pathname="c%20d","http://a/c%20d"===t.href&&t.searchParams}catch(t){return!1}}()||function(){var e=t.URL,i=function(t,e){"string"!=typeof t&&(t=String(t));var i=document.implementation.createHTMLDocument("");if(window.doc=i,e){var n=i.createElement("base");n.href=e,i.head.appendChild(n)}var a=i.createElement("a");if(a.href=t,i.body.appendChild(a),a.href=a.href,":"===a.protocol||!/:/.test(a.href))throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:a})},n=i.prototype,a=function(t){Object.defineProperty(n,t,{get:function(){return this._anchorElement[t]},set:function(e){this._anchorElement[t]=e},enumerable:!0})};["hash","host","hostname","port","protocol","search"].forEach(function(t){a(t)}),Object.defineProperties(n,{toString:{get:function(){var t=this;return function(){return t.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(t){this._anchorElement.href=t},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname},set:function(t){this._anchorElement.pathname=t},enumerable:!0},origin:{get:function(){return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(this._anchorElement.port?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(t){},enumerable:!0},username:{get:function(){return""},set:function(t){},enumerable:!0}}),i.createObjectURL=function(t){return e.createObjectURL.apply(e,arguments)},i.revokeObjectURL=function(t){return e.revokeObjectURL.apply(e,arguments)},t.URL=i}(),void 0!==t.location&&!("origin"in t.location)){var e=function(){return t.location.protocol+"//"+t.location.hostname+(t.location.port?":"+t.location.port:"")};try{Object.defineProperty(t.location,"origin",{get:e,enumerable:!0})}catch(i){setInterval(function(){t.location.origin=e()},100)}}}("undefined"!=typeof window?window:"undefined"!=typeof self?self:this),Ext.define("SYNO.SDS.MailClient.UrlPolyfill",{}),Ext.define("SYNO.SDS.MailClient.ComposerLib.Action",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.ComposerLib.Config","SYNO.SDS.MailClient.WebAPI","SYNO.SDS.MailClient.UrlPolyfill"],constructor:function(){this.callParent(arguments),this.init()},init:function(){this.WebAPI=SYNO.SDS.MailClient.WebAPI,this.Config=SYNO.SDS.MailClient.ComposerLib.Config},forwardOriginalContent:function(t){var e=SYNO.SDS.MailClient.Format,i=this.Config.getDefaultFromAddr();if(SYNO.SDS.MailClient.DraftLib.DraftManager.canOpenDraft())return this.WebAPI.send("createDraft",{from:e.normalAddrToRFC822Addr(i),eml_message_id:t,body:SYNO.SDS.MailClient.ComposerLib.Draft.getContentWithEmptyBody(i)}).then(function(t){return this.WebAPI.send("getDraft",{id:[t.id]})}.bind(this)).then(function(t){t.draft[0]=e.formatAddrsOfMsgToNormal(t.draft[0]),SYNO.SDS.MailClient.Window.popOutWinManager.openComposer(t.draft[0])}.bind(this)).catch(function(t){SYNO.Debug.error(t)}.bind(this))},openMailtoLink:function(t){var e,i,n=new URL(t),a=n.pathname;try{e=Ext.urlDecode(n.search.replace("?",""))}catch(t){e={}}Ext.iterate(e,function(t,i){e[t.toLowerCase()]=i}),i={to:this._splitAndDecodeEmails(a).concat(this._splitAndDecodeEmails(e.to)),cc:this._splitAndDecodeEmails(e.cc),bcc:this._splitAndDecodeEmails(e.bcc),subject:Ext.util.Format.htmlEncode(e.subject?e.subject:""),body:Ext.util.Format.htmlEncode(e.body?e.body:"").replace(/\r\n|\r|\n/g,"<br>")},SYNO.SDS.MailClient.Window.popOutWinManager.openComposerFromMailtoLink(i)},_splitAndDecodeEmails:function(t){return(t?t.split(","):[]).map(decodeURIComponent).map(function(t){return t.trim()})}}),Ext.define("SYNO.SDS.MailClient.ComposerLib.Draft",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.ComposerLib.Config"],constructor:function(){this.callParent(arguments),this.Config=SYNO.SDS.MailClient.ComposerLib.Config},getFromAddr:function(t){var e=this.Config.isEnableSMTPDetecting(),i=this.Config.getDefaultFromAddr(),n=this.Config.getSMTPAddr(),a=[];return t&&e?(t.from&&(a=[t.from]),this._getFromAddr([a,t.to,t.cc],n)):i},_getFromAddr:function(t,e){var i,n=function(t,e){return e.find(function(e){return this._isMailEqualForSMTP(t,e)},this)}.bind(this);return i=t.map(function(t){return t.map(function(t){return n(t,e)},this).filter(function(t){return!Ext.isEmpty(t)})},this),i.reduce(function(t,e){return t||this._pickOneFromAddr(e)}.bind(this),null)||this.Config.getDefaultFromAddr()},_pickOneFromAddr:function(t){var e,i=this.Config.getDefaultFromAddr();return 0===t.length?null:(e=t.some(function(t){return this._isMailEqualForSMTP(t,i)},this),e?i:t[0])},_isMailEqualForSMTP:function(t,e){var i=SYNO.SDS.MailClient.Format,n=i.getMailByNameAddrOrAddr(t),a=i.getMailByNameAddrOrAddr(e);return n&&a&&n.toLowerCase()===a.toLowerCase()},getSignature:function(t){return this._getSignature(function(e){return e.address===t})},_getSignature:function(t){if(!SYNO.SDS.MailClient.Settings.enable_signature)return"";var e=SYNO.SDS.MailClient.ComposerLib.Config.getSMTPData(),i=e.find(t);return i?i.signature.trim():""},getContentWithEmptyBody:function(t){return this.initNewDraftContent("",!1,t)},initNewDraftContent:function(t,e,i){var n,a='<div class="syno-mc-signature">'+this.getSignature(i)+"</div>",o=""===t?"":"<div><br></div>",s="";return n=SYNO.SDS.MailClient.Format.getTinyMCEDefaultStyle(),n&&(s=' style="'+n+'" '),a&&(e?(t=""===t?String.format("<div{0}><br></div>",s):t,t=t+String.format("<div{0}><br></div>",s)+a):t=a+o+t),t&&!e&&(t=String.format('<div{0}><br data-mce-bogus="1"></div><div{0}><br></div>',s)+t),t},isSameSubject:function(t,e){return this._getBaseSubject(t).toLowerCase()===this._getBaseSubject(e).toLowerCase()},_getBaseSubject:function(t){for(var e=t.replace(/[\t\r\n ]+/gi," ").trim(),i="";;){if(i=e.replace(/\(fwd\)$/gi,"").trim(),i=this.removePrefix(i),i=this._removeBlob(i),i=this._removeFwdHdr(i),Ext.isEmpty(i)||e===i)break;e=i}return e},removePrefix:function(t){var e=t.replace(/[\t\r\n ]+/gi," ").trim(),i=new RegExp("^(?:(?:अग्रेषित करें|प्रत्युत्तर|გადაგზავნა|अग्रेषित|ตอบกลับ|อ้างถึง|إعادة توجيه|პასუხიส่งต่อ|उत्तर|Препр.|Proslijedi|Persiųsta|ПРЕПРCavab ver|Ar aghaidh|Göndər|YML/FW|Maidir le|Відп|回覆|轉寄|答复|転送회신|전달|ATB/RE|Pārs.|Redir.|Отг|ОТН|Javob|Pros|Atb.|Ats.|Odp.|Paso|PROS|İLTΑΠ|Απ|ΠΡ|Πρ|НА|رد|fwd|ODP|返|Bls|Trs|Odg|Atb|YML|Ats|RESENC|Mō|MŌ|YNT|re|fw|sv|vs|Fs|AW|RV|WG|Ed|Ig|WL|JB|PD|Wm|VL|VB|>>|HA|R|I):\\s*)*(.*)$","i"),n=i.exec(e);return n?n[1]:t},_removeBlob:function(t){for(var e=t,i="";;){if(i=e.replace(/^\[([^\[\]])*\]/,"").trim(),Ext.isEmpty(i)||e===i)return e;e=i}},_removeFwdHdr:function(t){var e=t.match(/^\[fwd:(.*)\]$/);return e?e[1].trim():t}}),Ext.define("SYNO.SDS.MailClient.ComposerLib.Main",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.ComposerLib.Action","SYNO.SDS.MailClient.ComposerLib.Config","SYNO.SDS.MailClient.ComposerLib.Draft"]});Ext.define("SYNO.SDS.MailClient.UtilLib.DelayedPromise",{extend:"SYNO.SDS.MailClient.UtilLib.Deferred",statics:{makeDelayed:function(t){return function(e){return new SYNO.SDS.MailClient.UtilLib.DelayedPromise(t,e)}}},constructor:function(t,e,i){this.callParent(arguments),this._ms=t,this._delayedValue=e,i||this._setTimeout(t,e)},done:function(){this.resolve(this._delayedValue)},abort:function(){this._abort()},abortWithoutReject:function(){this._abort(!0)},delay:function(t){this._setTimeout(t)},start:function(){this._setTimeout(this._ms,this._delayedValue)},_setTimeout:function(t,e){this._timerId&&clearTimeout(this._timerId),this._ms=t,this._timerId=setTimeout(this.done.bind(this),this._ms),e&&(this._delayedValue=e)},_abort:function(t){this.isPending()&&(clearTimeout(this._timerId),t||this.reject("DelayedPromise aborted"))}}),Ext.define("SYNO.SDS.MailClient.UtilLib.DelayedTask",{requires:[],constructor:function(t,e,i){this._setAttr(t,e,i),this._id=null,this._disabled=!1},delay:function(t,e,i,n){this.cancel(),this._setAttr(e,i,n),this._setInterval(t)},cancel:function(){this._id&&this._clearInterval()},enable:function(){this._disabled=!1},disable:function(){this.cancel(),this._disabled=!0},isWaiting:function(){return!!this._id},_setInterval:function(t){this._id=setInterval(this._exec.bind(this),t)},_clearInterval:function(){clearInterval(this._id),this._id=null},_exec:function(){this._clearInterval(),this._disabled||this._fn.apply(this._scope,this._args||[])},_setAttr:function(t,e,i){this._fn=t||this._fn,this._scope=e||this._scope,this._args=i||this._args}}),Ext.define("SYNO.SDS.MailClient.DraftLib.DraftObject",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.SharingLinkWindow","SYNO.SDS.MailClient.UtilLib.DelayedTask"],constructor:function(t){var e,i,n,a=SYNO.SDS.MailClient.PGPSettings,o=SYNO.SDS.MailClient.DraftLib,s=t.data;this.callParent(arguments),this.addEvents("mask","unmask","error","syncsuccess","syncfailed","syncing"),delete t.data,e=Ext.apply({body:this.replaceInlineImageToIMAPFormat(s.body),temp_attachment:[],copied_attachment:[]},s),i=Ext.apply({},e),n=Ext.apply({autoSaveTime:2e3,id:null,data:e,newData:i,willEncrypt:a.enable_pgp&&a.default_enable_encrypt,willSign:a.enable_pgp&&a.default_enable_sign,clearReplyTo:!1},t),Ext.apply(this,n),Ext.apply(this,{editors:[],isSending:!1,isDiscarding:!1,masked:!1,saveTask:new SYNO.SDS.MailClient.UtilLib.DelayedTask(this.save,this),sendDelayedPromise:new SYNO.SDS.MailClient.UtilLib.Deferred,ctrl:new o.DraftObjectController(this),uploadOperator:new o.UploadOperator(this),saveOperator:new o.SaveOperator(this),sendOperator:new o.SendOperator(this),postCtrl:SYNO.SDS.MailClient.Define.isComposeMode?new o.ComposeModePostController(this):new o.DefaultPostController(this)}),this.sendDelayedPromise.resolve(),this.uploadOperator.on({empty:function(){var t=this.getWakedEditor();t?this._onEditorDataChange(t,"upload done"):this.runSaveTask("upload done (no editor)")},updateimage:function(t){this.ctrl.updateImage(t)},uploadprogress:function(t,e){this.ctrl.handleUploadProgress(t,e)},uploadfinish:function(t){this.ctrl.handleUploadFinish(t)},uploadrefresh:function(t){this.ctrl.handleUploadRefresh(t)},uploadfailed:function(t){this.ctrl.handleUploadFailed(t)},error:function(t,e){this._onError(t)},scope:this})},bind:function(t){this.editors.push(t),t.draftObj=this,t.ctrl=this.ctrl,t.on({scope:this,datachange:this._onEditorDataChange,beforedestroy:this._onEditorDestroy}),t.mon(this,{scope:t,mask:t.onDraftMask,unmask:t.onDraftUnmask,syncing:t.onEditorSync.createDelegate(t,["syncing"]),syncsuccess:t.onEditorSync.createDelegate(t,["syncsuccess"]),syncfailed:function(t){this.onEditorSync("syncfailed",t)}}),t.sleep(),this.wakeEditor(),t.refreshInlineImage()},isSaving:function(){return this.saveOperator.isSaving()},isUploading:function(){return this.uploadOperator.isBusy()},isBusy:function(t){return this.isSaving()||this.isUploading()||t&&this.saveTask.isWaiting()},upload:function(t){var e=this.uploadOperator,i=this.saveOperator;return e.add(t),i.ensureIdle().then(function(){e.process()}.bind(this))},runSaveTask:function(t,e){var i=this.getSavingValidateData(this.newData);this.checkDirty(i)&&this.saveTask.delay(e||this.autoSaveTime)},save:function(){return this._save()},forceSave:function(){return this._save(!0)},_save:function(t){var e,i=this.getWakedEditor()
;return this.isSaving()||this.isUploading()?void this.runSaveTask("saving",300):function(){return i?i.detectAndUploadImage():Promise.resolve()}().then(function(){return e=this.getSavingValidateData(this.newData),e.invalid?void this._showInvalidDraftMsg(e):t||this.checkDirtyAndUpdateDraft(e)?this._doSave(e,t):void 0}.bind(this))},_doSave:function(t,e){var i=this.saveOperator;return this.fireEvent("syncing"),i.save(t,e).then(function(t){var i=t.isCreated,n=t.clearReplyTo,a=t.copiedAttachment,o=t.draftResp.draft[0];this.isDiscarding||(i&&(this.isSending||this.isSentWithoutFirstTimeSaving||this.postCtrl.reloadMailAndSidebarIfNeeded()),n&&this.postCtrl.handleClearReplyTo(o),this.ctrl.repairBody(o.body.html,o.attachment,a,e),this._syncNewDataFromEditor(),this.fireEvent("syncsuccess"),this.postCtrl[i?"addDraft":"editDraft"]([{id:this.threadId,data:Ext.apply({id:this.id},this.newData)}]),this.checkDestroy())}.bind(this)).catch(function(t){this._handleSyncFailed(t)}.bind(this))},_handleSyncFailed:function(t){this.unmask(),this.fireEvent("syncfailed",SYNO.SDS.MailClient.Error.getErrorString(t)),this._stopSending(),this._stopDiscarding()},send:function(){var t,e=this.getSendingValidateData(this.newData);return e.invalid?void this._showInvalidDraftMsg(e):(this.id||(this.isSentWithoutFirstTimeSaving=!0),this._startSending(),this.isSentWithoutFirstTimeSaving?(this.mask(),this.uploadOperator.ensureIdle().then(this.doSendWithoutId.bind(this))):(this._prepareForSending(),t=this.isUploading()||this.isSaving(),this.uploadOperator.ensureIdle().then(this.saveOperator.ensureIdle.bind(this.saveOperator)).then(function(){t&&(this.uploadOperator.updateImagesByUploadedFiles(),this.postCtrl.updateSendingDraft())}.bind(this)).then(this.doSend.bind(this)).catch(function(t){SYNO.Debug.error("send failed",t),this._stopSending()}.bind(this))))},_prepareForSending:function(){this.ctrl.removeEditorAndAddSendingDraft(),this.postCtrl.prepareForSending()},doSendWithoutId:function(){return this._stopSending(),this.forceSave(),this._eventPromise("syncsuccess").then(function(){return this._startSending(),this._prepareForSending(),this.doSend()}.bind(this))},doSend:function(t){var e=SYNO.SDS.MailClient.DraftLib.PGP,i=SYNO.SDS.MailClient.DraftLib.SharingLink,n=this.getSendingValidateData(this.newData),a=SYNO.SDS.MailClient.Settings.delay_send_time,o=SYNO.SDS.MailClient.Switch.inMailboxId,s=this.sendOperator;return n.invalid?(this._showInvalidDraftMsg(n),this._stopSending(),Promise.resolve()):(this.mask(),i.process(n).then(function(t){return e.process(t,this.getReceivers(),this.willEncrypt,this.willSign,this.getTargetWin())}.bind(this)).then(function(t){return this.unmask(),n=t,this._showSendingToast(a),this.sendDelayedPromise=new SYNO.SDS.MailClient.UtilLib.DelayedPromise(1e3*a),this.sendDelayedPromise}.bind(this)).then(function(){return a&&SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","sending"),[],!0),n.reply_to>0&&this.postCtrl.markReplyForward(n.reply_to,n.draft_type),s.send(n,t,o)}.bind(this)).then(function(t){this._stopSendingAfterMailSentSucc(),this.postCtrl.updateAfterMailSent(t.getMessageResp.message[0]),SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","sent")),this.checkDestroy()}.bind(this)).catch(function(t){t.senderInfo=this.data,this.unmask(),SYNO.SDS.MailClient.Control.View.hideToast(),this._stopSending(),"DelayedPromise aborted"===t?this._resumeEditor():t.code===SYNO.SDS.MailClient.Define.PGPStat.CANCEL?this._resumeEditor():this._onError(t,_T("error","error_error_system")),SYNO.SDS.MailClient.Control.Mail.silentReloadMail(),this.checkDestroy()}.bind(this)))},_showSendingToast:function(t){t?SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","delay_send_in"),[[_T("common","cancel"),function(){this.cancelSend(),SYNO.SDS.MailClient.Control.View.hideToast()},this]],t,this.cancelDelay.createDelegate(this)):this.hasEmbedEditor()||SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","sending"),[],!0)},cancelSend:function(){this.sendDelayedPromise.isPending()&&this.sendDelayedPromise.abort()},cancelDelay:function(){this.sendDelayedPromise.isPending()&&this.sendDelayedPromise.delay(0)},_startSending:function(){this.isSending=!0,this.needToRestoreUnreadCount=this.postCtrl.decreaseDraftUnreadCountIfNeeded(),this.saveTask.disable()},_stopSending:function(){this._doStopSending(!1)},_stopSendingAfterMailSentSucc:function(){this._doStopSending(!0)},_doStopSending:function(t){this.isSending=!1,this.needToRestoreUnreadCount&&!t&&(this.needToRestoreUnreadCount=!1,this.postCtrl.increaseDraftUnreadCount()),this.saveTask.enable()},discard:function(){return this._startDiscarding(),this.ctrl.close(),this.isSaving()?this.id?(this.saveOperator.terminate(),this.doDiscard()):this.saveOperator.ensureIdle().then(this.doDiscard.bind(this)):this.id?(this.uploadOperator.isBusy()&&this.uploadOperator.terminate(),this.doDiscard()):(this._destroy(),Promise.resolve())},doDiscard:function(){return this.ctrl.close(),this._deleteDraft(),this.postCtrl.filterNotExistMsgs(),SYNO.SDS.MailClient.WebAPI.send("discardDraft",{id:[this.id]}).then(function(t){this._stopDiscarding(),this.saveTask.disable(),this.postCtrl.reloadMailboxList(),SYNO.SDS.MailClient.Window.showToast(SYNO.SDS.MailClient._T("notification","discard")),this.checkDestroy()}.bind(this)).catch(function(t){this._stopDiscarding(),SYNO.SDS.MailClient.Control.View.hideToast(),this.fireEvent("error",t,SYNO.SDS.MailClient._T("composer","discard_fail")),this._onError(t,_T("error","error_error_system")),this.checkDestroy()}.bind(this))},_startDiscarding:function(){this.isDiscarding=!0,this.saveTask.disable()},_stopDiscarding:function(){this.isDiscarding=!1,this.saveTask.enable()},mask:function(){this.masked=!0,this.fireEvent("mask")},unmask:function(){this.masked=!1,this.fireEvent("unmask")},showErrorMsg:function(t,e){(this.getWakedEditor()||this.editors[0]).findWindow().getMsgBox().alert("",SYNO.SDS.MailClient.Error.getErrorString(t,e))},_onError:function(t,e){this._resumeEditor(),this.showErrorMsg(t,e)},_resumeEditor:function(){0===this.editors.length&&this.postCtrl.resumeEditor()},canUnload:function(){var t;return!this.isBusy()&&!this.isSending&&(t=this.getSavingValidateData(this.newData),!!t.invalid||!this.checkDirty(t))},checkDirty:function(t){return SYNO.SDS.MailClient.DraftLib.DraftProcessor.checkDirty(t,this.data)},checkDirtyAndUpdateDraft:function(t){return SYNO.SDS.MailClient.DraftLib.DraftProcessor.checkDirtyAndUpdateDraft(t,this.data)},getWakedEditor:function(){return this.editors.find(function(t){return t.isWaked})},getActiveEditor:function(){return 0===this.editors.length?null:this.getWakedEditor()||this.editors[0]},getEmbedEditor:function(){return this.editors.find(function(t){return t.isEmbedded})},hasEmbedEditor:function(){return this.editors.some(function(t){return t.isEmbedded})},wakeEditor:function(t,e){var i=SYNO.SDS.MailClient.Editor.LevelEnum.NONE;t||Ext.each(this.editors,function(n){n.level>i&&n!==e&&(i=n.level,t=n)}),e||Ext.each(this.editors,function(i){i!==t&&i.isWaked&&(e=i)},this),e&&e.isWaked&&e.sleep(),t&&!t.isWaked&&t.wake()},closeOtherEditors:function(t){t=t||this.getWakedEditor(),t&&(t.preventDelete=!0),this._deleteDraft(),t&&delete t.preventDelete},closeNotWakedPopoutEditor:function(){this.editors.filter(function(t){return!t.isWaked&&t.level===SYNO.SDS.MailClient.Editor.LevelEnum.MAIN_WIN_POPOUT}).forEach(function(t){t.findWindow().close()})},_onEditorDataChange:function(t,e){this.newData=Ext.apply(this.newData,t.getData()),this._applySharedIconWorkaround(this.newData),this.runSaveTask(" [editor] "+e)},_syncNewDataFromEditor:function(){var t=this.getActiveEditor();t&&(this.newData=Ext.apply(this.newData,t.getData()),this._applySharedIconWorkaround(this.newData))},_applySharedIconWorkaround:function(t){Ext.isEmpty(this.getCurrentMailboxIfNeedCopyTo())||(t.isCopyBeforeSend=!0)},_onEditorDestroy:function(t){this.editors.length>1&&t.isWaked&&(t.checkSubjectChange(t.mailCmp.subject),this.wakeEditor(void 0,t)),this.editors.remove(t),this.checkDestroy()},replaceInlineImageToIMAPFormat:function(t){return SYNO.SDS.MailClient.DraftLib.DraftProcessor.replaceInlineImageToIMAPFormat(t)},checkDestroy:function(){this.editors.length||this.isBusy(!0)||this.isSending||this.isDiscarding||this._destroy()},_destroy:function(){delete this.manager.draftHash[this.id],this.saveTask.disable(),this.postCtrl.closeWindow(),Ext.destroy(this)},getReceivers:function(){var t=this.newData;return[t.from].concat(t.to).concat(t.cc)},getPublicKeyInfo:function(){return SYNO.SDS.MailClient.DraftLib.PGP.getPublicKeyInfo(this.getReceivers())},getSavingValidateData:function(t){return SYNO.SDS.MailClient.DraftLib.DraftProcessor.getSavingValidateData(t)},getSendingValidateData:function(t){return SYNO.SDS.MailClient.DraftLib.DraftProcessor.getSendingValidateData(t)},hasPendingAttachments:function(){var t=this.data;return t.temp_attachment.length>0||t.copied_attachment.length>0},getUploadQueue:function(){return this.uploadOperator.getUploadQueue()},isSenderHasPrivateKey:function(){var t=SYNO.SDS.MailClient.PGP.Encryption,e=SYNO.SDS.MailClient.Format.toEmail(this.newData.from);return t.getPrivateKeyByEmail(e).length>0},getTargetWin:function(){var t=this.getWakedEditor()||this.editors[0];return t?t.findWindow():SYNO.SDS.MailClient.Window},stripHTML:function(t){var e=document.createElement("div");return e.innerHTML=t,e.textContent},getCurrentMailboxIfNeedCopyTo:function(){return SYNO.SDS.MailClient.DraftLib.DraftProcessor.getCurrentMailboxIfNeedCopyTo(this.data)},_showInvalidDraftMsg:function(t){this.ctrl.showInvalidDraftMsg(t)},_deleteDraft:function(){this.postCtrl.deleteDraft([{id:this.threadId,data:[this.id]}])},_eventPromise:function(t){return new Promise(function(e,i){this.on(t,function(){e()},this,{single:!0})}.bind(this))},getSenderUploadLimit:function(){return SYNO.SDS.MailClient.Define.getUploadLimit(this.newData.from)},getSenderMaxMailSize:function(){return SYNO.SDS.MailClient.Define.getMaxMailSize(this.newData.from)}}),Ext.define("SYNO.SDS.MailClient.DraftLib.DraftManager",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.DraftLib.DraftObject"],statics:{canOpenDraft:function(){var t;return SYNO.SDS.MailClient.SMTP.smtp.length||(t=SYNO.SDS.MailClient.Define.badServerSMTPHint),!t||(SYNO.SDS.MailClient.Window.getMsgBox().alert("",t),!1)},delayedReloadMailboxList:function(){this._delayedReloadMailboxListTask||(this._delayedReloadMailboxListTask=new Ext.util.DelayedTask(function(){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()}.bind(this))),this._delayedReloadMailboxListTask.delay(3e3)}},constructor:function(){window.dm=this,this.callParent(arguments),this.draftHash={},window.onbeforeunload=function(){if(!1===this.onBeforeUnload())return _T("desktop","confirm_leave")}.createDelegate(this)},onBeforeUnload:function(){var t,e,i=window.tinymce.editors;for(t=0;t<i.length;t++)if((e=i[t].owner)instanceof SYNO.SDS.MailClient.Editor.EditorPanel&&e.draftObj&&!e.draftObj.canUnload())return!1;var n;for(n in this.draftHash)if(this.draftHash.hasOwnProperty(n)&&!this.draftHash[n].canUnload())return!1},open:function(t,e,i){i?e&&(this.draftHash[e]=i):e?this.draftHash.hasOwnProperty(e)?i=this.draftHash[e]:(i=this._createDraftObject(t,e),this.draftHash[e]=i):i=this._createDraftObject(t),i.bind(t),SYNO.SDS.MailClient.Control.View.hideToast()},_createDraftObject:function(t,e){var i=SYNO.SDS.MailClient.Define.DraftType,n={manager:this,refMsg:t.refMsg,replyType:t.replyType,canIncludeAttachment:t.canIncludeAttachment,data:Ext.copyTo({},t.draftRec.data,"id,from,to,cc,bcc,subject,body,attachment,draft_type,reply_to")};return e?(n.id=e,n.threadId=SYNO.SDS.MailClient.Settings.conversation_view?t.draftRec.data.thread_id:t.draftRec.data.reply_to):t.refMsg&&(n.data.reply_to=t.refMsg.id,n.data.draft_type="forward"===t.replyType?i.FORWARD:i.REPLY),new SYNO.SDS.MailClient.DraftLib.DraftObject(n)},getIdObj:function(t){var e,i,n,a,o=(Ext.isString(t)?t:"").split(" "),s=-1!==o.indexOf("send"),l=-1!==o.indexOf("discard"),r=Object.keys(this.draftHash),d={};for(e=0;e<r.length;e++)i=parseInt(r[e],10),n=this.draftHash[i],(a=n.threadId)&&(s&&n.isSending||l&&n.isDiscarding)&&(d[a]=d[a]||[],d[a].push(i));return d}}),Ext.define("SYNO.SDS.MailClient.DraftLib.DraftObjectController",{extend:"Ext.util.Observable",requires:[],constructor:function(t){this.callParent(arguments),this._obj=t},close:function(){this._forEachEmbed(function(t,e,i){e.removeEditor(t)},this),this._forEachPopout(function(t,e){e.close()},this),this._forEachNewWin(function(t,e){e.removeEditor()},this)},wakeEditor:function(t){var e=this._obj;e.wakeEditor(t),e.closeNotWakedPopoutEditor()},upload:function(t){this._obj.upload(t)},repairBody:function(t,e,i,n){this._forEachWaked(function(a){a.repairBody(t,e,i,n)},this)},updateImage:function(t){this._forEachWaked(function(e){e.ddupload.updateImage(t)},this)},showInvalidDraftMsg:function(t){this._forEachWaked(function(e){e.showInvalidDraftMsg(t)},this)},handleSubjectChange:function(t){var e=SYNO.SDS.MailClient.Define.DraftType,i=this._obj;Ext.isDefined(i.data.draft_type)&&i.data.draft_type!==e.NEW_THREAD&&(i.newData=Ext.apply(i.newData,{reply_to:0,draft_type:e.NEW_THREAD}),i.clearReplyTo=!0,i.closeOtherEditors(t))},handleUploadProgress:function(t,e){this._forEachWaked(function(i){i.ddupload.onProgress(t,e)},this)},handleUploadFinish:function(t){this._forEachWaked(function(e){e.ddupload.onFinish(t)},this)},handleUploadRefresh:function(t){this._forEachWaked(function(t){t.ddupload.fireEvent("refresh")},this)},handleUploadFailed:function(t){this._forEachWaked(function(e){e.ddupload.onFailed(t)},this)},removeEditorAndAddSendingDraft:function(){this._forEachEmbed(function(t,e,i){var n=this._obj,a=n.newData,o=n.tempDraftId,s=o||t.draftRec.id,l=n.getUploadQueue();!this.isSubjectChanged()&&SYNO.SDS.MailClient.Settings.conversation_view&&i.appendSendingDraft(s,a,l),e.removeEditor(t)},this)},isSubjectChanged:function(){var t,e,i=this._obj.getActiveEditor();return!!i&&(t=i.getSubject(),e=i.draftRec.get("subject"),!SYNO.SDS.MailClient.ComposerLib.Draft.isSameSubject(t,e))},_getActiveEditor:function(){return this._obj.getActiveEditor()},_forEachEmbed:function(t,e){this._forEachMatchedEditor(this._isEmbbedded,function(i){t.call(e||window,i,i.composerPanel,i.composerPanel.messagePanel)},e)},_forEachPopout:function(t,e){this._forEachMatchedEditor(this._isPopout,function(i){t.call(e||window,i,i.popoutWindow)},e)},_forEachNewWin:function(t,e){this._forEachMatchedEditor(this._isNewWin,function(i){t.call(e||window,i,i.newWinEditor)},e)},_forEachWaked:function(t,e){this._forEachMatchedEditor(this._isWaked,t,e)},_isEmbbedded:function(t){return t.isEmbedded},_isPopout:function(t){return t.level===SYNO.SDS.MailClient.Editor.LevelEnum.MAIN_WIN_POPOUT},_isNewWin:function(t){return t.level===SYNO.SDS.MailClient.Editor.LevelEnum.NEW_WIN},_isWaked:function(t){return t.isWaked},_forEachMatchedEditor:function(t,e,i){this._obj.editors.filter(t).forEach(e,i||window)}}),Ext.define("SYNO.SDS.MailClient.DraftLib.Uploader",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.AppLib.Html5Uploader"],upload:function(t,e){var i=SYNO.SDS.MailClient.AppLib.Html5Uploader,n=SYNO.SDS.MailClient.WebAPI;return"sticker"===t.format?n.send("uploadSticker",{id:t.sticker_id}):"ds"===t.format?n.send("uploadDSM",{source:t.source,is_inline:!!t.inline}):"external"===t.format?n.send("uploadUrl",{url:t.url}):i.upload({file:t,name:t.name,is_inline:!!t.inline},function(t,i){e(t,i)}.createDelegate(this,[t],!0))}}),Ext.define("SYNO.SDS.MailClient.DraftLib.UploadOperator",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.DraftLib.Uploader"],constructor:function(t){this.callParent(arguments),this._queue=[],this._doneFiles=[],this._draftObj=t,this._runningPromise=null,this._deferred=new SYNO.SDS.MailClient.UtilLib.Deferred,this._deferred.resolve()},getUploadQueue:function(){return this._queue},add:function(t){this._queue.push(t),this._deferred.isPending()||(this._deferred=new SYNO.SDS.MailClient.UtilLib.Deferred)},process:function(){this._runningPromise||this._processQueue()},isBusy:function(){return this._queue.length>0},ensureIdle:function(){return this._deferred},terminate:function(){this._runningPromise&&(this._runningPromise.abort(),this._runningPromise=null),this._deferred.resolve(),this._queue=[]},updateImagesByUploadedFiles:function(){var t=this._getDraft();this._doneFiles.forEach(function(e){SYNO.SDS.MailClient.DraftLib.DraftProcessor.updateImage(t,e)}.bind(this))},_upload:function(t){var e=SYNO.SDS.MailClient.DraftLib.DraftProcessor,i=SYNO.SDS.MailClient.DraftLib.Uploader;if(this._isFileSizeExceeded(t))return this._handleFileSizeExceeded(t);var n=function(t,e){this.fireEvent("uploadprogress",t,e)}.bind(this);return this._runningPromise=i.upload(t,n),this._runningPromise.then(function(i){var n=this._getDraft(),a=this._getEditor();this._runningPromise=null,n.temp_attachment.push(t),t.temp_id=i.id,t.md5=i.md5,i.content_id&&(t.cid=i.content_id),t.inline?(e.updateImage(n,t,a),this.fireEvent("updateimage",t),this._removeQueueAndProcessNext(t)):(this.fireEvent("uploadfinish",t),this.fireEvent("uploadrefresh"),this._removeQueueAndProcessNext(t))}.bind(this)).catch(function(e){this._runningPromise=null,this._handleUploadFileError(e,t)}.bind(this))},_getDraft:function(){return this._draftObj.newData},_getEditor:function(){return this._draftObj.getActiveEditor()},_removeQueueAndProcessNext:function(t){this._queue.remove(t),this._doneFiles.push(t),this._processQueue()},_processQueue:function(){this._queue.length>0?this._upload(this._queue[0]):(this._deferred.resolve(),this.fireEvent("empty"))},_isFileSizeExceeded:function(t){return Ext.isNumber(t.size)&&t.size>this._draftObj.getSenderUploadLimit()},_handleFileSizeExceeded:function(t){return this._updateUsageLimitInfo().then(function(){t.size>this._draftObj.getSenderMaxMailSize()?this._handleUploadFileError({code:502},t):this._handleUploadFileError({code:460},t)}.bind(this))},_updateUsageLimitInfo:function(){return SYNO.SDS.MailClient.WebAPI.send("getUsageLimit").then(function(t){SYNO.SDS.MailClient.Info.usage_limits=t.limit_list}).catch(function(t){}.bind(this))},_appendSenderInfo:function(t){return t.hasOwnProperty("senderInfo")||(t.senderInfo=this._draftObj.data),t},_handleUploadFileError:function(t,e){this.fireEvent("error",this._appendSenderInfo(t)),this.fireEvent("uploadfailed",e),this._removeQueueAndProcessNext(e)}}),Ext.define("SYNO.SDS.MailClient.DraftLib.PGP",{extend:"Ext.util.Observable",singleton:!0,requires:[],process:function(t,e,i,n,a){t=Ext.apply({},t);var o,s=[],l=[],r=SYNO.SDS.MailClient.Format.toEmail(t.from),d=this.stripHTMLWithBlockQuote(t.body),c=SYNO.SDS.MailClient.PGP.Encryption,h=function(){return n?c.getSigningKey(r,a).then(function(t){return l=[t],c.ensureKeysUnlocked(l,a)}.bind(this)):(l=[],Promise.resolve())}.bind(this);return i?(o=this.getPublicKeyInfo(e),s=o.publicKeys,c.showSendConfirmDialog(a).then(h).then(function(t){return c.encrypt(d,s,l)}).then(function(e){return t.body=e,t})):n?c.showSendConfirmDialog(a).then(h).then(function(t){return c.sign(d,l)}).then(function(e){return t.body=e.data,window.lastSign=e.data,t}):Promise.resolve(t)},getPublicKeyInfo:function(t){function e(t,e,i){return i.indexOf(t)===e}var i=[],n=[],a=SYNO.SDS.MailClient.PGP.Encryption;return Ext.each(t,function(t){var e=SYNO.SDS.MailClient.Format.toEmail(t);if(e){var o=a.getPublicKeyByEmail(e);o.length>0?i=i.concat(o):n.push(e)}}),{publicKeys:i.filter(e),unsatisfiedAddresses:n.filter(e)}},stripHTMLWithBlockQuote:function(t){var e,i,n=document.createElement("div");n.innerHTML=t;do{i=Ext.DomQuery.jsSelect("blockquote:not(:has(blockquote))",n),i.forEach(function(t){e=document.createElement("div"),e.textContent=t.textContent.replace(/^/gm,"> "),t.parentNode.replaceChild(e,t)})}while(i.length>0);return n.textContent}}),Ext.define("SYNO.SDS.MailClient.DraftLib.SaveOperator",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.DraftLib.DraftProcessor","SYNO.SDS.MailClient.DraftLib.Saver"],constructor:function(t){this.callParent(arguments),this._draftObj=t,this._runningPromise=null,this._deferred=new SYNO.SDS.MailClient.UtilLib.Deferred,this._deferred.resolve(),this._isSaving=!1},isSaving:function(){return this._isSaving},ensureIdle:function(){return this._deferred},save:function(t){var e=this._draftObj,i=e.id,n=!i,a=e.clearReplyTo,o={};return o.isCreated=n,o.clearReplyTo=a,this._runningPromise=this._createOrSetDraft(t),this._deferred=new SYNO.SDS.MailClient.UtilLib.Deferred,this._isSaving=!0,this._runningPromise.then(function(t){var e=t[0],s=t[1],l=i||e.id;return o.copiedAttachment=e.copied_attachment,n&&this._updateId(l),this._getAndUpdateDraft(l,n,a,s)}.bind(this)).then(function(t){return this._isSaving=!1,o.draftResp=t,this._deferred.resolve(),o}.bind(this)).catch(function(t){throw this._isSaving=!1,this._deferred.resolve(),t}.bind(this))},terminate:function(){this._runningPromise&&(this._runningPromise.abort(),this._runningPromise=null),this._isSaving=!1},_getAndUpdateDraft:function(t,e,i,n){var a=SYNO.SDS.MailClient.DraftLib.Saver;return this._runningPromise=a.getDraft([t]),this._runningPromise.then(function(e){if(0===e.draft.length)return Promise.reject({code:481});var i=this._draftObj,a=e.draft[0];return this._updateId(t,a.thread_id),this._updateAttachments(a.attachment,n),i.data.temp_attachment=[],i.data.attachment=a.attachment,e}.bind(this))},_createOrSetDraft:function(t){var e=SYNO.SDS.MailClient.DraftLib.Saver,i=this._draftObj,n=i.id,a=i.clearReplyTo,o=i.refMsg,s=i.replyType;return n?e.setDraft(t,n,a):e.createDraft(t,o,s,a)},_updateId:function(t,e){var i=this._draftObj;i.id=t,SYNO.SDS.MailClient.Settings.conversation_view?i.threadId=e:i.threadId=i.refMsg?i.refMsg.id:t,i.data.id=t,i.manager.draftHash[t]=i,Ext.each(i.editors,function(e){e.changeDraftId(t)})},_updateAttachments:function(t,e){SYNO.SDS.MailClient.DraftLib.DraftProcessor.updateAttachments(this._draftObj.newData,t,e)}}),Ext.define("SYNO.SDS.MailClient.DraftLib.SendOperator",{extend:"Ext.util.Observable",requires:["SYNO.SDS.MailClient.DraftLib.DraftProcessor","SYNO.SDS.MailClient.MessageHouseLib.Util"],constructor:function(t){this.callParent(arguments),this._draftObj=t},send:function(t,e,i){var n=SYNO.SDS.MailClient.DraftLib.DraftProcessor,a=this._draftObj,o=t.temp_attachment,s=a.willEncrypt||a.willSign,l={};return s?t.is_plain=!0:(t.body=n.replaceInlineImageToIMAPFormat(t.body),t.body=n.updateReplyQuoteForSet(t.body)),function(){return e||n.checkDirtyAndUpdateDraft(t,a.data)?this._setDraft(t,o):Promise.resolve()}.bind(this)().then(this._sendDraft.bind(this,i)).then(this._getMessage.bind(this)).then(function(t){return l.getMessageResp={message:SYNO.SDS.MailClient.Format.formatAddrsOfMsgsToNormal(t)},l}.bind(this))},_setDraft:function(t,e){var i,n=SYNO.SDS.MailClient.DraftLib.DraftProcessor,a=this._draftObj,o=a.id,s=a.clearReplyTo;return t.id=o,t.attachment=n.getAttachmentIds(t.attachment),t.temp_attachment=n.getAttachmentIds(t.temp_attachment,!0),s&&(t.draft_type=0),i=SYNO.SDS.MailClient.Format.formatAddrsOfMsgToRFC822(t),SYNO.SDS.MailClient.WebAPI.send("setDraft",i).then(function(t){return n.updateAttachments(a.newData,t.attachment,e),a.temp_attachment=[],a.attachment=t.attachment,a.clearReplyTo=!1,t}.bind(this))},_getMessage:function(){var t,e=this._draftObj,i=e.id;return t={id:[i],additional:["blockquote"]},SYNO.SDS.MailClient.WebAPI.send("getMessage",t).then(function(t){return SYNO.SDS.MailClient.MessageHouseLib.Util.fillEncryptionInfoForMsgs(t.message)})},_sendDraft:function(t){var e=SYNO.SDS.MailClient.DraftLib.DraftProcessor,i=this._draftObj,n=i.id;return SYNO.SDS.MailClient.WebAPI.sendDraft({id:n,copy_to:e.getCurrentMailboxIfNeedCopyTo(i.data,t)})}}),Ext.define("SYNO.SDS.MailClient.DraftLib.SharingLink",{extend:"Ext.util.Observable",singleton:!0,requires:[],process:function(t){var e=document.createElement("div");e.innerHTML=t.body;var i=[],n=Ext.get(e).query("[data-file-url]");return n.forEach(function(t){i.push(t.dataset.fileUrl)}),Ext.isEmpty(i)?Promise.resolve(t):(n.forEach(function(t){t.removeAttribute("data-file-url"),t.removeAttribute("data-config"),t.removeAttribute("data-file-size"),t.removeAttribute("data-file-name");var e=Ext.DomQuery.jsSelect("[data-link-setting-button]",t)[0],i=Ext.DomQuery.jsSelect("[data-link-delete-button]",t)[0];e.parentNode.removeChild(e),i.parentNode.removeChild(i)}),t.body=e.innerHTML,Promise.resolve(t))}}),Ext.define("SYNO.SDS.MailClient.DraftLib.DefaultPostController",{extend:"Ext.util.Observable",constructor:function(t){this.callParent(arguments),this._draftObj=t},prepareForSending:function(){var t=SYNO.SDS.MailClient.Control,e=this._draftObj;t.Draft.beforeSend(e.threadId,e.id,e.newData),t.View.expandLastMsg()},updateSendingDraft:function(){var t=this._draftObj;SYNO.SDS.MailClient.Control.Draft.updateSendingDraft(t.threadId,t.id,t.newData)},updateAfterMailSent:function(t){SYNO.SDS.MailClient.Control.Draft.updateSentDraft(t),SYNO.SDS.MailClient.DraftLib.DraftManager.delayedReloadMailboxList()},reloadMailAndSidebarIfNeeded:function(){var t=SYNO.SDS.MailClient.Control,e=SYNO.SDS.MailClient.Define;t.Sidebar.reloadMailboxList(),t.Mail.isDisplayingMailboxId(e.draftsId)&&t.Mail.reloadMail()},reloadMailboxList:function(){SYNO.SDS.MailClient.Control.Sidebar.reloadMailboxList()},filterNotExistMsgs:function(){SYNO.SDS.MailClient.Control.Mail.applyPostProcessor()},handleClearReplyTo:function(t){var e=this._draftObj;e.closeOtherEditors(),e.clearReplyTo=!1,SYNO.SDS.MailClient.Control.Thread.addNewThreadToDraftMailboxIfNeeded(t)},addDraft:function(t){SYNO.SDS.MailClient.Control.Thread.addDraft(t)},editDraft:function(t){SYNO.SDS.MailClient.Control.Thread.editDraft(t)},deleteDraft:function(t){SYNO.SDS.MailClient.Control.Thread.deleteDraft(t)},markReplyForward:function(t,e){SYNO.SDS.MailClient.Control.Thread.modifyThread("edit",[{id:this._draftObj.threadId,prop:{reply_forward:{id:t,draftType:e}}}])},decreaseDraftUnreadCountIfNeeded:function(){var t=SYNO.SDS.MailClient.Lib.Thread.hasLessOrEqualToOneDraftOrThreadNotExisted(this._draftObj.threadId),e=!1;return!this._draftObj.isSentWithoutFirstTimeSaving&&t&&(SYNO.SDS.MailClient.UIActorLib.Util.decreaseDraftUnreadCount(),e=!0),e},increaseDraftUnreadCount:function(){SYNO.SDS.MailClient.UIActorLib.Util.increaseDraftUnreadCount()},resumeEditor:function(){SYNO.SDS.MailClient.Control.Draft.resumeEditor(this._draftObj)},closeWindow:function(){}}),Ext.define("SYNO.SDS.MailClient.DraftLib.ComposeModePostController",{extend:"Ext.util.Observable",constructor:function(t){this.callParent(arguments),this._draftObj=t},prepareForSending:function(){SYNO.SDS.MailClient.Control.Main.get("ComposePage").removeEditor()},updateSendingDraft:function(){},updateAfterMailSent:function(){},reloadMailAndSidebarIfNeeded:function(){},reloadMailboxList:function(){},filterNotExistMsgs:function(){},handleClearReplyTo:function(){},addDraft:function(){},editDraft:function(){},deleteDraft:function(){},markReplyForward:function(){},decreaseDraftUnreadCountIfNeeded:function(){},increaseDraftUnreadCount:function(){},resumeEditor:function(){var t=this._draftObj;SYNO.SDS.MailClient.Control.Main.get("ComposePage").resumeEditor(t.newData,t.id,t.threadId)},closeWindow:function(){setTimeout(function(){window.close()},3e3)}}),Ext.define("SYNO.SDS.MailClient.DraftLib.Main",{extend:"Ext.util.Observable",singleton:!0,requires:["SYNO.SDS.MailClient.UtilLib.DelayedPromise","SYNO.SDS.MailClient.DraftLib.DraftManager","SYNO.SDS.MailClient.DraftLib.DraftObjectController","SYNO.SDS.MailClient.DraftLib.DraftProcessor","SYNO.SDS.MailClient.DraftLib.UploadOperator","SYNO.SDS.MailClient.DraftLib.PGP","SYNO.SDS.MailClient.DraftLib.Saver","SYNO.SDS.MailClient.DraftLib.SaveOperator","SYNO.SDS.MailClient.DraftLib.SendOperator","SYNO.SDS.MailClient.DraftLib.SharingLink","SYNO.SDS.MailClient.DraftLib.DefaultPostController","SYNO.SDS.MailClient.DraftLib.ComposeModePostController"]}),Ext.define("SYNO.SDS.MailClient.PopOutWindowComposer",{extend:"SYNO.SDS.Window",requires:["SYNO.SDS.MailClient.Editor.EditorPanel"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.on({scope:this,afterrender:function(){this.onWinResize(this.getWidth())},resize:function(t,e){this.onWinResize(e)},activate:function(){this.editor.onComposerUnmask()},deactivate:function(){this.editor.onComposerMask()}})},fillConfig:function(t){this.editor=new SYNO.SDS.MailClient.Editor.EditorPanel(Ext.apply({popoutWindow:this,level:SYNO.SDS.MailClient.Editor.LevelEnum.MAIN_WIN_POPOUT},t.editorConfig)),delete t.editorConfig;var e=Math.floor(.7*Ext.getBody().getWidth()),i=Math.floor(.9*(Ext.getBody().getHeight()-36)),n={owner:SYNO.SDS.MailClient.Window,cls:"syno-mc-composer-win syno-mc-modal-window",title:SYNO.SDS.MailClient._T("common","compose"),minWidth:600,minHeight:420,width:Math.max(Math.min(e,1150),600),height:Math.max(Math.min(i,800),420),layout:"fit",closable:!0,constrain:!0,minimizable:!0,maximizable:!1,buttonAlign:"left",fbar:new Ext.Toolbar({cls:"x-statusbar",items:[{itemId:"send",xtype:"syno_button",cls:"syno-mc-send",btnStyle:"blue",text:SYNO.SDS.MailClient._T("composer","send"),handler:this.editor.clickSend.createDelegate(this.editor,[])},{itemId:"includeAttachment",xtype:"syno_checkbox",boxLabel:SYNO.SDS.MailClient._T("composer","include_original_attachments"),hidden:!this.editor.draftObj||!this.editor.draftObj.refMsg||!this.editor.draftObj.refMsg.attachment.length||"forward"===this.editor.draftObj.replyType,listeners:{check:this.editor.checkIncludeAttachment.createDelegate(this.editor,[])}},"->",this.syncStatus=new SYNO.ux.DisplayField({cls:"sync-status"}),"-",{itemId:"discard",xtype:"syno_button",cls:"syno-mc-discard",iconCls:"syno-mc-print-icon",tooltip:SYNO.SDS.MailClient._T("composer","discard"),handler:this.editor.clickDiscard.createDelegate(this.editor,[])}]}),items:[this.editor]};return Ext.apply(n,t)},adjTopHeight:function(){this.editor&&this.editor.adjTopHeight()},afterRender:function(){this.callParent(arguments),this.alignTo(this.owner?this.owner.el:document.body,"c-c")},onDestroy:function(){this.callParent(arguments),this.animateTask&&this.animateTask.cancel()},show:function(){this.callParent(arguments),this.barItem.highlight(!0)},hide:function(){this.callParent(arguments),this.barItem.highlight(!1)},isAlwaysOnTop:function(){return!1},onWinResize:function(t){this.editor&&this.editor.adjTopWidth(t-this.body.getPadding("lr"))}}),Ext.define("SYNO.SDS.MailClient.PopOutWindowManager",{extend:"Ext.BoxComponent",requires:["SYNO.SDS.MailClient.PopOutWindowManagerItem"],singleton:!0,constructor:function(t){this.callParent([this.fillConfig(t)]),this.barItems=[],this.disableMask=new Ext.Container({cls:"syno-mc-popout-manager-bar-mask",renderTo:this.el})},fillConfig:function(t){var e={renderTo:Ext.getBody(),cls:"syno-mc-popoutwin-manager-bar"};return Ext.apply(e,t)},init:function(){this.mon(SYNO.SDS.MailClient.Window.el,"mousedown",this.onMainWinActivate,this),this.mon(SYNO.SDS.MailClient.Window,"deactivate",this.onMainWinDeactivate,this),this.mon(SYNO.SDS.MailClient.Switch,"cardwidthchange",this.onCardWidthChange,this)},onCardWidthChange:function(t){this.adjustItemDisplayOrder()},onMainWinActivate:function(t){this.hideComposer(),this.adjZIndex(SYNO.SDS.MailClient.Window)},onMainWinDeactivate:function(t){this.adjZIndex(t)},adjZIndex:function(t){var e=t.el.dom,i=e.currentStyle||window.getComputedStyle(e);this.el&&this.el.applyStyles("z-index: "+(parseInt(i.zIndex,10)+1))},hideComposer:function(){var t;for(t=0;t<this.barItems.length;t++)this.barItems[t].win.minimize()},disableComposer:function(){this.hideComposer(),this.disableMask.el.applyStyles("display: block;")},enableComposer:function(){this.disableMask.el.applyStyles("display: none;")},openComposerFromMailtoLink:function(t){this._openComposer(t,null,null,!0)},
openComposer:function(t,e,i){this._openComposer(t,e,i,!1)},_openComposer:function(t,e,i,n){if(SYNO.SDS.MailClient.DraftLib.DraftManager.canOpenDraft()){Ext.isObject(t)?t instanceof Ext.data.Record||(t=this.getDraftRecord(t)):t=this.getDraftRecord();var a={isNew:!t||!t.get("id"),isMailtoLink:n,draftRec:t};e&&(a.draftObj=e),i&&(a.focusTarget=i);var o={editorConfig:a,listeners:{scope:this,close:this.onWinClose}},s=new SYNO.SDS.MailClient.PopOutWindowComposer(o);this.addItem(t,s),s.show(),s.adjTopHeight()}},getDraftRecord:function(t){return new Ext.data.Record(Ext.apply({subject:"",to:[],cc:[],bcc:[],body:"",attachment:[]},t))},onSwitchDraftChange:function(t,e){if("edit"===t||"delete"===t){var i,n,a,o;for(i=0;i<e.length;i++)for(n=0;n<this.barItems.length;n++)if(o=this.barItems[n],"edit"===t)e[i].data.id===o.win.editor.draftRec.get("id")&&o.updateText(e[i].data.subject);else for(a=0;a<e[i].data.length;a++)e[i].data[a]!==o.win.editor.draftRec.get("id")||o.win.editor.preventDelete||o.win.close()}},onWinClose:function(t){this.deleteItem(t.barItem)},getItem:function(t){var e,i;for(e=0;e<this.barItems.length;e++)if(i=this.barItems[e],i.win.editor.draftRec.get("id")===t)return i},addItem:function(t,e){var i=new SYNO.SDS.MailClient.PopOutWindowManagerItem({win:e,listeners:{scope:this,itemclick:this.toggleItem}});e.barItem=i,this.barItems.push(i),i.render(this.el),i.updateText(t.get("subject")),this.adjustItemDisplayOrder()},deleteItem:function(t){this.barItems.remove(t),t.destroy(),this.adjustItemDisplayOrder()},toggleItem:function(t){if(t.win.isVisible())return void t.win.hide();var e,i,n;for(e=0;e<this.barItems.length;e++)if(i=this.barItems[e].win,i.el.hasClass("active-win")){n=i;break}n&&Math.abs(t.win.x-n.x)<10&&Math.abs(t.win.y-n.y)<10&&(t.win.x+=30,t.win.y+=30,(t.win.x+t.win.getWidth()>Ext.getBody().getWidth()||t.win.y+t.win.getHeight()>Ext.getBody().getHeight())&&(t.win.x=10,t.win.y=10)),t.win.show(),t.updateAccessTime(),this.adjustItemDisplayOrder()},repositionTodoPlugin:function(){var t=SYNO.SDS.AppMgr.getByAppName("SYNO.Cal.Todo.Plugin.Instance")[0],e=t&&t.window;e&&e.el.setStyle("right",12+(this.chatPluginWidth?this.chatPluginWidth+8:0)+"px")},shiftForChatPlugin:function(t,e){this.chatPluginWidth=t?e:0,this.shiftForPlugins(),this.repositionTodoPlugin(),this.adjustItemDisplayOrder()},shiftForTodoPlugin:function(t,e){this.todoPluginWidth=t?e:0,this.shiftForPlugins(),this.adjustItemDisplayOrder()},shiftForPlugins:function(){this.el.setStyle("right",12+(this.chatPluginWidth?this.chatPluginWidth+8:0)+(this.todoPluginWidth?this.todoPluginWidth+8:0)+"px")},adjustItemDisplayOrder:function(){if(0!==this.barItems.length){var t=0,e=parseInt(this.el.getStyle("right"),10),i=Math.floor((window.innerWidth-6-e)/208),n=[],a=0;if(i>=this.barItems.length)for(t=0;t<this.barItems.length;t++)this.barItems[t].setVisible(!0);else{for(t=0;t<this.barItems.length;t++)n.push(this.barItems[t].accessTime);for(n.sort(function(t,e){return e-t}),a=n[i-1],t=0;t<this.barItems.length;t++)this.barItems[t].setVisible(this.barItems[t].accessTime>=a)}}}}),Ext.define("SYNO.SDS.MailClient.PopOutWindowManagerItem",{extend:"Ext.Container",requires:["SYNO.SDS.MailClient.PopOutWindowComposer"],constructor:function(t){this.callParent([this.fillConfig(t)]),this.addEvents("itemclick"),this.on("afterrender",function(){this.el.on("click",this.click,this)},this),this.highlight(this.win.isVisible()),this.updateAccessTime()},fillConfig:function(t){var e={cls:"syno-mc-popoutwin-manager-bar-item",items:[{itemId:"text",cls:"text",xtype:"container"},{itemId:"close",cls:"close-btn",xtype:"syno_button",scope:this,handler:this.clickClose}]};return Ext.apply(e,t)},updateText:function(t){t=t.trim()||"("+SYNO.SDS.MailClient._T("mail","empty_subject")+")";var e=this.getComponent("text");e.update(Ext.util.Format.htmlEncode(t)),e.el.dom.title=t},clickClose:function(){this.win.close()},click:function(){this.updateAccessTime(),this.fireEvent("itemclick",this)},highlight:function(t){this[t?"addClass":"removeClass"]("highlight")},updateAccessTime:function(){this.accessTime=(new Date).getTime()}}),Ext.define("SYNO.SDS.MailClient.Application",{extend:"SYNO.SDS.AppInstance",appWindowName:"SYNO.SDS.MailClient.MainWindow"}),Ext.define("SYNO.SDS.MailClient.MainWindow",{extend:"SYNO.SDS.MailClient.AppWindow",xtype:"mc_MainWindow",isBeta:!1,isAlwaysOnBottom:function(){return!0},constructor:function(t){SYNO.SDS.MailClient.AppLib.IdleDetector.init(),SYNO.SDS.MailClient.AppLib.VisibleDetector.init(),SYNO.SDS.MailClient.AppLib.StyleLoader.findAndMarkMailClientStyleSheet(),this.panellist={},SYNO.SDS.MailClient.Settings={mark_as_read_time:1,conversations_per_page:100},SYNO.SDS.MailClient.Window=this,SYNO.SDS.MailClient.History.init(),SYNO.SDS.MailClient.Define.isMessageMode&&SYNO.SDS.MailClient.Framework.isAccessible("window.opener.SYNO.SDS.MailClient.Switch")&&SYNO.SDS.MailClient.Switch.copy(window.opener.SYNO.SDS.MailClient.Switch),SYNO.SDS.MailClient.Viewer=new SYNO.SDS.MailClient.AttachmentViewer,this.draftManager=new SYNO.SDS.MailClient.DraftLib.DraftManager,SYNO.SDS.MailClient.Define.isNormalMode&&(this.navigator=new SYNO.SDS.MailClient.KeyNavigator);var e={height:580,width:1080,minHeight:480,minWidth:1080,listeners:{scope:this,afterrender:function(){this.popOutWinManager=SYNO.SDS.MailClient.PopOutWindowManager,this.popOutWinManager.init(),this.setStatusBusy(),SYNO.SDS.MailClient.AppLib.ChatPlugin.init()}}};Ext.getBody().addClass("syno-mc-app"),SYNO.SDS.MailClient.Define.isNormalMode?(e.layout="fit",Ext.getBody().addClass("syno-mc-normal-page")):SYNO.SDS.MailClient.Define.isMessageMode||SYNO.SDS.MailClient.Define.isComposeMode?(e.layout="fit",e.showHelp=!1,Ext.getBody().addClass("syno-mc-message-page"),SYNO.SDS.MailClient.Format.isDSM6()?SYNO.SDS.Desktop.addClass("syno-mc-message-desktop"):SYNO.SDS.Desktop.$el.classList.add("syno-mc-message-desktop")):(e.showHelp=!1,e.autoHeight=!0,e.autoWidth=!0,Ext.getDoc().dom.documentElement.classList.add("syno-mc-print-reset"),Ext.getBody().addClass("syno-mc-print-page")),this.callParent([Ext.apply(e,t)]),this.navigator&&this.navigator.setupMainWin(this),this.initTinymcePlugins(),SYNO.SDS.MailClient.Define.isComposeMode?this.appInitSimple():this.appInit()},appInit:function(){var t=SYNO.SDS.MailClient.AppLib.Initiator,e=SYNO.SDS.MailClient.AppLib.StyleLoader,i=SYNO.SDS.MailClient.AppLib.DownloadTokenRunner;t.getAppInfo().then(function(e){var i=e.succ,n=e.resp,a=e.parsedResp;return!i||a.has_fail?(this._handleWebAPIError(n),Promise.reject("getAppInfo failed")):t.getMailboxAndLabelInfo()}.bind(this)).then(function(e){return Promise.all([t.getAppData(),SYNO.SDS.MailClient.Control.Mail.prefetchPriorityMailbox()]).catch(function(t){return this._handleWebAPIError(t),Promise.reject("getAppData or prefetchPriorityMailbox failed")}.bind(this))}.bind(this)).then(function(){e.load(),SYNO.SDS.MailClient.PushServerLib.Main.login(),SYNO.SDS.MailClient.PushServerLib.Main.monDetector(),t.getOtherAppData(),t.getContact(),this.delayConstructor()}.bind(this)).then(function(){return SYNO.SDS.MailClient.Define.isPrintMode||i.startTask(36e5),t.refreshCachedSetting()}).then(function(){return t.refreshCachedData()}).then(function(){setTimeout(function(){t.syncAA()},5e3)}).catch(function(t){SYNO.Debug.error(t)}.bind(this))},appInitSimple:function(){var t=SYNO.SDS.MailClient.AppLib.Initiator;t.getAppInfo().then(function(e){var i=e.succ,n=e.resp,a=e.parsedResp;return!i||a.has_fail?(this._handleWebAPIError(n),Promise.reject("getAppInfo failed")):Promise.all([t.getAppData(),t.getOtherAppData()]).catch(function(t){return this._handleWebAPIError(t),Promise.reject("getAppData or getOtherAppData failed")}.bind(this))}.bind(this)).then(function(){SYNO.SDS.MailClient.PushServerLib.Main.login(),SYNO.SDS.MailClient.PushServerLib.Main.monDetector(),t.getContact(),this.delayConstructor()}.bind(this)).then(function(){return t.refreshCachedSetting()}).then(function(){setTimeout(function(){t.syncAA()},5e3)}).catch(function(t){SYNO.Debug.error(t)}.bind(this))},delayConstructor:function(){var t;if(!this.rendered)return void this.delayConstructor.defer(10,this,arguments);Ext.util.CSS.updateRule("html, body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, p, blockquote, th, td","padding","");var e=[];SYNO.SDS.MailClient.Define.isPrintMode?e.push(this.mainpanel=new SYNO.SDS.MailClient.PrintPage):SYNO.SDS.MailClient.Define.isComposeMode?e.push(this.mainpanel=new SYNO.SDS.MailClient.ComposePage):e.push(this.mainpanel=new SYNO.SDS.MailClient.Main),this.clearStatusBusy(),this.removeAll(),this.add(e),this.doLayout(),SYNO.SDS.MailClient.UserSettingProperty.getNeedContactsTip()&&SYNO.SDS.MailClient.Define.isNormalMode&&SYNO.SDS.AppUtil.isValidApp("SYNO.Contacts.AppInstance")&&(t=new SYNO.SDS.MailClient.AppLib.ContactsTip({renderTo:this.el.dom})),SYNO.SDS.MailClient.UserSettingProperty.getNeedMobileAppTip()&&SYNO.SDS.MailClient.Define.isNormalMode&&(t?t.on("destroy",this._onContactTipDestroy,this):setTimeout(function(){new SYNO.SDS.MailClient.AppLib.MobileAppTip({renderTo:this.el.dom})}.bind(this),1e3));var i=SYNO.SDS.MailClient.Info.quota_info;i&&i.limit_byte>0&&i.usage_byte>=.99*i.limit_byte&&this.findAppWindow().getMsgBox().alert("",SYNO.SDS.MailClient._T("common","exceeding_limit_desc"))},_onContactTipDestroy:function(){new SYNO.SDS.MailClient.AppLib.MobileAppTip({renderTo:this.el.dom})},showToast:function(t,e,i,n){this.hideToast(),e=e||[],this.toastTpl=this.toastTpl||new Ext.XTemplate('<div class="syno-mc-toast-content">','<span class="message">{message}</span> ','<tpl for="actions">','<span class="action">{text}</span> ',"</tpl>","</div>",{compiled:!0}),this.toastCt=this.toastCt||Ext.DomHelper.append(this.el,{class:"syno-mc-toast"},!0);var a,o={message:Ext.isNumber(i)?String.format(t,i):t,actions:[]};for(a=0;a<e.length;++a)o.actions.push({text:e[a][0]});this.toastCt.setWidth("100%"),this.toastMsg=this.toastTpl.overwrite(this.toastCt,o,!0),this.toastMsg.hideCb=n,this.toastCt.setWidth(this.toastMsg.getWidth()+this.toastMsg.getPadding("lr")).alignTo(this.el,"t-t",[0,84]);var s=this.toastMsg.select(".action").elements;for(a=0;a<e.length;a++)Ext.isFunction(e[a][1])&&Ext.fly(s[a]).on("click",this.toastActionCb,this,{single:!0,actionCb:e[a][1],actionScope:e[a][2]});if(i)this.toastDelayedTask||(this.toastDelayedTask=new Ext.util.DelayedTask),this.toastMsg.show(),Ext.isNumber(i)?this.toastDelayedTask.delay(0,this.textCountdown,this.toastDelayedTask,[this.toastMsg.query(".message")[0],t,i]):0===e.length&&this.toastDelayedTask.delay(0,this.textAnimate,this.toastDelayedTask,[this.toastMsg.query(".message")[0],t,0]);else{var l=this,r=e.length?15:3;this.toastMsg.show().pause(r).queueFx({},function(){l.toastMsg&&(Ext.isFunction(l.toastMsg.hideCb)&&l.toastMsg.hideCb(),l.toastMsg.hide(),l.toastMsg.remove(),delete l.toastMsg)})}},hideToast:function(){SYNO.SDS.MailClient.PushServerLib.Main.isOffline()&&this.isOfflineMsg()||(this.toastMsg&&(this.toastMsg.stopFx(),Ext.isFunction(this.toastMsg.hideCb)&&this.toastMsg.hideCb(),this.toastMsg.hide(),this.toastMsg.remove(),delete this.toastMsg),this.toastDelayedTask&&this.toastDelayedTask.cancel())},toastActionCb:function(t,e,i){this.hideToast(),i.actionCb&&i.actionCb.apply(i.actionScope||e)},showLoading:function(t){this.mcMask||(this.mcMask=Ext.DomHelper.append(Ext.getBody(),{class:"syno-mc-mask x-hide-display",html:SYNO.SDS.MailClient._T("common","loading")},!0),this.mcMask.setVisibilityMode(Ext.Element.DISPLAY),this.mcMaskDelayedTask=new Ext.util.DelayedTask(this.textAnimate));var e=this.el.dom.currentStyle||window.getComputedStyle(this.el.dom);this.mcMask.setStyle("z-index",parseInt(e.zIndex,10)+2),this.mcMaskText=t||SYNO.SDS.MailClient._T("common","loading").slice(0,-3),this.mcMask.removeClass("x-hide-display"),this.mcMaskDelayedTask.delay(0,null,this.mcMaskDelayedTask,[this.mcMask.dom,this.mcMaskText,0])},hideLoading:function(){this.mcMask&&this.mcMask.addClass("x-hide-display"),this.mcMaskDelayedTask&&this.mcMaskDelayedTask.cancel()},textAnimate:function(t,e,i){switch(i){case 1:t.innerHTML=e+". ";break;case 2:t.innerHTML=e+".. ";break;case 3:t.innerHTML=e+"...";break;default:t.innerHTML=e+" "}this.delay(500,null,null,[t,e,(i+1)%4])},textCountdown:function(t,e,i){i>0&&(t.innerHTML=String.format(e,i),this.delay(1e3,null,null,[t,e,i-1]))},updateTaskIndicator:function(t,e,i){var n=Ext.getCmp(this.task_indicator_id),a=SYNO.SDS.MailClient._T("common","task_running_desc");Ext.isNumber(e)&&Ext.isNumber(i)&&(a+=Math.floor(100*e/i)+"%"),n.el.dom.innerHTML=a,n.setVisible(t)},updateDialogProgress:function(t,e){this.getMsgBox().updateProgress(t/e,t+"/"+e,this.getMsgBox().msg)},switchToMail:function(){this.navigator.regDefault(this.mainpanel.mainListPanel.mailList.mailboxList.treePanel)},getRefItems:function(){var t=this.items.getRange();return Ext.iterate(this.panellist,function(e,i){t.push(i)}),t},addPanel:function(t,e){this.panellist[t]=e},removePanel:function(t){delete this.panellist[t]},getPanel:function(t){return this.panellist[t]},initTinymcePlugins:function(){try{window.tinymce.synoReloadPlugins("SYNO.SDS.MailClient.Application",["syno_mc_formupload","syno_mc_ddupload","syno_mc_sticker","syno_mc_collapse_reply","syno_mc_link","syno_mc_autolink","syno_mc_image","syno_mc_indent_outdent"])}catch(t){}},regShortCut:function(t,e){this.navigator&&this.navigator.regShortCut(t,e)},isOfflineMsg:function(){if(!this.toastMsg)return!1;var t=this.toastMsg.query(".message")[0].innerHTML;return t===SYNO.SDS.MailClient._T("common","no_internet")||-1!==t.indexOf(SYNO.SDS.MailClient._T("common","no_internet_reconnecting"))},_handleWebAPIError:function(t){var e=SYNO.SDS.MailClient.Error,i=e.getErrorString(t),n=e.getErrorCode(t);e.isPrivilegeErrorCode(n)||e.isFatalErrorCode(n)||SYNO.SDS.MailClient.Window.el.mask(i)}}),Ext.define("SYNO.SDS.MailClient.PGP.KeyGridPanel",{extend:"SYNO.SDS.MailClient.Setting.GridPanel",constructor:function(t){this.encryption=SYNO.SDS.MailClient.PGP.Encryption,this.callParent([this.fillConfig(t)])},fillConfig:function(t){var e=new Ext.grid.RowSelectionModel({singleSelect:!0}),i=[{header:SYNO.SDS.MailClient._T("pgp","key_name"),dataIndex:"name",width:100,renderer:function(t,e,i){return t}},{header:_T("common","email"),dataIndex:"email",width:100},{header:SYNO.SDS.MailClient._T("pgp","key_id"),dataIndex:"key_id",width:100}],n=new Ext.grid.ColumnModel({columns:i}),a={autoExpandColumn:"email",enableColumnMove:!1,width:450,height:200,store:this.getStore(),view:new SYNO.ux.FleXcroll.grid.GridView({useArrows:!0,staticTree:!1}),sm:e,colModel:n};return Ext.apply(a,t),a},createStore:function(){return new Ext.data.JsonStore({autoDestroy:!0,fields:["key_id","name","email"]})},getStore:function(){return this.store=this.store||this.createStore(),this.store},loadData:function(t){var e=this.encryption.getContactData(t);this.store.loadData(e)},refresh:function(){this.loadData()}}),Ext.define("SYNO.SDS.MailClient.PGP.EncryptionTool",{extend:"Object",requires:["SYNO.SDS.MailClient.PGP.Encryption"],singleton:!0,constructor:function(t){this.callParent(arguments),window.et=this},init:function(){this.createFields(),enc.on("initialize",function(){window.kr=enc.keyring,this.keyring=enc.keyring}),enc.init(),window.et=this},createFields:function(){var t=this,e=document.createElement("div");e.style.background="burlywood",e.style.position="absolute",e.style.zIndex=1e5,e.style.padding="10px",e.style.right="0",e.style.bottom="0";var i=document.createElement("input");i.type="file",i.style.width="200px",i.style.height="50px",i.style.display="block",i.style.marginBottom="10px",i.style.border="1px solid black",Ext.fly(i).on("change",function(){t.file=i.files[0]}),e.appendChild(i);var n=document.createElement("textarea");n.style.width="200px",n.style.height="200px",Ext.fly(n).on("change",function(){t.text=n.value}),e.appendChild(n),document.body.appendChild(e)},genKey:function(t,e,i,n){t=t||"abc",e=e||"def@syno.com",i=i||2048,n=n||"a",delete this.newKey,enc.generateKey(t,e,i,n,function(t,e){t&&(this.newKey=e)},this)},getKeys:function(){var t={},e=enc.keyring.publicKeys.keys.concat(enc.keyring.privateKeys.keys);return Ext.each(e,function(e){var i=e.getUserIds().sort().join(),n=e.primaryKey.getKeyId().toHex(),a={};t[n]?(a=t[n],a.type="pair"):(t[n]=a,a.type=e.isPublic()?"public":"private",a.userId=i)}),t},listKeys:function(){var t,e=this.getKeys();for(t in e)e.hasOwnProperty(t)&&e[t]},showFileIds:function(){delete this.fileIds;var t=this;this.readFile(this.file,"binary").then(function(e){var i=enc.getMessage(e,"binary");if(!i)throw"failed";t.showIds(i.getEncryptionKeyIds())},function(t){})},showTextIds:function(){delete this.textIds;var t=enc.getMessage(this.text);if(t&&1===t.packets.filterByTag(openpgp.enums.packet.literal).length)return void this.showIds(t.getEncryptionKeyIds());var e=enc.getClearTextMessage(this.text);return e?void this.showIds(e.getSigningKeyIds()):void 0},showIds:function(t){Ext.each(t,function(t){})},importPublicKey:function(){return enc.importKey(this.text,!0)},importPrivateKey:function(){return enc.importKey(this.text,!1)}}),Ext.define("SYNO.SDS.MailClient.ThreadVaultLib.ThreadVaultUtil",{extend:"Ext.util.Observable",requires:[],mixins:["SYNO.SDS.MailClient.Mixin.Constructable"],singleton:!0,constructor:function(t){this.callParent(arguments)}},SYNO.SDS.MailClient.Framework.postDefine),Ext.define("SYNO.SDS.MailClient.RootNodeUI",{extend:"Ext.tree.TreeNodeUI",renderElements:function(t,e,i,n){this.callParent(arguments),Ext.fly(this.elNode).addClass("syno-mc-tree-root-node"),e.showAddBtn?this.createActionButton("syno-mc-add-btn-icon"):e.showManageBtn&&this.createActionButton("syno-mc-add-btn-icon syno-mc-manage-btn-icon")},createActionButton:function(t){this.btn=Ext.DomHelper.append(this.elNode,{tag:"div",cls:t},!0),this.btn.addClassOnClick("x-btn-click"),Ext.fly(this.btn).on("click",function(t,e,i,n){this.fireEvent("add"),t.stopEvent()},this),Ext.fly(this.btn).on("mouseenter",function(t,e,i){this.node.getUI().addClass("x-tree-node-over")},this),Ext.fly(this.btn).on("mouseout",function(t,e,i){this.node.getUI().removeClass("x-tree-node-over")},this)}}),Ext.define("SYNO.SDS.MailClient.TreeNode",{extend:"Ext.tree.TreeNode",constructor:function(t){var e={cls:"syno-mc-tree-node"};this.callParent([Ext.apply(e,t)])},setCount:function(t){0>t||(this.attributes.count=t,this.rendered&&this.ui.setCountUI(t))}});