%PDF- %PDF-
Direktori : /www/varak.net/mail2.varak.net_old/static/js/ |
Current File : //www/varak.net/mail2.varak.net_old/static/js/app.min.js |
/*! * Copyright 2004-2014, AfterLogic Corp. * Licensed under AGPLv3 license or AfterLogic license * if commerical version of the product was purchased. * See the LICENSE file for a full license statement. */ !function(e,t,i,s,o){"use strict";function n(){this.ie11=!!navigator.userAgent.match(/Trident.*rv[ :]*11\./),this.ie=/msie/.test(navigator.userAgent.toLowerCase())&&!t.opera||this.ie11,this.ieVersion=this.getIeVersion(),this.ie8AndBelow=this.ie&&this.ieVersion<=8,this.ie9AndBelow=this.ie&&this.ieVersion<=9,this.ie10AndAbove=this.ie&&this.ieVersion>=10,this.opera=!!t.opera||/opr/.test(navigator.userAgent.toLowerCase()),this.firefox=/firefox/.test(navigator.userAgent.toLowerCase()),this.chrome=/chrome/.test(navigator.userAgent.toLowerCase())&&!/opr/.test(navigator.userAgent.toLowerCase()),this.chromeIos=/crios/.test(navigator.userAgent.toLowerCase()),this.safari=/safari/.test(navigator.userAgent.toLowerCase())&&!this.chromeIos}function r(){this.sUrl="?/Ajax/",this.requests=i.observableArray([]),this.openedRequestsCount=i.observable(0),this.requests.subscribe(function(){this.openedRequestsCount(this.requests().length)},this)}function a(){this.defaultScreen=vi.Screens.Mailbox,this.currentScreen=vi.Screens.Mailbox,this.lastMailboxHash=i.observable(vi.Screens.Mailbox),this.lastHelpdeskHash=i.observable(vi.Screens.Helpdesk),this.lastSettingsHash=i.observable(vi.Screens.Settings),this.currentHash=i.observable(""),this.previousHash=i.observable("")}function l(){}function h(){this.replyText=i.observable(""),this.replyDraftUid=i.observable(""),this.postponedMailData=null}function c(){this.prefetchStarted=i.observable(!1),this.serverInitializationsDone=i.observable(!1),this.helpdeskInitialized=i.observable(!1),this.fetchersIdentitiesPrefetched=i.observable(!1),this.init()}function u(t,s,o,n,r,a,l,h,c,u){this.fBeforeSelectCallback=null,this.fSelectCallback=s||function(){},this.fDeleteCallback=o||function(){},this.fDblClickCallback=!Ii&&n?n:function(){},this.fEnterCallback=r||function(){},this.bResetCheckedOnClick=Si.isUnd(l)?!1:!!l,this.bCheckOnSelect=Si.isUnd(h)?!1:!!h,this.bUnselectOnCtrl=Si.isUnd(c)?!1:!!c,this.bDisableMultiplySelection=Si.isUnd(u)?!1:!!u,this.useKeyboardKeys=i.observable(!1),this.list=i.observableArray([]),t&&t.subscribe&&t.subscribe(function(e){this.list(e)},this),this.multiplyLineFactor=a,this.oLast=null,this.oListScope=null,this.oScrollScope=null,this.iTimer=0,this.iFactor=1,this.KeyUp=vi.Key.Up,this.KeyDown=vi.Key.Down,this.KeyLeft=vi.Key.Up,this.KeyRight=vi.Key.Down,this.multiplyLineFactor&&(this.multiplyLineFactor.subscribe?this.multiplyLineFactor.subscribe(function(e){this.iFactor=e>0?e:1},this):this.iFactor=Si.pInt(this.multiplyLineFactor),this.KeyUp=vi.Key.Up,this.KeyDown=vi.Key.Down,this.KeyLeft=vi.Key.Left,this.KeyRight=vi.Key.Right,e("html").hasClass("rtl")&&(this.KeyLeft=vi.Key.Right,this.KeyRight=vi.Key.Left)),this.sActionSelector="",this.sSelectabelSelector="",this.sCheckboxSelector="";var d=this;this.listChecked=i.computed({read:function(){var e=_.filter(this.list(),function(e){var t=e.checked(),i=e.selected();return t||d.bCheckOnSelect&&i});return e},write:function(e){e=!!e,_.each(this.list(),function(t){t.checked(e)}),this.list.valueHasMutated()},owner:this}),this.checkAll=i.computed({read:function(){return 0<this.listChecked().length},write:function(e){this.listChecked(!!e)},owner:this}),this.selectorHook=i.observable(null),this.selectorHook.subscribe(function(){var e=this.selectorHook();e&&e.selected(!1)},this,"beforeChange"),this.selectorHook.subscribe(function(e){e&&e.selected(!0)},this),this.itemSelected=i.computed({read:this.selectorHook,write:function(e){this.selectorHook(e),e&&(this.oLast=e)},owner:this}),this.list.subscribe(function(e){if(_.isArray(e)){var t=this.itemSelected();t&&(_.find(e,function(e){return t===e})||this.itemSelected(null))}else this.itemSelected(null)},this),this.listCheckedOrSelected=i.computed({read:function(){var e=this.itemSelected(),t=this.listChecked();return 0<t.length?t:e?[e]:[]},write:function(e){e?this.listChecked(!0):(this.itemSelected(null),this.listChecked(!1))},owner:this}),this.listCheckedAndSelected=i.computed({read:function(){var e=[],t=this.itemSelected(),i=this.listChecked();return i&&(e=i.slice(0)),t&&-1===_.indexOf(i,t)&&e.push(t),e},write:function(e){e?this.listChecked(!0):(this.itemSelected(null),this.listChecked(!1))},owner:this}),this.isIncompleteChecked=i.computed(function(){var e=this.list().length,t=this.listChecked().length;return e>0&&t>0&&e>t},this),this.onKeydownBinded=_.bind(this.onKeydown,this)}function d(){this.openPgp=null,this.openPgpCallbacks=[]}function p(){Data.init()}function g(){this.provider=null,this.report=i.observable(""),this.missedCalls=i.observable(!1),this.phoneToCall=i.observable(""),this.action=i.observable(vi.PhoneAction.Offline),this.action.subscribe(function(e){switch(e){case vi.PhoneAction.Offline:this.provider.reconnect(6e4);break;case vi.PhoneAction.OfflineError:this.provider.reconnect(6e4);break;case vi.PhoneAction.OfflineInit:this.provider.init();break;case vi.PhoneAction.OfflineActive:break;case vi.PhoneAction.Online:Ci.Screens.hidePopup(V),Ci.desktopNotify("hide"),this.missedCalls(!1),this.provider.reconnect(),this.provider.hangup();break;case vi.PhoneAction.OnlineActive:break;case vi.PhoneAction.Outgoing:this.provider.call(this.getFormattedPhone(this.phoneToCall()));break;case vi.PhoneAction.OutgoingConnect:break;case vi.PhoneAction.Incoming:break;case vi.PhoneAction.IncomingConnect:Ci.Screens.hidePopup(V),Ci.desktopNotify("hide"),this.missedCalls(!1),this.provider.answer()}},this)}function m(){this.phone=Ci.Phone,this.action=Ci.Phone.action,this.stack=i.observable(null),this.registerSession=i.observable(null),this.callSession=i.observable(null),this.stackConf=i.observable(null),this.registerConf=i.observable(null),this.hangupConf=i.observable(null),this.isStarted=i.observable(!1),this.eventSessionBinded=this.eventSession.bind(this),this.createStackErrorBinded=this.createStackError.bind(this),this.createStackBinded=this.createStack.bind(this),this.audioRemote=document.getElementById("audio_remote"),this.interval=0}function b(){this.flash=null,this.jqFlash=null,this.phone=Ci.Phone,this.voiceApp=Ci.Phone.voiceApp,this.report=Ci.Phone.report,this.action=Ci.Phone.action,this.voiceImpi=Ti.User.VoiceImpi,this.voicePassword=Ti.User.VoicePassword,this.sessionid=i.observable(""),this.callState=i.observable(""),this.initStatus=i.observable(!1),this.connectStatus=i.observable(!1),this.init()}function f(){this.phone=Ci.Phone,this.action=Ci.Phone.action,this.device=null,this.connection=null,this.token=null,this.webSocket=null}function y(e,t){this.pgp=e,this.pgpKeyring=new this.pgp.Keyring(new this.pgp.Keyring.localstore(t)),this.keys=i.observableArray([]),this.reloadKeysFromStorage()}function v(e){this.pgpKey=e;var t=this.pgpKey.getPrimaryUser();this.user=t&&t.user?t.user.userId.userid:this.pgpKey.users&&this.pgpKey.users[0]?this.pgpKey.users[0].userId.userid:"",this.emailParts=Si.getEmailParts(this.user)}function S(){this.result=!0,this.errors=null,this.notices=null,this.exceptions=null}function A(){this.alertDesc=i.observable(""),this.closeCallback=null,this.title=i.observable(""),this.okButtonText=i.observable(Si.i18n("MAIN/BUTTON_OK"))}function C(){this.fConfirmCallback=null,this.confirmDesc=i.observable(""),this.title=i.observable(""),this.okButtonText=i.observable(Si.i18n("MAIN/BUTTON_OK")),this.cancelButtonText=i.observable(Si.i18n("MAIN/BUTTON_CANCEL")),this.shown=!1}function E(){this.editedAccountId=Ti.Accounts.editedId,this.loading=i.observable(!1),this.friendlyName=i.observable(""),this.email=i.observable(""),this.incomingMailLogin=i.observable(""),this.incomingLoginFocused=i.observable(!1),this.incomingMailPassword=i.observable(""),this.incomingMailPort=i.observable(143),this.incomingMailServer=i.observable(""),this.outgoingMailLogin=i.observable(""),this.outgoingMailPassword=i.observable(""),this.outgoingMailPort=i.observable(25),this.outgoingMailServer=i.observable(""),this.incomingServerFocused=i.observable(!1),this.outServerFocused=i.observable(!1),this.useSmtpAuthentication=i.observable(!0),this.friendlyNameFocus=i.observable(!1),this.emailFocus=i.observable(!1),this.incomingPasswordFocus=i.observable(!1),this.incomingMailFocus=i.observable(!1),this.isFirstStep=i.observable(!0),this.isFirstStep.subscribe(function(e){e||this.clearServers()},this),this.incomingLoginFocused.subscribe(function(){this.incomingLoginFocused()&&""===this.incomingMailLogin()&&this.incomingMailLogin(this.email())},this),this.outServerFocused.subscribe(function(){this.outServerFocused()&&""===this.outgoingMailServer()&&this.outgoingMailServer(this.incomingMailServer())},this)}function T(){this.oIdentityPropertiesViewModel=new li(this,!0)}function F(){this.defaultAccountId=Ti.Accounts.defaultId,this.loading=i.observable(!1),this.newFolderCreating=i.observable(!1),this.incomingMailServer=i.observable(""),this.incomingMailPort=i.observable(110),this.incomingMailLogin=i.observable(""),this.incomingMailPassword=i.observable(""),this.folderList=Ci.MailCache.folderList,this.folder=i.observable(""),this.options=i.observable(this.folderList().getOptions("",!0,!1,!1)),this.folderList.subscribe(function(){this.options(this.folderList().getOptions("",!0,!1,!1))},this),this.addNewFolderCommand=Si.createCommand(this,this.onAddNewFolderClick),this.outgoingMailServer=i.observable(""),this.outgoingMailPort=i.observable(25),this.leaveMessagesOnServer=i.observable(!1),this.useSmtpAuthentication=i.observable(!1),this.serverIsSelected=i.observable(!1),this.loginIsSelected=i.observable(!1),this.passwordIsSelected=i.observable(!1),this.defaultOptionsAfterRender=Si.defaultOptionsAfterRender}function I(){this.folders=Ci.MailCache.editedFolderList,this.sentFolderFullName=i.observable(this.folders().sentFolderFullName()),this.draftsFolderFullName=i.observable(this.folders().draftsFolderFullName()),this.spamFolderFullName=i.observable(this.folders().spamFolderFullName()),this.trashFolderFullName=i.observable(this.folders().trashFolderFullName()),this.options=i.observableArray(this.folders().getOptions(Si.i18n("SETTINGS/ACCOUNT_FOLDERS_NO_USAGE_ASSIGNED"),!1,!1,!1)),this.defaultOptionsAfterRender=Si.defaultOptionsAfterRender,this.allowSpamFolderEditing=i.computed(function(){var e=Ti.Accounts.getEdited(),t=e.extensionExists("AllowSpamFolderExtension");return t&&!Ti.IsMailsuite},this)}function w(){this.folders=Ci.MailCache.editedFolderList,this.loading=i.observable(!1),Ci.MailCache.folderListLoading.subscribe(function(){!Ci.MailCache.folderListLoading()&&this.loading()&&(this.fCallback&&this.fCallback(this.folderName(),this.parentFolder()),this.loading(!1),this.closeCommand())},this),this.options=i.computed(function(){return this.folders().getOptions(Si.i18n("SETTINGS/ACCOUNT_FOLDERS_NO_PARENT"),!0,!1,!0)},this),this.namespace=i.computed(function(){return this.folders().sNamespaceFolder},this),this.parentFolder=i.observable(""),this.folderName=i.observable(""),this.folderNameFocus=i.observable(!1),this.fCallback=null,this.defaultOptionsAfterRender=Si.defaultOptionsAfterRender}function P(){this.currentPassword=i.observable(""),this.newPassword=i.observable(""),this.confirmPassword=i.observable(""),this.isHelpdesk=i.observable(!1)}function M(){this.fCallback=null,this.folderName=i.observable(""),this.folderName.focus=i.observable(!1),this.folderName.error=i.observable(""),this.folderName.subscribe(function(){this.folderName.error("")},this)}function R(){this.fCallback=null,this.link=i.observable(""),this.linkPrev=i.observable(""),this.linkFocus=i.observable(!1),this.checkTimeout=null,this.urlChecked=i.observable(!1),this.saveCommand=Si.createCommand(this,this.executeSave,function(){return this.urlChecked()}),this.fileItem=i.observable(new it)}function D(){this.fCallback=null,this.item=null,this.name=i.observable(""),this.name.focus=i.observable(!1),this.name.error=i.observable(""),this.name.subscribe(function(){this.name.error("")},this)}function N(){this.item=null,this.pub=i.observable(""),this.pubFocus=i.observable(!1)}function k(){this.fileStorageViewModel=new ci,this.fileStorageViewModel.isPopup=!0,this.fCallback=null}function L(){this.fCallback=null,this.calendarId=i.observable(null),this.calendarName=i.observable(""),this.calendarDescription=i.observable(""),this.calendarNameFocus=i.observable(!1),this.calendarDescriptionFocus=i.observable(!1),this.colors=i.observableArray([]),this.selectedColor=i.observable(this.colors()[0]),this.popupTitle=i.observable("")}function O(){this.fCallback=null,this.oJua=null,this.allowDragNDrop=i.observable(!1),this.visibility=i.observable(!1),this.importing=i.observable(!1),this.color=i.observable(""),this.calendarId=i.observable("")}function x(){this.defaultAccount=Ti.Accounts.getDefault(),this.fCallback=null,this.calendarId=i.observable(null),this.selectedColor=i.observable(""),this.calendarUrl=i.observable(""),this.exportUrl=i.observable(""),this.icsLink=i.observable(""),this.isPublic=i.observable(!1),this.shares=i.observableArray([]),this.oldShares=i.observableArray([]),this.owner=i.observable(""),this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500}),this.whomAnimate=i.observable(""),this.shareAutocompleteItem=i.observable(null),this.shareAutocompleteItem.subscribe(function(e){e&&this.setGlobal(e.email,this.newShareList())},this),this.newShareList=i.observableArray([]),this.newShare=i.observable(""),this.newShareFocus=i.observable(!1),this.newShareAccess=i.observable(vi.CalendarAccess.Read),this.sharedToAll=i.observable(!1),this.sharedToAllAccess=i.observable(vi.CalendarAccess.Read),this.canAdd=i.observable(!1),this.aAccess=[{value:vi.CalendarAccess.Read,display:Si.i18n("CALENDAR/CALENDAR_ACCESS_READ")},{value:vi.CalendarAccess.Write,display:Si.i18n("CALENDAR/CALENDAR_ACCESS_WRITE")}],this.autocompleteCallbackBinded=_.bind(this.autocompleteCallback,this),this.showGlobalContacts=!!Ti.User.ShowGlobalContacts}function U(){this.fCallback=null,this.calendarId=i.observable(null),this.selectedColor=i.observable(""),this.calendarUrl=i.observable(""),this.exportUrl=i.observable(""),this.icsLink=i.observable(""),this.isPublic=i.observable(!1),this.pubUrl=i.observable("")}function H(){this.defaultAccount=Ti.Accounts?Ti.Accounts.getDefault():null,this.modified=!1,this.isPublic=Fi,this.isEditable=i.observable(!1),this.isEditableReminders=i.observable(!1),this.selectedCalendarIsShared=i.observable(!1),this.selectedCalendarIsEditable=i.observable(!1),this.callbackSave=null,this.callbackDelete=null,this.timeFormatMoment="HH:mm",this.dateFormatMoment="MM/DD/YYYY",this.dateFormatDatePicker="mm/dd/yy",this.ampmTimeFormat=i.observable(!1),this.calendarId=i.observable(null),this.id=i.observable(null),this.uid=i.observable(null),this.recurrenceId=i.observable(null),this.allEvents=i.observable(vi.CalendarEditRecurrenceEvent.AllEvents),this.FCMoment=null,this.isMyEvent=i.observable(!1),this.startDom=i.observable(null),this.endDom=i.observable(null),this.repeatEndDom=i.observable(null),this.yearlyDate=i.observable(""),this.monthlyDate=i.observable(""),this.subject=i.observable(""),this.description=i.observable(""),this.startDate=i.observable(""),this.startTime=i.observable(""),this.startTime.subscribe(function(){this.selectStartDate()},this),this.allDay=i.observable(!1),this.allDay.subscribe(function(e){e||this.setActualTime()},this),this.endDate=i.observable(""),this.endTime=i.observable(""),this.endTime.subscribe(function(){this.selectEndDate()},this),this.repeatEndDate=i.observable(""),this.isEvOneDay=i.observable(!0),this.isEvOneTime=i.observable(!0),this.isRepeat=i.observable(!1),this.location=i.observable(""),this.repeatPeriodOptions=i.observableArray(this.getDisplayedPeriods()),this.repeatWeekIntervalOptions=i.observableArray([1,2,3,4]),this.repeatMonthIntervalOptions=i.observableArray(this.getDisplayedIntervals()),this.defaultAlarms=i.observableArray([5,10,15,30,60,120,180,240,300,360,420,480,540,600,660,720,1080,1440,2880,4320,5760,10080,20160]),this.alarmOptions=i.observableArray([]),this.timeOptions=i.observableArray(this.getDisplayedTimes(Ti.User.defaultTimeFormat()!==vi.TimeFormat.F24?"hh:mm A":"HH:mm")),Ti.User.defaultTimeFormat.subscribe(function(){this.timeOptions(this.getDisplayedTimes(Ti.User.defaultTimeFormat()!==vi.TimeFormat.F24?"hh:mm A":"HH:mm"))},this),this.displayedAlarms=i.observableArray([]),this.displayedAlarms.subscribe(function(){this.disableAlarms()},this),this.excluded=i.observable(!1),this.repeatPeriod=i.observable(0),this.repeatPeriod.subscribe(function(e){this.setDayOfWeek(),this.isRepeat(!!e)},this),this.repeatInterval=i.observable(1),this.repeatCount=i.observable(null),this.repeatWeekNum=i.observable(null),this.weekMO=i.observable(!1),this.weekTU=i.observable(!1),this.weekWE=i.observable(!1),this.weekTH=i.observable(!1),this.weekFR=i.observable(!1),this.weekSA=i.observable(!1),this.weekSU=i.observable(!1),this.appointment=i.observable(!1),this.attendees=i.observableArray([]),this.attenderStatus=i.observable(0),this.owner=i.observable(""),this.ownerName=i.observable(""),this.ownerDisplay=i.computed(function(){return""!==this.ownerName()?this.ownerName():this.owner()},this),this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500}),this.whomAnimate=i.observable(""),this.guestAutocompleteItem=i.observable(null),this.guestAutocomplete=i.observable(""),this.guestEmailFocus=i.observable(!1),this.guestAutocomplete.subscribe(function(e){""===e&&this.guestAutocompleteItem(null)},this),this.condition=i.observable(""),this.autosizeTrigger=i.observable(!0),this.calendars=null,this.calendarsList=i.observableArray([]),this.calendarColor=i.observable(""),this.selectedCalendarId=i.observable(""),this.selectedCalendarName=i.observable(""),this.selectedCalendarId.subscribe(function(e){if(e){var t=this.calendars.getCalendarById(e);this.selectedCalendarName(t.name()),this.selectedCalendarIsShared(t.isShared()),this.selectedCalendarIsEditable(t.isEditable()),this.changeCalendarColor(e)}},this),this.subjectFocus=i.observable(!1),this.descriptionFocus=i.observable(!1),this.locationFocus=i.observable(!1),this.dateEdit=i.observable(!1),this.repeatEdit=i.observable(!1),this.guestsEdit=i.observable(!1),this.defaultOptionsAfterRender=Si.defaultOptionsAfterRender,this.isEditForm=i.computed(function(){return!!this.id()},this),this.callbackAttendeeActionDecline=null,this.calendarAppointments=Ti.User.AllowCalendar&&Ti.User.CalendarAppointments,this.allChanges=i.computed(function(){this.subject(),this.description(),this.location(),this.isRepeat(),this.allDay(),this.repeatPeriod(),this.repeatInterval(),this.repeatCount(),this.repeatWeekNum(),this.startDate(),this.startTime(),this.endDate(),this.endTime(),this.repeatEndDate(),this.displayedAlarms(),this.weekMO(),this.weekTU(),this.weekWE(),this.weekTH(),this.weekFR(),this.weekSA(),this.weekSU(),this.attendees(),this.selectedCalendarId(),this.modified=!0},this),this.phaseArray=[""],_.each(Si.i18n("CALENDAR/REMINDER_PHRASE").split(/\s/),function(e){var t=this.phaseArray.length-1;"%"===e.substr(0,1)||"%"===this.phaseArray[t].substr(-1,1)?this.phaseArray.push(e):this.phaseArray[t]+=" "+e},this),this.isAppointmentButtonsVisible=i.observable(!1)}function G(){this.fCallback=null,this.confirmDesc=Si.i18n("CALENDAR/EDIT_RECURRENCE_CONFIRM_DESCRIPTION"),this.onlyThisInstanceButtonText=i.observable(Si.i18n("CALENDAR/ONLY_THIS_INSTANCE")),this.allEventsButtonText=i.observable(Si.i18n("CALENDAR/ALL_EVENTS_IN_THE_SERIES")),this.cancelButtonText=i.observable(Si.i18n("MAIN/BUTTON_CANCEL"))}function B(){this.fCallback=null,this.fProceedUploading=null,this.calendars=null,this.calendarsList=i.observableArray([]),this.calendarColor=i.observable(""),this.selectedCalendarName=i.observable(""),this.selectedCalendarId=i.observable(""),this.selectedCalendarId.subscribe(function(e){if(e){var t=this.calendars.getCalendarById(e);this.selectedCalendarName(t.name()),this.selectedCalendarIsEditable(t.isEditable()),this.changeCalendarColor(e)}},this),this.selectedCalendarIsEditable=i.observable(!1)}function V(){this.phone=Ci.Phone,this.action=this.phone.action,this.report=this.phone.report,this.text=i.observable(""),this.callback=null}function j(){this.pgp=null,this.emails=i.observableArray([]),this.selectedEmail=i.observable(""),this.password=i.observable(""),this.keyLengthOptions=[1024,2048],this.selectedKeyLength=i.observable(1024),this.process=i.observable(!1)}function K(){this.armor=i.observable(""),this.htmlArmor=i.computed(function(){return Si.encodeHtml(this.armor().replace(/\r/g,""))},this),this.user=i.observable(""),this.private=i.observable(!1),this.titleText=i.computed(function(){return this.private()?Si.i18n("OPENPGP/POPUP_TITLE_VIEW_PRIVATE_KEY",{USER:this.user()}):Si.i18n("OPENPGP/POPUP_TITLE_VIEW_PUBLIC_KEY",{USER:this.user()})},this),this.downloadLinkHref=i.computed(function(){var e="#",i=null;return t.URL=t.webkitURL||t.URL,Blob&&t.URL&&Si.isFunc(t.URL.createObjectURL)&&(i=new Blob([this.armor()],{type:"text/plain"}),e=t.URL.createObjectURL(i)),e},this),this.downloadLinkFilename=i.computed(function(){var e=this.user().replace(/</g,"").replace(/>/g,""),t=this.private()?"OPENPGP/PRIVATE_KEY_FILENAME":"OPENPGP/PUBLIC_KEY_FILENAME";return Si.i18n(t,{USER:e})+".asc"},this),this.domKey=i.observable(null)}function W(){this.pgp=null,this.keyArmor=i.observable(""),this.keyArmorFocused=i.observable(!1),this.keys=i.observableArray([]),this.hasExistingKeys=i.observable(!1),this.headlineText=i.computed(function(){return Si.i18n("OPENPGP/INFO_TEXT_INCLUDES_KEYS_PLURAL",{},null,this.keys().length)},this)}function q(){this.data=i.observable(""),this.fromEmail=i.observable(""),this.emails=i.observableArray([]),this.okCallback=null,this.cancelCallback=null,this.sign=i.observable(!0),this.password=i.observable(""),this.passwordFocused=i.observable(!1),this.encrypt=i.observable(!0),this.signEncryptButtonText=i.computed(function(){var e=Si.i18n("OPENPGP/BUTTON_SIGN_ENCRYPT");return this.sign()&&!this.encrypt()&&(e=Si.i18n("OPENPGP/BUTTON_SIGN")),!this.sign()&&this.encrypt()&&(e=Si.i18n("OPENPGP/BUTTON_ENCRYPT")),e},this),this.isEnableSignEncrypt=i.computed(function(){return this.sign()||this.encrypt()},this),this.signEncryptCommand=Si.createCommand(this,this.executeSignEncrypt,this.isEnableSignEncrypt),this.signAndSend=i.observable(!1)}function Y(){this.allowGoogle=Ti.SocialGoogle,this.googleKey=Ti.SocialGoogleApiKey,this.googleClientId=Ti.SocialGoogleId,this.picker=null,this.pickerCreated=!1,this.googleApiLoaded=!1,this.pickerApiLoaded=!1,this.fCallback=null,this.timeOut=null}function z(e){this.AllowWebMail=!0,this.AllowUsersChangeInterfaceSettings=!0,this.AllowUsersChangeEmailSettings=!0,this.AllowUsersAddNewAccounts=!0,this.SiteName="",this.Languages=[{name:"English",value:"en"}],this.Themes=["Default"],this.DateFormats=[],this.DefaultLanguage="English",this.AttachmentSizeLimit=1024e4,this.ImageUploadSizeLimit=1024e4,this.FileSizeLimit=1024e4,this.AutoSave=!0,this.AutoSaveIntervalSeconds=60,this.IdleSessionTimeout=0,this.AllowInsertImage=!0,this.AllowBodySize=!1,this.MaxBodySize=600,this.MaxSubjectSize=255,this.AllowPrefetch=!0,this.MaxPrefetchBodiesSize=5e4,this.LoginFormType=vi.LoginFormType.Email,this.LoginAtDomainValue="",this.AllowRegistration=!1,this.AllowPasswordReset=!1,this.RegistrationDomains=[],this.RegistrationQuestions=[],this.DemoWebMail=!0,this.DemoWebMailLogin="",this.DemoWebMailPassword="",this.LoginDescription="",this.GoogleAnalyticsAccount="",this.ShowQuotaBar=!1,this.ServerUseUrlRewrite=!1,this.AllowLanguageOnLogin=!1,this.FlagsLangSelect=!1,this.CustomLoginUrl="",this.CustomLogoutUrl="",this.IosDetectOnLogin=!1,this.AllowContactsSharing=!1,this.DefaultLanguageShort="en",this.AllowOpenPgp=e,this.DefaultTab="",this.AllowIosProfile=!0,this.PasswordMinLength=0,this.PasswordMustBeComplex=!1}function Q(){this.IdUser=1,this.MailsPerPage=20,this.ContactsPerPage=20,this.iInterval=-1,this.AutoCheckMailInterval=0,this.DefaultTheme="Default",this.DefaultLanguage="English",this.DefaultLanguageShort="en",this.DefaultDateFormat="MM/DD/YYYY",this.defaultTimeFormat=i.observable(vi.TimeFormat.F24),this.ThreadsEnabled=!0,this.useThreads=i.observable(!0),this.SaveRepliedToCurrFolder=!0,this.AllowChangeInputDirection=!1,this.DesktopNotifications=!1,this.AllowCompose=!0,this.AllowReply=!0,this.AllowForward=!0,this.SaveMail=vi.SaveMail.Checked,this.AllowFetcher=!1,this.OutlookSyncEnable=!0,this.MobileSyncEnable=!0,this.ShowPersonalContacts=!0,this.ShowGlobalContacts=!1,this.IsFilesSupported=!1,this.IsHelpdeskSupported=!1,this.IsHelpdeskAgent=!1,this.HelpdeskIframeUrl="",this.ShowContacts=this.ShowPersonalContacts||this.ShowGlobalContacts,this.LastLogin=0,this.IsDemo=!1,this.AllowVoice=!1,this.SipRealm="",this.SipWebsocketProxyUrl="",this.SipOutboundProxyUrl="",this.SipCallerID="",this.SipImpi="",this.SipImpu="",this.SipPassword="",this.VoiceProvider="",this.AllowCalendar=!0,this.CalendarSharing=!1,this.CalendarAppointments=!1,this.CalendarShowWeekEnds=!1,this.CalendarShowWorkDay=!1,this.CalendarWorkDayStarts=0,this.CalendarWorkDayEnds=0,this.CalendarWeekStartsOn=0,this.CalendarDefaultTab=vi.CalendarDefaultTab.Month,this.mobileSync=i.observable(null),this.MobileSyncDemoPass="demo",this.outlookSync=i.observable(null),this.OutlookSyncDemoPass="demo",this.AllowHelpdeskNotifications=!1,this.IsCollaborationSupported=!1,this.AllowFilesSharing=!1,this.DefaultFontName="Tahoma",this.fillDefaultFontName(),this.DefaultFontSize=3,this.fillDefaultFontSize(),this.enableOpenPgp=i.observable(!1),this.AllowAutosaveInDrafts=!0,this.AutosignOutgoingEmails=!1,this.filesEnable=i.observable(!0),this.SocialAccounts=i.observableArray([])}function $(){this.id=i.observable(0),this.email=i.observable(""),this.extensions=i.observableArray([]),this.fetchers=i.observable(null),this.identities=i.observable(null),this.friendlyName=i.observable(""),this.incomingMailLogin=i.observable(""),this.incomingMailPort=i.observable(143),this.incomingMailServer=i.observable(""),this.isInternal=i.observable(!1),this.isLinked=i.observable(!1),this.isDefault=i.observable(!1),this.outgoingMailAuth=i.observable(0),this.outgoingMailLogin=i.observable(""),this.outgoingMailPort=i.observable(25),this.outgoingMailServer=i.observable(""),this.isExtended=i.observable(!1),this.signature=i.observable(null),this.autoresponder=i.observable(null),this.forward=i.observable(null),this.filters=i.observable(null),this.quota=i.observable(0),this.usedSpace=i.observable(0),this.quotaRecieved=i.observable(!1),this.fullEmail=i.computed(function(){return""===this.friendlyName()?this.email():this.friendlyName()+" <"+this.email()+">"},this),this.isCurrent=i.observable(!1),this.isEdited=i.observable(!1),this.extensionsRequested=i.observable(!1),this.removeHint=i.computed(function(){var e="",t="";return this.isDefault()?(Ti.User.AllowCalendar&&Ti.User.ShowContacts?e=Si.i18n("SETTINGS/ACCOUNTS_REMOVE_CONTACTS_CALENDARS_HINT"):Ti.User.AllowCalendar?e=Si.i18n("SETTINGS/ACCOUNTS_REMOVE_CALENDARS_HINT"):Ti.User.ShowContacts&&(e=Si.i18n("SETTINGS/ACCOUNTS_REMOVE_CONTACTS_HINT")),t=Si.i18n("SETTINGS/ACCOUNTS_REMOVE_DEFAULT_HINT",{AND_OTHER:e}),Ti.Accounts.collection().length>1&&(t+=Si.i18n("SETTINGS/ACCOUNTS_REMOVE_DEFAULT_NOTSINGLE_HINT"))):t=Si.i18n("SETTINGS/ACCOUNTS_REMOVE_HINT"),t},this),this.removeConfirmation=i.computed(function(){return this.isDefault()?this.removeHint()+Si.i18n("SETTINGS/ACCOUNTS_REMOVE_DEFAULT_CONFIRMATION"):Si.i18n("SETTINGS/ACCOUNTS_REMOVE_CONFIRMATION")},this)}function J(){this.defaultId=i.observable(0),this.currentId=i.observable(0),this.editedId=i.observable(0),this.currentId.subscribe(function(e){var t=this.getCurrent();t.requestExtensions(),_.delay(_.bind(function(){this.editedId(e)},this),1e3)},this),this.collection=i.observableArray([])}function X(){this.sName="",this.sEmail="",this.sDisplay="",this.sFull="",this.loaded=i.observable(!1),this.founded=i.observable(!1)}function Z(){this.aCollection=[]}function et(){this.iTimeStampInUTC=0,this.oMoment=null}function tt(){this.enabled=i.observable(!0),this.email=i.observable(""),this.friendlyName=i.observable(""),this.fullEmail=i.computed(function(){return""!==this.friendlyName()?this.friendlyName()+" <"+this.email()+">":this.email()},this),this.accountId=i.observable(-1),this.id=i.observable(-1),this.signature=i.observable(""),this.useSignature=i.observable(!1)}function it(){this.isIosDevice=Pi,this.isFolder=i.observable(!1),this.isLink=i.observable(!1),this.linkType=i.observable(vi.FileStorageLinkType.Unknown),this.linkUrl=i.observable(""),this.isPopupItem=i.observable(!1),this.id=i.observable(""),this.fileName=i.observable(""),this.tempName=i.observable(""),this.displayName=i.observable(""),this.extension=i.observable(""),this.fileName.subscribe(function(){var e=this.fileName(),t=e.lastIndexOf(".");this.id(e),this.isFolder()?(this.displayName(e),this.extension("")):(this.displayName(e.substr(0,t)),this.extension(e.substr(t+1)))},this),this.size=i.observable(0),this.friendlySize=i.computed(function(){return Si.friendlySize(this.size())},this),this.content=i.observable(""),this.accountId=i.observable(Ti.Accounts?Ti.Accounts.defaultId():null),this.hash=i.observable(""),this.thumb=i.observable(!1),this.iframedView=i.observable(!1),this.downloadLink=i.computed(function(){return Si.getDownloadLinkByHash(this.accountId(),this.hash())},this),this.viewLink=i.computed(function(){var e=Si.getViewLinkByHash(this.accountId(),this.hash());return this.iframedView()?Si.getIframeWrappwer(this.accountId(),e):e},this),this.thumbnailSrc=i.observable(""),this.thumbnailLoaded=i.observable(!1),this.thumbnailSessionUid=i.observable(""),this.thumbnailLink=i.computed(function(){return this.thumb()?Si.getViewThumbnailLinkByHash(this.accountId(),this.hash()):""},this),this.type=i.observable(""),this.uploadUid=i.observable(""),this.uploaded=i.observable(!1),this.uploadError=i.observable(!1),this.visibleImportLink=i.computed(function(){return Ti.User.enableOpenPgp()&&"asc"===this.extension().toLowerCase()&&""!==this.content()&&!this.isPopupItem()},this),this.isViewMimeType=i.computed(function(){return-1!==e.inArray(this.type(),Di)||this.iframedView()},this),this.isMessageType=i.observable(!1),this.visibleViewLink=i.computed(function(){return this.isVisibleViewLink()&&!this.isPopupItem()},this),this.visibleDownloadLink=i.computed(function(){return!this.isPopupItem()},this),this.subFiles=i.observableArray([]),this.allowExpandSubFiles=i.observable(!1),this.subFilesLoaded=i.observable(!1),this.subFilesCollapsed=i.observable(!1),this.subFilesStartedLoading=i.observable(!1),this.visibleExpandLink=i.computed(function(){return this.allowExpandSubFiles()&&!this.subFilesCollapsed()&&!this.subFilesStartedLoading()},this),this.visibleExpandingText=i.computed(function(){return this.allowExpandSubFiles()&&!this.subFilesCollapsed()&&this.subFilesStartedLoading()},this),this.visibleSpinner=i.observable(!1),this.statusText=i.observable(""),this.progressPercent=i.observable(0),this.visibleProgress=i.observable(!1),this.uploadStarted=i.observable(!1),this.uploadStarted.subscribe(function(){this.uploadStarted()?(this.uploaded(!1),this.visibleProgress(!0),this.progressPercent(20)):(this.progressPercent(100),this.visibleProgress(!1),this.uploaded(!0))},this),this.allowDrag=i.observable(!1),this.allowSelect=i.observable(!1),this.allowCheck=i.observable(!1),this.allowDelete=i.observable(!1),this.allowUpload=i.observable(!1),this.allowSharing=i.observable(!1),this.allowHeader=i.observable(!1),this.allowDownload=i.observable(!0),this.downloadTitle=i.computed(function(){return this.allowDownload()?Si.i18n("MESSAGE/ATTACHMENT_CLICK_TO_DOWNLOAD",{FILENAME:this.fileName(),SIZE:this.friendlySize()}):""},this)}function st(){this.folderName=i.observable(""),this.messageUid=i.observable(""),this.cid=i.observable(""),this.contentLocation=i.observable(""),this.inline=i.observable(!1),this.linked=i.observable(!1),this.mimePartIndex=i.observable(""),this.messagePart=i.observable(null),it.call(this),this.isMessageType=i.computed(function(){return this.type(),this.mimePartIndex(),"message/rfc822"===this.type()&&""!==this.mimePartIndex() },this)}function ot(){this.iAccountId=0,this.account=i.computed(function(){return Ti.Accounts.getAccount(this.iAccountId)},this),this.parentFullName=i.observable(""),this.level=i.observable(0),this.name=i.observable(""),this.nameForEdit=i.observable(""),this.fullName=i.observable(""),this.fullNameHash=i.observable(""),this.uidNext=i.observable(""),this.hash=i.observable(""),this.routingHash=i.observable(""),this.delimiter=i.observable(""),this.type=i.observable(vi.FolderTypes.User),this.showUnseenMessages=i.computed(function(){return this.type()!==vi.FolderTypes.Drafts},this),this.withoutThreads=i.computed(function(){return this.type()===vi.FolderTypes.Drafts||this.type()===vi.FolderTypes.Spam||this.type()===vi.FolderTypes.Trash},this),this.messageCount=i.observable(0),this.unseenMessageCount=i.observable(0),this.unseenMessageCount.subscribe(function(){_.delay(_.bind(function(){Ci.MailCache.countMessages(this)},this),1e3)},this),this.realUnseenMessageCount=i.observable(0),this.enableEmptyFolder=i.computed(function(){return this.messageCount()>0&&(this.type()===vi.FolderTypes.Spam||this.type()===vi.FolderTypes.Trash)},this),this.virtual=i.observable(!1),this.virtualEmpty=i.computed(function(){return this.virtual()&&0===this.messageCount()},this),this.hasExtendedInfo=i.observable(!1),this.selectable=i.observable(!0),this.subscribed=i.observable(!0),this.subscribed.subscribe(function(){if(this.parentFullName()){var e=Ci.MailCache.folderList().getFolderByFullName(this.parentFullName());e&&Ci.MailCache.countMessages(e)}},this),this.existen=i.observable(!0),this.isNamespace=i.observable(!1),this.subfoldersMessagesCount=i.observable(0),this.subfolders=i.observableArray([]),this.subfolders.subscribe(function(e){var t=_.any(_.map(e,function(e){return e.subscribed()}));this.canExpand(t)},this),this.canExpand=i.observable(!0),this.expanded=i.observable(!1),this.isCollapseHandler=i.computed(function(){return 0!==this.subfolders().length&&!this.isNamespace()&&this.canExpand()},this),this.messageCountToShow=i.computed(function(){return this.canExpand()?this.showUnseenMessages()?this.unseenMessageCount()+this.subfoldersMessagesCount():this.messageCount():this.showUnseenMessages()?this.unseenMessageCount():this.messageCount()},this),this.isSubFolder=i.computed(function(){return this.level()>0},this),this.selected=i.observable(!1),this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500}),this.hasSubscribedSubfolders=i.computed(function(){return!!i.utils.arrayFirst(this.subfolders(),function(e){return e.subscribed()})},this),this.isSystem=i.computed(function(){return this.type()!==vi.FolderTypes.User?!0:!1},this),this.visible=i.computed(function(){var e=this.subscribed(),t=this.existen(),i=this.selectable(),s=this.hasSubscribedSubfolders(),o=this.isSystem();return e||o||s&&(!t||!i)},this),this.edited=i.observable(!1),this.edited.subscribe(function(e){e===!1&&this.nameForEdit(this.name())},this),this.canBeSelected=i.computed(function(){var e=this.existen(),t=this.selectable();return e&&t},this),this.canSubscribe=i.computed(function(){var e=this.account(),t=!1;return e&&(t=e.extensionExists("DisableManageSubscribe")),!this.isSystem()&&this.canBeSelected()&&!t},this),this.canDelete=i.computed(function(){return!this.isSystem()&&this.hasExtendedInfo()&&0===this.messageCount()&&0===this.subfolders().length},this),this.canRename=i.computed(function(){return!this.isSystem()&&this.canBeSelected()},this),this.subscribeButtonHint=i.computed(function(){return this.canSubscribe()?Si.i18n(this.subscribed()?"SETTINGS/ACCOUNT_FOLDERS_HIDE_FOLDER_HINT":"SETTINGS/ACCOUNT_FOLDERS_SHOW_FOLDER_HINT"):""},this),this.deleteButtonHint=i.computed(function(){return this.canDelete()?Si.i18n("SETTINGS/ACCOUNT_FOLDERS_DELETE_FOLDER_HINT"):""},this),this.usedAs=i.computed(function(){var e="";switch(this.type()){case vi.FolderTypes.Inbox:e=Si.i18n("SETTINGS/ACCOUNT_FOLDERS_USED_AS_INBOX");break;case vi.FolderTypes.Sent:e=Si.i18n("SETTINGS/ACCOUNT_FOLDERS_USED_AS_SENT");break;case vi.FolderTypes.Drafts:e=Si.i18n("SETTINGS/ACCOUNT_FOLDERS_USED_AS_DRAFTS");break;case vi.FolderTypes.Trash:e=Si.i18n("SETTINGS/ACCOUNT_FOLDERS_USED_AS_TRASH");break;case vi.FolderTypes.Spam:e=Si.i18n("SETTINGS/ACCOUNT_FOLDERS_USED_AS_SPAM");break;default:e=""}return e},this),this.oMessages={},this.oUids={},this.aResponseHandlers=[],this.displayName=i.computed(function(){var e=this.name();switch(this.type()){case vi.FolderTypes.Inbox:e=Si.i18n("MAIN/FOLDER_INBOX");break;case vi.FolderTypes.Sent:e=Si.i18n("MAIN/FOLDER_SENT");break;case vi.FolderTypes.Drafts:e=Si.i18n("MAIN/FOLDER_DRAFTS");break;case vi.FolderTypes.Trash:e=Si.i18n("MAIN/FOLDER_TRASH");break;case vi.FolderTypes.Spam:e=Si.i18n("MAIN/FOLDER_SPAM")}return e},this),this.aRequestedUids=[],this.aRequestedThreadUids=[],this.requestedLists=[],this.hasChanges=i.observable(!1),this.hasChanges.subscribe(function(){this.requestedLists=[]},this),this.unseenFilterCommand=Si.createCommand(this,this.executeUnseenFilter,this.showUnseenMessages),this.unseenMessagesTitle=i.computed(function(){return this.showUnseenMessages()?Si.i18n("MAILBOX/TITLE_UNSEEN_MESSAGES_ONLY"):""},this),this.relevantInformationLastMoment=null}function nt(){this.iAccountId=0,this.bInitialized=i.observable(!1),this.expandFolders=i.observable(!1),this.expandNames=i.observableArray([]),this.collection=i.observableArray([]),this.options=i.observableArray([]),this.sNamespace="",this.sNamespaceFolder="",this.oStarredFolder=null,this.oNamedCollection={};var e=this,t=function(e){return function(t){t&&t.type(e)}},s=function(t){return{read:function(){return this.collection(),t()?t().fullName():""},write:function(e){t(this.getFolderByFullName(e))},owner:e}};this.totalMessageCount=i.computed(function(){return this.getRecursivelyMessageCount(this.collection())},this),this.currentFolder=i.observable(null),this.inboxFolder=i.observable(null),this.sentFolder=i.observable(null),this.draftsFolder=i.observable(null),this.spamFolder=i.observable(null),this.trashFolder=i.observable(null),this.inboxFolder.subscribe(t(vi.FolderTypes.User),this,"beforeChange"),this.sentFolder.subscribe(t(vi.FolderTypes.User),this,"beforeChange"),this.draftsFolder.subscribe(t(vi.FolderTypes.User),this,"beforeChange"),this.spamFolder.subscribe(t(vi.FolderTypes.User),this,"beforeChange"),this.trashFolder.subscribe(t(vi.FolderTypes.User),this,"beforeChange"),this.inboxFolder.subscribe(t(vi.FolderTypes.Inbox)),this.sentFolder.subscribe(t(vi.FolderTypes.Sent)),this.draftsFolder.subscribe(t(vi.FolderTypes.Drafts)),this.spamFolder.subscribe(t(vi.FolderTypes.Spam)),this.trashFolder.subscribe(t(vi.FolderTypes.Trash)),this.inboxFolderFullName=i.computed(s(this.inboxFolder)),this.sentFolderFullName=i.computed(s(this.sentFolder)),this.draftsFolderFullName=i.computed(s(this.draftsFolder)),this.spamFolderFullName=i.computed(s(this.spamFolder)),this.trashFolderFullName=i.computed(s(this.trashFolder)),this.currentFolderFullName=i.computed(s(this.currentFolder)),this.currentFolderType=i.computed(function(){return this.currentFolder()?this.currentFolder().type():vi.FolderTypes.User},this),this.delimiter=i.computed(function(){return this.inboxFolder()?this.inboxFolder().delimiter():""},this)}function rt(){this.accountId=i.observable(0),this.folder=i.observable(""),this.uid=i.observable(""),this.subject=i.observable(""),this.emptySubject=i.computed(function(){return""===Si.trim(this.subject())},this),this.subjectForDisplay=i.computed(function(){return this.emptySubject()?Si.i18n("MAILBOX/EMPTY_SUBJECT"):this.subject()},this),this.messageId=i.observable(""),this.size=i.observable(0),this.friendlySize=i.computed(function(){return Si.friendlySize(this.size())},this),this.textSize=i.observable(0),this.oDateModel=new et,this.fullDate=i.observable(""),this.oFrom=new Z,this.fullFrom=i.observable(""),this.oTo=new Z,this.to=i.observable(""),this.fromOrToText=i.observable(""),this.oCc=new Z,this.cc=i.observable(""),this.oBcc=new Z,this.bcc=i.observable(""),this.oSender=new Z,this.oReplyTo=new Z,this.seen=i.observable(!1),this.flagged=i.observable(!1),this.partialFlagged=i.observable(!1),this.answered=i.observable(!1),this.forwarded=i.observable(!1),this.hasAttachments=i.observable(!1),this.hasIcalAttachment=i.observable(!1),this.hasVcardAttachment=i.observable(!1),this.showCalendarIcon=i.computed(function(){return Ti.User.AllowCalendar&&this.hasIcalAttachment()},this),this.threadsAllowed=i.computed(function(){var e=Ci.MailCache.getFolderByFullName(this.accountId(),this.folder()),t=e&&(e.type()===vi.FolderTypes.Drafts||e.type()===vi.FolderTypes.Spam||e.type()===vi.FolderTypes.Trash);return Ti.User.useThreads()&&!t},this),this.threadPart=i.observable(!1),this.threadPart.subscribe(function(){this.threadPart()&&this.partialFlagged(!1)},this),this.threadParentUid=i.observable(""),this.threadUids=i.observableArray([]),this.threadSenders=i.observableArray([]),this.threadSendersText=i.computed(function(){var e=this.threadSenders();return e.length>3?", "+e[0]+Si.i18n("MAILBOX/THREAD_MORE_SENDERS",{COUNT:e.length-1}):e.length>0?(e.unshift(""),e.join(", ")):""},this),this.threadSendersVisible=i.computed(function(){return this.threadSenders().length>0},this),this.threadCount=i.computed(function(){return this.threadUids().length},this),this.threadUnreedCount=i.observable(0),this.threadOpened=i.observable(!1),this.threadLoading=i.observable(!1),this.threadLoadingVisible=i.computed(function(){return this.threadsAllowed()&&this.threadOpened()&&this.threadLoading()},this),this.threadCountVisible=i.computed(function(){return this.threadsAllowed()&&this.threadCount()>0&&!this.threadLoading()},this),this.threadCountForLoad=i.observable(5),this.threadNextLoadingVisible=i.observable(!1),this.threadNextLoadingLinkVisible=i.observable(!1),this.threadFunctionLoadNext=null,this.threadShowAnimation=i.observable(!1),this.threadHideAnimation=i.observable(!1),this.importance=i.observable(vi.Importance.Normal),this.draftInfo=i.observableArray([]),this.sensitivity=i.observable(vi.Sensivity.Nothing),this.hash=i.observable(""),this.downloadLink=i.computed(function(){return this.hash().length>0?Si.getDownloadLinkByHash(this.accountId(),this.hash()):""},this),this.completelyFilled=i.observable(!1),this.checked=i.observable(!1),this.checked.subscribe(function(e){if(!this.threadOpened()&&Ci.MailCache.useThreadsInCurrentList()){var t=Ci.MailCache.folderList().getFolderByFullName(this.folder());_.each(this.threadUids(),function(i){var s=t.oMessages[i];s&&s.checked(e)})}},this),this.selected=i.observable(!1),this.deleted=i.observable(!1),this.trimmed=i.observable(!1),this.trimmedTextSize=i.observable(0),this.inReplyTo=i.observable(""),this.references=i.observable(""),this.readingConfirmation=i.observable(""),this.isPlain=i.observable(!1),this.text=i.observable(""),this.textBodyForNewWindow=i.observable(""),this.$text=null,this.rtl=i.observable(!1),this.hasExternals=i.observable(!1),this.isExternalsShown=i.observable(!1),this.isExternalsAlwaysShown=i.observable(!1),this.foundedCids=i.observableArray([]),this.attachments=i.observableArray([]),this.usesAttachmentString=!1,this.allAttachmentsHash="",this.safety=i.observable(!1),this.sourceHeaders=i.observable(""),this.date=i.observable(""),this.ical=i.observable(null),this.vcard=i.observable(null),this.textRaw=i.observable(""),this.encryptedMessage=i.observable(!1),this.signedMessage=i.observable(!1),this.domMessageForPrint=i.observable(null),this.Custom={},Ci.nowMoment&&Ci.nowMoment.subscribe(function(){this.updateMomentDate()},this)}function at(){this.resultCount=i.observable(-1),this.search=i.observable(""),this.filters=i.observable(""),this.collection=i.observableArray([]),this.threadUids={}}function lt(){this.uid=i.observable(""),this.file=i.observable(""),this.attendee=i.observable(""),this.type=i.observable(""),this.icalType=i.observable(""),this.icalConfig=i.observable(""),this.type.subscribe(function(){var e=this.type().split("-"),t=e.shift(),i=_.find(vi.IcalType,function(e){return t===e},this),s=e.join("-"),o=_.find(vi.IcalConfig,function(e){return s===e},this);t!==i&&(t=vi.IcalType.Save),this.icalType(t),s!==o&&(s=vi.IcalConfig.NeedsAction),this.icalConfig(s)},this),this.isRequestType=i.computed(function(){return this.icalType()===vi.IcalType.Request},this),this.isCancelType=i.computed(function(){return this.icalType()===vi.IcalType.Cancel},this),this.cancelDecision=i.observable(""),this.isReplyType=i.computed(function(){return this.icalType()===vi.IcalType.Reply},this),this.replyDecision=i.observable(""),this.isSaveType=i.computed(function(){return this.icalType()===vi.IcalType.Save},this),this.isJustSaved=i.observable(!1),this.fillDecisions(),this.isAccepted=i.computed(function(){return this.icalConfig()===vi.IcalConfig.Accepted},this),this.isDeclined=i.computed(function(){return this.icalConfig()===vi.IcalConfig.Declined},this),this.isTentative=i.computed(function(){return this.icalConfig()===vi.IcalConfig.Tentative},this),this.location=i.observable(""),this.description=i.observable(""),this.when=i.observable(""),this.calendarId=i.observable(""),this.calendars=i.observableArray([]),Ti.SingleMode&&t.opener?(this.calendars(t.opener.App.CalendarCache.calendars()),t.opener.App.CalendarCache.calendars.subscribe(function(){this.calendars(t.opener.App.CalendarCache.calendars())},this)):(this.calendars(Ci.CalendarCache.calendars()),Ci.CalendarCache.calendars.subscribe(function(){this.calendars(Ci.CalendarCache.calendars())},this)),this.selectedCalendarId=i.observable(""),this.chosenCalendarName=i.computed(function(){var e=null;return""!==this.calendarId()&&(e=_.find(this.calendars(),function(e){return e.id===this.calendarId()},this)),e?e.name:""},this),this.calendarIsChosen=i.computed(function(){return""!==this.chosenCalendarName()},this),this.visibleCalendarDropdown=i.computed(function(){return!this.calendarIsChosen()&&this.calendars().length>1&&(this.isRequestType()||this.isSaveType())},this),this.visibleCalendarName=i.computed(function(){return this.calendarIsChosen()},this),this.visibleFirstCalendarName=i.computed(function(){return 1===this.calendars().length&&!this.calendarIsChosen()},this),this.visibleCalendarRow=i.computed(function(){return""!==this.attendee()&&(this.visibleCalendarDropdown()||this.visibleCalendarName()||this.visibleFirstCalendarName())},this),this.visibleRequestButtons=i.computed(function(){return this.isRequestType()&&""!==this.attendee()},this),this.animation=i.observable(!1)}function ht(){this.uid=i.observable(""),this.file=i.observable(""),this.name=i.observable(""),this.email=i.observable(""),this.isExists=i.observable(!1),this.isJustSaved=i.observable(!1)}function ct(){this.sEmailDefaultType=vi.ContactEmailType.Personal,this.sPhoneDefaultType=vi.ContactPhoneType.Mobile,this.sAddressDefaultType=vi.ContactAddressType.Personal,this.voiceApp=null,Ci.Phone&&(this.voiceApp=Ci.Phone.voiceApp),this.idContact=i.observable(""),this.idUser=i.observable(""),this.global=i.observable(!1),this.itsMe=i.observable(!1),this.isNew=i.observable(!1),this.readOnly=i.observable(!1),this.edited=i.observable(!1),this.extented=i.observable(!1),this.personalCollapsed=i.observable(!1),this.businessCollapsed=i.observable(!1),this.otherCollapsed=i.observable(!1),this.groupsCollapsed=i.observable(!1),this.displayName=i.observable(""),this.firstName=i.observable(""),this.lastName=i.observable(""),this.nickName=i.observable(""),this.skype=i.observable(""),this.facebook=i.observable(""),this.displayNameFocused=i.observable(!1),this.primaryEmail=i.observable(this.sEmailDefaultType),this.primaryPhone=i.observable(this.sPhoneDefaultType),this.primaryAddress=i.observable(this.sAddressDefaultType),this.mainPrimaryEmail=i.computed({read:this.primaryEmail,write:function(e){this.primaryEmail(!Si.isUnd(e)&&0<=Si.inArray(e,[vi.ContactEmailType.Personal,vi.ContactEmailType.Business,vi.ContactEmailType.Other])?e:vi.ContactEmailType.Personal)},owner:this}),this.mainPrimaryPhone=i.computed({read:this.primaryPhone,write:function(e){this.primaryPhone(!Si.isUnd(e)&&0<=Si.inArray(e,[vi.ContactPhoneType.Mobile,vi.ContactPhoneType.Personal,vi.ContactPhoneType.Business])?e:vi.ContactPhoneType.Mobile)},owner:this}),this.mainPrimaryAddress=i.computed({read:this.primaryAddress,write:function(e){this.primaryAddress(!Si.isUnd(e)&&0<=Si.inArray(e,[vi.ContactAddressType.Personal,vi.ContactAddressType.Business])?e:vi.ContactAddressType.Personal)},owner:this}),this.personalEmail=i.observable(""),this.personalStreetAddress=i.observable(""),this.personalCity=i.observable(""),this.personalState=i.observable(""),this.personalZipCode=i.observable(""),this.personalCountry=i.observable(""),this.personalWeb=i.observable(""),this.personalFax=i.observable(""),this.personalPhone=i.observable(""),this.personalMobile=i.observable(""),this.businessEmail=i.observable(""),this.businessCompany=i.observable(""),this.businessDepartment=i.observable(""),this.businessJob=i.observable(""),this.businessOffice=i.observable(""),this.businessStreetAddress=i.observable(""),this.businessCity=i.observable(""),this.businessState=i.observable(""),this.businessZipCode=i.observable(""),this.businessCountry=i.observable(""),this.businessWeb=i.observable(""),this.businessFax=i.observable(""),this.businessPhone=i.observable(""),this.otherEmail=i.observable(""),this.otherBirthdayMonth=i.observable("0"),this.otherBirthdayDay=i.observable("0"),this.otherBirthdayYear=i.observable("0"),this.otherNotes=i.observable(""),this.etag=i.observable(""),this.sharedToAll=i.observable(!1),this.birthdayIsEmpty=i.computed(function(){var e="0"===this.otherBirthdayMonth(),t="0"===this.otherBirthdayDay(),i="0"===this.otherBirthdayYear();return e||t||i},this),this.otherBirthday=i.computed(function(){var e="",t=Si.pInt(this.otherBirthdayYear()),i=Si.pInt(this.otherBirthdayMonth()),s=Si.pInt(this.otherBirthdayDay()),o=new et;return this.birthdayIsEmpty()||(o.setDate(t,i>0?i-1:0,s),e=o.getShortDate()),e},this),this.groups=i.observableArray([]),this.groupsIsEmpty=i.computed(function(){return 0===this.groups().length},this),this.email=i.computed({read:function(){var e="";switch(this.primaryEmail()){case vi.ContactEmailType.Personal:e=this.personalEmail();break;case vi.ContactEmailType.Business:e=this.businessEmail();break;case vi.ContactEmailType.Other:e=this.otherEmail()}return e},write:function(e){switch(this.primaryEmail()){case vi.ContactEmailType.Personal:this.personalEmail(e);break;case vi.ContactEmailType.Business:this.businessEmail(e);break;case vi.ContactEmailType.Other:this.otherEmail(e);break;default:this.primaryEmail(this.sEmailDefaultType),this.email(e)}},owner:this}),this.personalIsEmpty=i.computed(function(){var e=this.personalEmail()!==this.email()?this.personalEmail():"";return""==""+e+this.personalStreetAddress()+this.personalCity()+this.personalState()+this.personalZipCode()+this.personalCountry()+this.personalWeb()+this.personalFax()+this.personalPhone()+this.personalMobile()},this),this.businessIsEmpty=i.computed(function(){var e=this.businessEmail()!==this.email()?this.businessEmail():"";return""==""+e+this.businessCompany()+this.businessDepartment()+this.businessJob()+this.businessOffice()+this.businessStreetAddress()+this.businessCity()+this.businessState()+this.businessZipCode()+this.businessCountry()+this.businessWeb()+this.businessFax()+this.businessPhone()},this),this.otherIsEmpty=i.computed(function(){var e=this.otherEmail()!==this.email()?this.otherEmail():"";return""==""+e+this.otherNotes()&&this.birthdayIsEmpty()},this),this.phone=i.computed({read:function(){var e="";switch(this.primaryPhone()){case vi.ContactPhoneType.Mobile:e=this.personalMobile();break;case vi.ContactPhoneType.Personal:e=this.personalPhone();break;case vi.ContactPhoneType.Business:e=this.businessPhone()}return e},write:function(e){switch(this.primaryPhone()){case vi.ContactPhoneType.Mobile:this.personalMobile(e);break;case vi.ContactPhoneType.Personal:this.personalPhone(e);break;case vi.ContactPhoneType.Business:this.businessPhone(e);break;default:this.primaryPhone(this.sEmailDefaultType),this.phone(e)}},owner:this}),this.address=i.computed({read:function(){var e="";switch(this.primaryAddress()){case vi.ContactAddressType.Personal:e=this.personalStreetAddress();break;case vi.ContactAddressType.Business:e=this.businessStreetAddress()}return e},write:function(e){switch(this.primaryAddress()){case vi.ContactAddressType.Personal:this.personalStreetAddress(e);break;case vi.ContactAddressType.Business:this.businessStreetAddress(e);break;default:this.primaryAddress(this.sEmailDefaultType),this.address(e)}},owner:this}),this.emails=i.computed(function(){var e=[];return""!==this.personalEmail()&&e.push({text:Si.i18n("CONTACTS/OPTION_PERSONAL")+": "+this.personalEmail(),value:vi.ContactEmailType.Personal}),""!==this.businessEmail()&&e.push({text:Si.i18n("CONTACTS/OPTION_BUSINESS")+": "+this.businessEmail(),value:vi.ContactEmailType.Business}),""!==this.otherEmail()&&e.push({text:Si.i18n("CONTACTS/OPTION_OTHER")+": "+this.otherEmail(),value:vi.ContactEmailType.Other}),e},this),this.phones=i.computed(function(){var e=[];return""!==this.personalMobile()&&e.push({text:Si.i18n("CONTACTS/LABEL_MOBILE")+": "+this.personalMobile(),value:vi.ContactPhoneType.Mobile}),""!==this.personalPhone()&&e.push({text:Si.i18n("CONTACTS/OPTION_PERSONAL")+": "+this.personalPhone(),value:vi.ContactPhoneType.Personal}),""!==this.businessPhone()&&e.push({text:Si.i18n("CONTACTS/OPTION_BUSINESS")+": "+this.businessPhone(),value:vi.ContactPhoneType.Business}),e},this),this.addresses=i.computed(function(){var e=[];return""!==this.personalStreetAddress()&&e.push({text:Si.i18n("CONTACTS/OPTION_PERSONAL")+": "+this.personalStreetAddress(),value:vi.ContactAddressType.Personal}),""!==this.businessStreetAddress()&&e.push({text:Si.i18n("CONTACTS/OPTION_BUSINESS")+": "+this.businessStreetAddress(),value:vi.ContactAddressType.Business}),e},this),this.hasEmails=i.computed(function(){return 0<this.emails().length},this),this.extented.subscribe(function(e){e&&(this.personalCollapsed(!this.personalIsEmpty()),this.businessCollapsed(!this.businessIsEmpty()),this.otherCollapsed(!this.otherIsEmpty()),this.groupsCollapsed(!this.groupsIsEmpty()))},this),this.birthdayMonthSelect=ct.birthdayMonthSelect,this.birthdayYearSelect=ct.birthdayYearSelect,this.birthdayDaySelect=i.computed(function(){for(var e=1,t=Si.pInt(Si.daysInMonth(this.otherBirthdayMonth(),this.otherBirthdayYear())),i="",s=[{text:Si.i18n("DATETIME/DAY"),value:"0"}];t>=e;e++)i=e.toString(),s.push({text:i,value:i});return s},this);for(var e=new Date,t="",s=e.getFullYear(),o=1932;s>=o;s--)t=s.toString(),this.birthdayYearSelect.push({text:t,value:t});this.canBeSave=i.computed(function(){return""!==this.displayName()||!!this.emails().length},this),this.sendMailLink=i.computed(function(){return this.getSendMailLink(this.email())},this),this.sendMailToPersonalLink=i.computed(function(){return this.getSendMailLink(this.personalEmail())},this),this.sendMailToBusinessLink=i.computed(function(){return this.getSendMailLink(this.businessEmail())},this),this.sendMailToOtherLink=i.computed(function(){return this.getSendMailLink(this.otherEmail())},this)}function ut(){this.isNew=i.observable(!1),this.readOnly=i.observable(!1),this.idGroup=i.observable(""),this.idUser=i.observable(""),this.name=i.observable(""),this.isOrganization=i.observable(!1),this.email=i.observable(""),this.country=i.observable(""),this.city=i.observable(""),this.company=i.observable(""),this.fax=i.observable(""),this.phone=i.observable(""),this.state=i.observable(""),this.street=i.observable(""),this.web=i.observable(""),this.zip=i.observable(""),this.edited=i.observable(!1),this.nameFocused=i.observable(!1),this.canBeSave=i.computed(function(){return""!==this.name()},this),this.newContactsInGroupCount=i.observable(0),this.newContactsInGroupHint=i.computed(function(){var e=this.newContactsInGroupCount();return this.isNew()&&e>0?Si.i18n("CONTACTS/CONTACT_ADD_TO_NEW_HINT_PLURAL",{COUNT:e},null,e):""},this),this.events=i.observableArray([])}function dt(){this.bIsGroup=!1,this.bIsOrganization=!1,this.bReadOnly=!1,this.bItsMe=!1,this.bGlobal=!1,this.sId="",this.sName="",this.sEmail="",this.bSharedToAll=!1,this.deleted=i.observable(!1),this.checked=i.observable(!1),this.selected=i.observable(!1),this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500})}function pt(){this.id=0,this.cTag=0,this.name=i.observable(""),this.description=i.observable(""),this.owner=i.observable(""),this.isDefault=!1,this.isShared=i.observable(!1),this.isSharedToAll=i.observable(!1),this.sharedToAllAccess=vi.CalendarAccess.Read,this.isPublic=i.observable(!1),this.url=i.observable(""),this.davUrl=i.observable(""),this.exportUrl=i.observable(""),this.pubUrl=i.observable(""),this.shares=i.observableArray([]),this.events=i.observableArray([]),this.eventsCount=i.computed(function(){return this.events().length},this),this.access=i.observable(vi.CalendarAccess.Write),this.control=i.computed(function(){return!(this.access()===vi.CalendarAccess.Read&&this.isSharedToAll())},this),this.color=i.observable(""),this.color.subscribe(function(){this.events(_.map(this.events(),function(e){return e.backgroundColor=e.borderColor=this.color(),e},this)),this.name.valueHasMutated()},this),this.active=i.observable(!0),this.startDateTime=0,this.endDateTime=0,this.account=Ti.Accounts?Ti.Accounts.getDefault():null}function gt(e){this.parentOnCalendarActiveChange=e.onCalendarActiveChange,this.parentOnCalendarCollectionChange=e.onCalendarCollectionChange,this.defaultCal=i.observable(null),this.currentCal=i.observable(null),this.collection=i.observableArray([]),this.collection.subscribe(function(){this.pickCurrentCalendar(this.defaultCal()),this.parentOnCalendarCollectionChange&&this.parentOnCalendarCollectionChange()},this),this.count=i.computed(function(){return this.collection().length},this),this.own=i.computed(function(){var e=_.filter(this.collection(),function(e){return!e.isShared()});return e},this),this.ownCount=i.computed(function(){return this.own().length},this),this.shared=i.computed(function(){var e=_.filter(this.collection(),function(e){return e.isShared()&&!e.isSharedToAll()});return e},this),this.sharedCount=i.computed(function(){return this.shared().length},this),this.sharedToAll=i.computed(function(){var e=_.filter(this.collection(),function(e){return e.isShared()&&e.isSharedToAll()});return e},this),this.sharedToAllCount=i.computed(function(){return this.sharedToAll().length},this),this.ids=i.computed(function(){return _.map(this.collection(),function(e){return e.id},this)},this)}function mt(){this.id=i.observable(""),this.fileName=i.observable(""),this.displayName=i.observable(""),this.nameForEdit=i.observable(""),this.storageType=i.observable(vi.FileStorageType.Personal),this.lastModified=i.observable(""),this.path=i.observable(""),this.fullPath=i.observable(""),this.publicHash=i.observable(""),this.selected=i.observable(!1),this.checked=i.observable(!1),this.isFolder=i.observable(!1),this.edited=i.observable(!1),this.isExternal=i.observable(!1),this.isLink=i.observable(!1),this.linkType=i.observable(0),this.linkUrl=i.observable(""),this.thumbnailExternalLink=i.observable(""),this.deleted=i.observable(!1),this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500}),this.shared=i.observable(!1),this.owner=i.observable(""),this.ownerHeaderText=i.computed(function(){return Si.i18n("FILESTORAGE/OWNER_HEADER_EMAIL",{OWNER:this.owner()})},this),this.lastModifiedHeaderText=i.computed(function(){return Si.i18n("FILESTORAGE/OWNER_HEADER_LAST_MODIFIED_DATE_TEXT",{LASTMODIFIED:this.lastModified()})},this),it.call(this),this.fileName.subscribe(function(e){this.nameForEdit(e),this.displayName(e)},this),this.displayName.subscribe(function(e){this.isFolder()||this.displayName(Si.getFileNameWithoutExtension(e))},this),this.type=this.storageType,this.uploaded=i.observable(!0),this.downloadLink=i.computed(function(){return Si.getFilestorageDownloadLinkByHash(Ti.Accounts?Ti.Accounts.currentId():null,this.hash(),this.publicHash())},this),this.viewLink=i.computed(function(){if(this.isLink())return this.linkUrl();var e=Si.getFilestorageViewLinkByHash(Ti.Accounts?Ti.Accounts.currentId():null,this.hash(),this.publicHash());return this.iframedView()?Si.getIframeWrappwer(Ti.Accounts?Ti.Accounts.currentId():null,e):e},this),this.isViewable=i.computed(function(){var e=!1,t=["JPEG","JPG","PNG","GIF","HTM","HTML","TXT","CSS","ASC","JS","PDF"];return _.indexOf(t,this.extension().toUpperCase())>=0&&(e=!0),(this.iframedView()||e||this.isLink())&&!this.isPopupItem()},this),this.visibleViewLink=this.isViewable,this.thumbnailLink=i.computed(function(){return this.isExternal()||this.isLink()&&this.linkType()===vi.FileStorageLinkType.GoogleDrive?this.thumbnailExternalLink():this.thumb()?Si.getFilestorageViewThumbnailLinkByHash(this.accountId(),this.hash(),this.publicHash()):""},this),this.edited.subscribe(function(e){e===!1&&this.nameForEdit(this.fileName())},this)}function bt(){this.Id=null,this.IdThread=null,this.IdOwner=null,this.sFrom="",this.sDate="",this.iType=null,this.bSysType=!1,this.bThreadOwner=null,this.sText="",this.collapsed=i.observable(!1),this.attachments=i.observableArray([]),this.allowDownloadAttachmentsLink=!0,this.itsMe=i.observable(!1),this.canBeDeleted=this.itsMe}function ft(){this.Id=null,this.ThreadHash="",this.IdOwner=null,this.ItsMe=!1,this.aOwner=[],this.sSubject="",this.sEmail="",this.sName="",this.sFrom="",this.sFromFull="",this.time=i.observable(0),this.state=i.observable(0),this.unseen=i.observable(!1),this.postsCount=i.observable(0),this.date=i.computed(function(){return moment(1e3*this.time()).fromNow(!1)},this),this.printableState=i.computed(function(){var e="",t=this.ItsMe?"_FOR_CLIENT":"";switch(this.state()){case vi.HelpdeskThreadStates.Pending:e=Si.i18n("HELPDESK/THREAD_STATE_PENDING"+t);break;case vi.HelpdeskThreadStates.Resolved:e=Si.i18n("HELPDESK/THREAD_STATE_RESOLVED"+t);break;case vi.HelpdeskThreadStates.Waiting:e=Si.i18n("HELPDESK/THREAD_STATE_WAITING"+t);break;case vi.HelpdeskThreadStates.Answered:e=Si.i18n("HELPDESK/THREAD_STATE_ANSWERED"+t);break;case vi.HelpdeskThreadStates.Deferred:e=Si.i18n("HELPDESK/THREAD_STATE_DEFERRED"+t)}return e},this),this.deleted=i.observable(!1),this.checked=i.observable(!1),this.selected=i.observable(!1)}function yt(){it.call(this),this.downloadLink=i.computed(function(){var e=!Fi&&Ti&&Ti.Accounts?Ti.Accounts.currentId():0,t=Fi&&Ti?Ti.TenantHash:"";return Si.getDownloadLinkByHash(e,this.hash(),Fi,t)},this),this.viewLink=i.computed(function(){var e=!Fi&&Ti&&Ti.Accounts?Ti.Accounts.currentId():0,t=Fi&&Ti?Ti.TenantHash:"";return Si.getViewLinkByHash(e,this.hash(),Fi,t)},this),this.thumbnailLink=i.computed(function(){var e=!Fi&&Ti&&Ti.Accounts?Ti.Accounts.currentId():0,t=Fi&&Ti?Ti.TenantHash:"",i=this.thumb()?Si.getViewThumbnailLinkByHash(e,this.hash(),Fi,t):"";return i},this)}function vt(){this.iAccountId=0,this.type=i.observable(!0),this.options=i.observable(0),this.signature=i.observable("")}function St(){this.iAccountId=0,this.enable=!1,this.subject="",this.message=""}function At(){this.FETCHER=!0,this.id=i.observable(0),this.accountId=i.observable(0),this.isEnabled=i.observable(!1),this.isLocked=i.observable(!1),this.email=i.observable(""),this.userName=i.observable(""),this.folder=i.observable(""),this.signatureOptions=i.observable(!1),this.signature=i.observable(""),this.incomingMailServer=i.observable(""),this.incomingMailPort=i.observable(0),this.incomingMailLogin=i.observable(""),this.leaveMessagesOnServer=i.observable(""),this.isOutgoingEnabled=i.observable(!1),this.outgoingMailServer=i.observable(""),this.outgoingMailPort=i.observable(0),this.outgoingMailAuth=i.observable(!1),this.fullEmail=i.computed(function(){return""===this.userName()?this.email():this.userName()+" <"+this.email()+">"},this)}function Ct(){this.accountId=0,this.collection=i.observableArray([])}function Et(){this.iAccountId=0,this.enable=!1,this.email="" }function Tt(){this.iAccountId=0,this.collection=i.observableArray([])}function Ft(e){this.iAccountId=e,this.enable=i.observable(!0).extend({reversible:!0}),this.field=i.observable("").extend({reversible:!0}),this.condition=i.observable("").extend({reversible:!0}),this.filter=i.observable("").extend({reversible:!0}),this.action=i.observable("").extend({reversible:!0}),this.folder=i.observable("").extend({reversible:!0})}function It(){this.iAnimationDuration=500,this.iReportDuration=5e3,this.iErrorDuration=1e4,this.loadingMessage=i.observable(""),this.loadingHidden=i.observable(!0),this.loadingVisible=i.observable(!1),this.reportMessage=i.observable(""),this.reportHidden=i.observable(!0),this.reportVisible=i.observable(!1),this.iReportTimeout=-1,this.errorMessage=i.observable(""),this.errorHidden=i.observable(!0),this.errorVisible=i.observable(!1),this.iErrorTimeout=-1,this.isHtmlError=i.observable(!1),this.gray=i.observable(!1)}function wt(){this.mobileApp=Ii,this.allowWebMail=Ti.App.AllowWebMail,this.currentAccountId=Ti.Accounts.currentId,this.currentAccountId.subscribe(function(){this.changeCurrentAccount()},this),this.tabs=Ci.headerTabs,this.email=i.observable(""),this.accounts=Ti.Accounts.collection,this.currentTab=Ci.Screens.currentScreen,this.isMailboxTab=i.computed(function(){return this.currentTab()===vi.Screens.Mailbox},this),this.helpdeskUnseenCount=Ci.helpdeskUnseenCount,this.helpdeskUnseenVisible=i.computed(function(){return this.currentTab()!==vi.Screens.Helpdesk&&!!this.helpdeskUnseenCount()},this),this.mailUnseenCount=Ci.mailUnseenCount,this.mailUnseenVisible=i.computed(function(){return this.currentTab()!==vi.Screens.Mailbox&&!!this.mailUnseenCount()},this),this.mailboxHash=Ci.Routing.lastMailboxHash,this.settingsHash=Ci.Routing.lastSettingsHash,this.contactsRecivedAnim=Ci.ContactsCache.recivedAnim,this.calendarRecivedAnim=Ci.CalendarCache.recivedAnim,this.appCustomLogo=i.observable(Ti.AppStyleImage||"")}function Pt(){wt.call(this),this.oPhone=Ci.Phone?new _t:null}function Mt(e,t){this.shown=!1,this.currentPage=i.observable(1),this.count=i.observable(e),this.perPage=i.observable(t),this.firstPage=i.observable(1),this.lastPage=i.observable(1),this.pagesCount=i.computed(function(){var e=Math.ceil(this.count()/this.perPage());return e>0?e:1},this),i.computed(function(){var e=20,t=4,i=this.pagesCount(),s=this.currentPage(),o=s,n=s;if(i>1)for(;;){if(e--,o>1&&(o--,t--),0===t)break;if(i>n&&(n++,t--),0===t)break;if(0===e)break}this.firstPage(o),this.lastPage(n)},this),this.visibleFirst=i.computed(function(){return this.firstPage()>1},this),this.visibleLast=i.computed(function(){return this.lastPage()<this.pagesCount()},this),this.clickPage=_.bind(this.clickPage,this),this.pages=i.computed(function(){var e=this.firstPage(),t=[];if(this.firstPage()<this.lastPage())for(;e<=this.lastPage();e++)t.push({number:e,current:e===this.currentPage(),clickFunc:this.clickPage});return t},this),this.hotKeysBind()}function Rt(e,s){this.mobileApp=Ii,this.oParent=s,this.creaId="creaId"+Math.random().toString().replace(".",""),this.textFocused=i.observable(!1),this.workareaDom=i.observable(),this.uploaderAreaDom=i.observable(),this.editorUploaderBodyDragOver=i.observable(!1),this.editorUploaderProgress=i.observable(!1),this.colorPickerDropdownDom=i.observable(),this.insertLinkDropdownDom=i.observable(),this.insertImageDropdownDom=i.observable(),this.isEnable=i.observable(!0),this.isEnable.subscribe(function(){this.oCrea&&this.oCrea.setEditable(this.isEnable())},this),this.bInsertImageAsBase64=e,this.bAllowFileUpload=!(e&&void 0===t.File),this.allowInsertImage=i.observable(Ti.App.AllowInsertImage),this.lockFontSubscribing=i.observable(!1),this.bAllowImageDragAndDrop=!Ci.browser.ie10AndAbove,this.aFonts=["Arial","Arial Black","Courier New","Tahoma","Times New Roman","Verdana"],this.sDefaultFont=Ti.User.DefaultFontName,this.correctFontFromSettings(),this.selectedFont=i.observable(""),this.selectedFont.subscribe(function(){!this.oCrea||this.lockFontSubscribing()||this.inactive()||this.oCrea.fontName(this.selectedFont())},this),this.iDefaultSize=Ti.User.DefaultFontSize,this.selectedSize=i.observable(0),this.selectedSize.subscribe(function(){!this.oCrea||this.lockFontSubscribing()||this.inactive()||this.oCrea.fontSize(this.selectedSize())},this),this.visibleInsertLinkPopup=i.observable(!1),this.linkForInsert=i.observable(""),this.linkFocused=i.observable(!1),this.visibleLinkPopup=i.observable(!1),this.linkPopupTop=i.observable(0),this.linkPopupLeft=i.observable(0),this.linkHref=i.observable(""),this.visibleLinkHref=i.observable(!1),this.visibleImagePopup=i.observable(!1),this.visibleImagePopup.subscribe(function(){this.onImageOut()},this),this.imagePopupTop=i.observable(0),this.imagePopupLeft=i.observable(0),this.imageSelected=i.observable(!1),this.tooltipText=i.observable(""),this.tooltipPopupTop=i.observable(0),this.tooltipPopupLeft=i.observable(0),this.visibleInsertImagePopup=i.observable(!1),this.imageUploaderButton=i.observable(null),this.uploadedImagePathes=i.observableArray([]),this.imagePathFromWeb=i.observable(""),this.visibleFontColorPopup=i.observable(!1),this.oFontColorPicker=new Dt(Si.i18n("HTMLEDITOR/TEXT_COLOR_CAPTION"),this.setTextColorFromPopup,this),this.oBackColorPicker=new Dt(Si.i18n("HTMLEDITOR/BACKGROUND_COLOR_CAPTION"),this.setBackColorFromPopup,this),this.activitySource=i.observable(1),this.activitySourceSubscription=null,this.inactive=i.observable(!1),this.inactive.subscribe(function(){var e=this.removeAllTags(this.getText());this.inactive()?(""===e||" "===e)&&(this.setText('<span style="color: #AAAAAA;">'+Si.i18n("HTMLEDITOR/SIGNATURE_PLACEHOLDER")+"</span>"),this.oCrea&&this.oCrea.setBlur()):e===Si.i18n("HTMLEDITOR/SIGNATURE_PLACEHOLDER")&&this.setText("")},this),this.allowChangeInputDirection=Si.isRTL()||Ti.User.AllowChangeInputDirection,this.disabled=i.observable(!1)}function Dt(e,t,s){this.aGreyColors=["rgb(0, 0, 0)","rgb(68, 68, 68)","rgb(102, 102, 102)","rgb(153, 153, 153)","rgb(204, 204, 204)","rgb(238, 238, 238)","rgb(243, 243, 243)","rgb(255, 255, 255)"],this.aBrightColors=["rgb(255, 0, 0)","rgb(255, 153, 0)","rgb(255, 255, 0)","rgb(0, 255, 0)","rgb(0, 255, 255)","rgb(0, 0, 255)","rgb(153, 0, 255)","rgb(255, 0, 255)"],this.aColorLines=[["rgb(244, 204, 204)","rgb(252, 229, 205)","rgb(255, 242, 204)","rgb(217, 234, 211)","rgb(208, 224, 227)","rgb(207, 226, 243)","rgb(217, 210, 233)","rgb(234, 209, 220)"],["rgb(234, 153, 153)","rgb(249, 203, 156)","rgb(255, 229, 153)","rgb(182, 215, 168)","rgb(162, 196, 201)","rgb(159, 197, 232)","rgb(180, 167, 214)","rgb(213, 166, 189)"],["rgb(224, 102, 102)","rgb(246, 178, 107)","rgb(255, 217, 102)","rgb(147, 196, 125)","rgb(118, 165, 175)","rgb(111, 168, 220)","rgb(142, 124, 195)","rgb(194, 123, 160)"],["rgb(204, 0, 0)","rgb(230, 145, 56)","rgb(241, 194, 50)","rgb(106, 168, 79)","rgb(69, 129, 142)","rgb(61, 133, 198)","rgb(103, 78, 167)","rgb(166, 77, 121)"],["rgb(153, 0, 0)","rgb(180, 95, 6)","rgb(191, 144, 0)","rgb(56, 118, 29)","rgb(19, 79, 92)","rgb(11, 83, 148)","rgb(53, 28, 117)","rgb(116, 27, 71)"],["rgb(102, 0, 0)","rgb(120, 63, 4)","rgb(127, 96, 0)","rgb(39, 78, 19)","rgb(12, 52, 61)","rgb(7, 55, 99)","rgb(32, 18, 77)","rgb(76, 17, 48)"]],this.caption=e,this.pickHandler=t,this.pickContext=s,this.colorPickerDom=i.observable(null)}function _t(){this.phone=Ci.Phone,this.action=this.phone.action,this.report=this.phone.report,this.logs=i.observableArray([]),this.logsToShow=i.observableArray([]),this.spinner=i.observable(!0),this.tooltip=i.observable(Si.i18n("PHONE/NOT_CONNECTED")),this.indicator=i.observable(Si.i18n("PHONE/MISSED_CALLS")),this.dropdownShow=i.observable(!1),this.input=i.observable(""),this.input.subscribe(function(e){this.dropdownShow(""===e&&this.action()===vi.PhoneAction.OnlineActive)},this),this.inputFocus=i.observable(!1),this.inputFocus.subscribe(function(e){e&&""===this.input()&&this.action()===vi.PhoneAction.OnlineActive&&this.dropdownShow(!0)},this),this.phoneAutocompleteItem=i.observable(null),this.action.subscribe(function(e){switch(e){case vi.PhoneAction.Offline:this.tooltip(Si.i18n("PHONE/NOT_CONNECTED"));break;case vi.PhoneAction.OfflineError:this.tooltip(Si.i18n("Connection error"));break;case vi.PhoneAction.OfflineInit:this.tooltip(Si.i18n("PHONE/CONNECTING"));break;case vi.PhoneAction.OfflineActive:break;case vi.PhoneAction.Online:this.tooltip(Si.i18n("PHONE/CONNECTED")),this.input(""),this.report(""),this.timer("stop");break;case vi.PhoneAction.OnlineActive:break;case vi.PhoneAction.Outgoing:this.timer("start");break;case vi.PhoneAction.OutgoingConnect:this.tooltip(Si.i18n("In Call"));break;case vi.PhoneAction.Incoming:break;case vi.PhoneAction.IncomingConnect:this.tooltip(Si.i18n("In Call")),this.report(""),this.timer("start")}},this),e(document).on("click",_.bind(function(t){0===e(t.target).closest(".item.phone").length&&this.action()===vi.PhoneAction.OnlineActive&&(this.action(vi.PhoneAction.Online),this.dropdownShow(!1))},this))}function Nt(){this.rtl=i.observable(Si.isRTL()),this.allowRegistration=Ti.App.AllowRegistration,this.allowPasswordReset=Ti.App.AllowPasswordReset,this.oLoginViewModel=new kt,this.allowRegistration&&(this.oRegisterViewModel=new Ot),this.allowPasswordReset&&(this.oForgotViewModel=new Lt),this.gotoForgot=this.allowPasswordReset?this.oForgotViewModel.gotoForgot:i.observable(!1),this.gotoRegister=i.observable(!1),this.emailVisible=this.oLoginViewModel.emailVisible,this.loginVisible=this.oLoginViewModel.loginVisible,this.loginDescription=i.observable(Ti.App.LoginDescription||""),this.aLanguages=Ti.App.Languages,this.currentLanguage=i.observable(Ti.App.DefaultLanguage),this.allowLanguages=i.observable(Ti.App.AllowLanguageOnLogin),this.viewLanguagesAsDropdown=i.observable(!Ti.App.FlagsLangSelect),this.loginCustomLogo=i.observable(Ti.LoginStyleImage||""),Ei.runPluginHook&&Ei.runPluginHook("view-model-defined",[this.__name,this])}function kt(){this.allowRegistration=Ti.App.AllowRegistration,this.allowPasswordReset=Ti.App.AllowPasswordReset,this.email=i.observable(""),this.login=i.observable(""),this.password=i.observable(""),this.emailFocus=i.observable(!1),this.loginFocus=i.observable(!1),this.passwordFocus=i.observable(!1),this.loading=i.observable(!1),this.changingLanguage=i.observable(!1),this.loginFocus.subscribe(function(e){e&&""===this.login()&&this.login(this.email())},this),this.loginFormType=i.observable(Ti.App.LoginFormType),this.loginAtDomainValue=i.observable(Ti.App.LoginAtDomainValue),this.loginAtDomainValueWithAt=i.computed(function(){var e=this.loginAtDomainValue();return""===e?"":"@"+e},this),this.emailVisible=i.computed(function(){return vi.LoginFormType.Login!==this.loginFormType()},this),this.loginVisible=i.computed(function(){return vi.LoginFormType.Email!==this.loginFormType()},this),this.signMeType=i.observable(Ti.App.LoginSignMeType),this.signMe=i.observable(vi.LoginSignMeType.DefaultOn===this.signMeType()),this.signMeType.subscribe(function(){this.signMe(vi.LoginSignMeType.DefaultOn===this.signMeType())},this),this.signMeFocused=i.observable(!1),this.emailDom=i.observable(null),this.loginDom=i.observable(null),this.passwordDom=i.observable(null),this.focusedField="",this.canBeLogin=i.computed(function(){return!this.loading()&&!this.changingLanguage()},this),this.signInButtonText=i.computed(function(){return Si.i18n(this.loading()?"LOGIN/BUTTON_SIGNING_IN":"LOGIN/BUTTON_SIGN_IN")},this),this.loginCommand=Si.createCommand(this,this.signIn,this.canBeLogin),this.email(Ti.App.DemoWebMailLogin||""),this.password(Ti.App.DemoWebMailPassword||""),Ei.runPluginHook&&Ei.runPluginHook("view-model-defined",[this.__name,this]),this.shake=i.observable(!1).extend({autoResetToFalse:800})}function Lt(){this.gotoForgot=i.observable(!1),this.gotoForgot.subscribe(function(){this.visibleEmailForm(!0),this.visibleQuestionForm(!1),this.visiblePasswordForm(!1)},this),this.visibleEmailForm=i.observable(!0),this.email=i.observable(""),this.emailFocus=i.observable(!1),this.gettingQuestion=i.observable(!1),this.getQuestionButtonText=i.computed(function(){return Si.i18n(this.gettingQuestion()?"LOGIN/BUTTON_GETTING_QUESTION":"LOGIN/BUTTON_GET_QUESTION")},this),this.allowGetQuestion=i.computed(function(){return!this.gettingQuestion()&&""!==Si.trim(this.email())},this),this.getQuestionCommand=Si.createCommand(this,this.executeGetQuestion,this.allowGetQuestion),this.visibleQuestionForm=i.observable(!1),this.question=i.observable(""),this.answer=i.observable(""),this.answerFocus=i.observable(!1),this.validatingAnswer=i.observable(!1),this.validateAnswerButtonText=i.computed(function(){return Si.i18n(this.validatingAnswer()?"LOGIN/BUTTON_VALIDATING_ANSWER":"LOGIN/BUTTON_VALIDATE_ANSWER")},this),this.allowValidatingAnswer=i.computed(function(){return!this.validatingAnswer()&&""!==Si.trim(this.answer())},this),this.validateAnswerCommand=Si.createCommand(this,this.executeValidateAnswer,this.allowValidatingAnswer),this.visiblePasswordForm=i.observable(!1),this.password=i.observable(""),this.confirmPassword=i.observable(""),this.passwordFocus=i.observable(!1),this.confirmPasswordFocus=i.observable(!1),this.changingPassword=i.observable(!1),this.changePasswordButtonText=i.computed(function(){return Si.i18n(this.changingPassword()?"LOGIN/BUTTON_RESETTING_PASSWORD":"LOGIN/BUTTON_RESET_PASSWORD")},this),this.allowChangePassword=i.computed(function(){var e=Si.trim(this.password()),t=Si.trim(this.confirmPassword()),i=""===e||""===t;return!this.changingPassword()&&!i},this),this.changePasswordCommand=Si.createCommand(this,this.executeChangePassword,this.allowChangePassword),Ei.runPluginHook&&Ei.runPluginHook("view-model-defined",[this.__name,this])}function Ot(){this.name=i.observable(""),this.login=i.observable(""),this.password=i.observable(""),this.confirmPassword=i.observable(""),this.question=i.observable(""),this.yourQuestion=i.observable(""),this.answer=i.observable(""),this.allowQuestionPart=Si.isNonEmptyArray(Ti.App.RegistrationQuestions),this.visibleYourQuestion=i.computed(function(){return this.question()===Si.i18n("LOGIN/OPTION_YOUR_QUESTION")},this),this.nameFocus=i.observable(!1),this.loginFocus=i.observable(!1),this.passwordFocus=i.observable(!1),this.confirmPasswordFocus=i.observable(!1),this.questionFocus=i.observable(!1),this.answerFocus=i.observable(!1),this.yourQuestionFocus=i.observable(!1),this.domains=i.observable(Si.isNonEmptyArray(Ti.App.RegistrationDomains)?Ti.App.RegistrationDomains:[]),this.domain=i.computed(function(){return 1===this.domains().length?this.domains()[0]:""},this),this.selectedDomain=i.observable(this.domains().length>0?this.domains()[0]:""),this.registrationQuestions=[],this.allowQuestionPart&&(this.registrationQuestions=_.map(_.union("",_.without(Ti.App.RegistrationQuestions,"*")),function(e){return{text:""!==e?e:Si.i18n("LOGIN/LABEL_SELECT_QUESTION"),value:e}}),-1!==_.indexOf(Ti.App.RegistrationQuestions,"*")&&this.registrationQuestions.push({text:Si.i18n("LOGIN/OPTION_YOUR_QUESTION"),value:Si.i18n("LOGIN/OPTION_YOUR_QUESTION")})),this.loading=i.observable(!1),this.canBeRegister=i.computed(function(){var e=Si.trim(this.login()),t=Si.trim(this.password()),i=Si.trim(this.confirmPassword()),s=Si.trim(this.visibleYourQuestion()?this.yourQuestion():this.question()),o=Si.trim(this.answer()),n=""===e||""===t||""===i||this.allowQuestionPart&&(""===s||""===o);return!this.loading()&&!n},this),this.registerButtonText=i.computed(function(){return Si.i18n(this.loading()?"LOGIN/BUTTON_REGISTERING":"LOGIN/BUTTON_REGISTER")},this),this.registerCommand=Si.createCommand(this,this.registerAccount,this.canBeRegister),Ei.runPluginHook&&Ei.runPluginHook("view-model-defined",[this.__name,this])}function xt(){this.accounts=Ti.Accounts.collection,this.mobileApp=Ii,this.folderList=Ci.MailCache.folderList,this.manageFoldersHash=Ci.Routing.buildHashFromArray([vi.Screens.Settings,vi.SettingsTab.EmailAccounts,vi.AccountSettingsTab.Folders]),this.quotaProc=i.observable(-1),this.quotaDesc=i.observable(""),i.computed(function(){if(!Ti.App||Ti.App&&!Ti.App.ShowQuotaBar)return!0;Ci.MailCache.quotaChangeTrigger();var e=Ti.Accounts.getCurrent(),t=e?e.quota():0,i=e?e.usedSpace():0,s=t>0?Math.ceil(i/t*100):-1;return s=s>100?100:s,this.quotaProc(s),this.quotaDesc(s>-1?Si.i18n("MAILBOX/QUOTA_TOOLTIP",{PROC:s,QUOTA:Si.friendlySize(1024*t)}):""),!0},this)}function Ut(e){this.isPublic=Fi,this.uploaderArea=i.observable(null),this.bDragActive=i.observable(!1),this.bDragActiveComp=i.computed(function(){return this.bDragActive()},this),this.openMessageInNewWindowBinded=e,this.isFocused=i.observable(!1),this.messagesContainer=i.observable(null),this.searchInput=i.observable(""),this.searchInputFrom=i.observable(""),this.searchInputTo=i.observable(""),this.searchInputSubject=i.observable(""),this.searchInputText=i.observable(""),this.searchSpan=i.observable(""),this.highlightTrigger=i.observable(""),this.currentMessage=Ci.MailCache.currentMessage,this.currentMessage.subscribe(function(){this.isFocused(!1),this.selector.itemSelected(this.currentMessage())},this),this.folderList=Ci.MailCache.folderList,this.folderList.subscribe(this.onFolderListSubscribe,this),this.folderFullName=i.observable(""),this.filters=i.observable(""),this.uidList=Ci.MailCache.uidList,this.uidList.subscribe(function(){this.uidList().searchCountSubscription&&(this.uidList().searchCountSubscription.dispose(),this.uidList().searchCountSubscription=void 0),this.uidList().searchCountSubscription=this.uidList().resultCount.subscribe(function(){this.uidList().resultCount()>=0&&this.oPageSwitcher.setCount(this.uidList().resultCount())},this),this.uidList().resultCount()>=0&&this.oPageSwitcher.setCount(this.uidList().resultCount())},this),this.useThreads=i.computed(function(){var e=this.folderList().currentFolder(),t=e&&e.withoutThreads(),i=""===this.uidList().search()&&""===this.uidList().filters();return Ti.User.useThreads()&&!t&&i},this),this.collection=Ci.MailCache.messages,this._search=i.observable(""),this.search=i.computed({read:function(){return Si.trim(this._search())},write:this._search,owner:this}),this.isEmptyList=i.computed(function(){return 0===this.collection().length},this),this.isNotEmptyList=i.computed(function(){return 0!==this.collection().length},this),this.isSearch=i.computed(function(){return this.search().length>0},this),this.isUnseenFilter=i.computed(function(){return this.filters()===vi.FolderFilter.Unseen},this),this.isLoading=Ci.MailCache.messagesLoading,this.isError=Ci.MailCache.messagesLoadingError,this.visibleInfoLoading=i.computed(function(){return!this.isSearch()&&this.isLoading()},this),this.visibleInfoSearchLoading=i.computed(function(){return this.isSearch()&&this.isLoading()},this),this.visibleInfoSearchList=i.computed(function(){return this.isSearch()&&!this.isUnseenFilter()&&!this.isLoading()&&!this.isEmptyList()},this),this.visibleInfoMessageListEmpty=i.computed(function(){return!this.isLoading()&&!this.isSearch()&&""===this.filters()&&this.isEmptyList()&&!this.isError()},this),this.visibleInfoStarredFolderEmpty=i.computed(function(){return!this.isLoading()&&!this.isSearch()&&this.filters()===vi.FolderFilter.Flagged&&this.isEmptyList()&&!this.isError()},this),this.visibleInfoSearchEmpty=i.computed(function(){return this.isSearch()&&!this.isUnseenFilter()&&this.isEmptyList()&&!this.isError()&&!this.isLoading()},this),this.visibleInfoMessageListError=i.computed(function(){return!this.isSearch()&&this.isError()},this),this.visibleInfoSearchError=i.computed(function(){return this.isSearch()&&this.isError()},this),this.visibleInfoUnseenFilterList=i.computed(function(){return this.isUnseenFilter()&&!this.isLoading()&&!this.isEmptyList()},this),this.visibleInfoUnseenFilterEmpty=i.computed(function(){return this.isUnseenFilter()&&this.isEmptyList()&&!this.isError()&&!this.isLoading()},this),this.searchText=i.computed(function(){return Si.i18n("MAILBOX/INFO_SEARCH_RESULT",{SEARCH:this.calculateSearchStringForDescription(),FOLDER:this.folderList().currentFolder()?this.folderList().currentFolder().displayName():""})},this),this.unseenFilterText=i.computed(function(){return""===this.search()?Si.i18n("MAILBOX/INFO_UNSEEN_FILTER_RESULT",{FOLDER:this.folderList().currentFolder()?this.folderList().currentFolder().displayName():""}):Si.i18n("MAILBOX/INFO_SEARCH_UNSEEN_FILTER_RESULT",{SEARCH:this.calculateSearchStringForDescription(),FOLDER:this.folderList().currentFolder()?this.folderList().currentFolder().displayName():""})},this),this.unseenFilterEmptyText=i.computed(function(){return Si.i18n(""===this.search()?"MAILBOX/INFO_UNSEEN_FILTER_EMPTY":"MAILBOX/INFO_SEARCH_UNSEEN_FILTER_EMPTY")},this),this.isEnableGroupOperations=i.observable(!1).extend({throttle:250}),this.selector=new u(this.collection,_.bind(this.routeForMessage,this),_.bind(this.onDeletePress,this),_.bind(this.onMessageDblClick,this),_.bind(this.onEnterPress,this)),this.checkedUids=i.computed(function(){var e=this.selector.listChecked(),t=_.map(e,function(e){return e.uid()}),i=Ci.MailCache.folderList().currentFolder(),s=i?i.getThreadCheckedUidsFromList(e):[],o=_.union(t,s);return o},this),this.checkedOrSelectedUids=i.computed(function(){var e=this.checkedUids();return 0===e.length&&Ci.MailCache.currentMessage()&&!Ci.MailCache.currentMessage().deleted()&&(e=[Ci.MailCache.currentMessage().uid()]),e},this),i.computed(function(){this.isEnableGroupOperations(0<this.selector.listCheckedOrSelected().length)},this),this.checkAll=this.selector.koCheckAll(),this.checkAllIncomplite=this.selector.koCheckAllIncomplete(),this.pageSwitcherLocked=i.observable(!1),this.oPageSwitcher=new Mt(0,Ti.User.MailsPerPage),this.oPageSwitcher.currentPage.subscribe(function(e){var t=this.folderList().currentFolderFullName(),i=!Ii&&this.currentMessage()?this.currentMessage().uid():"",s=this.search();this.pageSwitcherLocked()||this.changeRoutingForMessageList(t,e,i,s,this.filters())},this),this.currentPage=i.observable(0),this.listChangedThrottle=Ci.browser.firefox||Ci.browser.ie?i.observable(!1).extend({throttle:10}):i.observable(!1),this.firstCompleteCollection=i.observable(!0),this.collection.subscribe(function(){this.collection().length>0&&this.firstCompleteCollection(!1)},this),this.currentAccountId=Ti.Accounts.currentId,this.listChanged=i.computed(function(){return[this.firstCompleteCollection(),this.currentAccountId(),this.folderFullName(),this.filters(),this.search(),this.oPageSwitcher.currentPage()]},this),this.listChanged.subscribe(function(){this.listChangedThrottle(!this.listChangedThrottle())},this),this.bAdvancedSearch=i.observable(!1),this.searchAttachmentsCheckbox=i.observable(!1),this.searchAttachments=i.observable(""),this.searchAttachments.subscribe(function(e){this.searchAttachmentsCheckbox(!!e)},this),this.panelTopDom=i.observable(null),this.extendedDom=i.observable(null),this.searchAttachmentsFocus=i.observable(!1),this.searchFromFocus=i.observable(!1),this.searchSubjectFocus=i.observable(!1),this.searchToFocus=i.observable(!1),this.searchTextFocus=i.observable(!1),this.searchTrigger=i.observable(null),this.searchDateStartFocus=i.observable(!1),this.searchDateEndFocus=i.observable(!1),this.searchDateStartDom=i.observable(null),this.searchDateStart=i.observable(""),this.searchDateEndDom=i.observable(null),this.searchDateEnd=i.observable(""),this.dateFormatDatePicker="yy.mm.dd",this.attachmentsPlaceholder=i.computed(function(){return Si.i18n("MAILBOX/SEARCH_FIELD_HAS_ATTACHMENTS")},this),_.delay(_.bind(function(){this.createDatePickerObject(this.searchDateStartDom()),this.createDatePickerObject(this.searchDateEndDom())},this),1e3)}function Ht(e){this.openMessageInNewWindowBinded=e,this.singleMode=i.observable(Ti.SingleMode),this.isLoading=i.observable(!1),this.messages=Ci.MailCache.messages,this.messages.subscribe(this.onMessagesSubscribe,this),this.currentMessage=Ci.MailCache.currentMessage,this.currentMessage.subscribe(this.onCurrentMessageSubscribe,this),Ti.User.defaultTimeFormat.subscribe(this.onCurrentMessageSubscribe,this),this.displayedMessageUid=i.observable(""),this.isCurrentMessage=i.computed(function(){return!!this.currentMessage()},this),this.isCurrentMessageLoaded=i.computed(function(){return this.isCurrentMessage()&&!this.isLoading()},this),this.visibleNoMessageSelectedText=i.computed(function(){return this.messages().length>0&&!this.isCurrentMessage()},this),this.prevMessageUid=Ci.MailCache.prevMessageUid,this.nextMessageUid=Ci.MailCache.nextMessageUid,this.isEnablePrevMessage=i.computed(function(){return"string"==typeof this.prevMessageUid()&&""!==this.prevMessageUid()},this),this.isEnableNextMessage=i.computed(function(){return"string"==typeof this.nextMessageUid()&&""!==this.nextMessageUid()},this),this.isEnableDelete=this.isCurrentMessage,this.isEnableReply=this.isCurrentMessageLoaded,this.isEnableReplyAll=this.isCurrentMessageLoaded,this.isEnableResend=this.isCurrentMessageLoaded,this.isEnableForward=this.isCurrentMessageLoaded,this.isEnablePrint=this.isCurrentMessageLoaded,this.isEnableSave=this.isCurrentMessage,this.allowSaveAsPdf=i.observable(!!Ti.AllowSaveAsPdf),this.isEnableSaveAsPdf=i.computed(function(){return this.isCurrentMessageLoaded()&&this.allowSaveAsPdf()},this),this.deleteCommand=Si.createCommand(this,this.executeDeleteMessage,this.isEnableDelete),this.prevMessageCommand=Si.createCommand(this,this.executePrevMessage,this.isEnablePrevMessage),this.nextMessageCommand=Si.createCommand(this,this.executeNextMessage,this.isEnableNextMessage),this.replyCommand=Si.createCommand(this,this.executeReply,this.isEnableReply),this.replyAllCommand=Si.createCommand(this,this.executeReplyAll,this.isEnableReplyAll),this.resendCommand=Si.createCommand(this,this.executeResend,this.isEnableResend),this.forwardCommand=Si.createCommand(this,this.executeForward,this.isEnableForward),this.printCommand=Si.createCommand(this,this.executePrint,this.isEnablePrint),this.saveCommand=Si.createCommand(this,this.executeSave,this.isEnableSave),this.saveAsPdfCommand=Si.createCommand(this,this.executeSaveAsPdf,this.isEnableSaveAsPdf),this.moreCommand=Si.createCommand(this,null,this.isCurrentMessageLoaded),this.ical=i.observable(null),this.icalSubscription=this.ical.subscribe(function(){null!==this.ical()&&(Ci.CalendarCache.firstRequestCalendarList(),this.icalSubscription.dispose())},this),this.vcard=i.observable(null),this.processed=i.observable(!1),this.visiblePicturesControl=i.observable(!1),this.visibleShowPicturesLink=i.observable(!1),this.visibleAppointmentInfo=i.computed(function(){return null!==this.ical()},this),this.visibleVcardInfo=i.computed(function(){return null!==this.vcard()},this),this.sensitivityText=i.computed(function(){var e="";if(this.currentMessage())switch(this.currentMessage().sensitivity()){case vi.Sensivity.Confidential:e=Si.i18n("MESSAGE/SENSIVITY_CONFIDENTIAL");break;case vi.Sensivity.Personal:e=Si.i18n("MESSAGE/SENSIVITY_PERSONAL");break;case vi.Sensivity.Private:e=Si.i18n("MESSAGE/SENSIVITY_PRIVATE")}return e},this),this.visibleConfirmationControl=i.computed(function(){return this.currentMessage()&&""!==this.currentMessage().readingConfirmation()},this),this.isCurrentNotDraftOrSent=i.computed(function(){var e=Ci.MailCache.folderList().currentFolder();return e&&e.fullName().length>0&&e.type()!==vi.FolderTypes.Drafts&&e.type()!==vi.FolderTypes.Sent},this),this.isCurrentSentFolder=i.computed(function(){var e=Ci.MailCache.folderList().currentFolder();return e&&e.fullName().length>0&&e.type()===vi.FolderTypes.Sent},this),this.isCurrentNotDraftFolder=i.computed(function(){var e=Ci.MailCache.folderList().currentFolder();return e&&e.fullName().length>0&&e.type()!==vi.FolderTypes.Drafts},this),this.isVisibleReplyTool=this.isCurrentNotDraftOrSent,this.isVisibleResendTool=this.isCurrentSentFolder,this.isVisibleForwardTool=this.isCurrentNotDraftFolder,this.uid=i.observable(""),this.folder=i.observable(""),this.subject=i.observable(""),this.emptySubject=i.computed(function(){return""===Si.trim(this.subject())},this),this.subjectForDisplay=i.computed(function(){return this.emptySubject()?Si.i18n("MAILBOX/EMPTY_SUBJECT"):this.subject()},this),this.importance=i.observable(vi.Importance.Normal),this.oFromAddr=i.observable(null),this.from=i.observable(""),this.fromEmail=i.observable(""),this.fullFrom=i.observable(""),this.to=i.observable(""),this.aToAddr=i.observableArray([]),this.cc=i.observable(""),this.aCcAddr=i.observableArray([]),this.bcc=i.observable(""),this.aBccAddr=i.observableArray([]),this.allRecipients=i.observable(""),this.aAllRecipients=i.observableArray([]),this.recipientsContacts=i.observableArray([]),this.currentAccountEmail=i.observable(),this.meSender=Si.i18n("MESSAGE/ME_SENDER"),this.meRecipient=Si.i18n("MESSAGE/ME_RECIPIENT"),this.fullDate=i.observable(""),this.midDate=i.observable(""),this.textBody=i.observable(""),this.textBodyForNewWindow=i.observable(""),this.domTextBody=i.observable(null),this.rtlMessage=i.observable(!1),this.contentHasFocus=i.observable(!1),this.decryptPassword=i.observable(""),this.visibleDecryptControl=i.observable(!1),this.visibleVerifyControl=i.observable(!1),this.fakeHeader=i.computed(function(){return!(this.visiblePicturesControl()||this.visibleConfirmationControl()||""!==this.sensitivityText()||this.visibleDecryptControl()||this.visibleVerifyControl())},this),this.mobileApp=Ii,this.attachments=i.observableArray([]),this.usesAttachmentString=!0,this.attachmentsInString=i.computed(function(){return _.map(this.attachments(),function(e){return e.fileName()},this).join(", ")},this),this.notInlineAttachments=i.computed(function(){return _.filter(this.attachments(),function(e){return!e.linked()})},this),this.visibleDownloadAllAttachments=i.computed(function(){return Ti.ZipAttachments&&this.notInlineAttachments().length>1},this),this.visibleSaveAttachmentsToFiles=Ti.User.IsFilesSupported,this.visibleDownloadAllAttachmentsSeparately=i.computed(function(){return this.notInlineAttachments().length>1},this),this.visibleExtendedDownload=i.computed(function(){return!this.mobileApp&&(this.visibleDownloadAllAttachments()||this.visibleDownloadAllAttachmentsSeparately()||this.visibleSaveAttachmentsToFiles)},this),this.detailsVisible=i.observable(!1),this.hasNotInlineAttachments=i.computed(function(){return this.notInlineAttachments().length>0},this),this.scrollToAttachment=i.observable(".attachments"),this.hasBodyText=i.computed(function(){return this.textBody().length>0},this),this.visibleAddMenu=i.observable(!1),this.replyText=i.observable(""),this.replyTextFocus=i.observable(!1),this.replyPaneVisible=i.computed(function(){return this.currentMessage()&&this.currentMessage().completelyFilled()},this),this.replySendingStarted=i.observable(!1),this.replySavingStarted=i.observable(!1),this.replyAutoSavingStarted=i.observable(!1),this.requiresPostponedSending=i.observable(!1),this.replyAutoSavingStarted.subscribe(function(){!this.replyAutoSavingStarted()&&this.requiresPostponedSending()&&(Ci.MessageSender.sendPostponedMail(this.replyDraftUid()),this.requiresPostponedSending(!1))},this),i.computed(function(){(!this.replyTextFocus()||this.replyAutoSavingStarted()||this.replySavingStarted()||this.replySendingStarted())&&this.stopAutosaveTimer(),!this.replyTextFocus()||this.replyAutoSavingStarted()||this.replySavingStarted()||this.replySendingStarted()||this.startAutosaveTimer()},this),this.saveButtonText=i.computed(function(){return Si.i18n(this.replyAutoSavingStarted()?"COMPOSE/TOOL_SAVING":"COMPOSE/TOOL_SAVE")},this),this.replyDraftUid=i.observable(""),this.replyLoadingText=i.computed(function(){return this.replySendingStarted()?Si.i18n("COMPOSE/INFO_SENDING"):this.replySavingStarted()?Si.i18n("COMPOSE/INFO_SAVING"):""},this),this.isEnableSaveQuickReply=i.computed(function(){return this.isCurrentMessageLoaded()&&""!==this.replyText()&&!this.replySavingStarted()&&!this.replyAutoSavingStarted()},this),this.isEnableSendQuickReply=i.computed(function(){return this.isCurrentMessageLoaded()&&""!==this.replyText()&&!this.replySendingStarted() },this),this.saveQuickReplyCommand=Si.createCommand(this,this.executeSaveQuickReply,this.isEnableSaveQuickReply),this.sendQuickReplyCommand=Si.createCommand(this,this.executeSendQuickReplyCommand,this.isEnableSendQuickReply),this.domMessageHeader=i.observable(null),this.domQuickReply=i.observable(null),this.domMessageForPrint=i.observable(null),this.replyTextFocusThrottled=i.observable(!1).extend({throttle:50}),this.replyTextFocus.subscribe(function(){this.replyTextFocusThrottled(this.replyTextFocus())},this),this.isQuickReplyActive=i.computed(function(){return this.replyText().length>0||this.replyTextFocusThrottled()},this),this.jqPanelHelper=null,this.visibleAttachments=i.observable(!1),this.showMessage=function(){this.visibleAttachments(!1)},this.showAttachments=function(){this.visibleAttachments(!0)},this.defaultFontName=Ti.User.DefaultFontName,Ci.nowMoment&&Ci.nowMoment.subscribe(function(){this.updateMomentDate()},this)}function Gt(){this.folderList=Ci.MailCache.folderList,this.domFolderList=i.observable(null),this.openMessageInNewWindowBinded=_.bind(this.openMessageInNewWindow,this),this.oFolderList=new xt,this.oMessageList=new Ut(this.openMessageInNewWindowBinded),this.oMessagePane=new Ht(this.openMessageInNewWindowBinded),this.isEnableGroupOperations=this.oMessageList.isEnableGroupOperations,this.composeLink=i.observable(Ci.Routing.buildHashFromArray(Ci.Links.compose())),this.checkMailCommand=Si.createCommand(this,this.executeCheckMail),this.checkMailIndicator=i.computed(function(){return Ci.MailCache.checkMailStarted()||Ci.MailCache.messagesLoading()},this),this.markAsReadCommand=Si.createCommand(this.oMessageList,this.oMessageList.executeMarkAsRead,this.isEnableGroupOperations),this.markAsUnreadCommand=Si.createCommand(this.oMessageList,this.oMessageList.executeMarkAsUnread,this.isEnableGroupOperations),this.markAllReadCommand=Si.createCommand(this.oMessageList,this.oMessageList.executeMarkAllRead),this.moveToFolderCommand=Si.createCommand(this,Si.emptyFunction,this.isEnableGroupOperations),this.deleteCommand=Si.createCommand(this.oMessageList,this.oMessageList.executeDelete,this.isEnableGroupOperations),this.selectedCount=i.computed(function(){return this.oMessageList.checkedUids().length},this),this.emptyTrashCommand=Si.createCommand(Ci.MailCache,Ci.MailCache.executeEmptyTrash,this.oMessageList.isNotEmptyList),this.emptySpamCommand=Si.createCommand(Ci.MailCache,Ci.MailCache.executeEmptySpam,this.oMessageList.isNotEmptyList),this.spamCommand=Si.createCommand(this.oMessageList,this.oMessageList.executeSpam,this.isEnableGroupOperations),this.notSpamCommand=Si.createCommand(this.oMessageList,this.oMessageList.executeNotSpam,this.isEnableGroupOperations),this.bVisibleComposeMessage=Ti.User.AllowCompose,this.isVisibleReplyTool=i.computed(function(){return this.folderList().currentFolder()&&this.folderList().currentFolderFullName().length>0&&this.folderList().currentFolderType()!==vi.FolderTypes.Drafts&&this.folderList().currentFolderType()!==vi.FolderTypes.Sent},this),this.isVisibleForwardTool=i.computed(function(){return this.folderList().currentFolder()&&this.folderList().currentFolderFullName().length>0&&this.folderList().currentFolderType()!==vi.FolderTypes.Drafts},this),this.isSpamFolder=i.computed(function(){return this.folderList().currentFolderType()===vi.FolderTypes.Spam},this),this.allowedSpamAction=i.computed(function(){var e=Ti.Accounts.getCurrent();return e?e.extensionExists("AllowSpamFolderExtension")&&!this.isSpamFolder():!1},this),this.allowedNotSpamAction=i.computed(function(){var e=Ti.Accounts.getCurrent();return e?e.extensionExists("AllowSpamFolderExtension")&&this.isSpamFolder():!1},this),this.isTrashFolder=i.computed(function(){return this.folderList().currentFolderType()===vi.FolderTypes.Trash},this),this.jqPanelHelper=null,this.mobileApp=Ii,this.selectedPanel=i.observable(vi.MobilePanel.Items),Ci.MailCache.currentMessage.subscribe(function(){this.gotoMessagePane()},this)}function Bt(){var s=this;this.toAddrDom=i.observable(),this.ccAddrDom=i.observable(),this.bccAddrDom=i.observable(),this.folderList=Ci.MailCache.folderList,this.folderList.subscribe(function(){this.getMessageOnRoute()},this),this.singleMode=i.observable(Ti.SingleMode),this.isDemo=i.observable(Ti.User.IsDemo),this.sending=i.observable(!1),this.sending.subscribe(this.sendingAndSavingSubscription,this),this.saving=i.observable(!1),this.saving.subscribe(this.sendingAndSavingSubscription,this),this.oHtmlEditor=new Rt(!1,this),this.textFocused=this.oHtmlEditor.textFocused,this.visibleBcc=i.observable(!1),this.visibleBcc.subscribe(function(){wi.toggleClass("screen-compose-bcc",this.visibleCc()),_.defer(_.bind(function(){e(this.bccAddrDom()).inputosaurus("resizeInput")},this))},this),this.visibleCc=i.observable(!1),this.visibleCc.subscribe(function(){wi.toggleClass("screen-compose-cc",this.visibleCc()),_.defer(_.bind(function(){e(this.ccAddrDom()).inputosaurus("resizeInput")},this))},this),this.visibleCounter=i.observable(!1),this.readingConfirmation=i.observable(!1),this.saveMailInSentItems=i.observable(!0),this.useSaveMailInSentItems=i.observable(!1),this.composeUploaderButton=i.observable(null),this.composeUploaderDropPlace=i.observable(null),this.composeUploaderBodyDragOver=i.observable(!1),this.composeUploaderDragOver=i.observable(!1),this.allowDragNDrop=i.observable(!1),this.uploaderBodyDragOver=i.computed(function(){return this.allowDragNDrop()&&this.composeUploaderBodyDragOver()},this),this.uploaderDragOver=i.computed(function(){return this.allowDragNDrop()&&this.composeUploaderDragOver()},this),this.selectedImportance=i.observable(vi.Importance.Normal),this.selectedSensitivity=i.observable(vi.Sensivity.Nothing),this.senderList=i.observableArray([]),this.visibleFrom=i.computed(function(){return this.senderList().length>1},this),this.selectedSender=i.observable(""),this.selectedFetcherOrIdentity=i.observable(null),this.selectedFetcherOrIdentity.subscribe(function(){this.selectedSender(this.selectedFetcherOrIdentity()?this.selectedFetcherOrIdentity().FETCHER===!0?"fetcher"+this.selectedFetcherOrIdentity().id():Si.pString(this.selectedFetcherOrIdentity().id()):"")},this),this.selectedSender.subscribe(function(){var e=Ti.Accounts.getAccount(this.senderAccountId()),t=this.selectedSender(),i=null;this.oHtmlEditor.oCrea&&this.oHtmlEditor.oCrea.editableSave(),0===t.indexOf("fetcher")?e.fetchers()&&(t=t.replace("fetcher",""),i=_.find(e.fetchers().collection(),function(e){return e.id()===Si.pInt(t)})):i=_.find(e.identities(),function(e){return e.id()===Si.pInt(t)}),this.changeSelectedFetcherOrIdentity(i)},this),this.selectedIdentityId=i.observable(0),this.senderAccountId=i.observable(Ti.Accounts.currentId()),this.signature=i.observable(""),this.prevSignature=i.observable(null),i.computed(function(){var e=Ci.MessageSender.getClearSignature(this.senderAccountId(),this.selectedFetcherOrIdentity());null===this.prevSignature()?(this.prevSignature(e),this.signature(e)):(this.prevSignature(this.signature()),this.signature(e),this.oHtmlEditor.changeSignatureContent(this.signature(),this.prevSignature()))},this),this.lockToAddr=i.observable(!1),this.toAddr=i.observable("").extend({reversible:!0}),this.toAddr.subscribe(function(){this.lockToAddr()||(e(this.toAddrDom()).val(this.toAddr()),e(this.toAddrDom()).inputosaurus("refresh"))},this),this.lockCcAddr=i.observable(!1),this.ccAddr=i.observable("").extend({reversible:!0}),this.ccAddr.subscribe(function(){this.lockCcAddr()||(e(this.ccAddrDom()).val(this.ccAddr()),e(this.ccAddrDom()).inputosaurus("refresh"))},this),this.lockBccAddr=i.observable(!1),this.bccAddr=i.observable("").extend({reversible:!0}),this.bccAddr.subscribe(function(){this.lockBccAddr()||(e(this.bccAddrDom()).val(this.bccAddr()),e(this.bccAddrDom()).inputosaurus("refresh"))},this),this.recipientEmails=i.computed(function(){var e=[this.toAddr(),this.ccAddr(),this.bccAddr()].join(",").split(","),t=[];return _.each(e,function(e){var i=Si.trim(e),s=null;""!==i&&(s=Si.getEmailParts(i),s.email&&t.push(s.email))}),t},this),this.subject=i.observable("").extend({reversible:!0}),this.counter=i.observable(0),this.commitedTextBody=i.observable(""),this.plainText=i.observable(!1),this.textBody=i.observable(""),this.textBody.subscribe(function(){this.oHtmlEditor.setText(this.textBody(),this.plainText()),this.commitedTextBody(this.oHtmlEditor.getText())},this),this.toAddrFocused=i.observable(!1),this.toAddrFocused.subscribe(function(){this.toAddrFocused()&&e(this.toAddrDom()).inputosaurus("focus")},this),this.ccAddrFocused=i.observable(!1),this.ccAddrFocused.subscribe(function(){this.ccAddrFocused()&&e(this.ccAddrDom()).inputosaurus("focus")},this),this.bccAddrFocused=i.observable(!1),this.bccAddrFocused.subscribe(function(){this.bccAddrFocused()&&e(this.bccAddrDom()).inputosaurus("focus")},this),this.subjectFocused=i.observable(!1),this.draftUid=i.observable(""),this.draftInfo=i.observableArray([]),this.routeType=i.observable(""),this.routeParams=i.observableArray([]),this.inReplyTo=i.observable(""),this.references=i.observable(""),this.bUploadStatus=!1,this.iUploadAttachmentsTimer=0,this.messageUploadAttachmentsStarted=i.observable(!1),this.messageUploadAttachmentsStarted.subscribe(function(e){t.clearTimeout(s.iUploadAttachmentsTimer),e?s.iUploadAttachmentsTimer=t.setTimeout(function(){s.bUploadStatus=!0,Ci.Api.showLoading(Si.i18n("COMPOSE/INFO_ATTACHMENTS_LOADING"))},4e3):s.bUploadStatus?s.iUploadAttachmentsTimer=t.setTimeout(function(){s.bUploadStatus=!1,Ci.Api.hideLoading()},1e3):Ci.Api.hideLoading()},this),this.attachments=i.observableArray([]),this.attachmentsChanged=i.observable(!1),this.attachments.subscribe(function(){this.attachmentsChanged(!0)},this),this.notUploadedAttachments=i.computed(function(){return _.filter(this.attachments(),function(e){return!e.uploaded()})},this),this.allAttachmentsUploaded=i.computed(function(){return 0===this.notUploadedAttachments().length&&!this.messageUploadAttachmentsStarted()},this),this.notInlineAttachments=i.computed(function(){return _.filter(this.attachments(),function(e){return!e.linked()})},this),this.notInlineAttachments.subscribe(function(){wi.toggleClass("screen-compose-attachments",this.notInlineAttachments().length>0)},this),this.allowStartSending=i.computed(function(){return!this.saving()},this),this.allowStartSending.subscribe(function(){this.allowStartSending()&&this.requiresPostponedSending()&&(Ci.MessageSender.sendPostponedMail(this.draftUid()),this.requiresPostponedSending(!1))},this),this.requiresPostponedSending=i.observable(!1),this.oJua=null,this.isDraftsCleared=i.observable(!1),this.autoSaveTimer=-1,this.shown=i.observable(!1),this.shown.subscribe(function(){this.shown()||this.stopAutosaveTimer()},this),this.backToListOnSendOrSave=i.observable(!1),this.enableOpenPgp=Ti.User.enableOpenPgp,this.pgpSecured=i.observable(!1),this.pgpSecured.subscribe(function(){this.oHtmlEditor.disabled(this.pgpSecured())},this),this.pgpEncrypted=i.observable(!1),this.fromDrafts=i.observable(!1),this.visibleDoPgpButton=i.computed(function(){return this.enableOpenPgp()&&(!this.pgpSecured()||this.pgpEncrypted()&&this.fromDrafts())},this),this.visibleUndoPgpButton=i.computed(function(){return this.enableOpenPgp()&&this.pgpSecured()&&(!this.pgpEncrypted()||!this.fromDrafts())},this),this.isEnableOpenPgpCommand=i.computed(function(){return this.enableOpenPgp()&&!this.pgpSecured()},this),this.backToListCommand=Si.createCommand(this,this.executeBackToList),this.sendCommand=Si.createCommand(this,this.executeSend,this.isEnableSending),this.saveCommand=Si.createCommand(this,this.executeSaveCommand,this.isEnableSaving),this.openPgpCommand=Si.createCommand(this,this.confirmOpenPgp,this.isEnableOpenPgpCommand),this.messageFields=i.observable(null),this.bottomPanel=i.observable(null),this.editableArea=i.observable(null),this.mobileApp=Ii,this.allowFiles=i.observable(!1),this.dropboxConnected=i.observable(!1),this.allowDropbox=i.computed(function(){return Ti.SocialDropbox&&this.dropboxConnected()},this),this.dropboxKey=Ti.SocialDropboxKey,this.googleConnected=i.observable(!1),this.allowGoogle=i.computed(function(){return Ti.SocialGoogle&&this.googleConnected()},this),t.opener&&setTimeout(function(){t.onbeforeunload=function(){return!s.isChanged()||s.isEmpty()||s.sending()||s.saving()?void 0:(s.beforeHide(t.close),"")}},1e3)}function Vt(e){this.oJua=null,this.oParent=e,this.visibility=i.observable(!1),this.importing=i.observable(!1)}function jt(){this.importingHelpLink=Ci.getHelpLink("ImportingContacts"),this.allowWebMail=Ti.App.AllowWebMail,this.loadingList=i.observable(!1),this.loadingViewPane=i.observable(!1),this.showPersonalContacts=i.observable(!1),this.showGlobalContacts=i.observable(!1),this.showSharedToAllContacts=i.observable(!1),this.showAllContacts=i.computed(function(){return 1<[this.showPersonalContacts()?"1":"",this.showGlobalContacts()?"1":"",this.showSharedToAllContacts()?"1":""].join("").length},this),this.recivedAnimShare=i.observable(!1).extend({autoResetToFalse:500}),this.recivedAnimUnshare=i.observable(!1).extend({autoResetToFalse:500}),this.selectedGroupType=i.observable(vi.ContactsGroupListType.Personal),this.selectedGroupInList=i.observable(null),this.selectedGroupInList.subscribe(function(){var e=this.selectedGroupInList();e&&e.selected(!1)},this,"beforeChange"),this.selectedGroupInList.subscribe(function(e){e&&this.showPersonalContacts()&&(e.selected(!0),this.selectedGroupType(vi.ContactsGroupListType.SubGroup),this.requestContactList())},this),this.selectedGroup=i.observable(null),this.selectedContact=i.observable(null),this.selectedGroupContactsList=i.observable(null),this.currentGroupId=i.observable(""),this.oContactModel=new ct,this.oGroupModel=new ut,this.oContactImportViewModel=new Vt(this),this.selectedOldItem=i.observable(null),this.selectedItem=i.computed({read:function(){return this.selectedContact()||this.selectedGroup()||null},write:function(e){e instanceof ct?(this.oContactImportViewModel.visibility(!1),this.selectedGroup(null),this.selectedContact(e)):e instanceof ut?(this.oContactImportViewModel.visibility(!1),this.selectedContact(null),this.selectedGroup(e),this.currentGroupId(e.idGroup())):(this.selectedGroup(null),this.selectedContact(null)),this.loadingViewPane(!1)},owner:this}),this.sortOrder=i.observable(!0),this.sortType=i.observable(vi.ContactSortType.Name),this.collection=i.observableArray([]),this.contactUidForRequest=i.observable(""),this.collection.subscribe(function(){this.collection().length>0&&""!==this.contactUidForRequest()&&(this.requestContact(this.contactUidForRequest()),this.contactUidForRequest(""))},this),this.isSearchFocused=i.observable(!1),this.searchInput=i.observable(""),this.search=i.observable(""),this.groupFullCollection=i.observableArray([]),this.selectedContact.subscribe(function(e){if(e){var t=e.groups();_.each(this.groupFullCollection(),function(e){e.checked(e&&0<=Si.inArray(e.Id(),t))})}},this),this.selectedGroupType.subscribe(function(e){vi.ContactsGroupListType.All!==e||this.showAllContacts()?vi.ContactsGroupListType.Personal===e&&!this.showPersonalContacts()&&this.showGlobalContacts()?this.selectedGroupType(vi.ContactsGroupListType.Global):vi.ContactsGroupListType.Global===e&&!this.showGlobalContacts()&&this.showPersonalContacts()?this.selectedGroupType(vi.ContactsGroupListType.Personal):(vi.ContactsGroupListType.Personal===e||vi.ContactsGroupListType.Global===e||vi.ContactsGroupListType.SharedToAll===e||vi.ContactsGroupListType.All===e)&&(this.selectedGroupInList(null),this.selectedItem(null),this.selector.listCheckedOrSelected(!1),this.requestContactList()):this.selectedGroupType(vi.ContactsGroupListType.Personal)},this),this.pageSwitcherLocked=i.observable(!1),this.oPageSwitcher=new Mt(0,Ti.User.ContactsPerPage),this.oPageSwitcher.currentPage.subscribe(function(){var e=this.selectedGroupType(),t=e===vi.ContactsGroupListType.SubGroup?this.currentGroupId():"";this.pageSwitcherLocked()||Ci.Routing.setHash(Ci.Links.contacts(e,t,this.search(),this.oPageSwitcher.currentPage()))},this),this.currentPage=i.observable(1),this.search.subscribe(function(e){this.searchInput(e)},this),this.searchSubmitCommand=Si.createCommand(this,function(){var e=this.selectedGroupType(),t=e===vi.ContactsGroupListType.SubGroup?this.currentGroupId():"";Ci.Routing.setHash(Ci.Links.contacts(e,t,this.searchInput()))}),this.selector=new u(this.collection,_.bind(function(e){if(e){var t=this.selectedGroupType(),i=t===vi.ContactsGroupListType.SubGroup?this.currentGroupId():"";Ci.Routing.setHash(Ci.Links.contacts(t,i,this.search(),this.oPageSwitcher.currentPage(),e.sId))}},this),_.bind(this.executeDelete,this),_.bind(this.onContactDblClick,this)),this.checkAll=this.selector.koCheckAll(),this.checkAllIncomplite=this.selector.koCheckAllIncomplete(),this.allowContactsSharing=!!Ti.App.AllowContactsSharing,this.isCheckedOrSelected=i.computed(function(){return 0<this.selector.listCheckedOrSelected().length},this),this.isEnableAddContacts=this.isCheckedOrSelected,this.isEnableRemoveContactsFromGroup=this.isCheckedOrSelected,this.isEnableDeleting=this.isCheckedOrSelected,this.isEnableSharing=this.isCheckedOrSelected,this.visibleShareCommand=i.computed(function(){return this.showPersonalContacts()&&this.showSharedToAllContacts()&&this.selectedGroupType()===vi.ContactsGroupListType.Personal},this),this.visibleUnshareCommand=i.computed(function(){return this.showPersonalContacts()&&this.showSharedToAllContacts()&&this.selectedGroupType()===vi.ContactsGroupListType.SharedToAll},this),this.isSelectedGroupTypeNotGlobal=i.computed(function(){return this.selectedGroupType()!==vi.ContactsGroupListType.Global},this),this.newContactCommand=Si.createCommand(this,this.executeNewContact,this.isSelectedGroupTypeNotGlobal),this.newGroupCommand=Si.createCommand(this,this.executeNewGroup),this.addContactsCommand=Si.createCommand(this,Si.emptyFunction,this.isEnableAddContacts),this.deleteCommand=Si.createCommand(this,this.executeDelete,this.isEnableDeleting),this.shareCommand=Si.createCommand(this,this.executeShare,this.isEnableSharing),this.removeFromGroupCommand=Si.createCommand(this,this.executeRemoveFromGroup,this.isEnableRemoveContactsFromGroup),this.importCommand=Si.createCommand(this,this.executeImport),this.exportCSVCommand=Si.createCommand(this,this.executeCSVExport),this.exportVCFCommand=Si.createCommand(this,this.executeVCFExport),this.saveCommand=Si.createCommand(this,this.executeSave),this.updateSharedToAllCommand=Si.createCommand(this,this.executeUpdateSharedToAll,function(){return 1===this.selector.listCheckedOrSelected().length}),this.newMessageCommand=Si.createCommand(this,function(){var e=this.selector.listCheckedOrSelected(),t=[];_.isArray(e)&&0<e.length&&(t=_.map(e,function(e){return e.EmailAndName()}),t=_.compact(t),Ci.Api.openComposeMessage(t.join(", ")))},function(){return 0<this.selector.listCheckedOrSelected().length}),this.selector.listCheckedOrSelected.subscribe(function(e){this.oGroupModel.newContactsInGroupCount(e.length)},this),this.isLoading=this.loadingList,this.isSearch=i.computed(function(){return""!==this.search()},this),this.isEmptyList=i.computed(function(){return 0===this.collection().length},this),this.inGroup=i.computed(function(){return vi.ContactsGroupListType.SubGroup===this.selectedGroupType()},this),this.searchText=i.computed(function(){return Si.i18n("CONTACTS/INFO_SEARCH_RESULT",{SEARCH:this.search()})},this),this.mobileApp=Ii,this.selectedPanel=i.observable(vi.MobilePanel.Items),this.selectedItem.subscribe(function(){var e=this.selectedItem()&&this.selectedItem()instanceof ut&&!this.selectedItem().isNew();this.selectedItem()&&!e?this.gotoViewPane():this.gotoContactList()},this)}function Kt(){this.aTabs=[],Ti.App.AllowUsersChangeInterfaceSettings&&this.aTabs.push(new Wt),Ti.App.AllowWebMail&&this.aTabs.push(new qt),Ti.App.AllowUsersChangeInterfaceSettings&&Ti.User.AllowCalendar&&this.aTabs.push(new Yt),(Ti.User.IsFilesSupported||Ti.SocialGoogle&&Ti.SocialGoogleApiKey&&Ti.SocialGoogleId||Ti.SocialDropbox&&Ti.SocialDropboxKey)&&this.aTabs.push(new ai),Ti.User.MobileSyncEnable&&this.aTabs.push(new zt),Ti.User.OutlookSyncEnable&&this.aTabs.push(new Qt),Ti.User.IsHelpdeskSupported&&this.aTabs.push(new ri),Ti.App.AllowOpenPgp&&this.aTabs.push(new $t),Ei&&Ei.getPluginsSettingsTabs&&_.each(Ei.getPluginsSettingsTabs(),_.bind(function(e){this.aTabs.push(new e)},this)),this.tab=i.observable(vi.SettingsTab.Common),Ti.Accounts.currentId.subscribe(function(){Ci.Routing.lastSettingsHash(vi.Screens.Settings)},this),this.allowFolderListOrder=i.computed(function(){var e=Ti.Accounts.getEdited();return e?!e.extensionExists("DisableFoldersManualSort"):!1},this),this.folderListOrderUpdateDebounce=_.debounce(_.bind(this.folderListOrderUpdate,this),3e3),this.afterSortableFolderMoveBinded=_.bind(this.afterSortableFolderMove,this)}function Wt(){this.allowWebMail=Ti.App.AllowWebMail,this.isRtl=Si.isRTL(),this.aSkins=Ti.App.Themes,this.selectedSkin=i.observable(Ti.User.DefaultTheme),this.aLanguages=Ti.App.Languages,this.selectedLanguage=i.observable(Ti.User.DefaultLanguage),this.loading=i.observable(!1),this.rangeOfNumbers=[10,20,30,50,75,100,150,200],this.messagesPerPageValues=i.observableArray(this.rangeOfNumbers),this.messagesPerPage=i.observable(this.rangeOfNumbers[0]),this.setMessagesPerPage(Ti.User.MailsPerPage),this.contactsPerPageValues=i.observableArray(this.rangeOfNumbers),this.contactsPerPage=i.observable(this.rangeOfNumbers[0]),this.setContactsPerPage(Ti.User.ContactsPerPage),this.autocheckmailInterval=i.observable(Ti.User.AutoCheckMailInterval),this.timeFormat=i.observable(Ti.User.defaultTimeFormat()),this.aDateFormats=Si.getDateFormatsForSelector(),this.dateFormat=i.observable(Ti.User.DefaultDateFormat),this.useThreads=i.observable(Ti.User.useThreads()),this.saveRepliedToCurrFolder=i.observable(Ti.User.SaveRepliedToCurrFolder),this.allowChangeInputDirection=i.observable(Ti.User.AllowChangeInputDirection),this.desktopNotifications=i.observable(Ti.User.DesktopNotifications),this.desktopNotifications.subscribe(function(e){var i=this;e&&"default"===t.Notification.permission&&t.Notification.requestPermission(function(e){"denied"===e&&(i.desktopNotifications(!1),i.desktopNotificationsIsEnable(!1))})},this),this.desktopNotificationsIsEnable=i.observable(t.Notification&&"denied"!==t.Notification.permission),this.isMailto=i.observable(Ci.browser.firefox||Ci.browser.chrome),this.bAllowContacts=Ti.User.ShowContacts,this.bAllowCalendar=Ti.User.AllowCalendar,this.bAllowThreads=Ti.User.ThreadsEnabled,this.firstState=this.getState()}function qt(){this.accounts=Ti.Accounts.collection,this.onlyOneAccount=i.computed(function(){var e=1===this.accounts().length&&!Ti.App.AllowUsersAddNewAccounts;return e&&(this.TabTitle=Si.i18n("SETTINGS/TAB_EMAIL_ACCOUNT")),e},this),this.title=i.computed(function(){return Si.i18n(this.onlyOneAccount()?"SETTINGS/TITLE_EMAIL_ACCOUNT":"SETTINGS/TITLE_EMAIL_ACCOUNTS")},this),this.currentAccountId=Ti.Accounts.currentId,this.editedAccountId=Ti.Accounts.editedId,this.defaultAccountId=Ti.Accounts.defaultId,this.defaultAccount=Ti.Accounts.getDefault(),this.isAllowFetcher=!!Ti.User.AllowFetcher,this.isAllowIdentities=!!Ti.AllowIdentities,this.oAccountProperties=new Jt(this),this.oAccountSignature=new Zt(this),this.oAccountFilters=new ii(this),this.oAccountAutoresponder=new ti(this),this.oAccountForward=new ei(this),this.oAccountFolders=new Xt(this),this.oFetcherIncoming=new si(this),this.oFetcherOutgoing=new oi(this),this.oFetcherSignature=new ni(this),this.oIdentityProperties=new li(this,!1),this.fetcher=i.observable(null),this.fetchers=i.observable(null),this.firstFetcher=i.observable(null),this.editedFetcherId=i.observable(null),this.editedIdentityId=i.observable(null),this.defaultAccount.fetchers.subscribe(function(e){if(e){var t=this.defaultAccount.fetchers(),i=t.collection()[0],s=i.id(),o=this.isFetcherTab(this.tab());this.fetchers(t),this.firstFetcher(i),this.editedFetcherId()&&o?this.onChangeFetcher(this.editedFetcherId()):o&&(this.editedFetcherId(s),this.editedIdentityId(null),this.onChangeFetcher(s))}else this.changeAccount(this.defaultAccountId())},this),this.tab=i.observable(vi.AccountSettingsTab.Properties),this.allowUsersAddNewAccounts=Ti.App.AllowUsersAddNewAccounts,this.allowUsersChangeInterfaceSettings=Ti.App.AllowUsersChangeInterfaceSettings,this.allowAutoresponderExtension=i.observable(!1),this.allowForwardExtension=i.observable(!1),this.allowSieveFiltersExtension=i.observable(!1),this.changeAccount(this.editedAccountId())}function Yt(){this.showWeekends=i.observable(Ti.User.CalendarShowWeekEnds),this.loading=i.observable(!1),this.availableTimes=i.observableArray(this.getDisplayedTimes(Ti.User.defaultTimeFormat()!==vi.TimeFormat.F24?"hh:mm A":"HH:mm")),Ti.User.defaultTimeFormat.subscribe(function(){this.availableTimes(this.getDisplayedTimes(Ti.User.defaultTimeFormat()!==vi.TimeFormat.F24?"hh:mm A":"HH:mm"))},this),this.selectedWorkdayStarts=i.observable(Ti.User.CalendarWorkDayStarts),this.selectedWorkdayEnds=i.observable(Ti.User.CalendarWorkDayEnds),this.showWorkday=i.observable(Ti.User.CalendarShowWorkDay),this.weekStartsOn=i.observable(Ti.User.CalendarWeekStartsOn),this.defaultTab=i.observable(Ti.User.CalendarDefaultTab),this.firstState=this.getState()}function zt(){this.mobileSync=Ti.User.mobileSync,this.mobileSync.subscribe(this.onMobileSyncSubscribe,this),this.enableDav=i.observable(!1),this.davLogin=i.observable(""),this.davServer=i.observable(""),this.davCalendars=i.observable([]),this.visibleCalendars=i.computed(function(){return this.davCalendars().length>0},this),this.davPersonalContactsUrl=i.observable(""),this.davCollectedAddressesUrl=i.observable(""),this.davGlobalAddressBookUrl=i.observable(""),this.davSharedWithAllUrl=i.observable(""),this.bVisiblePersonalContacts=Ti.User.ShowPersonalContacts,this.bVisibleGlobalContacts=Ti.User.ShowGlobalContacts,this.bVisibleSharedWithAllContacts=!!Ti.App.AllowContactsSharing,this.bVisibleContacts=Ti.User.ShowContacts,this.bVisibleCalendar=Ti.User.AllowCalendar,this.bVisibleFiles=Ti.User.IsFilesSupported,this.bVisibleIosLink=Pi,this.visibleDavViaUrls=i.computed(function(){return this.visibleCalendars()||this.bVisibleContacts},this),this.bChanged=!1,this.isDemo=Ti.User.IsDemo,this.credentialsHintText=i.observable(Si.i18n("SETTINGS/MOBILE_CREDENTIALS_TITLE",{EMAIL:Ti.Accounts.getDefault().email()}))}function Qt(){this.outlookSync=Ti.User.outlookSync,this.outlookSync.subscribe(this.onOutlookSyncSubscribe,this),this.visibleOutlookSync=i.observable(!1),this.server=i.observable(""),this.bChanged=!1,this.isDemo=Ti.User.IsDemo,this.outlookSyncPlugin32=Ci.getHelpLink("OutlookSyncPlugin32"),this.outlookSyncPlugin64=Ci.getHelpLink("OutlookSyncPlugin64"),this.outlookSyncPluginReadMore=Ci.getHelpLink("OutlookSyncPluginReadMore"),this.credentialsHintText=i.observable(Si.i18n("SETTINGS/OUTLOOKSYNC_CREDENTIALS_TITLE",{EMAIL:Ti.Accounts.getDefault().email()}))}function $t(){this.pgp=null,this.pgpLoaded=i.observable(!1),this.keys=i.observableArray([]),this.publicKeys=i.computed(function(){var e=_.filter(this.keys(),function(e){return e.isPublic()});return _.map(e,function(e){return{user:e.getUser(),armor:e.getArmor(),key:e,"private":!1}})},this),this.privateKeys=i.computed(function(){var e=_.filter(this.keys(),function(e){return e.isPrivate()});return _.map(e,function(e){return{user:e.getUser(),armor:e.getArmor(),key:e}})},this),this.loading=i.observable(!1),this.enableOpenPgp=i.observable(Ti.User.enableOpenPgp()),this.allowAutosaveInDrafts=i.observable(Ti.User.AllowAutosaveInDrafts),this.autosignOutgoingEmails=i.observable(Ti.User.AutosignOutgoingEmails),this.bAllowAutoSave=Ti.App.AutoSave,this.firstState=this.getState()}function Jt(){this.allowUsersChangeInterfaceSettings=Ti.App.AllowUsersChangeInterfaceSettings,this.allowUsersChangeEmailSettings=Ti.App.AllowUsersChangeEmailSettings,this.account=i.observable(0),this.isInternal=i.observable(!0),this.isLinked=i.observable(!0),this.isDefault=i.observable(!1),this.removeHint=i.observable(""),this.friendlyName=i.observable(""),this.email=i.observable(""),this.incomingMailLogin=i.observable(""),this.incomingMailPassword=i.observable(""),this.incomingMailPort=i.observable(0),this.incomingMailServer=i.observable(""),this.outgoingMailLogin=i.observable(""),this.outgoingMailPassword=i.observable(""),this.outgoingMailPort=i.observable(0),this.outgoingMailServer=i.observable(""),this.loading=i.observable(!1),this.allowChangePassword=i.observable(!1),this.useSmtpAuthentication=i.observable(!1),this.incLoginFocused=i.observable(!1),this.incLoginFocused.subscribe(function(){this.incLoginFocused()&&""===this.incomingMailLogin()&&this.incomingMailLogin(this.email())},this),this.outServerFocused=i.observable(!1),this.outServerFocused.subscribe(function(){this.outServerFocused()&&""===this.outgoingMailServer()&&this.outgoingMailServer(this.incomingMailServer())},this),this.firstState=null}function Xt(e){this.parent=e,this.highlighted=i.observable(!1).extend({autoResetToFalse:500}),this.collection=i.observableArray(Ci.MailCache.editedFolderList().collection()),this.totalMessageCount=i.computed(function(){return Ci.MailCache.editedFolderList().totalMessageCount()},this),this.enableButtons=i.computed(function(){return Ci.MailCache.editedFolderList().bInitialized()},this),Ci.MailCache.editedFolderList.subscribe(function(e){this.collection(e.collection())},this),this.addNewFolderCommand=Si.createCommand(this,this.onAddNewFolderClick,this.enableButtons),this.systemFoldersCommand=Si.createCommand(this,this.onSystemFoldersClick,this.enableButtons),this.showMovedWithMouseItem=i.computed(function(){var e=Ti.Accounts.getEdited();return e?!Ri&&!e.extensionExists("DisableFoldersManualSort"):!1},this)}function Zt(e){this.parent=e,this.account=i.observable(0),this.type=i.observable(!1),this.useSignature=i.observable(0),this.signature=i.observable(""),this.loading=i.observable(!1),this.account.subscribe(function(){this.getSignature()},this),this.oHtmlEditor=new Rt(!0),this.enableImageDragNDrop=i.observable(!1),this.enabled=i.observable(!0),this.signature.subscribe(function(){this.oHtmlEditor.setText(this.signature())},this),this.getSignature(),this.firstState=null}function ei(){this.account=i.observable(0),this.available=i.computed(function(){var e=this.account();return e&&e.forward()},this),this.loading=i.observable(!1),this.enable=i.observable(!1),this.email=i.observable(""),this.emailFocus=i.observable(!1),this.account.subscribe(function(){this.getForward()},this),this.firstState=null}function ti(){this.account=i.observable(0),this.available=i.computed(function(){var e=this.account();return e&&e.autoresponder()},this),this.loading=i.observable(!1),this.enable=i.observable(!1),this.subject=i.observable(""),this.message=i.observable(""),this.account.subscribe(function(){this.getAutoresponder()},this),this.firstState=null}function ii(){this.account=i.observable(0),this.folderList=i.observable(Ci.MailCache.editedFolderList()),Ci.MailCache.editedFolderList.subscribe(function(e){e&&0!==e.iAccountId&&this.folderList(e)},this),this.foldersOptions=i.computed(function(){return this.folderList()?this.folderList().getOptions(Si.i18n("SETTINGS/ACCOUNT_FOLDERS_NOT_SELECTED"),!0,!0,!1):[]},this),this.foldersOptions.subscribe(function(){this.getFilters()},this),this.available=i.computed(function(){var e=this.account();return!(!e||!e.filters())},this),this.loading=i.observable(!0),this.saving=i.observable(!1),this.collection=i.observableArray([]),this.fieldOptions=[{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_FIELD_FROM"),value:0},{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_FIELD_TO"),value:1},{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_FIELD_SUBJECT"),value:2}],this.conditionOptions=[{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_COND_CONTAIN_SUBSTR"),value:0},{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_COND_EQUAL_TO"),value:1},{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_COND_NOT_CONTAIN_SUBSTR"),value:2}],this.actionOptions=[{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_ACTION_MOVE"),value:3},{text:Si.i18n("SETTINGS/ACCOUNT_FILTERS_ACTION_DELETE"),value:1}],this.phaseArray=[""],_.each(Si.i18n("SETTINGS/ACCOUNT_FILTERS_PHRASE").split(/\s/),function(e){var t=this.phaseArray.length-1; "%"===e.substr(0,1)||"%"===this.phaseArray[t].substr(-1,1)?this.phaseArray.push(e):this.phaseArray[t]+=" "+e},this),this.firstState=null}function si(){this.defaultAccountId=Ti.Accounts.defaultId,this.folderList=Ci.MailCache.folderList,this.loading=i.observable(!1),this.fetcher=i.observable(null),this.idFetcher=i.observable(null),this.isEnabled=i.observable(!0),this.incomingMailServer=i.observable(""),this.incomingMailPort=i.observable(110),this.incomingMailLogin=i.observable(""),this.incomingMailPassword=i.observable(""),this.folder=i.observable(""),this.options=i.computed(function(){return this.folderList().getOptions("",!0,!1,!1)},this),this.leaveMessagesOnServer=i.observable(!1),this.folderList.subscribe(function(){this.folder(this.fetcher()?this.fetcher().folder():"")},this),this.serverIsSelected=i.observable(!1),this.loginIsSelected=i.observable(!1),this.passwordIsSelected=i.observable(!1),this.defaultOptionsAfterRender=Si.defaultOptionsAfterRender}function oi(){this.defaultAccountId=Ti.Accounts.defaultId,this.loading=i.observable(!1),this.fetcher=i.observable(null),this.idFetcher=i.observable(null),this.isEnabled=i.observable(!0),this.email=i.observable(""),this.userName=i.observable(""),this.isOutgoingEnabled=i.observable(!1),this.outgoingMailServer=i.observable(""),this.outgoingMailPort=i.observable(25),this.outgoingMailAuth=i.observable(!1),this.serverIsSelected=i.observable(!1)}function ni(e){this.defaultAccountId=Ti.Accounts.defaultId,this.idFetcher=i.observable(null),this.fetcher=i.observable(null),this.signature=i.observable(""),this.loading=i.observable(!1),this.type=i.observable(!1),this.useSignature=i.observable(0),this.oHtmlEditor=new Rt(!0),this.enableImageDragNDrop=i.observable(!1),this.enabled=e.oFetcherIncoming.isEnabled,this.enabled.subscribe(function(){this.oHtmlEditor.isEnable(this.enabled())},this),this.signature.subscribe(function(){this.oHtmlEditor.setText(this.signature())},this),this.firstState=null}function ri(){this.allowNotifications=i.observable(Ti.User.AllowHelpdeskNotifications),this.loading=i.observable(!1)}function ai(){this.loading=i.observable(!1),this.allowFiles=Ti.User.IsFilesSupported,this.allowGoogle=Ti.SocialGoogle,this.googleKey=Ti.SocialGoogleApiKey,this.googleClientId=Ti.SocialGoogleId,this.allowDropbox=Ti.SocialDropbox,this.googleApiLoaded=i.observable(!1),this.loading=i.observable(!1),this.checkGoogleApiLoadTimeout=null,this.googleConnected=i.observable(!1),this.dropboxConnected=i.observable(!1),this.enableFiles=i.observable(Ti.User.filesEnable()),this.firstState=this.getState()}function li(e,t){this.defaultAccountId=Ti.Accounts.defaultId,this.oParent=e,this.bCreate=t,this.loading=i.observable(!1),this.identity=i.observable(null),this.enabled=i.observable(!0),this.email=i.observable(""),this.friendlyName=i.observable(""),this.friendlyNameHasFocus=i.observable(!1),this.signature=i.observable(""),this.useSignature=i.observable(0),this.oHtmlEditor=new Rt(!0),this.enableImageDragNDrop=i.observable(!1),this.signature.subscribe(function(){this.oHtmlEditor.setText(this.signature())},this),this.enabled.subscribe(function(){this.oHtmlEditor.isEnable(this.enabled())},this)}function hi(){var e=this;this.initialized=i.observable(!1),this.isPublic=Fi,this.uploaderArea=i.observable(null),this.bDragActive=i.observable(!1),this.bDragActiveComp=i.computed(function(){return this.bDragActive()},this),this.defaultAccount=Ti.Accounts?Ti.Accounts.getDefault():null,this.todayDate=new Date,this.aDayNames=Si.i18n("DATETIME/DAY_NAMES").split(" "),this.publicCalendarId=this.isPublic?Ti.CalendarPubHash:"",this.publicCalendarName=i.observable(""),this.timeFormat=Ti.User.defaultTimeFormat()===vi.TimeFormat.F24?"HH:mm":"hh:mm A",this.dateFormat=Ti.User.DefaultDateFormat,this.dateTitle=i.observable(""),this.dateTitleHelper=i.observableArray(Si.i18n("DATETIME/MONTH_NAMES").split(" ")),this.selectedView=i.observable(""),this.visibleWeekdayHeader=i.computed(function(){return"month"===this.selectedView()},this),this.selectedView.subscribe(function(){this.resize()},this),this.$calendarGrid=null,this.calendarGridDom=i.observable(null),this.$datePicker=null,this.datePickerDom=i.observable(null),this.calendars=new gt({onCalendarCollectionChange:function(){e.refreshView()},onCalendarActiveChange:function(){e.refreshView()}}),this.colors=["#f09650","#f68987","#6fd0ce","#8fbce2","#b9a4f5","#f68dcf","#d88adc","#4afdb4","#9da1ff","#5cc9c9","#77ca71","#aec9c9"],this.busyDays=i.observableArray([]),this.$inlineEditedEvent=null,this.inlineEditedEventText=null,this.checkStarted=i.observable(!1),this.loaded=!1,this.startDateTime=0,this.endDateTime=0,this.needsToReload=!1,this.calendarListClick=function(e){e.active(!e.active())},this.currentCalendarDropdown=i.observable(!1),this.currentCalendarDropdownOffset=i.observable(0),this.calendarDropdownToggle=function(t,i){if(i&&t){var s=i.position(),o=i.outerHeight();e.currentCalendarDropdownOffset(parseInt(s.top,10)+o)}e.currentCalendarDropdown(t)},this.dayNamesResizeBinding=_.throttle(_.bind(this.resize,this),50),this.customscrollTop=i.observable(0),this.fullcalendarOptions={eventLimit:10,header:!1,editable:!this.isPublic,selectable:!this.isPublic,allDayText:Si.i18n("CALENDAR/TITLE_ALLDAY"),dayNames:this.aDayNames,isRTL:Si.isRTL(),scrollTime:moment.duration(8,"hours"),forceEventDuration:!0,columnFormat:{month:"dddd",week:"dddd D",day:"dddd D"},titleFormat:{month:"MMMM YYYY",week:"MMMM D[ YYYY]{ '-'[ MMMM] D YYYY}",day:"MMMM D, YYYY"},displayEventEnd:{month:!0,basicWeek:!0,"default":!0},select:_.bind(this.createEventFromGrid,this),eventClick:_.bind(this.eventClickCallback,this),eventDragStart:_.bind(this.onEventDragStart,this),eventDragStop:_.bind(this.onEventDragStop,this),eventResizeStart:_.bind(this.onEventResizeStart,this),eventResizeStop:_.bind(this.onEventResizeStop,this),eventDrop:_.bind(this.moveEvent,this),eventResize:_.bind(this.resizeEvent,this),viewRender:_.bind(this.viewRenderCallback,this),events:_.bind(this.eventsSource,this)},this.revertFunction=null,this.calendarSharing=Ti.User.AllowCalendar&&Ti.User.CalendarSharing,this.defaultViewName=i.computed(function(){var e="month";switch(Ti.User.CalendarDefaultTab){case vi.CalendarDefaultTab.Day:e="agendaDay";break;case vi.CalendarDefaultTab.Week:e="agendaWeek";break;case vi.CalendarDefaultTab.Month:e="month"}return e},this),this.iAutoReloadTimer=-1,this.dragEventTrigger=!1,this.delayOnEventResult=!1,this.delayOnEventResultData=[],this.refreshView=_.throttle(_.bind(this.refreshViewSingle,this),100),this.defaultCalendarId=i.computed(function(){var e=this.calendars.defaultCal();return e?e.id:void 0},this),this.uploadCalendarId=i.observable(""),this.changeFullCalendarDate=!0}function ci(){this.allowWebMail=!(!Ti.App||!Ti.App.AllowWebMail),this.loaded=i.observable(!1),this.isPublic=Fi,this.publicHash=Fi?Ti.FileStoragePubHash:"",this.IsCollaborationSupported=Ti.User.IsCollaborationSupported,this.AllowFilesSharing=Ti.User.AllowFilesSharing,this.storages=i.observableArray(),this.folders=i.observableArray(),this.files=i.observableArray(),this.uploadingFiles=i.observableArray(),this.selected=i.observable(!1),this.rootPath=i.observable(Si.i18n("FILESTORAGE/TAB_PERSONAL_FILES")),this.storageType=i.observable(vi.FileStorageType.Personal),this.storageType.subscribe(function(){var e=null;this.isPublic?this.rootPath(Ti.FileStoragePubParams.Name):(e=this.getStorageByType(this.storageType()),e&&this.rootPath(e.displayName())),this.selector.listCheckedAndSelected(!1)},this),this.iPathIndex=i.observable(-1),this.pathItems=i.observableArray(),this.dropPath=i.observable(""),this.path=i.computed(function(){var e=_.map(this.pathItems(),function(e){return e.id()});return e.join("/")},this),this.path.subscribe(function(e){this.dropPath(e)},this),this.collection=i.computed(function(){var e=_.union(this.files(),this.getUploadingFiles());return e.sort(function(e,t){return e.fileName()===t.fileName()?0:e.fileName()<t.fileName()?-1:1}),_.union(this.folders(),e)},this),this.columnCount=i.observable(1),this.selector=new u(this.collection,null,_.bind(this.onItemDelete,this),_.bind(this.onItemDblClick,this),_.bind(this.onEnter,this),this.columnCount,!0,!0,!0),this.searchPattern=i.observable(""),this.isSearchFocused=i.observable(!1),this.renameCommand=Si.createCommand(this,this.executeRename,function(){var e=this.selector.listCheckedAndSelected();return 1===e.length&&!e[0].isLink()}),this.deleteCommand=Si.createCommand(this,this.executeDelete,function(){var e=this.selector.listCheckedAndSelected();return 0<e.length}),this.downloadCommand=Si.createCommand(this,this.executeDownload,function(){var e=this.selector.listCheckedAndSelected();return 1===e.length&&!e[0].isFolder()}),this.shareCommand=Si.createCommand(this,this.executeShare,function(){var e=this.selector.listCheckedAndSelected();return 1===e.length&&!e[0].isLink()}),this.sendCommand=Si.createCommand(this,this.executeSend,function(){var e=this.selector.listCheckedAndSelected(),t=_.filter(e,function(e){return!e.isFolder()},this);return t.length>0}),this.uploaderButton=i.observable(null),this.uploaderArea=i.observable(null),this.bDragActive=i.observable(!1),this.bDragActiveComp=i.computed(function(){var e=this.bDragActive();return e&&""===this.searchPattern()},this),this.uploadError=i.observable(!1),this.quota=i.observable(0),this.used=i.observable(0),this.quotaDesc=i.observable(""),this.quotaProc=i.observable(-1),i.computed(function(){if(!Ti.App||Ti.App&&!Ti.App.ShowQuotaBar)return!0;var e=this.quota(),t=this.used(),i=e>0?Math.ceil(t/e*100):-1;return i=i>100?100:i,this.quotaProc(i),this.quotaDesc(i>-1?Si.i18n("MAILBOX/QUOTA_TOOLTIP",{PROC:i,QUOTA:Si.friendlySize(e)}):""),!0},this),this.dragover=i.observable(!1),this.loading=i.observable(!1),this.loadedFiles=i.observable(!1),this.fileListInfoText=i.computed(function(){var e="";return this.loading()?e=Si.i18n("FILESTORAGE/INFO_LOADING"):this.loadedFiles()&&0===this.collection().length&&(e=Si.i18n(this.isPublic?"FILESTORAGE/INFO_PUBLIC_FOLDER_NOT_EXIST":""!==this.searchPattern()||this.isPublic?"FILESTORAGE/INFO_NO_ITEMS_FOUND":""!==this.path()||this.isPopup?"FILESTORAGE/INFO_FOLDER_IS_EMPY":"FILESTORAGE/INFO_FILESTORAGE_IS_EMTY")),e},this),this.dragAndDropHelperBinded=_.bind(this.dragAndDropHelper,this),this.isPopup=!1,this.isCurrentStorageExternal=i.computed(function(){var e=this.getStorageByType(this.storageType());return e&&e.isExternal()},this),this.timerId=null}function ui(){var e=this,t=function(t){return function(){e.executeChangeState(t),e.isQuickReplyHidden(!e.bAgent),t===vi.HelpdeskThreadStates.Resolved&&e.selectedItem(null)}};this.bRtl=Si.isRTL(),this.iAutoCheckTimer=0,this.bExtApp=Fi,this.ajaxSendFunc=this.bExtApp?"sendExt":"send",this.bAgent=Ti.User.IsHelpdeskAgent,this.singleMode=Ti.SingleMode,this.externalUrl=i.observable(Ti.HelpdeskIframeUrl),this.loadingList=i.observable(!0),this.loadingViewPane=i.observable(!1),this.loadingMoreMessages=i.observable(!1),this.threads=i.observableArray([]),this.posts=i.observableArray([]),this.iPingInterval=-1,this.iPingStartTimer=-1,this.selectedItem=i.observable(null),this.selectedItem.subscribe(function(){this.subject(this.selectedItem()?this.bExtApp?this.selectedItem().sSubject:this.selectedItem().sFromFull:""),this.internalNote(!1),!this.bExtApp&&this.selectedItem()&&Ci.ContactsCache.getContactByEmail(this.selectedItem().sEmail,this.onOwnerContactResponse,this),clearInterval(this.iPingInterval),clearTimeout(this.iPingStartTimer),this.watchers([]),this.selectedItem()&&(this.iPingStartTimer=setTimeout(_.bind(function(){this.executeThreadPing(this.selectedItem().Id),clearInterval(this.iPingInterval),this.iPingInterval=setInterval(_.bind(function(){this.executeThreadPing(this.selectedItem().Id)},this),18e4)},this),5e3))},this),this.listFilter=i.observable(this.bAgent?vi.HelpdeskFilters.Open:vi.HelpdeskFilters.All),this.listFilter.subscribe(function(){this.requestThreadsList()},this),this.prevListFilter=i.observable(""),this.hasMorePosts=i.computed(function(){var e=this.selectedItem();return e&&e.postsCount()>this.posts().length},this).extend({throttle:1}),this.selector=new u(this.threads,_.bind(this.onItemClick,this),_.bind(this.onItemDelete,this),null,null,null,!1,!1,!1,!0),this.checkStarted=i.observable(!1),this.checkAll=this.selector.koCheckAll(),this.checkAllIncomplite=this.selector.koCheckAllIncomplete(),this.ThreadsPerPage=10,this.oPageSwitcher=new Mt(0,this.ThreadsPerPage),this.oPageSwitcher.currentPage.subscribe(function(){this.requestThreadsList()},this),this.isSearchFocused=i.observable(!1),this.searchPattern=i.observable(""),this.search=i.observable(""),this.search.subscribe(function(e){this.searchPattern(e)},this),this.searchText=i.computed(function(){return Si.i18n("HELPDESK/INFO_SEARCH_RESULT",{SEARCH:this.search()})},this),this.searchSubmitCommand=Si.createCommand(this,function(){this.oPageSwitcher.currentPage(1),this.search(this.searchPattern()),this.requestThreadsList()}),this.deleteCommand=Si.createCommand(this,this.executeDelete,this.isEnableListActions),this.openNewWindowCommand=Si.createCommand(this,this.executeOpenNewWindow,this.isEnableListActions),this.checkCommand=Si.createCommand(this,function(){this.requestThreadsList(),this.requestPosts(),this.startAutocheckmail()}),this.closeCommand=Si.createCommand(this,t(vi.HelpdeskThreadStates.Resolved),this.isEnableListActions),this.waitCommand=Si.createCommand(this,t(vi.HelpdeskThreadStates.Waiting),this.isEnableListActions),this.pendingCommand=Si.createCommand(this,t(vi.HelpdeskThreadStates.Pending),this.isEnableListActions),this.deferCommand=Si.createCommand(this,t(vi.HelpdeskThreadStates.Deferred),this.isEnableListActions),this.answerCommand=Si.createCommand(this,t(vi.HelpdeskThreadStates.Answered),this.isEnableListActions),this.postCommand=Si.createCommand(this,this.executePostCreate,function(){return!!this.selectedItem()&&this.replyText().length>0&&this.allAttachmentsUploaded()}),this.visibleNewThread=i.observable(!1),this.newThreadText=i.observable(""),this.newThreadCreating=i.observable(!1),this.createThreadCommand=Si.createCommand(this,this.executeThreadCreate,function(){return this.visibleNewThread()&&this.newThreadText().length>0&&!this.newThreadCreating()}),this.createThreadButtonText=i.computed(function(){return Si.i18n(this.newThreadCreating()?"HELPDESK/BUTTON_SENDING":"HELPDESK/BUTTON_CREATE")},this),this.showThreadsByOwnerCommand=Si.createCommand(this,this.executeShowThreadsByOwner),this.commandGetOlderPosts=function(){var e=this.posts(),t=e[0]?e[0].Id:0;this.requestPosts(null,t)},this.externalContentUrl=i.observable(""),Ti.HelpdeskIframeUrl&&(this.bAgent?this.externalContentUrl=i.computed(function(){var e="",t=this.selectedItem();return t&&(e=t.Email()),e?Ti.HelpdeskIframeUrl.replace(/\[EMAIL\]/g,e):""},this):Ti.User.Email&&(this.externalContentUrl=i.computed(function(){return Ti.HelpdeskIframeUrl.replace(/\[EMAIL\]/g,Ti.User.Email)},this))),this.clientDetailsVisible=i.observable(Ci.Storage.hasData("HelpdeskUserDetails")?Ci.Storage.getData("HelpdeskUserDetails"):!0),this.clientDetailsVisible.subscribe(function(e){Ci.Storage.setData("HelpdeskUserDetails",e)},this),this.subject=i.observable(""),this.watchers=i.observableArray([]),this.ownerExistsInContacts=i.observable(!1),this.ownerContactInfoReceived=i.observable(!1),this.ownerContact=i.observable(this.bExtApp?null:new ct),this.hasOwnerContact=i.computed(function(){return!this.singleMode&&this.ownerContactInfoReceived()&&this.ownerExistsInContacts()},this),this.visibleAddToContacts=i.computed(function(){return!this.singleMode&&this.ownerContactInfoReceived()&&!this.ownerExistsInContacts()},this),this.contactCardWidth=i.observable(0),this.uploadedFiles=i.observableArray([]),this.allAttachmentsUploaded=i.computed(function(){var e=_.filter(this.uploadedFiles(),function(e){return!e.uploaded()});return 0===e.length},this),this.uploaderButton=i.observable(null),this.uploaderButtonCompose=i.observable(null),this.uploaderArea=i.observable(null),this.bDragActive=i.observable(!1),this.internalNote=i.observable(!1),this.isQuickReplyHidden=i.observable(!this.bAgent),this.domQuickReply=i.observable(null),this.replySendingStarted=i.observable(!1),this.replyPaneVisible=i.observable(!0),this.replyText=i.observable(""),this.replyTextFocus=i.observable(!1),this.isQuickReplyActive=i.observable(!1),this.replyTextFocus.subscribe(function(){this.replyTextFocus()&&this.isQuickReplyActive(!0)},this),this.isQuickReplyActive.subscribe(function(){this.isQuickReplyActive()&&this.replyTextFocus(!0)},this),this.isEmptyQuickReplyPane=i.computed(function(){return 0===this.replyText().length&&!this.internalNote()&&0===this.uploadedFiles().length},this),this.isSearch=i.computed(function(){return""!==this.search()},this),this.isEmptyList=i.computed(function(){return 0===this.threads().length},this),this.dynamicEmptyListInfo=this.bAgent?i.computed(function(){return Si.i18n(this.isEmptyList()&&this.isSearch()?"HELPDESK/INFO_SEARCH_EMPTY":"HELPDESK/INFO_EMPTY_OPEN_THREAD_LIST_AGENT")},this):i.computed(function(){return Si.i18n(this.isEmptyList()&&this.isSearch()?"HELPDESK/INFO_SEARCH_EMPTY":"HELPDESK/INFO_EMPTY_THREAD_LIST")},this),this.simplePreviewPane=i.computed(function(){var e=this.selectedItem();return e?e.ItsMe:!this.bAgent},this),this.allowInternalNote=i.computed(function(){return!this.simplePreviewPane()},this),this.scrollToTopTrigger=i.observable(!1),this.scrollToBottomTrigger=i.observable(!1),this.allowDownloadAttachmentsLink=!1,this.newThreadButtonWidth=i.observable(0),this.requestFromLogin(),this.requestThreadsList()}function di(){var s=e(t);this.resizeAll=_.debounce(function(){s.resize()},100),this.oScreens={},this.currentScreen=i.observable(""),this.popupVisibility=i.observable(!1),this.informationScreen=i.observable(null),this.popups=[]}function pi(){this.currentAccountId=Ti.Accounts.currentId,this.currentAccountId.subscribe(function(e){var t=Ti.Accounts.getAccount(e),i=this.oFolderListItems[e],s={Action:"FolderList",AccountID:e};t&&(t.quotaRecieved(!1),this.messagesLoadingError(!1),i?this.folderList(i):(this.messagesLoading(!0),this.folderList(new nt),this.messages([]),this.currentMessage(null),Ci.Ajax.send(s,this.onFolderListResponse,this)))},this),this.editedAccountId=Ti.Accounts.editedId,this.editedAccountId.subscribe(function(e){var t=this.oFolderListItems[e],i={};t?this.editedFolderList(t):this.currentAccountId()!==e&&(this.editedFolderList(new nt),i={Action:"FolderList",AccountID:e},Ci.Ajax.send(i,this.onFolderListResponse,this))},this),this.oFolderListItems={},this.quotaChangeTrigger=i.observable(!1),this.checkMailStarted=i.observable(!1),this.checkMailStartedAccountId=i.observable(0),this.defaultFolderList=i.observable(new nt),this.folderList=i.observable(new nt),this.folderListLoading=i.observable(!1),this.editedFolderList=i.observable(new nt),this.newMessagesCount=i.computed(function(){var e=this.folderList().inboxFolder();return e?e.unseenMessageCount():0},this),this.newMessagesCount.subscribe(function(e){Ci.mailUnseenCount(e>99?"99+":e)},this),this.messages=i.observableArray([]),this.messages.subscribe(function(){this.messages().length>0&&this.messagesLoadingError(!1)},this),this.uidList=i.observable(new at),this.page=i.observable(1),this.messagesLoading=i.observable(!0),this.messagesLoadingError=i.observable(!1),this.currentMessage=i.observable(null),this.currentMessage.subscribe(function(){this.currentMessage()&&Ei.runPluginHook("view-message",[Ti.Accounts.currentId(),this.currentMessage().folder(),this.currentMessage().uid()])},this),this.nextMessageUid=i.computed(function(){var e="",i="",s=null,o=null,n=!1;return this.currentMessage()&&Ti.SingleMode&&(n=this.currentMessage().threadPart()&&""!==this.currentMessage().threadParentUid(),s=this.folderList().getFolderByFullName(this.currentMessage().folder()),e=this.currentMessage().uid(),Ti.ThreadLevel||n?(Ti.ThreadLevel=!0,n&&(o=s.getMessageByUid(this.currentMessage().threadParentUid()),o&&(_.each(o.threadUids(),function(t,s,o){t===e&&s>0&&(i=o[s-1])}),(Si.isUnd(i)||""===i)&&(i=o.uid())))):(_.each(this.uidList().collection(),function(t,s,o){t===e&&s>0&&(i=o[s-1])}),Si.isUnd(i)&&(i=""),""===i&&t.opener&&t.opener.App&&t.opener.App.Prefetcher&&t.opener.App.Prefetcher.prefetchNextPage(e))),i},this),this.prevMessageUid=i.computed(function(){var e=this.currentMessage()?this.currentMessage().uid():"",i="",s=null,o=null,n=!1;return this.currentMessage()&&Ti.SingleMode&&(n=this.currentMessage().threadPart()&&""!==this.currentMessage().threadParentUid(),s=this.folderList().getFolderByFullName(this.currentMessage().folder()),e=this.currentMessage().uid(),Ti.ThreadLevel||n?(Ti.ThreadLevel=!0,n?(o=s.getMessageByUid(this.currentMessage().threadParentUid()),o&&(_.each(o.threadUids(),function(t,s,o){t===e&&s+1<o.length&&(i=o[s+1])}),Si.isUnd(i)&&(i=""))):this.currentMessage().threadCount()>0&&(i=this.currentMessage().threadUids()[0])):(_.each(this.uidList().collection(),function(t,s,o){t===e&&s+1<o.length&&(i=o[s+1])}),Si.isUnd(i)&&(i=""),""===i&&t.opener&&t.opener.App&&t.opener.App.Prefetcher&&t.opener.App.Prefetcher.prefetchPrevPage(e))),i},this),this.deletedDraftMessageUid=i.observable(""),this.aResponseHandlers=[],Ti.User.useThreads.subscribe(function(){_.each(this.oFolderListItems,function(e){_.each(e.collection(),function(e){e.markHasChanges(),e.removeAllMessageListsFromCacheIfHasChanges()},this)},this),this.messages([])},this),this.iAutoCheckMailTimer=-1,this.waitForUnseenMessages=i.observable(!0),this.iMessageSetSeenCount=0}function gi(){this.contacts={},this.responseHandlers={},this.vcardAttachments=[],this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500})}function mi(){this.calendars=i.observableArray([]),this.calendarsLoadingStarted=i.observable(!1),this.icalAttachments=[],this.recivedAnim=i.observable(!1).extend({autoResetToFalse:500}),this.calendarSettingsChanged=i.observable(!1),this.calendarChanged=i.observable(!1),this.canRequestCalendarList=i.observable(!1)}function bi(){this.browser=new n,this.favico=t.Favico?new t.Favico({animation:"none"}):null,this.Ajax=new r,this.Screens=new di,this.Api=new d,this.Storage=new p,this.helpdeskUnseenCount=i.observable(0),this.mailUnseenCount=i.observable(0)}function fi(){bi.call(this),this.headerTabs=i.observableArray([]),this.screensTitle={},this.Phone=null,this.Routing=new a,this.Links=new l,this.MessageSender=new h,this.Prefetcher=new c,this.MailCache=null,this.ContactsCache=new gi,this.CalendarCache=new mi,this.currentScreen=this.Screens.currentScreen,this.currentScreen.subscribe(this.setTitle,this),this.focused=i.observable(!0),this.focused.subscribe(function(){Ti.SingleMode||t.opener||this.setTitle()},this),this.filesRecievedAnim=i.observable(!1).extend({autoResetToFalse:500}),this.init(),this.newMessagesCount=this.MailCache.newMessagesCount,this.newMessagesCount.subscribe(this.setTitle,this),this.currentMessage=this.MailCache.currentMessage,this.currentMessage.subscribe(this.setTitle,this),this.notification=null,this.initHeaderInfo(),this.sessionTimeoutFunctions=[],this.initSessionTimeout()}function yi(){fi.call(this)}var vi={},Si={},Ai=t.pSevenI18N||{},Ci={},Ei={},Ti=t.pSevenAppData||{},Fi=!1,Ii=!1,wi=e("html"),Pi=-1<navigator.userAgent.indexOf("iPhone")||-1<navigator.userAgent.indexOf("iPod")||-1<navigator.userAgent.indexOf("iPad"),Mi=-1<navigator.userAgent.toLowerCase().indexOf("android"),Ri=Pi||Mi,Di=["image/jpeg","image/png","image/gif","text/html","text/plain","text/css","text/rfc822-headers","message/delivery-status","application/x-httpd-php","application/javascript","application/pdf"];if(t.Modernizr&&navigator&&t.Modernizr.addTest("pdf",function(){for(var e=navigator.mimeTypes,t=0,i=e.length;i>t;t++)if("application/pdf"===e[t].type)return!0;return!1}),Date.now||(Date.now=function(){return(new Date).getTime()}),n.prototype.getIeVersion=function(){var e=navigator.userAgent.toLowerCase(),t=Si.pInt(e.slice(e.indexOf("msie")+4,e.indexOf(";",e.indexOf("msie")+4)));return this.ie11&&(t=11),t},r.prototype.hasOpenedRequests=function(e){return e=Si.isUnd(e)?"":e,this.requests(_.filter(this.requests(),function(t){var i=t&&4===t.Xhr.readyState,s=!t||0===t.Xhr.readyState&&"abort"===t.Xhr.statusText,o=""===e||t&&t.Parameters.Action===e;return t&&!i&&!s&&o})),this.requests().length>0},r.prototype.isSearchMessages=function(){var e=!1;return _.each(this.requests(),function(t){t&&t.Parameters&&"MessageList"===t.Parameters.Action&&""!==t.Parameters.Search&&(e=!0)},this),e},r.prototype.isAllowedActionWithoutAuth=function(e){var t=["Login","LoginLanguageUpdate","Logout","AccountCreate","SetMobile","RegisterAccount","GetForgotAccountQuestion","ValidateForgotAccountQuestion","ChangeForgotAccountPassword"];return-1!==_.indexOf(t,e)},r.prototype.isAllowedExtAction=function(e){return"SocialRegister"===e||"HelpdeskRegister"===e||"HelpdeskForgot"===e||"HelpdeskLogin"===e||"Logout"===e},r.prototype.doSend=function(t,i,s,o){var n=_.bind(o||null,this,t,i,s),r=_.bind(this.fail,this,t,i,s),a=_.bind(this.always,this,t),l=null;Ei.runPluginHook&&Ei.runPluginHook("ajax-default-request",[t.Action,t]),Ti.Token&&(t.Token=Ti.Token),this.abortRequests(t),Si.log("Ajax request send",t.Action,t),l=e.ajax({url:this.sUrl,type:"POST",async:!0,dataType:"json",data:t,success:n,error:r,complete:a}),this.requests().push({Parameters:t,Xhr:l})},r.prototype.send=function(e,t,i){var s=void 0===e.AccountID,o=s||Ti.Accounts.hasAccountWithId(e.AccountID);e&&(Ti.Auth&&o||this.isAllowedActionWithoutAuth(e.Action))&&(s&&"Login"!==e.Action&&(e.AccountID=Ti.Accounts.currentId()),this.doSend(e,t,i,this.done))},r.prototype.sendExt=function(e,t,i){var s=["SocialRegister","HelpdeskRegister","HelpdeskForgot","HelpdeskLogin","HelpdeskForgotChangePassword","Logout","CalendarList","EventList","FilesPub"],o=-1!==_.indexOf(s,e.Action);e&&(Ti.Auth||o)&&(Ti.TenantHash&&(e.TenantHash=Ti.TenantHash),this.doSend(e,t,i,this.doneExt))},r.prototype.abortRequests=function(e){switch(e.Action){case"MessageMove":case"MessageDelete":this.abortRequestByActionName("MessageList",{Folder:e.Folder}),this.abortRequestByActionName("Message");break;case"MessageList":case"MessageSetSeen":this.abortRequestByActionName("MessageList",{Folder:e.Folder});break;case"MessageSetAllSeen":this.abortRequestByActionName("MessageList",{Folder:e.Folder}),this.abortRequestByActionName("MessageListByUids",{Folder:e.Folder});break;case"FolderClear":this.abortRequestByActionName("MessageList",{Folder:e.Folder}),this.abortRequestByActionName("FolderCounts");break;case"ContactList":case"GlobalContactList":this.abortRequestByActionName("ContactList"),this.abortRequestByActionName("GlobalContactList");break;case"Contact":case"GlobalContact":this.abortRequestByActionName("Contact"),this.abortRequestByActionName("GlobalContact");break;case"EventUpdate":this.abortRequestByActionName("EventUpdate",{calendarId:e.calendarId,uid:e.uid})}},r.prototype.abortRequestByActionName=function(e,t){var i;_.each(this.requests(),function(s,o){if(i=!1,s&&s.Parameters.Action===e)switch(e){case"MessageList":t.Folder===s.Parameters.Folder&&(i=!0);break;case"EventUpdate":t.calendarId===s.Parameters.calendarId&&t.uid===s.Parameters.uid&&(i=!0);break;default:i=!0}i&&(s.Xhr.abort(),this.requests()[o]=void 0)},this),this.requests(_.compact(this.requests()))},r.prototype.abortAllRequests=function(){_.each(this.requests(),function(e){e&&e.Xhr.abort()},this),this.requests([])},r.prototype.done=function(e,t,i,s,o){var n=this.isAllowedActionWithoutAuth(e.Action),r=Ti.Accounts.hasAccountWithId(e.AccountID),a=e.AccountID===Ti.Accounts.defaultId();if(Si.log("Ajax request done",e.Action,o,Si.getAjaxDataForLog(e.Action,s),e),n||r){if(s&&!s.Result)switch(s.ErrorCode){case vi.Errors.InvalidToken:n||Ci.tokenProblem();break;case vi.Errors.AuthError:a&&!n&&(this.abortAllRequests(),Ci.authProblem())}this.executeResponseHandler(t,i,s,e)}},r.prototype.doneExt=function(e,t,i,s){this.executeResponseHandler(t,i,s,e)},r.prototype.fail=function(e,t,i,s,o,n){var r={Result:!1,ErrorCode:0};switch(Si.log("Ajax request fail",e.Action,o,e),o){case"abort":r={Result:!1,ErrorCode:vi.Errors.NotDisplayedError};break;default:case"error":case"parseerror":r=""===n?{Result:!1,ErrorCode:vi.Errors.NotDisplayedError}:{Result:!1,ErrorCode:vi.Errors.DataTransferFailed}}this.executeResponseHandler(t,i,r,e)},r.prototype.executeResponseHandler=function(e,t,i,s){i||(i={Result:!1,ErrorCode:0}),Ei.runPluginHook&&Ei.runPluginHook("ajax-default-response",[s.Action,i]),"function"==typeof e&&e.apply(t,[i,s])},r.prototype.always=function(e,t,i){_.each(this.requests(),function(t,i){t&&_.isEqual(t.Parameters,e)&&(this.requests()[i]=void 0)},this),this.requests(_.compact(this.requests())),Si.checkConnection(e.Action,i),Ci.Prefetcher&&"abort"!==i&&!this.hasOpenedRequests()&&Ci.Prefetcher.start()},vi.Screens={Login:"login",Information:"information",Header:"header",Mailbox:"mailbox",SingleMessageView:"single-message-view",Compose:"compose",SingleCompose:"single-compose",Settings:"settings",Contacts:"contacts",Calendar:"calendar",FileStorage:"files",Helpdesk:"helpdesk",SingleHelpdesk:"single-helpdesk"},vi.CalendarDefaultTab={Day:1,Week:2,Month:3},vi.TimeFormat={F24:"0",F12:"1"},vi.Errors={InvalidToken:101,AuthError:102,DataBaseError:104,LicenseProblem:105,DemoLimitations:106,Captcha:107,AccessDenied:108,CanNotGetMessage:202,ImapQuota:205,NotSavedInSentItems:304,NoRequestedMailbox:305,CanNotChangePassword:502,AccountOldPasswordNotCorrect:503,FetcherIncServerNotAvailable:702,FetcherLoginNotCorrect:703,HelpdeskThrowInWebmail:805,HelpdeskUserNotExists:807,HelpdeskUserNotActivated:808,MailServerError:901,DataTransferFailed:1100,NotDisplayedError:1155},vi.FolderTypes={Inbox:1,Sent:2,Drafts:3,Spam:4,Trash:5,Virus:6,Starred:7,System:9,User:10},vi.FolderFilter={Flagged:"flagged",Unseen:"unseen"},vi.LoginFormType={Email:0,Login:3,Both:4},vi.LoginSignMeType={DefaultOff:0,DefaultOn:1,Unuse:2},vi.ReplyType={Reply:"reply",ReplyAll:"reply-all",Resend:"resend",Forward:"forward"},vi.Importance={Low:5,Normal:3,High:1},vi.Sensivity={Nothing:0,Confidential:1,Private:2,Personal:3},vi.ContactEmailType={Personal:"Personal",Business:"Business",Other:"Other"},vi.ContactPhoneType={Mobile:"Mobile",Personal:"Personal",Business:"Business"},vi.ContactAddressType={Personal:"Personal",Business:"Business"},vi.ContactSortType={Email:"Email",Name:"Name",Frequency:"Frequency"},vi.SaveMail={Hidden:0,Checked:1,Unchecked:2},vi.SettingsTab={Common:"common",EmailAccounts:"accounts",Calendar:"calendar",MobileSync:"mobile_sync",OutLookSync:"outlook_sync",Helpdesk:"helpdesk",Pgp:"pgp",Services:"services"},vi.AccountSettingsTab={Properties:"properties",Signature:"signature",Filters:"filters",Autoresponder:"autoresponder",Forward:"forward",Folders:"folders",FetcherInc:"fetcher-inc",FetcherOut:"fetcher-out",FetcherSig:"fetcher-sig",IdentityProperties:"identity-properties",IdentitySignature:"identity-signature"},vi.ContactsGroupListType={Personal:0,SubGroup:1,Global:2,SharedToAll:3,All:4},vi.IcalType={Request:"REQUEST",Reply:"REPLY",Cancel:"CANCEL",Save:"SAVE"},vi.IcalConfig={Accepted:"ACCEPTED",Declined:"DECLINED",Tentative:"TENTATIVE",NeedsAction:"NEEDS-ACTION"},vi.IcalConfigInt={Accepted:1,Declined:2,Tentative:3,NeedsAction:0},vi.Key={Tab:9,Enter:13,Shift:16,Ctrl:17,Esc:27,Space:32,PageUp:33,PageDown:34,End:35,Home:36,Up:38,Down:40,Left:37,Right:39,Del:46,Six:54,a:65,b:66,c:67,f:70,i:73,k:75,n:78,p:80,q:81,r:82,s:83,u:85,v:86,y:89,z:90,F5:116,Comma:188,Dot:190,Dash:192,Apostrophe:222},vi.MouseKey={Left:0,Middle:1,Right:2},vi.FileStorageType={Personal:0,Corporate:1,Shared:2,GoogleDrive:3,Dropbox:4},vi.FileStorageLinkType={Unknown:0,GoogleDrive:1,Dropbox:2},vi.HelpdeskThreadStates={None:0,Pending:1,Waiting:2,Answered:3,Resolved:4,Deferred:5},vi.HelpdeskPostType={Normal:0,Internal:1,System:2},vi.HelpdeskFilters={All:0,Pending:1,Resolved:2,InWork:3,Open:4,Archived:9},vi.CalendarAccess={Full:0,Write:1,Read:2},vi.CalendarEditRecurrenceEvent={None:0,OnlyThisInstance:1,AllEvents:2},vi.CalendarRepeatPeriod={None:0,Daily:1,Weekly:2,Monthly:3,Yearly:4},vi.PhoneAction={Offline:"offline",OfflineError:"offline_error",OfflineInit:"offline_init",OfflineActive:"offline_active",Online:"online",OnlineActive:"online_active",Incoming:"incoming",IncomingConnect:"incoming_connect",Outgoing:"outgoing",OutgoingConnect:"outgoing_connect",Settings:"settings"},vi.HtmlEditorImageSizes={Small:"small",Medium:"medium",Large:"large",Original:"original"},vi.MobilePanel={Groups:1,Items:2,View:3},vi.PgpAction={Import:"import",Generate:"generate",Encrypt:"encrypt",Sign:"sign",EncryptSign:"encrypt-sign",Verify:"ferify",DecryptVerify:"decrypt-ferify"},vi.SocialType={Unknown:0,Google:1,Dropbox:2,Facebook:3,Twitter:4,Vkontakte:5},vi.notificationPermission={Granted:"granted",Denied:"denied",Default:"default"},Si.inArray=e.inArray,Si.isFunc=e.isFunction,Si.trim=e.trim,Si.emptyFunction=function(){},Si.isUnd=function(e){return void 0===e },Si.isNull=function(e){return null===e},Si.isNormal=function(e){return!Si.isUnd(e)&&!Si.isNull(e)},Si.isNumeric=function(e){return Si.isNormal(e)?/^[1-9]+[0-9]*$/.test(e.toString()):!1},Si.pInt=function(e){var i=t.parseInt(e,10);return isNaN(i)&&(i=0),i},Si.pString=function(e){return Si.isNormal(e)?e.toString():""},Si.isNonEmptyArray=function(e,t){return t=t||1,_.isArray(e)&&t<=e.length},Si.pImport=function(e,t,i){e[t]=i},Si.pExport=function(e,t,i){return Si.isUnd(e[t])?i:e[t]},Si.encodeHtml=function(e){return e?e.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""},Si.i18n=function(e,t,i,s){var o="",n=Si.isUnd(Ai[e])?Si.isNormal(i)?i:e:Ai[e];if(Si.isUnd(s)||(n=function(e,t){var i=Si.getPlural(Ti.User.DefaultLanguage,e),s=t.split("|");return s&&s[i]?s[i]:s&&s[0]?s[0]:t}(s,n)),Si.isNormal(t))for(o in t)t.hasOwnProperty(o)&&(n=n.replace("%"+o+"%",t[o]));return n},Si.roundNumber=function(e,t){return Math.round(e*Math.pow(10,t))/Math.pow(10,t)},Si.friendlySize=function(e){var t=1024,i=t*t,s=t*t*t;return e=Si.pInt(e),e>=s?Si.roundNumber(e/s,1)+Si.i18n("MAIN/GIGABYTES"):e>=i?Si.roundNumber(e/i,1)+Si.i18n("MAIN/MEGABYTES"):e>=t?Si.roundNumber(e/t,0)+Si.i18n("MAIN/KILOBYTES"):e+Si.i18n("MAIN/BYTES")},Si.timeOutAction=function(){var e={};return function(i,s,o){Si.isUnd(e[i])&&(e[i]=0),t.clearTimeout(e[i]),e[i]=t.setTimeout(s,o)}}(),Si.$log=null,Si.aLog=[],Si.log=function(){function t(e,t){return"string"==typeof t&&t.length>50?t.substring(0,50):t}if(Ti&&Ti.ClientDebug&&Ci.browser&&!Ci.browser.ie9AndBelow){var i=Si.$log||e('<div style="display: none;"></div>').appendTo("body"),s=[];_.each(arguments,function(e){var i="string"==typeof e?e:JSON.stringify(e,t);0===s.length&&(i=" *** "+i+" *** "),s.push(i)}),s.push(moment().format(" *** D MMMM, YYYY, HH:mm:ss *** ")),Si.$log=i,Si.aLog.length>200&&Si.aLog.shift(),Si.aLog.push(Si.encodeHtml(s.join(", "))),i.html(Si.aLog.join("<br /><br />"))}},Si.getAjaxDataForLog=function(e,t){var i=t;if(t&&t.Result)switch(e){case"MessageList":case"MessageListByUids":i={Result:{Uids:t.Result.Uids,UidNext:t.Result.UidNext,FolderHash:t.Result.FolderHash,MessageCount:t.Result.MessageCount,MessageUnseenCount:t.Result.MessageUnseenCount,MessageResultCount:t.Result.MessageResultCount}};break;case"Message":i={Result:{Folder:t.Result.Folder,Uid:t.Result.Uid,Subject:t.Result.Subject,Size:t.Result.Size,TextSize:t.Result.TextSize,From:t.Result.From,To:t.Result.To}};break;case"Messages":i={Result:_.map(t.Result,function(e){return{Uid:e.Uid,Subject:e.Subject}})}}else t&&(i={Result:t.Result,ErrorCode:t.ErrorCode});return i},Si.getEmailParts=function(e){for(var t=e.indexOf('"'),i=e.indexOf('"',t+1),s=e.indexOf("<",i),o=-1,n=-1,r="",a="";-1!==s;)o=s,s=e.indexOf("<",s+1);return s=o,n=e.indexOf(">",s+1),-1===s?a=Si.trim(e):(r=Si.trim(-1===t?e.substring(0,s):e.substring(t+1,i)),a=Si.trim(e.substring(s+1,n))),{name:r,email:a,FullEmail:e}},Si.isCorrectEmail=function(e){return!!e.match(/^[A-Z0-9\"!#\$%\^\{\}`~&'\+\-=_\.]+@[A-Z0-9\.\-]+$/i)},Si.getIncorrectEmailsFromAddressString=function(e){for(var t=e.replace(/"[^"]*"/g,"").replace(/;/g,",").split(","),i=[],s=0,o=t.length,n="",r=null;o>s;s++)n=Si.trim(t[s]),n.length>0&&(r=Si.getEmailParts(Si.trim(t[s])),Si.isCorrectEmail(r.email)||i.push(r.email));return i},Si.getArrayRecipients=function(e){if(!e)return[];for(var t=[],i=Si.trim(e)+" ",s=0,o=0,n=!1,r='"',a=!1,l=!1,h=0,c=i.length,u="",d="",p=null,g=!1,m=0,b=0;c>h;){switch(u=i.substring(h,h+1)){case"'":case'"':n?r===u&&(n=!1):a||l||(r=u,n=!0);break;case"<":n||a||l||(a=!0);break;case">":a&&(a=!1);break;case"(":n||a||l||(l=!0);break;case")":l&&(l=!1);break;default:if(","!==u&&";"!==u&&h!==c-1)break;if(!a&&!l&&!n){if(o=h!==c-1?h:c,d=i.substring(s,o),Si.trim(d).length>0){for(p=Si.getEmailParts(d),g=!1,m=t.length,b=0;m>b;b++)t[b].email===p.email&&(g=!0);!g&&Si.isCorrectEmail(p.email)&&t.push(p)}s=h+1}}h++}return t},Si.getImportContactsLink=function(){return"?/ImportContacts/"},Si.getExportContactsLink=function(e){return"?/Raw/Contacts"+e+"/"},Si.getExportCalendarLinkByHash=function(e,t){return"?/Raw/Calendar/"+e+"/"+t},Si.getDownloadLinkByHash=function(e,t,i,s){return i=Si.isUnd(i)?!1:!!i,s=Si.isUnd(s)?"":s,"?/Raw/Download/"+e+"/"+t+"/"+(i?"1":"0")+(""===s?"":"/"+s)},Si.getViewLinkByHash=function(e,t,i,s){return i=Si.isUnd(i)?!1:!!i,s=Si.isUnd(s)?"":s,"?/Raw/View/"+e+"/"+t+"/"+(i?"1":"0")+(""===s?"":"/"+s)},Si.getIframeLinkByHash=function(e,t,i,s){return i=Si.isUnd(i)?!1:!!i,s=Si.isUnd(s)?"":s,"?/Raw/Iframe/"+e+"/"+t+"/"+(i?"1":"0")+(""===s?"":"/"+s)},Si.getIframeWrappwer=function(e,i){return"?/Raw/Iframe/"+e+"/"+t.encodeURIComponent(i)+"/"},Si.getViewThumbnailLinkByHash=function(e,t,i,s){return i=Si.isUnd(i)?!1:!!i,s=Si.isUnd(s)?"":s,"?/Raw/Thumbnail/"+e+"/"+t+"/"+(i?"1":"0")+(""===s?"":"/"+s)},Si.getFilestorageDownloadLinkByHash=function(e,t,i){var s="?/Raw/FilesDownload/"+e+"/"+t;return Si.isUnd(i)||(s=s+"/0/"+i),s},Si.getFilestorageViewLinkByHash=function(e,t,i){var s="?/Raw/FilesView/"+e+"/"+t;return Si.isUnd(i)||(s=s+"/0/"+i),s},Si.getFilestorageViewThumbnailLinkByHash=function(e,t,i){var s="?/Raw/FilesThumbnail/"+e+"/"+t;return Si.isUnd(i)||(s=s+"/0/"+i),s},Si.getFilestoragePublicViewLinkByHash=function(e){return"?/Window/Files/0/"+e},Si.getFilestoragePublicDownloadLinkByHash=function(e){return"?/Raw/FilesPub/0/"+e},Si.daysInMonth=function(e,t){return e>0&&13>e&&t>0?new Date(t,e,0).getDate():31},Si.getAppPath=function(){return t.location.protocol+"//"+t.location.host+t.location.pathname},Si.WindowOpener={_iDefaultRatio:.8,_aOpenedWins:[],openMessage:function(e,t){if(e){var i=e.folder(),s=e.uid(),o="",n=null;o=Ci.Routing.buildHashFromArray(t?[vi.Screens.SingleCompose,"drafts",i,s]:[vi.Screens.SingleMessageView,i,"msg"+s]),n=this.openTab(o)}},openTab:function(e){var i=null;return i=t.open(e,"_blank"),i.focus(),i.name=Ti.Accounts.currentId(),this._aOpenedWins.push(i),i},open:function(e,i,s){var o=s?",menubar=yes":",menubar=no",n="location=no,toolbar=no,status=no,scrollbars=yes,resizable=yes"+o,r=null;return i=i.replace(/\W/g,""),n+=this._getSizeParameters(),r=t.open(e,i,n),r.focus(),r.name=Ti.Accounts.currentId(),this._aOpenedWins.push(r),r},closeAll:function(){for(var e=this._aOpenedWins.length,t=0,i=null;e>t;t++)i=this._aOpenedWins[t],i.closed||i.close();this._aOpenedWins=[]},_getSizeParameters:function(){var e=t.screen.width,i=Math.ceil(e*this._iDefaultRatio),s=Math.ceil((e-i)/2),o=t.screen.height,n=Math.ceil(o*this._iDefaultRatio),r=Math.ceil((o-n)/2);return",width="+i+",height="+n+",top="+r+",left="+s}},Si.delegateRun=function(e,t,i){e&&e[t]&&e[t].apply(e,_.isArray(i)?i:[])},Si.strRepeat=function(e,t){return new Array(t+1).join(e)},Si.deferredUpdate=function(e,i,s,o){!e.__interval&&i?(e.__state=!0,o(e,!0),e.__interval=t.setInterval(function(){e.__state||(o(e,!1),t.clearInterval(e.__interval),e.__interval=null)},s)):i||(e.__state=!1)},Si.draggableMessages=function(){return e('<div class="draggable draggableMessages"><div class="content"><span class="count-text"></span></div></div>').appendTo("#pSevenHidden")},Si.draggableContacts=function(){return e('<div class="draggable draggableContacts"><div class="content"><span class="count-text"></span></div></div>').appendTo("#pSevenHidden")},Si.removeActiveFocus=function(){if(document&&document.activeElement&&document.activeElement.blur){var t=e(document.activeElement);(t.is("input")||t.is("textarea"))&&document.activeElement.blur()}},Si.uiDropHelperAnim=function(i,s){var o=0,n=0,r=0,a=0,l=0,h=0,c=s.helper.clone().appendTo("#pSevenHidden"),u=e(i.target).find(".animGoal"),d=null;u=e(u[0]?u[0]:i.target),d=u&&u[0]?u.offset():null,d&&(o=t.Math.round(d.left),n=t.Math.round(d.top),l=u.width(),h=u.height(),r=o,l>0&&(r+=t.Math.round(l/2)),a=n,h>0&&(a+=t.Math.round(h/2)),c.animate({left:r+"px",top:a+"px","font-size":"0px",opacity:0},800,"easeOutQuint",function(){e(this).remove()}))},Si.isTextFieldFocused=function(){var e=document&&document.activeElement?document.activeElement:null,t=e?e.tagName:null,i=e&&e.type?e.type.toLowerCase():null,s=e?e.contentEditable:null;return"INPUT"===t&&("text"===i||"password"===i||"email"===i)||"TEXTAREA"===t||"IFRAME"===t||"true"===s},Si.removeSelection=function(){t.getSelection?t.getSelection().removeAllRanges():document.selection&&document.selection.empty()},Si.getMonthNamesArray=function(){for(var e=Si.i18n("DATETIME/MONTH_NAMES").split(" "),t=12,i=e.length;t>i;i++)e[i]="";return e},Si.getPlural=function(e,t){var i=0;switch(t=Si.pInt(t),e){case"Arabic":i=0===t?0:1===t?1:2===t?2:t%100>=3&&10>=t%100?3:t%100>=11?4:5;break;case"Bulgarian":i=1===t?0:1;break;case"Chinese-Simplified":i=0;break;case"Chinese-Traditional":i=1===t?0:1;break;case"Czech":i=1===t?0:t>=2&&4>=t?1:2;break;case"Danish":i=1===t?0:1;break;case"Dutch":i=1===t?0:1;break;case"English":i=1===t?0:1;break;case"Estonian":i=1===t?0:1;break;case"Finish":i=1===t?0:1;break;case"French":i=1===t?0:1;break;case"German":i=1===t?0:1;break;case"Greek":i=1===t?0:1;break;case"Hebrew":i=1===t?0:1;break;case"Hungarian":i=1===t?0:1;break;case"Italian":i=1===t?0:1;break;case"Japanese":i=0;break;case"Korean":i=0;break;case"Latvian":i=t%10===1&&t%100!==11?0:0!==t?1:2;break;case"Lithuanian":i=t%10===1&&t%100!==11?0:t%10>=2&&(10>t%100||t%100>=20)?1:2;break;case"Norwegian":i=1===t?0:1;break;case"Persian":i=0;break;case"Polish":i=1===t?0:t%10>=2&&4>=t%10&&(10>t%100||t%100>=20)?1:2;break;case"Portuguese-Portuguese":i=1===t?0:1;break;case"Portuguese-Brazil":i=1===t?0:1;break;case"Romanian":i=1===t?0:0===t||t%100>0&&20>t%100?1:2;break;case"Russian":i=t%10===1&&t%100!==11?0:t%10>=2&&4>=t%10&&(10>t%100||t%100>=20)?1:2;break;case"Serbian":i=t%10===1&&t%100!==11?0:t%10>=2&&4>=t%10&&(10>t%100||t%100>=20)?1:2;break;case"Spanish":i=1===t?0:1;break;case"Swedish":i=1===t?0:1;break;case"Thai":i=0;break;case"Turkish":i=1===t?0:1;break;case"Ukrainian":i=t%10===1&&t%100!==11?0:t%10>=2&&4>=t%10&&(10>t%100||t%100>=20)?1:2;break;default:i=0}return i},Si.getFileExtension=function(e){var t="",i=e.lastIndexOf(".");return i>-1&&(t=e.substr(i+1)),t},Si.getFileNameWithoutExtension=function(e){var t=e,i=e.lastIndexOf(".");return i>-1&&(t=e.substr(0,i)),t},Si.defaultOptionsAfterRender=function(e,t){t&&(Si.isUnd(t.disable)||i.applyBindingsToNode(e,{disable:t.disable},t))},Si.getDateFormatForMoment=function(e){var t="MM/DD/YYYY";switch(e){case"MM/DD/YYYY":t="MM/DD/YYYY";break;case"DD/MM/YYYY":t="DD/MM/YYYY";break;case"DD Month YYYY":t="DD MMMM YYYY"}return t},Si.getDateFormatForDatePicker=function(e){var t="mm/dd/yy";switch(e){case"MM/DD/YYYY":t="mm/dd/yy";break;case"DD/MM/YYYY":t="dd/mm/yy";break;case"DD Month YYYY":t="dd MM yy"}return t},Si.getDateFormatsForSelector=function(){return _.map(Ti.App.DateFormats,function(e){switch(e){case"MM/DD/YYYY":return{name:Si.i18n("DATETIME/DATEFORMAT_MMDDYYYY"),value:e};case"DD/MM/YYYY":return{name:Si.i18n("DATETIME/DATEFORMAT_DDMMYYYY"),value:e};case"DD Month YYYY":return{name:Si.i18n("DATETIME/DATEFORMAT_DDMONTHYYYY"),value:e};default:return{name:e,value:e}}})},Si.getTitleForEvent=function(e){var t=e?Si.trim(e.replace(/[\n\r]/," ")):"",i=t.indexOf(" ",180);return i>=0&&(t=t.substring(0,i)+"..."),t.length>200&&(t=t.substring(0,200)+"..."),t},Si.desktopNotify=function(){var e=[],i=0;return function(s){if(Ti.User.DesktopNotifications&&t.Notification&&!Ci.focused())if(s&&"show"===s.action&&t.Notification.permission!==vi.notificationPermission.Denied){var o,n={body:s.body||"",dir:s.dir||"auto",lang:s.lang||"",tag:s.tag||Math.floor(900*Math.random()+100),icon:s.icon||!1},r=function(){o=new t.Notification(s.title,n),o.onclick=function(){s.callback&&s.callback(),o.close()},o.onshow=function(){},o.onclose=function(){},o.onerror=function(){},s.timeout&&(i=setTimeout(function(){o.close()},s.timeout)),e.push(o)};"granted"===t.Notification.permission?r():"default"===t.Notification.permission&&t.Notification.requestPermission(function(e){"granted"===e&&r()})}else s&&"hide"===s.action?_.each(e,function(t,i){s.tag===t.tag&&(t.close(),e.splice(i,1))}):s&&"hideAll"===s.action&&(_.each(e,function(e){e.close()}),e.length=0)}}(),Si.isRTL=function(){return wi.hasClass("rtl")},Si.validateFileOrFolderName=function(e){return e=Si.trim(e),""!==e&&!/["\/\\*?<>|:]/.test(e)},Si.shadeColor=function(e,i){var s=!1,o=0,n=0,r=0,a=0;return"#"===e[0]&&(e=e.slice(1),s=!0),o=t.parseInt(e,16),n=(o>>16)+i,n>255?n=255:0>n&&(n=0),r=(o>>8&255)+i,r>255?r=255:0>r&&(r=0),a=(255&o)+i,a>255?a=255:0>a&&(a=0),(s?"#":"")+(a|r<<8|n<<16).toString(16)},Si.extend=function(e,t){var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e},Si.thumbQueue=function(){var e={},t={},i=2;return function(s,o,n){o&&n?!(s in t)||t[s]>0?(s in t||(t[s]=i,e[s]=[]),t[s]--,n(o)):e[s].push({imageSrc:o,imageSrcObserver:n,messageUid:s}):e[s]&&e[s].length&&(e[s][0].imageSrcObserver(e[s][0].imageSrc),e[s].shift())}}(),Si.checkConnection=function(){var e=-1,t=(new Date).getTime(),i=0,s=!1;return setInterval(function(){i=(new Date).getTime(),s=i>t+5e3+1e3,t=i,s&&Ci.Api.hideError(!0)},5e3),function(t,i){clearTimeout(e),"error"!==i?Ci.Api.hideError(!0):"Ping"===t?(Ci.Api.showError(Si.i18n("WARNING/NO_INTERNET_CONNECTION"),!1,!0,!0),e=setTimeout(function(){Ci.Ajax.send({Action:"Ping"})},6e4)):Ci.Ajax.send({Action:"Ping"})}}(),Si.loadScript=function(e,i,s,o){var n=document.createElement("script");!Si.isUnd(o)&&i&&(t[o]=i),Si.isUnd(s)&&(s={}),_.each(s,function(e,t){n.setAttribute(t,e)}),n.type="text/javascript",n.src=e,document.body.appendChild(n)},Si.registerMailto=function(e){!t.navigator||!Si.isFunc(t.navigator.registerProtocolHandler)||e&&1===Ci.Storage.getData("MailtoAsked")||(t.navigator.registerProtocolHandler("mailto",Si.getAppPath()+"#"+vi.Screens.Compose+"/to/%s",""!==Ti.App.SiteName?Ti.App.SiteName:"WebMail"),Ci.Storage.setData("MailtoAsked",1))},Si.CustomTooltip={_$Region:null,_$ArrowTop:null,_$Text:null,_$ArrowBottom:null,_iArrowBorderLeft:0,_iArrowMarginLeft:0,_iLeftShift:0,_bInitialized:!1,init:function(){this._bInitialized||(this._$Region=e('<span class="custom_tooltip"></span>').appendTo("body").hide(),this._$ArrowTop=e('<span class="custom_tooltip_arrow top"></span>').appendTo(this._$Region),this._$Text=e('<span class="custom_tooltip_text"></span>').appendTo(this._$Region),this._$ArrowBottom=e('<span class="custom_tooltip_arrow bottom"></span>').appendTo(this._$Region),this._iArrowMarginLeft=Si.pInt(this._$ArrowTop.css("margin-left")),this._iArrowBorderLeft=Si.pInt(this._$ArrowTop.css("border-left-width")),this._iLeftShift=this._iArrowBorderLeft+this._iArrowMarginLeft+Si.pInt(this._$Region.css("margin-left")),this._bInitialized=!0),this._$ArrowTop.show(),this._$ArrowBottom.hide(),this._$ArrowTop.css({"margin-left":this._iArrowMarginLeft+"px"}),this._$ArrowBottom.css({"margin-left":this._iArrowMarginLeft+"px"})},show:function(t,i){this.init();var s=i.offset(),o=Math.round(i.innerWidth()/2),n=this._iLeftShift-o;this._$Text.html(t),this._$Region.fadeIn().css({top:s.top+i.height(),left:s.left-n,right:"auto"}),e("body").height()<this._$Region.height()+this._$Region.offset().top&&(this._$ArrowTop.hide(),this._$ArrowBottom.show(),this._$Region.css({top:s.top-this._$Region.height()})),e("body").width()<this._$Region.outerWidth(!0)+this._$Region.offset().left&&(this._$Region.css({left:"auto",right:0}),this._$ArrowTop.css({"margin-left":o+s.left-this._$Region.offset().left-this._iArrowBorderLeft+"px"}))},hide:function(){this._bInitialized&&this._$Region.hide()}},i.bindingHandlers.command={init:function(t,s,o,n){var r=e(t),a=s();if(!a||!a.enabled||!a.canExecute)throw new Error("You are not using command function");r.addClass("command"),i.bindingHandlers[r.is("form")?"submit":"click"].init.apply(n,arguments)},update:function(t,i){var s=!0,o=e(t),n=i();s=n.enabled(),o.toggleClass("command-not-enabled",!s),s&&(s=n.canExecute(),o.toggleClass("unavailable",!s)),o.toggleClass("command-disabled disable disabled",!s),o.toggleClass("command-disabled",!s)}},i.bindingHandlers.simpleTemplate={init:function(t,s){var o=i.utils.unwrapObservable(s()),n=e("#"+o);n&&n[0]&&e(t).html(n.html().replace(/<script(.*?)>/i,"<script$1>").replace(/<\/script(.*?)>/i,"</script>"))}},i.bindingHandlers.findFocused={init:function(t){var i=e(t),s=null;s=i.find(".catch-focus"),s&&1===s.length&&s[0]&&s.on("blur",function(){i.removeClass("focused")}).on("focus",function(){i.addClass("focused")})}},i.bindingHandlers.findFilled={init:function(t){var i=e(t),s=null,o=null;s=i.find(".catch-filled"),s&&1===s.length&&s[0]&&(o=function(){i.toggleClass("filled",""!==s.val())},o(),_.delay(o,200),s.on("change",o))}},i.bindingHandlers.alert={init:function(e,s){t.alert(i.utils.unwrapObservable(s()))},update:function(e,s){t.alert(i.utils.unwrapObservable(s()))}},i.bindingHandlers.onEnter={init:function(s,o,n,r){i.bindingHandlers.event.init(s,function(){return{keyup:function(i,n){n&&13===t.parseInt(n.keyCode,10)&&(e(s).trigger("change"),o().call(this,i))}}},n,r)}},i.bindingHandlers.onCtrlEnter={init:Ii?null:function(s,o,n,r){i.bindingHandlers.event.init(s,function(){return{keydown:function(i,n){return n&&13===t.parseInt(n.keyCode,10)&&n.ctrlKey?(e(s).trigger("change"),o().call(this,i),!1):!0}}},n,r)}},i.bindingHandlers.onEsc={init:Ii?null:function(s,o,n,r){i.bindingHandlers.event.init(s,function(){return{keyup:function(i,n){n&&27===t.parseInt(n.keyCode,10)&&(e(s).trigger("change"),o().call(this,i))}}},n,r)}},i.bindingHandlers.onFocusSelect={init:function(e,t,s,o){i.bindingHandlers.event.init(e,function(){return{focus:function(){e.select()}}},s,o)}},i.bindingHandlers.onEnterChange={init:function(s,o,n,r){i.bindingHandlers.event.init(s,function(){return{keyup:function(i,o){o&&13===t.parseInt(o.keyCode,10)&&e(s).trigger("change")}}},n,r)}},i.bindingHandlers.fadeIn={update:function(t,s){i.utils.unwrapObservable(s())&&e(t).hide().fadeIn("fast")}},i.bindingHandlers.fadeOut={update:function(t,s){i.utils.unwrapObservable(s())&&e(t).fadeOut()}},i.bindingHandlers.csstext={init:function(t,s){t&&t.styleSheet&&!Si.isUnd(t.styleSheet.cssText)?t.styleSheet.cssText=i.utils.unwrapObservable(s()):e(t).text(i.utils.unwrapObservable(s()))},update:function(t,s){t&&t.styleSheet&&!Si.isUnd(t.styleSheet.cssText)?t.styleSheet.cssText=i.utils.unwrapObservable(s()):e(t).text(i.utils.unwrapObservable(s()))}},i.bindingHandlers.i18n={init:function(t,i){var s=e(t).data("i18n"),o=s?Si.i18n(s):s;if(""!==o)switch(i()){case"value":e(t).val(o);break;case"text":e(t).text(o);break;case"html":e(t).html(o);break;case"title":e(t).attr("title",o);break;case"placeholder":e(t).attr({placeholder:o})}}},i.bindingHandlers.link={init:function(t,s){e(t).attr("href",i.utils.unwrapObservable(s()))}},i.bindingHandlers.title={init:function(t,s){e(t).attr("title",i.utils.unwrapObservable(s()))},update:function(t,s){e(t).attr("title",i.utils.unwrapObservable(s()))}},i.bindingHandlers.initDom={init:function(t,i){if(i())if(_.isArray(i()))for(var s=i(),o=s.length-1;o>=0;o--)s[o](e(t));else i()(e(t))}},i.bindingHandlers.customScrollbar={init:Ii?null:function(t,i){if(!Ri){var s=e(t),o=i();o=o,s.addClass("scroll-wrap").customscroll(o),Si.isUnd(o.reset)||(t._customscroll_reset=_.throttle(function(){s.data("customscroll").reset()},100)),!Si.isUnd(o.scrollToTopTrigger)&&Si.isFunc(o.scrollToTopTrigger.subscribe)&&o.scrollToTopTrigger.subscribe(function(){s.data("customscroll")&&s.data("customscroll").scrollToTop()}),!Si.isUnd(o.scrollToBottomTrigger)&&Si.isFunc(o.scrollToBottomTrigger.subscribe)&&o.scrollToBottomTrigger.subscribe(function(){s.data("customscroll")&&s.data("customscroll").scrollToBottom()}),!Si.isUnd(o.scrollTo)&&Si.isFunc(o.scrollTo.subscribe)&&o.scrollTo.subscribe(function(){s.data("customscroll")&&s.data("customscroll").scrollTo(o.scrollTo())})}},update:Ii?null:function(t,i){Ri||(t._customscroll_reset&&t._customscroll_reset(),Si.isUnd(i().top)||e(t).data("customscroll").vertical.set(i().top))}},i.bindingHandlers.customOptions={init:function(){return{controlsDescendantBindings:!0}},update:function(e,t,s,o,n){for(var r=0,a=0,l=i.utils.arrayMap(i.utils.arrayFilter(e.childNodes,function(e){return e.tagName&&"OPTION"===e.tagName&&e.selected}),function(e){return i.selectExtensions.readValue(e)||e.innerText||e.textContent}),h=e.scrollTop,c=i.utils.unwrapObservable(t());e.length>0;)i.cleanNode(e.options[0]),e.remove(0);if(c){"number"!=typeof c.length&&(c=[c]);var u=s().optionsBind;for(r=0,a=c.length;a>r;r++){var d=document.createElement("OPTION"),p=i.utils.unwrapObservable(c[r]);i.selectExtensions.writeValue(d,p),d.appendChild(document.createTextNode(p)),e.appendChild(d),u&&(d.setAttribute("data-bind",u),i.applyBindings(n.createChildContext(p),d))}var g=e.getElementsByTagName("OPTION"),m=0,b=navigator.userAgent.indexOf("MSIE 6")>=0;for(r=0,a=g.length;a>r;r++)i.utils.arrayIndexOf(l,i.selectExtensions.readValue(g[r]))>=0&&(b?g[r].setAttribute("selected",!0):g[r].selected=!0,m++);e.scrollTop=h,m<l.length&&i.utils.triggerEvent(e,"change")}}},i.bindingHandlers.splitter={init:Ii?null:function(t,i){var s=e(t),o=i();setTimeout(function(){s.splitter(_.defaults(o,{}))},1)}},i.bindingHandlers.dropdown={init:function(i,s,o,n){var r,a,l,h=e(i),c=_.defaults(s(),{disabled:"disabled",expand:"expand",control:!0,container:".dropdown_content",scrollToTopContainer:".scroll-inner",passClick:!0,trueValue:!0}),u=c.control?h.find(".control"):h,d=h.find(".dropdown_helper"),p=h.find(".dropdown_arrow"),g=e(document),m=!1,b=function(){Si.isUnd(c.callback)||c.callback.call(n,h.hasClass(c.expand)?c.trueValue:!1,h)},f=function(e){e.stopPropagation()},y=function(){c.scrollToTopContainer&&h.find(c.scrollToTopContainer).scrollTop(0)},v=function(e){Si.isUnd(e)&&(e=!h.hasClass(c.expand)),!e&&h.hasClass(c.expand)&&y(),h.toggleClass(c.expand,e)},S=function(i){r=d.offset(),Si.isUnd(r)||(a=r.left+10,l=e(t).width()-(a+d.outerWidth()),l>0&&(l=0),d.css("left",i||l+"px"),p.css("left",i||Math.abs(l?l+parseInt(p.css("margin-left")):0)+"px"))};c.passClick||(h.find(c.container).click(f),u.click(f)),v(!1),c.close&&c.close.subscribe&&c.close.subscribe(function(e){e||(g.unbind("click.dropdown"),v(!1)),b()}),h.on("mousedown",function(t){m=e(t.target).hasClass("customscroll-scrollbar")||e(t.target.parentElement).hasClass("customscroll-scrollbar")}),u.click(function(){h.hasClass(c.disabled)||m||(v(),_.defer(function(){b()}),h.hasClass(c.expand)&&(c.close&&c.close.subscribe&&c.close(!0),_.defer(function(){g.on("click.dropdown",function(e){!c.passClick&&e.button===vi.MouseKey.Right||m||(g.unbind("click.dropdown"),c.close&&c.close.subscribe&&c.close(!1),v(!1),b(),S(0)),m=!1})}),S()))})}},i.bindingHandlers.customSelect={init:function(t,i,s,o){var n=e(t),r=_.defaults(i(),{disabled:"disabled",selected:"selected",expand:"expand",control:!0,input:!1,expandState:function(){}}),a=[],l=r.control?n.find(".control"):n,h=n.find(".dropdown_content"),c=n.find(".link"),u=function(t){_.each(a,function(e){e.removeClass(r.selected)});var i=_.find(r.options,function(e){return e[r.optionsValue]===t});return Si.isUnd(i)?i=r.options[0]:(a[_.indexOf(r.options,i)].addClass(r.selected),c.text(e.trim(i[r.optionsText]))),i[r.optionsValue]},d=function(t){h.empty(),a=[],_.each(t?t:r.options,function(t){var i=e('<span class="item"></span>').text(t[r.optionsText]).data("value",t[r.optionsValue]),s=t.isDisabled;s?i.data("isDisabled",s).addClass("disabled"):i.data("isDisabled",s).removeClass("disabled"),a.push(i),h.append(i)},this)};d(),h.on("click",".item",function(){var t=e(this);t.data("isDisabled")||r.value(t.data("value"))}),!r.input&&r.value&&r.value.subscribe&&(r.value.subscribe(function(){var e=u(r.value());r.value()!==e&&r.value(e)},o),r.value.valueHasMutated()),r.input&&r.value&&r.value.subscribe&&(r.value.subscribe(function(){u(r.value())},o),r.value.valueHasMutated()),r.input&&r.value&&r.value.subscribe&&(r.value.subscribe(function(){u(r.value())},o),r.value.valueHasMutated()),r.alarmOptions&&r.alarmOptions.subscribe(function(){d()},o),r.timeOptions&&r.timeOptions.subscribe(function(e){d(e)},o),n.removeClass(r.expand),l.click(function(){if(!n.hasClass(r.disabled)&&(n.toggleClass(r.expand),r.expandState(n.hasClass(r.expand)),n.hasClass(r.expand))){var t=n.find(".dropdown_content"),i=t.find(".selected");i.position()&&(t.scrollTop(0),t.scrollTop(i.position().top-100)),_.defer(function(){e(document).one("click",function(){n.removeClass(r.expand),r.expandState(!1)})})}})}},i.bindingHandlers.moveToFolderFilter={init:function(t,i){var s=e(t),o=i(),n=e(t).find(o.container),r=_.isArray(o.options)?o.options:o.options(),a=o.value?o.value():"",l=_.find(r,function(e){return e[o.optionsValue]===a});l||(a="",o.value("")),s.removeClass("expand"),n.empty(),_.each(r,function(t){var i=e('<span class="item"></span>').text(t[o.optionsText]).data("value",t[o.optionsValue]);a===t[o.optionsValue]&&i.addClass("selected"),t.jq=i,n.append(i)}),n.on("click",".item",function(){var t=e(this).data("value");o.value(t)}),s.click(function(){s.toggleClass("expand"),s.hasClass("expand")&&_.defer(function(){e(document).one("click",function(){s.removeClass("expand")})})})},update:function(t,i){var s=e(t),o=i(),n=_.isArray(o.options)?o.options:o.options(),r=o.value?o.value():"",a=_.find(n,function(e){return e[o.optionsValue]===r}),l=s.find(".link");_.each(n,function(e){e.jq&&e.jq.toggleClass("selected",r===e[o.optionsValue])}),a&&l.text(e.trim(a[o.optionsText]))}},i.bindingHandlers.contactcard={init:Ii?null:function(t,i){var s=e(t),o=!1,n=_.defaults(i(),{disabled:"disabled",expand:"expand",control:!0}),r=n.control?s.find(".control"):s;void 0!==n.trigger&&void 0!==n.trigger.subscribe&&(s.removeClass(n.expand),r.bind({mouseover:function(){!s.hasClass(n.disabled)&&n.trigger()&&(o=!0,_.delay(function(){o&&(void 0!==n.controlWidth&&void 0!==n.controlWidth.subscribe&&n.controlWidth(r.width()),s.addClass(n.expand))},200))},mouseout:function(){n.trigger()&&(o=!1,_.delay(function(){o||s.removeClass(n.expand)},200))}}))}},i.bindingHandlers.checkmail={update:function(t,i){var s=t.oOptions||null,o=t.jqElement||null,n=t.oIconIE||null,r=i(),a=r.state;void 0!==r.state&&(o||(t.jqElement=o=e(t)),s||(t.oOptions=s=_.defaults(r,{activeClass:"process",duration:800})),Si.deferredUpdate(o,a,s.duration,function(e,i){if(Ci.browser.ie9AndBelow)if(n||(t.oIconIE=n=o.find(".icon")),!n.__intervalIE&&i){var r=0,a="";n.__intervalIE=setInterval(function(){a="0px -"+20*r+"px",r=7>r?r+1:0,n.css({"background-position":a})},1e3/12)}else n.css({"background-position":"0px 0px"}),clearInterval(n.__intervalIE),n.__intervalIE=null;else e.toggleClass(s.activeClass,i)}))}},i.bindingHandlers.heightAdjust={update:function(t,i){var s=t.jqElement||null,o=0,n=i().location,r=i().delay||400;s||(t.jqElement=s=e(t)),_.delay(function(){_.each(i().elements,function(e){var t=e();t&&(o+=t.is(":visible")?t.outerHeight():0)}),"top"===n||void 0===n?s.css({"padding-top":o,"margin-top":-o}):"bottom"===n&&s.css({"padding-bottom":o,"margin-bottom":-o})},r)}},i.bindingHandlers.triggerInview={update:function(t,i){i().trigger().length<=0||_.defer(function(){var s=e(t),o=s.height(),n=i(),r=null,a=null;n=n,r=s.find(n.selector),r.each(function(){this.$el=e(this),this.inviewHeight=this.$el.height(),this.inview=!1}),a=_.debounce(function(){r.each(function(){var e=this.inview||!1,t=this.$el.position().top+parseInt(this.$el.css("margin-top"),10);t>0&&o>t?e||(this.inview=!0,this.$el.trigger("inview")):this.inview=!1})},2e3),s.scroll(a),a()})}},i.bindingHandlers.watchWidth={init:function(t,i){var s=!1;s||i().subscribe(function(){i()(e(t).outerWidth()),s=!0},this)}},i.bindingHandlers.columnCalc={init:function(i,s){var o=e(i),n=s().prop,r=null,a=0;r=o.find(s().itemSelector),void 0!==r[0]&&(a=r.outerWidth(!0),a=1>=a?1:a,n&&e(t).bind("resize",function(){var e=o.width();n(e>0?Math.floor(e/a):1)}))}},i.bindingHandlers.quickReplyAnim={update:Ii?null:function(t,i){var s=t.jqTextarea||null,o=t.jqStatus||null,n=t.jqButtons||null,r=t.jqElement||null,a=t.oPrevActions||null,l=i(),h=null;h=_.defaults(l,{saveAction:!1,sendAction:!1,activeAction:!1}),r||(t.jqElement=r=e(t),t.jqTextarea=s=r.find("textarea"),t.jqStatus=o=r.find(".status"),t.jqButtons=n=r.find(".buttons"),t.oPrevActions=a={saveAction:null,sendAction:null,activeAction:null}),r.is(":visible")&&(Ci.browser.ie9AndBelow?(!s||r.defualtHeight||s.defualtHeight||(r.defualtHeight=r.outerHeight(),s.defualtHeight=s.outerHeight(),o.defualtHeight=n.outerHeight(),n.defualtHeight=n.outerHeight()),_.defer(function(){var e=a.activeAction!==h.activeAction,t=a.sendAction!==h.sendAction,i=a.saveAction!==h.saveAction;e&&(h.activeAction?(s.animate({height:s.defualtHeight+50},300),r.animate({"max-height":r.defualtHeight+n.defualtHeight+50},300)):(s.animate({height:s.defualtHeight},300),r.animate({"max-height":r.defualtHeight},300))),(t||i)&&(h.sendAction?(r.animate({"max-height":"30px"},300),o.animate({"max-height":"30px",opacity:1},300)):h.saveAction?r.animate({"max-height":0},300):(r.animate({"max-height":r.defualtHeight+n.defualtHeight+50},300),o.animate({"max-height":0,opacity:0},300)))})):(r.toggleClass("saving",h.saveAction),r.toggleClass("sending",h.sendAction),r.toggleClass("active",h.activeAction))),_.defer(function(){a=h})}},i.extenders.reversible=function(e){var t=e();return e.commit=function(){t=e()},e.revert=function(){e(t)},e.commitedValue=function(){return t},e.changed=function(){return t!==e()},e},i.extenders.autoResetToFalse=function(e,i){return e.iTimeout=0,e.subscribe(function(s){s&&(t.clearTimeout(e.iTimeout),e.iTimeout=t.setTimeout(function(){e.iTimeout=0,e(!1)},Si.pInt(i)))}),e},Si.createCommand=function(e,t,s){var o=t?function(){return o.canExecute&&o.canExecute()?t.apply(e,Array.prototype.slice.call(arguments)):!1}:function(){};return o.enabled=i.observable(!0),s=Si.isUnd(s)?!0:s,o.canExecute=i.computed(Si.isFunc(s)?function(){return o.enabled()&&s.call(e)}:function(){return o.enabled()&&!!s}),o},i.bindingHandlers.autocomplete={init:function(t,i){function s(e){return e.split(/,\s*/)}function o(e){return s(e).pop()}var n=i(),r=e(t);n&&r&&r[0]&&r.autocomplete({minLength:1,autoFocus:!0,source:function(e,t){n(o(e.term),t)},search:function(){var e=o(this.value);return e.length<1?!1:!0},focus:function(){return!1},select:function(e,t){var i=s(this.value),o=null;return i.pop(),i.push(t.item.value),i.push(""),this.value=i.join(", ").slice(0,-2),r.trigger("change"),o=function(e){var t=e.value.length;e.blur(),e.focus(),e.setSelectionRange&&e.setSelectionRange(t,t)},o(r[0]),!1}})}},i.bindingHandlers.autocompleteSimple={init:function(t,i){var s=e(t),o=i(),n=o.callback,r=o.dataAccessor;n&&s&&s[0]&&s.autocomplete({minLength:1,autoFocus:!0,position:{collision:"flip"},source:function(e,t){n(e.term,t)},focus:function(){return!1},select:function(e,t){return _.delay(function(){s.trigger("change")},5),r&&r(t.item),!0}})}},i.bindingHandlers.draggablePlace={init:Ii?null:function(t,s,o,n){if(null===s())return null;var r=o?o():null;e(t).draggable({distance:20,handle:".dragHandle",cursorAt:{top:0,left:0},helper:function(e){return s().call(n,e&&e.target?i.dataFor(e.target):null)},start:r&&r.draggableDragStartCallback?r.draggableDragStartCallback:Si.emptyFunction,stop:r&&r.draggableDragStopCallback?r.draggableDragStopCallback:Si.emptyFunction}).on("mousedown",function(){Si.removeActiveFocus()})}},i.bindingHandlers.droppable={init:Ii?null:function(t,i){var s=i(),o=s.valueFunc,n=s.switchObserv;!1!==o&&e(t).droppable({hoverClass:"droppableHover",drop:function(e,t){o(e,t)}}),n&&o!==!1&&(n.subscribe(function(i){e(t).data().droppable&&e(t).droppable(i?"disable":"enable")},this),n.valueHasMutated())}},i.bindingHandlers.draggable={init:Ii?null:function(t,s){e(t).attr("draggable",i.utils.unwrapObservable(s()))}},i.bindingHandlers.autosize={init:function(t,i){var s=e(t),o=i(),n=s.height(),r=s.outerHeight(),a=s.innerHeight(),l=r-a,h=a-n,c=o.minHeight?o.minHeight:0,u=o.maxHeight?o.maxHeight:0,d=o.scrollableHeight?o.scrollableHeight:1e3,p=o.autosizeTrigger?o.autosizeTrigger:null,g=function(e){var t=0;Ci.browser.firefox&&(t=2*parseInt(s.css("padding-top"),10)),u?setTimeout(function(){s.prop("scrollHeight")<u?(s.height(c-h-l),s.height(s.prop("scrollHeight")+t-h)):s.height(u-h-l) },100):(e||s.prop("scrollHeight")<d)&&setTimeout(function(){s.height(c-h-l),s.height(s.prop("scrollHeight")+t-h)},100)};s.on("keydown",function(){g()}),s.on("paste",function(){g()}),p&&p.subscribe(function(e){g(e)},this),g()}},i.bindingHandlers.customBind={init:function(e,t,s,o){var n=t(),r=n.onKeydown?n.onKeydown:null,a=n.onKeyup?n.onKeyup:null,l=n.onPaste?n.onPaste:null,h=n.onInput?n.onInput:null,c=n.valueObserver?n.valueObserver:null;i.bindingHandlers.event.init(e,function(){return{keydown:function(t,i){return r&&r.call(this,e,i,c),!0},keyup:function(t,i){return a&&a.call(this,e,i,c),!0},paste:function(t,i){return l&&l.call(this,e,i,c),!0},input:function(t,i){return h&&h.call(this,e,i,c),!0}}},s,o)}},i.bindingHandlers.fade={init:function(t,i){var s=e(t),o=e('<span class="faded"></span>'),n=_.defaults(i(),{color:null,css:"fadeout"}),r=n.color,a=n.css,l=function(e){if(""!==e){var t=h(e),i="rgba("+t.r+","+t.g+","+t.b;c(e,i)}},h=function(e){var t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i,i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return e=e.replace(t,function(e,t,i,s){return t+t+i+i+s+s}),i?{r:parseInt(i[1],16),g:parseInt(i[2],16),b:parseInt(i[3],16)}:null},c=function(e,t){Si.isRTL()?o.css("filter","progid:DXImageTransform.Microsoft.gradient(startColorstr='"+e+"', endColorstr='"+e+"',GradientType=1 )").css("background-image","-webkit-gradient(linear, left top, right top, color-stop(0%,"+t+",1)), color-stop(100%,"+t+",0)))").css("background-image","-moz-linear-gradient(left, "+t+",1)0%, "+t+",0)100%)").css("background-image","-webkit-linear-gradient(left, "+t+"1)0%,"+t+",0)100%)").css("background-image","-o-linear-gradient(left, "+t+",1)0%,"+t+",0)100%)").css("background-image","-ms-linear-gradient(left, "+t+",1)0%,"+t+",0)100%)").css("background-image","linear-gradient(left, "+t+",1)0%,"+t+",0)100%)"):o.css("filter","progid:DXImageTransform.Microsoft.gradient(startColorstr='"+e+"', endColorstr='"+e+"',GradientType=1 )").css("background-image","-webkit-gradient(linear, left top, right top, color-stop(0%,"+t+",0)), color-stop(100%,"+t+",1)))").css("background-image","-moz-linear-gradient(left, "+t+",0)0%, "+t+",1)100%)").css("background-image","-webkit-linear-gradient(left, "+t+",0)0%,"+t+",1)100%)").css("background-image","-o-linear-gradient(left, "+t+",0)0%,"+t+",1)100%)").css("background-image","-ms-linear-gradient(left, "+t+",0)0%,"+t+",1)100%)").css("background-image","linear-gradient(left, "+t+",0)0%,"+t+",1)100%)")};s.parent().addClass(a),s.after(o),void 0!==n.color.subscribe&&(l(r()),r.subscribe(function(e){l(e)},this))}},i.bindingHandlers.highlighter={init:function(s,o,n,r){function a(t){if(A){var i=0,s=c.text(),o=s.split(b),n=[],r='<span class="search_highlight">$&</span>';e.each(o,function(t,i){_.any(m,function(e){return e===i})?e.each(i,function(t,i){n.push(e(i.replace(/(.)/,r)))}):e.each(i,function(e,t){n.push(" "===t?document.createTextNode(" "):document.createTextNode(t))})}),t?c.empty().append(n):(i=l(),c.empty().append(n),h(i))}}function l(){var e,i,o,n,r=0;return"undefined"!=typeof t.getSelection?(e=t.getSelection().getRangeAt(0),i=e.cloneRange(),i.selectNodeContents(s),i.setEnd(e.endContainer,e.endOffset),r=i.toString().length):"undefined"!=typeof document.selection&&"Control"!==document.selection.type&&(o=document.selection.createRange(),n=document.body.createTextRange(),n.moveToElementText(s),n.setEndPoint("EndToEnd",o),r=n.text.length),r}function h(e){var i,o,n;if(!s)return!1;if(document.createRange)i=document.createRange(),i.selectNodeContents(s),i.setStart(s,e),i.setEnd(s,e),o=t.getSelection(),o.removeAllRanges(),o.addRange(i);else{if(s.createTextRange)return n=s.createTextRange(),n.collapse(!0),n.moveEnd(e),n.moveStart(e),n.select(),!0;if(s.setSelectionRange)return s.setSelectionRange(e,e),!0}return!1}var c=e(s),u=o(),d=u.valueObserver?u.valueObserver:null,p=u.highlighterValueObserver?u.highlighterValueObserver:null,g=u.highlightTrigger?u.highlightTrigger:null,m=["from:","to:","subject:","text:","email:","has:","date:","text:","body:"],b=function(){var t="";return e.each(m,function(e,i){t=e?t+"|\\b"+i:t+"\\b"+i}),new RegExp("("+t+")","g")}(),f=function(e){return e.replace(/\xC2\xA0/g," ").replace(/\xA0/g," ").replace(/[\s]+/g," ")},y=-1,v=t.navigator.language||t.navigator.userLanguage,S=["zh","zh-TW","zh-CN","zh-HK","zh-SG","zh-MO","ja","ja-JP","ko","ko-KR","vi","vi-VN","th","th-TH"],A=!_.include(S,v);i.bindingHandlers.event.init(s,function(){return{keydown:function(e,t){return t.keyCode!==vi.Key.Enter},keyup:function(e,t){var i=[vi.Key.Left,vi.Key.Right,vi.Key.Home,vi.Key.End],s=-1!==Si.inArray(t.keyCode,i);return t.keyCode===vi.Key.Shift||t.keyCode===vi.Key.Ctrl||t.keyCode===vi.Key.Dash||t.keyCode===vi.Key.Apostrophe||t.keyCode===vi.Key.Six&&t.shiftKey||s||(t.ctrlKey||y===vi.Key.Ctrl)&&t.keyCode===vi.Key.a||(d(f(c.text())),a(!1)),y=t.keyCode,!0},paste:function(){return setTimeout(function(){d(f(c.text())),a(!1)},0),!0}}},n,r),setTimeout(function(){a(!0)},0),g.notifySubscribers(),g.subscribe(function(e){setTimeout(function(){a(!!e)},0)},this),p.subscribe(function(){c.text(d())},this)}},i.bindingHandlers.quoteText={init:function(t,i,s,o){var n=(e(t),e('<span class="button_quote">'+Si.i18n("HELPDESK/BUTTON_QUOTE")+"</span>")),r=i(),a=r.actionHandler,l=!1,h=null,c="";e("#pSevenContent").append(n),e(document.body).on("click",function(t){l=!!e(t.target).parents(".posts")[0],document.getSelection?(h=document.getSelection(),h&&(c=h.toString())):c=document.selection.createRange().text,l&&""!==c.replace(/[\n\r\s]/,"")?n.css({top:t.clientY+20,left:t.clientX+20}).show():n.hide()}),n.on("click",function(){a.call(o,c)})}},i.bindingHandlers.adjustHeightToContent={init:function(t){var i=e(t),s=null,o=null,n=null;_.delay(_.bind(function(){s=e(_.max(i.find(".title .text"),function(e){return e.offsetWidth})),o=s.parent(),n=o.find(".icon"),i.css("min-width",parseInt(o.css("margin-left"))+parseInt(o.css("padding-left"))+parseInt(n.width())+parseInt(n.css("margin-left"))+parseInt(n.css("margin-right"))+parseInt(n.css("padding-left"))+parseInt(n.css("padding-right"))+parseInt(s.width())+parseInt(s.css("margin-left"))+parseInt(s.css("padding-left"))+10)},this),1)}},i.bindingHandlers.customTooltip={update:Ii?null:function(t,i){var s=Si.i18n(i());e(t).attr("title",s)}},a.prototype.init=function(e){this.defaultScreen=e,o.initialized.removeAll(),o.changed.removeAll(),o.initialized.add(this.parseRouting,this),o.changed.add(this.parseRouting,this),o.init(),o.initialized.removeAll()},a.prototype.finalize=function(){o.dispose(),this.setHashFromString("")},a.prototype.setHashFromString=function(e){var t=location.hash===decodeURIComponent(e);return t||(location.hash=e),t},a.prototype.replaceHashWithoutPart=function(e){var t=location.hash.replace(e,"");this.replaceHashFromString(t)},a.prototype.replaceHashFromString=function(e){location.hash!==e&&location.replace(e)},a.prototype.setHash=function(e){return this.setHashFromString(this.buildHashFromArray(e))},a.prototype.replaceHash=function(e){this.replaceHashFromString(this.buildHashFromArray(e))},a.prototype.setPreviousHash=function(){location.hash=this.previousHash()},a.prototype.buildHashFromArray=function(e){var t=0,i=0,s="";if(_.isArray(e))for(i=e.length;i>t;t++)e[t]=encodeURIComponent(e[t]);else e=[encodeURIComponent(e.toString())];return s=e.join("/"),""!==s&&(s="#"+s),s},a.prototype.getHashFromHref=function(){var e=location.href.indexOf("#"),t="";return-1!==e&&(t=location.href.substr(e+1)),t},a.prototype.isSingleMode=function(){var e=this.getScreenFromHash(),t=e===vi.Screens.SingleMessageView||e===vi.Screens.SingleCompose||e===vi.Screens.SingleHelpdesk;return this.currentScreen=e,t},a.prototype.goDirectly=function(e,t){o.stop(),this.setHash(e),this.parseRouting(t),o.init()},a.prototype.historyBackWithoutParsing=function(){o.stop(),location.hash=this.currentHash(),o.init()},a.prototype.getScreenFromHash=function(){var e=this.getHashFromHref(),t=e.split("/");return decodeURIComponent(t.shift())||this.defaultScreen},a.prototype.parseRouting=function(e){var t=Ci.Screens.getCurrentScreenModel(),i=_.bind(this.chooseScreen,this,e);t&&Si.isFunc(t.beforeHide)?t.beforeHide(i):i()},a.prototype.chooseScreen=function(t){var i=this.getHashFromHref(),s=i.split("/"),o=decodeURIComponent(s.shift())||this.defaultScreen,n=_.find(vi.Screens,function(e){return e===o},this),r=0,a=s.length;for(o===vi.Screens.Mailbox&&this.lastMailboxHash(i),o===vi.Screens.Helpdesk&&this.lastHelpdeskHash(i),o===vi.Screens.Settings&&this.lastSettingsHash(i),this.previousHash(this.currentHash()),this.currentHash(i);a>r;r++)s[r]=decodeURIComponent(s[r]);switch(e.isArray(t)&&(s=_.union(s,t)),this.currentScreen=o,o){case vi.Screens.SingleMessageView:case vi.Screens.SingleCompose:case vi.Screens.SingleHelpdesk:Ti.SingleMode=!0,Ci.Screens.showCurrentScreen(o,s);break;default:n||(o=this.defaultScreen),Ti.SingleMode=!1,Ci.Screens.showNormalScreen(vi.Screens.Header),Ci.Screens.showCurrentScreen(o,s);break;case vi.Screens.Mailbox:Ti.SingleMode=!1,Ci.Screens.showNormalScreen(vi.Screens.Header),Ci.Screens.showCurrentScreen(vi.Screens.Mailbox,s)}},l.prototype.mailbox=function(e,t,i,s,o){var n=[vi.Screens.Mailbox];return t=Si.isNormal(t)?Si.pInt(t):1,i=Si.isNormal(i)?Si.pString(i):"",s=Si.isNormal(s)?Si.pString(s):"",o=Si.isNormal(o)?Si.pString(o):"",e&&""!==e&&n.push(e),o&&""!==o&&n.push("filter:"+o),t>1&&n.push("p"+t),i&&""!==i&&n.push("msg"+i),s&&""!==s&&n.push(s),n},l.prototype.inbox=function(){return this.mailbox()},l.prototype.parseMailbox=function(e){var t="INBOX",i=1,s="",o="",n="",r="",a=0;return Si.isNonEmptyArray(e)&&(t=Si.pString(e[a]),a++,e.length>a&&(r=Si.pString(e[a]),r==="filter:"+vi.FolderFilter.Flagged&&(n=vi.FolderFilter.Flagged,a++),r==="filter:"+vi.FolderFilter.Unseen&&(n=vi.FolderFilter.Unseen,a++)),e.length>a&&(r=Si.pString(e[a]),this.isPageParam(r)&&(i=Si.pInt(r.substr(1)),0>=i&&(i=1),a++)),e.length>a&&(r=Si.pString(e[a]),this.isMsgParam(r)&&(s=r.substr(3),a++)),e.length>a&&(o=Si.pString(e[a]))),{Folder:t,Page:i,Uid:s,Search:o,Filters:n}},l.prototype.contacts=function(e,t,i,s,o){var n=[vi.Screens.Contacts];return"number"==typeof e&&n.push(e),t&&""!==t&&n.push(t),i&&""!==i&&n.push(i),Si.isNumeric(s)&&n.push("p"+s),o&&""!==o&&n.push("cnt"+o),n},l.prototype.parseContacts=function(e){var t=0,i=[vi.ContactsGroupListType.Personal,vi.ContactsGroupListType.SharedToAll,vi.ContactsGroupListType.Global,vi.ContactsGroupListType.All],s=vi.ContactsGroupListType.All,o="",n="",r=1,a="";return Si.isNonEmptyArray(e)&&(s=Si.pInt(e[t]),t++,-1===Si.inArray(s,i)&&(s=vi.ContactsGroupListType.SubGroup),s===vi.ContactsGroupListType.SubGroup&&(e.length>t?(o=Si.pString(e[t]),t++):s=vi.ContactsGroupListType.Personal),e.length>t&&!this.isPageParam(e[t])&&!this.isContactParam(e[t])&&(n=Si.pString(e[t]),t++),e.length>t&&this.isPageParam(e[t])&&(r=Si.pInt(e[t].substr(1)),t++,0>=r&&(r=1)),e.length>t&&this.isContactParam(e[t])&&(a=Si.pString(e[t].substr(3)),t++)),{Type:s,GroupId:o,Search:n,Page:r,Uid:a}},l.prototype.isPageParam=function(e){return"p"===e.substr(0,1)&&/^[1-9][\d]*$/.test(e.substr(1))},l.prototype.isContactParam=function(e){return"cnt"===e.substr(0,3)&&/^[1-9][\d]*$/.test(e.substr(3))},l.prototype.isMsgParam=function(e){return"msg"===e.substr(0,3)&&/^[1-9][\d]*$/.test(e.substr(3))},l.prototype.compose=function(){var e=Ti.SingleMode?vi.Screens.SingleCompose:vi.Screens.Compose;return[e]},l.prototype.composeFromMessage=function(e,t,i){var s=Ti.SingleMode?vi.Screens.SingleCompose:vi.Screens.Compose;return[s,e,t,i]},l.prototype.composeWithToField=function(e){var t=Ti.SingleMode?vi.Screens.SingleCompose:vi.Screens.Compose;return[t,"to",e]},l.prototype.parseToAddr=function(e){var t=decodeURI(Si.pString(e)),i=-1!==t.indexOf("mailto:"),s=[],o=[],n="",r="",a="",l="";return i&&(s=t.replace(/^mailto:/,"").split("?"),t=s[0],2===s.length&&(o=s[1].split("&"),_.each(o,function(e){var t=e.split("=");if(2===t.length)switch(t[0]){case"subject":n=t[1];break;case"cc":r=t[1];break;case"bcc":a=t[1];break;case"body":l=t[1]}}))),{to:t,hasMailto:i,subject:n,cc:r,bcc:a,body:l}},h.prototype.setReplyData=function(e,t){this.replyText(e),this.replyDraftUid(t)},h.prototype.send=function(e,t,i,s,o,n,r){var a="",l=Ci.MailCache.folderList().sentFolderFullName(),h=Ci.MailCache.folderList().draftsFolderFullName(),c=Ti.Accounts.getCurrent().email(),u=t.To.indexOf(c)>-1||t.Cc.indexOf(c)>-1||t.Bcc.indexOf(c)>-1;switch(Ti.User.SaveRepliedToCurrFolder&&!u&&Si.isNonEmptyArray(t.DraftInfo,3)&&(l=t.DraftInfo[2]),t.Action=e,t.ShowReport=s,e){case"MessageSend":a=Si.i18n("COMPOSE/INFO_SENDING"),i&&(t.SentFolder=l),""!==t.DraftUid&&(t.DraftFolder=h);break;case"MessageSave":a=Si.i18n("COMPOSE/INFO_SAVING"),t.DraftFolder=h}s&&Ci.Api.showLoading(a),r?this.postponedMailData={Parameters:t,MessageSendResponseHandler:o,MessageSendResponseContext:n}:Ci.Ajax.send(t,o,n)},h.prototype.sendPostponedMail=function(e){var t=this.postponedMailData,i=Ci.MailCache.folderList().draftsFolderFullName();""!==e&&(t.Parameters.DraftUid=e,t.Parameters.DraftFolder=i),this.postponedMailData&&(Ci.Ajax.send(t.Parameters,t.MessageSendResponseHandler,t.MessageSendResponseContext),this.postponedMailData=null)},h.prototype.sendReplyMessage=function(e,t,i,s,o,n){var r=null,a=null,l=Ci.MailCache.currentMessage(),h=!1;Ci.MailCache.currentMessage()&&(r=this.getReplyDataFromMessage(Ci.MailCache.currentMessage(),vi.ReplyType.ReplyAll,Ti.Accounts.currentId(),Ci.MessageSender.getFetcherOrIdentityByRecipients(l.oTo.aCollection.concat(l.oCc.aCollection),l.accountId()),!1,t,i),a=Ci.MessageSender.getFetcherOrIdentityByRecipients(l.oTo.aCollection.concat(l.oCc.aCollection),l.accountId()),h=Ci.MessageSender.isFetcherOrIdentitySameAsChiefAccount(),a&&!h&&(r.FetcherID=a&&a.FETCHER?a.id():"",r.IdentityID=a&&!a.FETCHER?a.id():""),r.Bcc="",r.Importance=vi.Importance.Normal,r.Sensivity=vi.Sensivity.Nothing,r.ReadingConfirmation="0",r.IsQuickReply="1",r.IsHtml="1",r.Attachments=this.convertAttachmentsForSending(r.Attachments),this.send(e,r,Ti.User.getSaveMailInSentItems(),!1,s,o,n))},h.prototype.convertAttachmentsForSending=function(e){var t={};return _.each(e,function(e){t[e.tempName()]=[e.fileName(),e.cid(),e.inline()?"1":"0",e.linked()?"1":"0",e.contentLocation()]}),t},h.prototype.onMessageSendOrSaveResponse=function(e,i){var s,o,n,r=Ti.SingleMode?t.opener.App:Ci,a=!!e.Result;switch(Ci.Api.hideLoading(),i.Action){case"MessageSave":a?(i.ShowReport&&Ci.Api.showReport(Si.i18n("COMPOSE/REPORT_MESSAGE_SAVED")),e.Result.NewUid||(Ti.User.AllowAutosaveInDrafts=!1)):i.ShowReport&&Ci.Api.showErrorByCode(e,Si.i18n("COMPOSE/ERROR_MESSAGE_SAVING"));break;case"MessageSend":a||e.ErrorCode===vi.Errors.NotSavedInSentItems?(a||e.ErrorCode!==vi.Errors.NotSavedInSentItems?i.IsQuickReply?Ci.Api.showReport(Si.i18n("COMPOSE/REPORT_MESSAGE_SENT")):r.Api.showReport(Si.i18n("COMPOSE/REPORT_MESSAGE_SENT")):Ci.Api.showError(Si.i18n("WARNING/SENT_EMAIL_NOT_SAVED")),_.isArray(i.DraftInfo)&&3===i.DraftInfo.length&&(n=i.DraftInfo[0],o=i.DraftInfo[1],s=i.DraftInfo[2],Ci.MailCache.markMessageReplied(i.AccountID,s,o,n))):Ci.Api.showErrorByCode(e,Si.i18n("COMPOSE/ERROR_MESSAGE_SENDING")),i.SentFolder&&r.MailCache.removeMessagesFromCacheForFolder(i.SentFolder)}return i.DraftFolder&&r.MailCache.removeMessagesFromCacheForFolder(i.DraftFolder,i.DraftUid),{Action:i.Action,Result:a,NewUid:e.Result?e.Result.NewUid:""}},h.prototype.getReplyDataFromMessage=function(e,t,i,s,o,n,r){var a={DraftInfo:[],DraftUid:"",To:"",Cc:"",Bcc:"",Subject:"",Attachments:[],InReplyTo:e.messageId(),References:this.getReplyReferences(e)},l=[],h=e.oReplyTo.getFull(),c=e.oTo.getFull();switch((""===h||e.oFrom.getFirstEmail()===e.oReplyTo.getFirstEmail()&&""===e.oReplyTo.getFirstName())&&(h=e.oFrom.getFull()),n&&""!==n||(n=this.replyText(),this.replyText("")),"forward"===t?a.Text=n+this.getForwardMessageBody(e,i,s):"resend"===t?(a.Text=e.getConvertedHtml(),a.Cc=e.cc(),a.Bcc=e.bcc()):a.Text=n+this._getReplyMessageBody(e,i,s,o),r?a.DraftUid=r:(a.DraftUid=this.replyDraftUid(),this.replyDraftUid("")),t){case vi.ReplyType.Reply:a.DraftInfo=[vi.ReplyType.Reply,e.uid(),e.folder()],a.To=h,a.Subject=this.subjectCompiler(e.subject(),!0),l=_.filter(e.attachments(),function(e){return e.linked()});break;case vi.ReplyType.ReplyAll:a.DraftInfo=[vi.ReplyType.ReplyAll,e.uid(),e.folder()],a.To=h,a.Cc=this._getReplyAllCcAddr(e,i,s),a.Subject=this.subjectCompiler(e.subject(),!0),l=_.filter(e.attachments(),function(e){return e.linked()});break;case vi.ReplyType.Resend:a.DraftInfo=[vi.ReplyType.Resend,e.uid(),e.folder(),e.cc(),e.bcc()],a.To=c,a.Subject=e.subject(),l=e.attachments();break;case vi.ReplyType.Forward:a.DraftInfo=[vi.ReplyType.Forward,e.uid(),e.folder()],a.Subject=this.subjectCompiler(e.subject(),!1),l=e.attachments()}return _.each(l,function(e){if(e.getCopy){var t=e.getCopy(),i=Date.now().toString();t.getInThumbQueue(i),a.Attachments.push(t)}}),a},h.prototype.getReplyReferences=function(e){var t=e.references(),i=e.messageId(),s=t.indexOf(i);return-1===s&&(t+=" "+i),t},h.prototype._getReplyMessageBody=function(e,t,i,s){var o=Si.i18n("COMPOSE/REPLY_MESSAGE_TITLE",{DATE:e.oDateModel.getDate(),TIME:e.oDateModel.getTime(),SENDER:Si.encodeHtml(e.oFrom.getFull())}),n="<br /><br />"+this.getSignatureText(t,i,s)+'<br /><br /><div data-anchor="reply-title">'+o+"</div><blockquote>"+e.getConvertedHtml()+"</blockquote>";return n},h.prototype.getClearSignature=function(e,t){var i=Ti.Accounts.getAccount(e),s=!!(t?t.useSignature?t.useSignature():t.signatureOptions():!0),o="";return i&&s&&(o=t&&t.accountId()===i.id()?t.signature():i.signature()&&parseInt(i.signature().options())?i.signature().signature():""),o},h.prototype.getSignatureText=function(e,t,i){var s=this.getClearSignature(e,t);return i?'<div data-anchor="signature">'+s+"</div>":"<div>"+s+"</div>"},h.prototype.getFetcherOrIdentityByRecipients=function(e,t){var i=Ti.Accounts.getAccount(t),s=this.getAccountFetchersIdentitiesList(i),o=!1,n=null;return _.each(e,function(e){o||_.each(s,function(t){o||e.sEmail!==t.email||e.sName!==t.name||(o=!0,n=t.result)})}),o||_.each(e,function(e){o||_.each(s,function(t){o||e.sEmail!==t.email||(o=!0,n=t.result)})}),n},h.prototype.getAccountFetchersIdentitiesList=function(e){var t=[];return e&&(t.push({email:e.email(),name:e.friendlyName(),result:null}),e.fetchers()&&_.each(e.fetchers().collection(),function(e){t.push({email:e.email(),name:e.userName(),result:e})}),_.each(e.identities(),function(e){t.push({email:e.email(),name:e.friendlyName(),result:e})})),t},h.prototype.getForwardMessageBody=function(e,t,i){var s=Si.encodeHtml(e.oCc.getFull()),o=""!==s?Si.i18n("COMPOSE/FORWARD_MESSAGE_BODY_CC",{CCADDR:s}):"",n=Si.i18n("COMPOSE/FORWARD_MESSAGE_TITLE",{FROMADDR:Si.encodeHtml(e.oFrom.getFull()),TOADDR:Si.encodeHtml(e.oTo.getFull()),CCPART:o,FULLDATE:e.oDateModel.getFullDate(),SUBJECT:e.subject()}),r="<br /><br />"+this.getSignatureText(t,i,!0)+'<br /><br /><div data-anchor="reply-title">'+n+"</div><br /><br />"+e.getConvertedHtml();return r},h.prototype._getReplyAllCcAddr=function(e,t,i){var s=new Z,o=_.union(e.oTo.aCollection,e.oCc.aCollection,e.oBcc.aCollection),n=_.find(Ti.Accounts.collection(),function(e){return e.id()===t},this),r=new X,a=new X;return r.sEmail=n.email(),a.sEmail=i?i.email():"",s.addCollection(o),s.excludeCollection(_.union(e.oFrom.aCollection,[r,a])),s.getFull()},h._subjectPrefixes=_.map(_.uniq([Si.i18n("COMPOSE/REPLY_PREFIX"),Si.i18n("COMPOSE/FORWARD_PREFIX"),"Re","Fwd","НА","HA"]),function(e){return e.toUpperCase()}),h.prototype.subjectCompiler=function(e,i){e=Si.trim(e.replace(/[\s]+/g," "));var s=!0,o=Si.i18n("COMPOSE/REPLY_PREFIX"),n=Si.i18n("COMPOSE/FORWARD_PREFIX"),r=o.toUpperCase(),a=n.toUpperCase(),l=!1,c=!1,u={},d=[],p=[],g=e.split(":");return u[i?o:n]=1,_.each(g,function(e){if(l)p.push(e);else{e=Si.trim(e);var i=e.toUpperCase();e&&-1<_.indexOf(h._subjectPrefixes,i)?(e=r===i?o:e,e=a===i?n:e,u[e]=Si.isUnd(u[e])?1:0+u[e]+1):(c=!1,e&&!l&&_.each(h._subjectPrefixes,function(s){if(!c){var l="",h=new t.RegExp("^"+s+"\\s?[\\[\\(]([\\d]+)[\\]\\)]$","gi").exec(i);h&&h[1]&&(l=Si.trim(e.replace(/[\s]*[\[\(][\d]+[\]\)]$/g,"")),c=!0,l=r===i?o:l,l=a===i?n:l,u[l]=Si.isUnd(u[l])?Si.pInt(h[1]):0+u[l]+Si.pInt(h[1]))}}),c||(l=!0,p.push(e)))}}),_.each(u,function(e,t){e&&d.push(t+(s&&e>1?"["+e+"]":""))}),Si.trim((d.join(": ")+(d.length?": ":"")+p.join(":")).replace(/[\s]+/g," "))},h.prototype.getHtmlFromText=function(e){return e.replace(/&/g,"&").replace(/>/g,">").replace(/</g,"<").replace(/\r/g,"").replace(/\n/g,"<br />")},h.prototype.isFetcherOrIdentitySameAsChiefAccount=function(e){var t=Ti.Accounts.getAccount(e||Ti.Accounts.currentId()),i=t.email(),s=t.friendlyName(),o=[];return t.identities()&&(o=t.identities()),t.fetchers()&&(o=o.concat(t.fetchers().collection())),_.any(o,function(e){return e.email()===i&&(e.friendlyName?e.friendlyName()===s:e.userName()===s)})},c.prototype.init=function(){setInterval(_.bind(function(){this.start()},this),2e3)},c.prototype.start=function(){!Ti.Auth||Ti.SingleMode||Ci.Ajax.hasOpenedRequests()||(this.prefetchStarted(!1),this.prefetchAll())},c.prototype.prefetchAll=function(){this.prefetchFetchersIdentities(),Ti.App.AllowPrefetch?(this.startMessagesPrefetch(),this.startThreadListPrefetch(),this.doServerInitializations(),this.startOtherPagesPrefetch(),this.prefetchStarredMessageList(),this.prefetchUnseenMessageList(),this.startOtherFoldersPrefetch(),this.prefetchAccountQuota(),this.prefetchCalendarList(),this.initHelpdesk()):(this.doServerInitializations(),this.prefetchStarredMessageList(),this.prefetchAccountQuota(),this.prefetchCalendarList(),this.initHelpdesk())},c.prototype.prefetchCalendarList=function(){this.prefetchStarted()||this.prefetchStarted(Ci.CalendarCache.firstRequestCalendarList())},c.prototype.prefetchFetchersIdentities=function(){Ti.SingleMode||this.fetchersIdentitiesPrefetched()||this.prefetchStarted()||!Ti.User.AllowFetcher&&!Ti.AllowIdentities||(Ti.Accounts.populateFetchersIdentities(),this.fetchersIdentitiesPrefetched(!0),this.prefetchStarted(!0))},c.prototype.initHelpdesk=function(){!Ti.User.IsHelpdeskSupported||this.prefetchStarted()||this.helpdeskInitialized()||(Ci.Screens.initHelpdesk(),this.helpdeskInitialized(!0),this.prefetchStarted(!0))},c.prototype.doServerInitializations=function(){Ti.SingleMode||this.prefetchStarted()||this.serverInitializationsDone()||(Ci.Ajax.send({Action:"DoServerInitializations"}),this.serverInitializationsDone(!0),this.prefetchStarted(!0))},c.prototype.prefetchStarredMessageList=function(){if(!this.prefetchStarted()){var e=Ci.MailCache.folderList(),t=e?e.inboxFolder():null,i=null;t&&!t.hasChanges()&&(i=Ci.MailCache.requestMessageList(t.fullName(),1,"",vi.FolderFilter.Flagged,!1,!1),i.RequestStarted&&this.prefetchStarted(!0))}},c.prototype.prefetchUnseenMessageList=function(){if(!this.prefetchStarted()){var e=Ci.MailCache.folderList(),t=e?e.inboxFolder():null,i=null;t&&!t.hasChanges()&&(i=Ci.MailCache.requestMessageList(t.fullName(),1,"",vi.FolderFilter.Unseen,!1,!1),i.RequestStarted&&this.prefetchStarted(!0))}},c.prototype.startOtherPagesPrefetch=function(){this.prefetchStarted()||this.startPagePrefetch(Ci.MailCache.page()+1),this.prefetchStarted()||this.startPagePrefetch(Ci.MailCache.page()-1)},c.prototype.prefetchNextPage=function(e){var t=Ci.MailCache.uidList(),i=_.indexOf(t.collection(),e),s=Math.ceil(i/Ti.User.MailsPerPage)+1;this.startPagePrefetch(s-1)},c.prototype.prefetchPrevPage=function(e){var t=Ci.MailCache.uidList(),i=_.indexOf(t.collection(),e),s=Math.ceil((i+1)/Ti.User.MailsPerPage)+1;this.startPagePrefetch(s)},c.prototype.startPagePrefetch=function(e){var t=Ci.MailCache.folderList().currentFolder(),i=Ci.MailCache.uidList(),s=(e-1)*Ti.User.MailsPerPage,o=e>0&&s<i.resultCount(),n=null,r=null;t&&!t.hasChanges()&&o&&(n={folder:t.fullName(),page:e,search:i.search()},t.hasListBeenRequested(n)||(r=Ci.MailCache.requestMessageList(n.folder,n.page,n.search,"",!1,!1),r&&r.RequestStarted&&this.prefetchStarted(!0)))},c.prototype.startOtherFoldersPrefetch=function(){if(!this.prefetchStarted()){var e=Ci.MailCache.folderList(),t=e.currentFolderFullName(),i=Ti.Accounts.getCurrentFetchersAndFiltersFolderNames(),s=e?[e.inboxFolderFullName(),e.sentFolderFullName(),e.draftsFolderFullName(),e.spamFolderFullName()]:[],o=i.length<3?this.getOtherFolderNames(3-i.length):[],n=_.uniq(_.compact(_.union(s,i,o)));_.each(n,_.bind(function(i){t!==i&&this.startFolderPrefetch(e.getFolderByFullName(i))},this))}},c.prototype.getOtherFolderNames=function(e){var t=Ci.MailCache.folderList().inboxFolder(),i=t?t.subfolders():[],s=_.filter(Ci.MailCache.folderList().collection(),function(e){return!e.isSystem()},this),o=_.first(_.union(i,s),e);return _.map(o,function(e){return e.fullName()})},c.prototype.startFolderPrefetch=function(e){if(!this.prefetchStarted()&&e){var t=1,i="",s={folder:e.fullName(),page:t,search:i},o=null;e.hasListBeenRequested(s)||(o=Ci.MailCache.requestMessageList(s.folder,s.page,s.search,"",!1,!1),o&&o.RequestStarted&&this.prefetchStarted(!0))}},c.prototype.startThreadListPrefetch=function(){if(!this.prefetchStarted()){var e=[],t=Ci.MailCache.getCurrentFolder();_.each(Ci.MailCache.messages(),function(i){i.threadCount()>0&&_.each(i.threadUids(),function(i){var s=t.oMessages[i];s&&t.hasThreadUidBeenRequested(i)||e.push(i)})},this),e.length>0&&(e=e.slice(0,Ti.User.MailsPerPage),t.addRequestedThreadUids(e),t.loadThreadMessages(e),this.prefetchStarted(!0))}},c.prototype.startMessagesPrefetch=function(){if(!this.prefetchStarted()){var e=Ci.MailCache.currentAccountId(),t=Ci.MailCache.getCurrentFolder(),i=0,s=Ti.App.MaxPrefetchBodiesSize,o=[],n=null,r=2048,a=function(e){var n=!e.deleted()&&!e.completelyFilled(),a=!_.find(o,function(t){return t===e.uid()},this),l=!t.hasUidBeenRequested(e.uid());s>i&&n&&a&&l&&(o.push(e.uid()),i+=e.trimmedTextSize()+r)};t&&t.selected()&&(_.each(Ci.MailCache.messages(),a),_.each(t.oMessages,a),o.length>0&&(t.addRequestedUids(o),n={AccountID:e,Action:"Messages",Folder:t.fullName(),Uids:o},Ci.Ajax.send(n,this.onPrefetchResponse,this),this.prefetchStarted(!0)))}},c.prototype.onPrefetchResponse=function(e,t){var i=Ci.MailCache.getFolderByFullName(t.AccountID,t.Folder);_.isArray(e.Result)&&_.each(e.Result,function(e){i.parseAndCacheMessage(e,!1,!1)})},c.prototype.prefetchAccountQuota=function(){var e=Ti.Accounts.getCurrent(),t=Ti.App&&Ti.App.ShowQuotaBar,i=e&&!e.quotaRecieved();!this.prefetchStarted()&&t&&i&&(e.updateQuotaParams(),this.prefetchStarted(!0))},u.prototype.iTimer=0,u.prototype.bResetCheckedOnClick=!1,u.prototype.bCheckOnSelect=!1,u.prototype.bUnselectOnCtrl=!1,u.prototype.bDisableMultiplySelection=!1,u.prototype.setBeforeSelectCallback=function(e){this.fBeforeSelectCallback=e||null},u.prototype.getLastOrSelected=function(){var e=0,t=null;return _.each(this.list(),function(i){i.checked()&&e++,i.selected()&&(t=i)}),0===e&&t?t:this.oLast},u.prototype.initOnApplyBindings=function(t,s,o,n,r){e(document).on("keydown",this.onKeydownBinded),this.oListScope=n,this.oScrollScope=r,this.sActionSelector=t,this.sSelectabelSelector=s,this.sCheckboxSelector=o;var a=this,l=function(e,t,i){var s=0,o=0,n=null,r=!1,l=!1,h=[],c=!1;if(t=t?t:null,i&&i.shiftKey&&null!==t&&null!==e&&t!==e)for(h=a.list(),c=t.checked(),s=0,o=h.length;o>s;s++)n=h[s],r=!1,(n===e||n===t)&&(r=!0),r&&(l=!l),(l||r)&&n.checked(c);t&&(a.oLast=t)};e(this.oListScope).on("dblclick",t,function(e){var t=i.dataFor(this);!t||!e||e.ctrlKey||e.altKey||e.shiftKey||a.onDblClick(t)}),Ri&&e(this.oListScope).on("touchstart",t,function(t){if(t){var i=t.timeStamp,s=e(this).data("lastTouch")||i,o=i-s,n=t.originalEvent&&t.originalEvent.touches?t.originalEvent.touches.length:0;e(this).data("lastTouch",i),!o||o>250||n>1||(t.preventDefault(),e(this).trigger("dblclick"))}}),e(this.oListScope).on("click",t,function(e){var t=!0,s=null,o=a.getLastOrSelected(),n=i.dataFor(this);n&&e&&(e.shiftKey?(t=!1,a.bDisableMultiplySelection||(null===a.oLast&&(a.oLast=n),n.checked(!n.checked()),l(o,n,e))):e.ctrlKey&&(t=!1,a.bDisableMultiplySelection||(a.oLast=n,s=a.itemSelected(),!s||s.checked()||n.checked()||s.checked(!0),a.bUnselectOnCtrl&&n===a.itemSelected()?(n.checked(!n.selected()),a.itemSelected(null)):n.checked(!n.checked()))),t&&(a.onSelect(n),a.scrollToSelected()))}),e(this.oListScope).on("click",o,function(e){var t=i.dataFor(this);t&&e&&!a.bDisableMultiplySelection&&(e.shiftKey?(null===a.oLast&&(a.oLast=t),l(a.getLastOrSelected(),t,e)):a.oLast=t),e&&e.stopPropagation&&e.stopPropagation()}),e(this.oListScope).on("dblclick",o,function(e){e&&e.stopPropagation&&e.stopPropagation()})},u.prototype.getResultSelection=function(e,t){var i=this,s=!1,o=!1,n=null,r=this.iFactor,a=!!this.multiplyLineFactor,l=0,h=0,c=[];if(!e&&-1<Si.inArray(t,[this.KeyUp,this.KeyDown,this.KeyLeft,this.KeyRight,vi.Key.PageUp,vi.Key.PageDown,vi.Key.Home,vi.Key.End]))c=this.list(),c&&0<c.length&&(-1<Si.inArray(t,[this.KeyDown,this.KeyRight,vi.Key.PageUp,vi.Key.Home])?n=c[0]:-1<Si.inArray(t,[this.KeyUp,this.KeyLeft,vi.Key.PageDown,vi.Key.End])&&(n=c[c.length-1]));else if(e&&(c=this.list(),h=c?c.length:0,h>0))if(vi.Key.Home===t||vi.Key.PageUp===t||vi.Key.End===t||vi.Key.PageDown===t||a&&(vi.Key.Left===t||vi.Key.Right===t)||!a&&(vi.Key.Up===t||vi.Key.Down===t))_.each(c,function(r){if(!s)switch(t){case i.KeyUp:case i.KeyLeft:e===r?s=!0:n=r;break;case vi.Key.Home:case vi.Key.PageUp:n=r,s=!0;break;case i.KeyDown:case i.KeyRight:o?(n=r,s=!0):e===r&&(o=!0);break;case vi.Key.End:case vi.Key.PageDown:n=r}});else if(a&&this.KeyDown===t){for(;h>l;l++)if(e===c[l]){l+=r,l>h-1&&(l-=r),n=c[l];break}}else if(a&&this.KeyUp===t)for(l=h;l>=0;l--)if(e===c[l]){l-=r,0>l&&(l+=r),n=c[l];break}return n},u.prototype.shiftClickResult=function(e,t,i){if(t){var s=!!this.multiplyLineFactor,o=!1,n=!1;-1<Si.inArray(i,s?[vi.Key.Left,vi.Key.Right]:[vi.Key.Up,vi.Key.Down])?t.checked(!t.checked()):-1<Si.inArray(i,s?[vi.Key.Up,vi.Key.Down,vi.Key.PageUp,vi.Key.PageDown,vi.Key.Home,vi.Key.End]:[vi.Key.Left,vi.Key.Right,vi.Key.PageUp,vi.Key.PageDown,vi.Key.Home,vi.Key.End])&&(n=!t.checked(),_.each(this.list(),function(i){var s=!1;(i===e||t===i)&&(o=!o,s=!0),(o||s)&&(i.checked(n),s=!1)}),s&&e&&(i===vi.Key.Up||i===vi.Key.Down)&&e.checked(!e.checked()))}},u.prototype.clickNewSelectPosition=function(e,i){var s=this,o=0,n=null,r=this.itemSelected();n=this.getResultSelection(r,e),n?(i&&this.shiftClickResult(n,r,e),n&&this.fBeforeSelectCallback?(this.fBeforeSelectCallback(n,function(e){e&&(s.itemSelected(n),o=0===s.iTimer?50:150,0!==s.iTimer&&t.clearTimeout(s.iTimer),s.iTimer=t.setTimeout(function(){s.iTimer=0,s.onSelect(n,!1)},o),this.scrollToSelected())}),this.scrollToSelected()):(this.itemSelected(n),o=0===this.iTimer?50:150,0!==this.iTimer&&t.clearTimeout(this.iTimer),this.iTimer=t.setTimeout(function(){s.iTimer=0,s.onSelect(n)},o),this.scrollToSelected())):r&&i&&-1<Si.inArray(e,[this.KeyUp,this.KeyDown,this.KeyLeft,this.KeyRight,vi.Key.PageUp,vi.Key.PageDown,vi.Key.Home,vi.Key.End])&&r.checked(!r.checked())},u.prototype.onKeydown=function(e){var t=!0,i=0;return this.useKeyboardKeys()&&e&&!Si.isTextFieldFocused()&&(i=e.keyCode,e.ctrlKey||this.KeyUp!==i&&this.KeyDown!==i&&this.KeyLeft!==i&&this.KeyRight!==i&&vi.Key.PageUp!==i&&vi.Key.PageDown!==i&&vi.Key.Home!==i&&vi.Key.End!==i?vi.Key.Del!==i||e.ctrlKey||e.shiftKey?vi.Key.Enter===i?0<this.list().length&&!e.ctrlKey&&(this.onEnter(this.itemSelected()),t=!1):!e.ctrlKey||e.altKey||e.shiftKey||vi.Key.a!==i||(this.checkAll(!(this.checkAll()&&!this.isIncompleteChecked())),t=!1):0<this.list().length&&(this.onDelete(),t=!1):(this.clickNewSelectPosition(i,e.shiftKey),t=!1)),t},u.prototype.onDelete=function(){this.fDeleteCallback.call(this,this.listCheckedOrSelected())},u.prototype.onEnter=function(e){var t=this;e&&this.fBeforeSelectCallback?this.fBeforeSelectCallback(e,function(i){i&&(t.itemSelected(e),t.fEnterCallback.call(this,e))}):(this.itemSelected(e),this.fEnterCallback.call(this,e))},u.prototype.selectionFunc=function(e){this.itemSelected(null),this.bResetCheckedOnClick&&this.listChecked(!1),this.itemSelected(e),this.fSelectCallback.call(this,e) },u.prototype.onSelect=function(e,t){if(t=Si.isUnd(t)?!0:!!t,this.fBeforeSelectCallback&&t){var i=this;this.fBeforeSelectCallback(e,function(t){t&&i.selectionFunc(e)})}else this.selectionFunc(e)},u.prototype.onDblClick=function(e){this.fDblClickCallback.call(this,e)},u.prototype.koCheckAll=function(){return i.computed({read:this.checkAll,write:this.checkAll,owner:this})},u.prototype.koCheckAllIncomplete=function(){return i.computed({read:this.isIncompleteChecked,write:this.isIncompleteChecked,owner:this})},u.prototype.scrollToSelected=function(){if(!this.oListScope||!this.oScrollScope)return!1;var t=20,i=e(this.sSelectabelSelector,this.oScrollScope),s=i.position(),o=this.oScrollScope.height(),n=i.outerHeight();return s&&(s.top<0||s.top+n>o)?(this.oScrollScope.scrollTop(s.top<0?this.oScrollScope.scrollTop()+s.top-t:this.oScrollScope.scrollTop()+s.top-o+n+t),!0):!1},function(e){e.fn.splitter=function(i){return i=i||{},this.each(function(){var s=!1,o=i.name,n=0,r=0,a={},l={},h=function(t){s=!0,y.addClass(m.activeClass),m._posSplit=-((v?b._overallWidth-t[m.eventPos]:t[m.eventPos])-f.get(0)[m.pxSplit]),e("body").attr({unselectable:"on"}).addClass("unselectable"),e(document).bind("mousemove",c).bind("mouseup",u)},c=function(e){var t=(v?b._overallWidth-e[m.eventPos]:e[m.eventPos])+m._posSplit;d(t),Si.isFunc(i.resizeFunc)&&i.resizeFunc()},u=function S(){y.removeClass(m.activeClass),e("body").attr({unselectable:"off"}).removeClass("unselectable"),o&&Ci.Storage.setData(o+"ResizerWidth",f.get(0)[m.pxSplit]),e(document).unbind("mousemove",c).unbind("mouseup",S),Si.isFunc(i.resizeFunc)&&i.resizeFunc()},d=function(e,i){i||(e=t.Math.max(f.get(0)._min,b._overallWidth-f.get(1)._max,t.Math.min(e,f.get(0)._max,b._overallWidth-f.get(1)._min))),f.get(0).$.css(m.split,e),f.get(1).$.css(m.split,b._overallWidth-e),Ci.browser.ie8AndBelow||f.trigger("resize")},p=function(e){for(var i=0,s=1;s<arguments.length;s++)i+=t.Math.max(t.parseInt(e.css(arguments[s]),10)||0,0);return i},g=(i.splitHorizontal?"h":i.splitVertical?"v":i.type)||"v",m=e.extend({activeClass:"active",pxPerKey:8,tabIndex:0,accessKey:""},{v:{keyLeft:39,keyRight:37,type:"v",eventPos:"pageX",origin:"left",split:"width",pxSplit:"offsetWidth",side1:"Left",side2:"Right",fixed:"height",pxFixed:"offsetHeight",side3:"Top",side4:"Bottom"},h:{keyTop:40,keyBottom:38,type:"h",eventPos:"pageY",origin:"top",split:"height",pxSplit:"offsetHeight",side1:"Top",side2:"Bottom",fixed:"width",pxFixed:"offsetWidth",side3:"Left",side4:"Right"}}[g],i),b=e(this),f=e(">*:not(css3pie)",b).each(function(){this.$=e(this)}),y=e(".resize_handler",f.get(0)).attr({unselectable:"on"}).bind("mousedown",h),v="rtl"===b.css("direction");f.get(0)._paneName=m.side1,f.get(1)._paneName=m.side2,f.each(function(){this._min=m["min"+this._paneName]||p(this.$,"min-"+m.split),this._max=m["max"+this._paneName]||p(this.$,"max-"+m.split)||9999,this._init=void 0===m["size"+this._paneName]?t.parseInt(e.css(this,m.split),10):m["size"+this._paneName]}),n=o?Ci.Storage.getData(o+"ResizerWidth")||f.get(0)._init:f.get(0)._init,isNaN(n)&&(n=b[0][m.pxSplit],n=t.Math.round(n/f.length)),m.resizeToWidth&&!Ci.browser.ie8AndBelow&&e(t).bind("resize",function(e){e.target===this&&b.trigger("resize")}),b.bind("resize",function(e,t,i,o){var n=e.target.className+"_"+i;s&&(a={}),e.target===this&&(b._overallWidth=b[0][m.pxSplit],b._overallWidth<=0||(r=m.sizeRight||m.sizeBottom?b._overallWidth-f.get(1)[m.pxSplit]:f.get(0)[m.pxSplit],isNaN(t)?t=r:i&&(s=!1,a[n]?(t=a[n],a[n]=null):(t===r?(a[n]=null,t=l[n]):a[n]=l[n]=r,_.each(a,function(e,t){t!==n&&(a[t]=null)}))),d(t,o)))}).trigger("resize",[n])})}}(jQuery),function(e){e.ui.autocomplete.prototype._renderItem=function(t,i){return i.label=Si.trim(i.label),i.label=i.label.replace(/\([^\)]+\)$/i,function(e){return"~~1~~"+e+"~~2~~"}),i.label=i.label.replace(/<[^>]+>$/i,function(e){return"~~1~~"+e+"~~2~~"}),i.label=Si.encodeHtml(i.label),i.label=i.label.replace(/~~1~~/,'<span style="opacity: 0.5">').replace(/~~2~~/,"</span>"),e("<li>").append("<a>"+i.label+"</a>").appendTo(t)},e.ui.autocomplete.prototype._renderMenu=function(t,i){var s=this,o="";e.each(i,function(e,i){i&&i.category&&i.category!==o&&(o=i.category,t.append('<li class="ui-autocomplete-category">'+i.category+"</li>")),s._renderItemData(t,i)})}}(jQuery),d.prototype.openComposeMessage=function(e){Ci.Routing.setHash(Ci.Links.composeWithToField(e))},d.prototype.downloadByUrl=function(i){var s=null;Ri?t.open(i):(s=e('<iframe style="display: none;"></iframe>').appendTo(document.body),s.attr("src",i),setTimeout(function(){s.remove()},6e4))},d.prototype.isPgpSupported=function(){return!(!t.crypto||!t.crypto.getRandomValues)},d.prototype.pgp=function(i,s){if(Si.isFunc(i))if(this.openPgp)i(this.openPgp);else if(this.isPgpSupported()){null!==this.openPgpCallbacks?this.openPgpCallbacks.push(i):i(!1);var o=this;this.openPgpRequest||(this.openPgpRequest=!0,e.ajax({url:"static/js/openpgp.js",dataType:"script",cache:!0,complete:function(){o.openPgp=t.openpgp?new y(t.openpgp,"user_"+(s||"0")+"_"):!1,null!==o.openPgpCallbacks&&_.each(o.openPgpCallbacks,function(e){e(o.openPgp)}),o.openPgpCallbacks=null}}))}else i(!1)},d.prototype.showLoading=function(e){Ci.Screens.showLoading(e)},d.prototype.hideLoading=function(){Ci.Screens.hideLoading()},d.prototype.showReport=function(e,t){Ci.Screens.showReport(e,t)},d.prototype.showError=function(e,t,i,s){Ci.Screens.showError(e,t,i,s)},d.prototype.hideError=function(e){Ci.Screens.hideError(e)},d.prototype.showPgpErrorByCode=function(e,t,i){var s=Si.isNonEmptyArray(e.errors)?e.errors:[],o=Si.isNonEmptyArray(e.notices)?e.notices:[],n=[],r=[],a="",l=!1,h=!0;if(_.each(_.union(s,o),function(e){if(2===e.length)switch(e[0]){case S.Enum.GenerateKeyError:a=Si.i18n("OPENPGP/ERROR_GENERATE_KEY");break;case S.Enum.ImportKeyError:a=Si.i18n("OPENPGP/ERROR_IMPORT_KEY");break;case S.Enum.ImportNoKeysFoundError:a=Si.i18n("OPENPGP/ERROR_IMPORT_NO_KEY_FOUNDED");break;case S.Enum.PrivateKeyNotFoundError:case S.Enum.PrivateKeyNotFoundNotice:r.push(e[1]);break;case S.Enum.PublicKeyNotFoundError:h=!1,n.push(e[1]);break;case S.Enum.PublicKeyNotFoundNotice:n.push(e[1]);break;case S.Enum.KeyIsNotDecodedError:t===vi.PgpAction.DecryptVerify?a=Si.i18n("OPENPGP/ERROR_DECRYPT")+" "+Si.i18n("OPENPGP/ERROR_KEY_NOT_DECODED",{USER:e[1]}):(t===vi.PgpAction.Sign||t===vi.PgpAction.EncryptSign)&&(a=Si.i18n("OPENPGP/ERROR_SIGN")+" "+Si.i18n("OPENPGP/ERROR_KEY_NOT_DECODED",{USER:e[1]}));break;case S.Enum.SignError:a=Si.i18n("OPENPGP/ERROR_SIGN");break;case S.Enum.VerifyError:a=Si.i18n("OPENPGP/ERROR_VERIFY");break;case S.Enum.EncryptError:a=Si.i18n("OPENPGP/ERROR_ENCRYPT");break;case S.Enum.DecryptError:a=Si.i18n("OPENPGP/ERROR_DECRYPT");break;case S.Enum.SignAndEncryptError:a=Si.i18n("OPENPGP/ERROR_ENCRYPT_OR_SIGN");break;case S.Enum.VerifyAndDecryptError:a=Si.i18n("OPENPGP/ERROR_DECRYPT_OR_VERIFY");break;case S.Enum.DeleteError:a=Si.i18n("OPENPGP/ERROR_DELETE_KEY");break;case S.Enum.VerifyErrorNotice:a=Si.i18n("OPENPGP/ERROR_VERIFY");break;case S.Enum.NoSignDataNotice:l=!0}}),n.length>0?(n=_.without(n,""),n.length>0?a=Si.i18n("OPENPGP/ERROR_NO_PUBLIC_KEYS_FOR_USERS_PLURAL",{USERS:n.join(", ")},null,n.length):t===vi.PgpAction.Verify&&(a=Si.i18n("OPENPGP/ERROR_NO_PUBLIC_KEY_FOUND_FOR_VERIFY")),h&&""!==a&&(a+=" "+Si.i18n("OPENPGP/ERROR_MESSAGE_WAS_NOT_VERIFIED"))):r.length>0&&(r=_.without(r,""),r.length>0?a=Si.i18n("OPENPGP/ERROR_NO_PRIVATE_KEYS_FOR_USERS_PLURAL",{USERS:r.join(", ")},null,r.length):t===vi.PgpAction.DecryptVerify&&(a=Si.i18n("OPENPGP/ERROR_NO_PRIVATE_KEY_FOUND_FOR_DECRYPT"))),""===a&&!l){switch(t){case vi.PgpAction.Generate:a=Si.i18n("OPENPGP/ERROR_GENERATE_KEY");break;case vi.PgpAction.Import:a=Si.i18n("OPENPGP/ERROR_IMPORT_KEY");break;case vi.PgpAction.DecryptVerify:a=Si.i18n("OPENPGP/ERROR_DECRYPT");break;case vi.PgpAction.Verify:a=Si.i18n("OPENPGP/ERROR_VERIFY");break;case vi.PgpAction.Encrypt:a=Si.i18n("OPENPGP/ERROR_ENCRYPT");break;case vi.PgpAction.EncryptSign:a=Si.i18n("OPENPGP/ERROR_ENCRYPT_OR_SIGN");break;case vi.PgpAction.Sign:a=Si.i18n("OPENPGP/ERROR_SIGN")}a=i}return""!==a&&Ci.Api.showError(a),l},d.prototype.showErrorByCode=function(e,t){var i=e.ErrorCode,s=e.ErrorMessage||"";switch(""!==s&&(s=" ("+s+")"),i){default:t&&t.length>0?this.showError(t+s):""!==s&&this.showError(s);break;case vi.Errors.AuthError:this.showError(Si.i18n("WARNING/LOGIN_PASS_INCORRECT")+s);break;case vi.Errors.DemoLimitations:this.showError(Si.i18n("DEMO/WARNING_THIS_FEATURE_IS_DISABLED")+s);break;case vi.Errors.Captcha:this.showError(Si.i18n("WARNING/CAPTCHA_IS_INCORRECT")+s);break;case vi.Errors.CanNotGetMessage:this.showError(Si.i18n("MESSAGE/ERROR_MESSAGE_DELETED")+s);break;case vi.Errors.NoRequestedMailbox:this.showError(t+" "+Si.i18n("COMPOSE/ERROR_INVALID_ADDRESS",{ADDRESS:e.Mailbox})+s);break;case vi.Errors.CanNotChangePassword:this.showError(Si.i18n("WARNING/UNABLE_CHANGE_PASSWORD")+s);break;case vi.Errors.AccountOldPasswordNotCorrect:this.showError(Si.i18n("WARNING/CURRENT_PASSWORD_NOT_CORRECT")+s);break;case vi.Errors.FetcherIncServerNotAvailable:this.showError(Si.i18n("WARNING/FETCHER_SAVE_ERROR")+s);break;case vi.Errors.FetcherLoginNotCorrect:this.showError(Si.i18n("WARNING/FETCHER_SAVE_ERROR")+s);break;case vi.Errors.HelpdeskUserNotExists:this.showError(Si.i18n("HELPDESK/ERROR_FORGOT_NO_ACCOUNT")+s);break;case vi.Errors.MailServerError:this.showError(Si.i18n("WARNING/CANT_CONNECT_TO_SERVER")+s);break;case vi.Errors.DataTransferFailed:this.showError(Si.i18n("WARNING/DATA_TRANSFER_FAILED")+s);break;case vi.Errors.NotDisplayedError:""!==s&&this.showError(s)}},Ei.addScreenToHeader=function(e,t,i,s,o){Ci.addScreenToHeader(e,t,i,s,o,!0)},Ei.aSettingsTabs=[],Ei.addSettingsTab=function(e){e.prototype.TabName&&(vi.SettingsTab[e.prototype.TabName]=e.prototype.TabName,Ei.aSettingsTabs.push(e))},Ei.getPluginsSettingsTabs=function(){return Ei.aSettingsTabs},Ei.getSetting=function(e){return Ti.App[e]},Ei.getPluginSettings=function(e){return Ti&&Ti.Plugins?Ti.Plugins[e]:null},Ei.oPluginHooks={},Ei.addPluginHook=function(t,i){Si.isFunc(i)&&(e.isArray(this.oPluginHooks[t])||(this.oPluginHooks[t]=[]),this.oPluginHooks[t].push(i))},Ei.runPluginHook=function(t,i){e.isArray(this.oPluginHooks[t])&&(i=i||[],_.each(this.oPluginHooks[t],function(e){e.apply(null,i)}))},Ei.sendAjaxRequest=function(e,t,i){Ci.Ajax.send(e,t,i)},Ei.i18n=Si.i18n,Ei.getArrayRecipients=Si.getArrayRecipients,Ei.getEmailParts=Si.getEmailParts,Ei.showAlertPopup=function(e){Ci.Screens.showPopup(A,[e])},Ei.showConfirmPopup=function(e,t){Ci.Screens.showPopup(C,[e,t])},Ei.showReport=function(e,t){Ci.Screens.showReport(e,t)},Ei.showError=function(e){Ci.Screens.showError(e)},Ei.getPrimaryAccountData=function(){var e=Ti.Accounts.getDefault();return{Id:e.id(),Email:e.email(),FriendlyName:e.friendlyName()}},Ei.getCurrentAccountData=function(){var e=Ti.Accounts.getCurrent();return{Id:e.id(),Email:e.email(),FriendlyName:e.friendlyName()}},Ei.isMobile=function(){return Ti.IsMobile},p.prototype.setData=function(e,t){Data.setVar(e,t)},p.prototype.removeData=function(e){Data.setVar(e,"")},p.prototype.getData=function(e){return Data.getVar(e)},p.prototype.hasData=function(e){return Data.hasVar(e)},g.prototype.init=function(){e.ajaxSettings.cache=!0,this.provider="sip"===Ti.User.VoiceProvider?new m:new f,this.action(vi.PhoneAction.OfflineInit)},g.prototype.log=function(){},g.prototype.onGetScript=function(e){e&&"success"===e?this.log("*************** gettingScript_success"):(this.log("*************** gettingScript_unknownError"),this.action(vi.PhoneAction.OfflineError))},g.prototype.showError=function(e){1===Si.pInt(e)&&Ci.Api.showError(Si.i18n("PHONE/ERROR_SERVER_UNAVAILABLE"),!1,!0)},g.prototype.phoneSupport=function(e,t){var i=function(){try{try{var e=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");try{e.AllowScriptAccess="always"}catch(t){return"6,0,0"}}catch(t){}return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version").replace(/\D+/g,",").match(/^,?(.+),?$/)[1]}catch(t){try{if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)return(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g,",").match(/^,?(.+),?$/)[1]}catch(i){}}return"0,0,0"};!e||Ci.browser.chrome||t||Pi?Pi?this.log("*************** Device not supported"):t&&"0,0,0"===i()?this.log("*************** Please install flash player"):t&&i()<t&&this.log("*************** Please reinstall flash player"):this.log("*************** Browser not supported")},g.prototype.incomingCall=function(t){var i,s,o;this.action(vi.PhoneAction.Incoming),t&&(i=this,s={Action:"ContactSuggestions",Search:t,PhoneOnly:"1"},o=function(e){i.report(Si.i18n("PHONE/INCOMING_CALL_FROM")+" "+e),Ci.Screens.showPopup(V,[{text:e}]),Ci.desktopNotify({action:"show",title:e+" calling...",body:"Click here to answer.\r\n To drop the call, click End in the web interface.",callback:_.bind(function(){i.action(vi.PhoneAction.IncomingConnect)},i),timeout:6e4})},Ci.Ajax.send(s,function(i){if(i&&i.Result&&i.Result.List&&i.Result.List[0]&&i.Result.List[0].Phones){var s="";e.each(i.Result.List[0].Phones,function(e,n){var r=i.Result.List[0],a=/[()\s_\-]/g,l=t.replace(a,""),h=n.replace(a,"");return l===h?(s=""===r.Name?r.Email+" "+n:r.Name+" "+n,o(s),!1):void 0},this),""===s&&o(t)}else o(t)},this),this.missedCalls(!0))},g.prototype.getFormattedPhone=function(e){e=e.toString();var t={8:"7"},i=/#/g.test(e)?e.split("#")[1]:e.replace(/[()\s_\-+]/g,"");return _.each(t,function(e,t){i=i.replace(new RegExp("^"+t,"g"),e)}),i},g.prototype.getLogs=function(e,t){this.missedCalls(!1),this.provider.getLogs(e,t)},g.prototype.getCleanedPhone=function(e){return e=e?e:"",e.replace("client:","")},m.prototype.init=function(){var t=this;e.getScript("static/js/sipml.js",function(e,i){t.phone.onGetScript(i),"success"===i&&(t.setConfigs(),SIPml.setDebugLevel("fatal"),SIPml.init(t.createStackBinded,t.createStackErrorBinded))})},m.prototype.setConfigs=function(){this.stackConf({realm:Ti.User.SipRealm,impi:Ti.User.SipImpi,impu:"sip:"+Ti.User.SipImpi+"@"+Ti.User.SipRealm,password:Ti.User.SipPassword,enable_rtcweb_breaker:!0,websocket_proxy_url:Ti.User.SipWebsocketProxyUrl,ice_servers:'[{ url: "stun:stun.afterlogic.com:3478"}]',events_listener:{events:"*",listener:this.eventSessionBinded}}),this.registerConf({audio_remote:this.audioRemote,expires:3600,events_listener:{events:"*",listener:this.eventSessionBinded},sip_caps:[{name:"+g.oma.sip-im",value:null},{name:"+audio",value:null},{name:"+sip.ice"},{name:"language",value:'"en,fr"'}]}),this.hangupConf({events_listener:{events:"*",listener:this.eventSessionBinded}})},m.prototype.createStack=function(){this.stack(new SIPml.Stack(this.stackConf())),this.stack().start()},m.prototype.createStackError=function(){this.phone.log("*************** Failed to initialize the engine")},m.prototype.register=function(){this.registerSession(this.stack().newSession("register",this.registerConf())),this.registerSession().register()},m.prototype.eventSession=function(e){this.phone.log("*************** "+e.type+" ("+e.description+")");var t=e.type;switch(t){case"starting":break;case"started":Ci.Api.hideError(),this.isStarted(!0),this.register();break;case"stopping":case"stopped":this.isStarted(!1),this.createStack();break;case"failed_to_stop":break;case"failed_to_start":this.phone.action(vi.PhoneAction.OfflineError),this.isStarted(!1),this.reconnect(30);break;case"connecting":break;case"connected":"Connected"===e.description?this.phone.action(vi.PhoneAction.Online):"In call"===e.description&&Ci.desktopNotify("hide");break;case"terminating":case"terminated":this.phone.action(vi.PhoneAction.Online),"Disconnected"===e.description&&this.createStack();break;case"i_ao_request":break;case"media_added":break;case"media_removed":break;case"m_stream_video_remote_added":break;case"m_stream_audio_local_added":break;case"m_stream_audio_remote_added":break;case"i_request":break;case"o_request":break;case"sent_request":break;case"cancelled_request":break;case"i_new_call":this.callSession(e.newSession),this.callSession().setConfiguration(this.registerConf()),this.phone.incomingCall(this.callSession().getRemoteFriendlyName());break;case"i_new_message":break;case"m_permission_requested":break;case"m_permission_accepted":break;case"m_permission_refused":break;case"transport_error":break;case"global_error":break;case"message_error":break;case"webrtc_error":}},m.prototype.call=function(e){this.isStarted()?(this.action("outgoing"),this.callSession(this.stack().newSession("call-audio",this.registerConf())),this.callSession().call(e),this.phone.log("*************** "+this.callSession().getRemoteFriendlyName())):this.createStack()},m.prototype.answer=function(){this.callSession()&&this.callSession().accept(this.registerConf())},m.prototype.hangup=function(){this.callSession()&&(this.callSession().hangup(this.hangupConf()),this.callSession().hangup({events_listener:{events:"*",listener:this.eventSessionBinded}}))},m.prototype.reconnect=function(){var e=0;return function(t){clearInterval(e),t&&(e=setInterval(_.bind(function(){},this),t))}}(),m.prototype.getLogs=function(e,t){e.call(t)},b.prototype.init=function(){var t=this;e.getScript("static/js/swfobject.js",function(e,i){"success"===i&&(t.voiceApp(!0),swfobject.embedSWF("static/freeswitch.swf","flash","214","137","9.0.0","expressInstall.swf",{rtmp_url:"rtmp://217.199.220.26/phone"},{allowScriptAccess:"always",bgcolor:"#ece9e0"},[],!1),t.callbacks())})},b.prototype.log=function(){},b.prototype.showPrivacy=function(){Ci.Screens.showPopup(V,[{Action:vi.PhoneAction.Settings,Callback:this.launchFlash.bind(this)}]);var t=e("#fake_flash"),i=t.offset(),s=t.width();this.jqFlash.css("left",i.left+s/2-107),this.jqFlash.css("top",i.top),this.jqFlash.css("visibility","visible"),this.flash.showPrivacy()},b.prototype.checkMic=function(){return this.flash.isMuted()},b.prototype.login=function(e,t){this.flash.login(e,t)},b.prototype.newCall=function(){},b.prototype.call=function(){this.flash.makeCall("sip:7002@217.199.220.24","7003@217.199.220.26",[])},b.prototype.answer=function(e){this.flash.answer(e)},b.prototype.hangup=function(e){this.flash.hangup(e)},b.prototype.addCall=function(){},b.prototype.launchFlash=function(){this.jqFlash.css("top","-200px")},b.prototype.callbacks=function(){var i=this;t.onInit=function(){i.log("**************** onInit"),i.initStatus(!0)},t.onConnected=function(t){i.log("**************** onConnected ("+t+")"),i.connectStatus(!0),i.sessionid(t),i.jqFlash=e("#flash"),i.flash=i.jqFlash[0],i.checkMic()&&i.showPrivacy(),i.login("7003@217.199.220.26","7003voippassword")},t.onDisconnected=function(){i.log("**************** onDisconnected")},t.onEvent=function(e){i.log("**************** onEvent ("+e+")")},t.onLogin=function(e,t,s){i.log("**************** onLogin ("+e+", "+t+", "+s+")")},t.onLogout=function(e,t){i.log("**************** onLogout ("+e+", "+t+")")},t.onMakeCall=function(e,t,s){i.log("**************** onMakeCall ("+e+", "+t+", "+s+")")},t.onHangup=function(e,t){i.log("**************** onHangup ("+e+", "+t+")")},t.onIncomingCall=function(e,t,s,o,n){i.log("**************** onIncomingCall ("+e+", "+t+", "+s+", "+o+", "+n+")"),i.addCall(e,t,s)},t.onDisplayUpdate=function(e,t,s){i.log("**************** onDisplayUpdate ("+e+", "+t+", "+s+")")},t.onCallState=function(e,t){i.log("**************** onCallState ("+e+", "+t+")"),i.callState(t)},t.onDebug=function(e){i.log("**************** onDebug ("+e+")")},t.onAttach=function(e){i.log("**************** onAttach ("+e+")")}},f.prototype.init=function(){Ci.Ajax.send({Action:"GetTwilioToken"},this.onTokenResponse,this)},f.prototype.onTokenResponse=function(t){var i=this;t&&t.Result?(this.phone.log("*************** twilioToken_requestTrue"),e.ajaxSettings.cache=!0,e.getScript("//static.twilio.com/libs/twiliojs/1.2/twilio.min.js",function(e,s){i.phone.onGetScript(s),"success"===s&&(i.token=t.Result,i.setupDevice(t.Result))})):i.phone.onGetScript()},f.prototype.setupDevice=function(e){var i=this;this.phone.log("*************** setup"),this.phone.phoneSupport(!1,"10,1,000"),this.device=Twilio.Device,this.device.setup(e,{}),this.device.ready(function(e){i.phone.log("*************** ready ",e),i.webSocket=t.socket,i.action(vi.PhoneAction.Online)}),this.device.offline(function(e){i.phone.log("*************** offline ",e),i.action(vi.PhoneAction.Offline)}),this.device.error(function(e){switch(i.phone.log("*************** error ",e),e.message){case"This AccessToken is no longer valid":case"Cannot register. Token not validated":i.token=null,i.device.destroy()}i.action(vi.PhoneAction.OfflineError)}),this.device.connect(function(e){i.phone.log("*************** connect ",e),"outbound"===e.message.Direction?i.action(vi.PhoneAction.Outgoing):"inbound"===e.message.Direction&&i.action(vi.PhoneAction.Incoming)}),this.device.disconnect(function(e){i.phone.log("*************** disconnect ",e),i.action(vi.PhoneAction.Online)}),this.device.incoming(function(e){i.phone.log("*************** incoming ",e),i.connection=e,i.phone.incomingCall(e.parameters.From)}),this.device.cancel(function(e){i.phone.log("*************** cancel ",e),i.action(vi.PhoneAction.Online)}),this.device.presence(function(e){i.phone.log("*************** presence ",e)})},f.prototype.call=function(e){this.connection=this.device.connect({PhoneNumber:e,Direction:"outbound"})},f.prototype.answer=function(){this.connection.accept()},f.prototype.hangup=function(){this.connection&&(this.connection.status&&"pending"===this.connection.status()?this.connection.reject():this.connection.disconnect(),"closed"!==this.connection.status()&&_.delay(_.bind(function(){this.hangup()},this),1e3))},f.prototype.reconnect=function(){var e=0;return function(t){clearInterval(e),t&&(e=setInterval(_.bind(function(){this.device&&this.token?this.device.setup(this.token):this.init()},this),t))}}(),f.prototype.getLogs=function(e,t){var i={Action:"GetTwilioLogs",StartTime:moment().subtract("months",3).format("YYYY-MM-DD")};Ci.Ajax.send(i,e,t)},y.prototype.pgp=null,y.prototype.pgpKeyring=null,y.prototype.keys=[],y.prototype.getKeys=function(){return this.keys()},y.prototype.getKeysObservable=function(){return this.keys},y.prototype.reloadKeysFromStorage=function(){var e=[],t=this.pgpKeyring.getAllKeys();_.each(t,function(t){t&&t.primaryKey&&e.push(new v(t))}),this.keys(e)},y.prototype.convertToNativeKeys=function(e){return _.map(e,function(e){return e&&e.pgpKey?e.pgpKey:e})},y.prototype.cloneKey=function(e){var t=null;return e&&(t=this.pgp.key.readArmored(e.armor()),t&&!t.err&&t.keys&&t.keys[0]?(t=t.keys[0],t&&t.primaryKey||(t=null)):t=null),t},y.prototype.decryptKeyHelper=function(e,t,i,s){if(t)try{t.decrypt(Si.pString(i)),t&&t.primaryKey&&t.primaryKey.isDecrypted||e.addError(S.Enum.KeyIsNotDecodedError,s||"")}catch(o){e.addExceptionMessage(o,S.Enum.KeyIsNotDecodedError,s||"")}else e.addError(S.Enum.KeyIsNotDecodedError,s||"")},y.prototype.verifyMessageHelper=function(e,t,i){var s=!1,o=null,n=[],r=[],a=[];if(i&&i.getSigningKeyIds)if(r=i.getSigningKeyIds(),r&&0<r.length)if(a=this.findKeysByEmails([t],!0),a&&0!==a.length){n=[];try{n=i.verify(this.convertToNativeKeys(a))}catch(l){e.addNotice(S.Enum.VerifyErrorNotice,t)}n&&0<n.length&&(o=_.find(n,function(e){return e&&e.keyid&&e.valid}),o&&o.keyid&&a&&a[0]&&o.keyid.toHex().toLowerCase()===a[0].getId()?s=!0:e.addNotice(S.Enum.VerifyErrorNotice,t))}else e.addNotice(S.Enum.PublicKeyNotFoundNotice,t);else e.addNotice(S.Enum.NoSignDataNotice);else e.addError(S.Enum.UnknownError);return s||e.hasNotices()||e.addNotice(S.Enum.VerifyErrorNotice),s},y.prototype.generateKey=function(e,t,i){var s=new S,o=null;try{o=this.pgp.generateKeyPair({userId:e,numBits:Si.pInt(i),passphrase:Si.trim(t)})}catch(n){s.addExceptionMessage(n)}if(o&&o.privateKeyArmored)try{this.pgpKeyring.privateKeys.importKey(o.privateKeyArmored),this.pgpKeyring.publicKeys.importKey(o.publicKeyArmored),this.pgpKeyring.store()}catch(n){s.addExceptionMessage(n,S.Enum.GenerateKeyError)}else s.addError(S.Enum.GenerateKeyError);return this.reloadKeysFromStorage(),s},y.prototype.splitKeys=function(e){var t=[],i=0,s=30,o=null,n=Si.trim(e),r=/[\-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}[\s\S]+?[\-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}/gi;for(n=n.replace(/[\r\n]([a-zA-Z0-9]{2,}:[^\r\n]+)[\r\n]+([a-zA-Z0-9\/\\+=]{10,})/g,"\n$1---xyx---$2").replace(/[\n\r]+/g,"\n").replace(/---xyx---/g,"\n\n");;){if(o=r.exec(n),!o||0>s)break;o[0]&&o[1]&&o[2]&&o[1]===o[2]&&("PRIVATE"===o[1]||"PUBLIC"===o[1])&&(t.push([o[1],o[0]]),i++),s--}return t},y.prototype.importKeys=function(e){e=Si.trim(e);var t=0,i=0,s=new S,o=null,n=[];if(!e)return s.addError(S.Enum.InvalidArgumentErrors);for(n=this.splitKeys(e),t=0;t<n.length;t++)if(o=n[t],"PRIVATE"===o[0])try{this.pgpKeyring.privateKeys.importKey(o[1]),i++}catch(r){s.addExceptionMessage(r,S.Enum.ImportKeyError,"private")}else if("PUBLIC"===o[0])try{this.pgpKeyring.publicKeys.importKey(o[1]),i++}catch(r){s.addExceptionMessage(r,S.Enum.ImportKeyError,"public")}return i>0?this.pgpKeyring.store():s.addError(S.Enum.ImportNoKeysFoundError),this.reloadKeysFromStorage(),s},y.prototype.getArmorInfo=function(e){e=Si.trim(e);var t=0,i=0,s=null,o=[],n=null,r=[];if(!e)return!1;for(r=this.splitKeys(e),t=0;t<r.length;t++)if(n=r[t],"PRIVATE"===n[0])try{s=this.pgp.key.readArmored(n[1]),s&&!s.err&&s.keys&&s.keys[0]&&o.push(new v(s.keys[0])),i++}catch(a){o.push(null)}else if("PUBLIC"===n[0])try{s=this.pgp.key.readArmored(n[1]),s&&!s.err&&s.keys&&s.keys[0]&&o.push(new v(s.keys[0])),i++}catch(a){o.push(null)}return o},y.prototype.findKeyByID=function(e,t){t=!!t,e=e.toLowerCase();var i=_.find(this.keys(),function(i){var s=!1,o=null;return i&&t===i.isPublic()&&(o=i.pgpKey.getKeyIds(),o&&(s=_.find(o,function(t){return t&&t.toHex&&e===t.toHex().toLowerCase()}))),!!s});return i?i:null},y.prototype.findKeysByEmails=function(e,t,i){t=!!t;var s=[],o=this.keys();return _.each(e,function(e){var n=_.find(o,function(i){return i&&t===i.isPublic()&&e===i.getEmail()});n?s.push(n):i&&i.addError(t?S.Enum.PublicKeyNotFoundError:S.Enum.PrivateKeyNotFoundError,e)}),s},y.prototype.decryptAndVerify=function(e,t,i,s){var o=this,n=null,r=null,a=null,l=null,h=null,c=new S,u=[];if(n=this.pgp.message.readArmored(e),n&&n.decrypt)if(u=n.getEncryptionKeyIds(),u&&(a=null,r=null,_.each(u,function(e){r||(r=o.findKeyByID(e.toHex(),!1),r&&t!==r.getEmail()&&(r=null))}),r&&(a=r),a||_.each(u,function(e){a||(a=o.findKeyByID(e.toHex(),!1))})),a){if(l=this.cloneKey(this.convertToNativeKeys([a])[0]),this.decryptKeyHelper(c,l,s,a.getEmail()),l&&!c.hasErrors())try{h=n.decrypt(l)}catch(d){c.addExceptionMessage(d,S.Enum.DecryptError),h=null}h&&!c.hasErrors()&&(this.verifyMessageHelper(c,i,h),c.result=h.getText())}else c.addError(S.Enum.PrivateKeyNotFoundError);return c},y.prototype.verify=function(e,t){var i=null,s=new S;return i=this.pgp.cleartext.readArmored(e),i&&i.getText&&i.verify?(this.verifyMessageHelper(s,t,i),s.result=i.getText()):s.addError(S.Enum.CanNotReadMessage),s},y.prototype.encrypt=function(e,t){var i=new S,s=this.findKeysByEmails(t,!0,i);if(!i.hasErrors())try{i.result=this.pgp.encryptMessage(this.convertToNativeKeys(s),e)}catch(o){i.addExceptionMessage(o,S.Enum.EncryptError)}return i},y.prototype.sign=function(e,t,i){var s=new S,o=null,n=null,r=this.findKeysByEmails([t],!1,s);if(!s.hasErrors()&&(o=this.convertToNativeKeys(r)[0],n=this.cloneKey(o),this.decryptKeyHelper(s,n,i,t),n&&!s.hasErrors()))try{s.result=this.pgp.signClearMessage([n],e)}catch(a){s.addExceptionMessage(a,S.Enum.SignError,t)}return s},y.prototype.signAndEncrypt=function(e,t,i,s){var o=null,n=null,r=new S,a=this.findKeysByEmails([t],!1,r),l=this.findKeysByEmails(i,!0,r);if(!r.hasErrors()&&(o=this.convertToNativeKeys(a)[0],n=this.cloneKey(o),this.decryptKeyHelper(r,n,s,t),n&&!r.hasErrors()))try{r.result=this.pgp.signAndEncryptMessage(this.convertToNativeKeys(l),n,e)}catch(h){r.addExceptionMessage(h,S.Enum.SignAndEncryptError)}return r},y.prototype.deleteKey=function(e){var t=new S;if(e)try{this.pgpKeyring[e.isPrivate()?"privateKeys":"publicKeys"].removeForId(e.getFingerprint()),this.pgpKeyring.store()}catch(i){t.addExceptionMessage(i,S.Enum.DeleteError)}else t.addError(e?S.Enum.UnknownError:S.Enum.InvalidArgumentError);return this.reloadKeysFromStorage(),t},v.prototype.pgpKey=null,v.prototype.emailParts=null,v.prototype.user="",v.prototype.getId=function(){return this.pgpKey.primaryKey.getKeyId().toHex().toLowerCase()},v.prototype.getEmail=function(){return this.emailParts.email||this.user},v.prototype.getUser=function(){return this.user},v.prototype.getFingerprint=function(){return this.pgpKey.primaryKey.getFingerprint()},v.prototype.getBitSize=function(){return this.pgpKey.primaryKey.getBitSize()},v.prototype.getArmor=function(){return this.pgpKey.armor()},v.prototype.isPrivate=function(){return!!this.pgpKey.isPrivate()},v.prototype.isPublic=function(){return!this.isPrivate()},S.Enum={UnknownError:0,UnknownNotice:1,InvalidArgumentError:2,GenerateKeyError:10,ImportKeyError:20,ImportNoKeysFoundError:21,PrivateKeyNotFoundError:30,PublicKeyNotFoundError:31,KeyIsNotDecodedError:32,SignError:40,VerifyError:41,EncryptError:42,DecryptError:43,SignAndEncryptError:44,VerifyAndDecryptError:45,CanNotReadMessage:50,CanNotReadKey:51,DeleteError:60,PublicKeyNotFoundNotice:70,PrivateKeyNotFoundNotice:71,VerifyErrorNotice:72,NoSignDataNotice:73},S.prototype.result=!1,S.prototype.errors=null,S.prototype.notices=null,S.prototype.addError=function(e,t){return this.result=!1,this.errors=this.errors||[],this.errors.push([e||S.Enum.UnknownError,t||""]),this},S.prototype.addNotice=function(e,t){return this.notices=this.notices||[],this.notices.push([e||S.Enum.UnknownNotice,t||""]),this},S.prototype.addExceptionMessage=function(e,t,i){return e&&(this.result=!1,this.exceptions=this.exceptions||[],this.exceptions.push(""+(e.name||"unknown")+": "+(e.message||""))),Si.isUnd(t)||this.addError(t,i),this},S.prototype.hasErrors=function(){return this.errors&&0<this.errors.length},S.prototype.hasNotices=function(){return this.notices&&0<this.notices.length},A.prototype.onShow=function(e,t,i,s){this.alertDesc(e),this.closeCallback=t||null,this.title(i||""),this.okButtonText(s||Si.i18n("MAIN/BUTTON_OK"))},A.prototype.popupTemplate=function(){return"Popups_AlertPopupViewModel"},A.prototype.onEnterHandler=function(){this.close()},A.prototype.close=function(){Si.isFunc(this.closeCallback)&&this.closeCallback(),this.closeCommand()},C.prototype.onShow=function(e,t,i,s,o){this.title(i||""),this.okButtonText(s||Si.i18n("MAIN/BUTTON_OK")),this.cancelButtonText(o||Si.i18n("MAIN/BUTTON_CANCEL")),Si.isFunc(t)&&(this.fConfirmCallback=t,this.confirmDesc(e)),this.shown=!0},C.prototype.onHide=function(){this.shown=!1},C.prototype.popupTemplate=function(){return"Popups_ConfirmPopupViewModel"},C.prototype.onEnterHandler=function(){this.yesClick()},C.prototype.yesClick=function(){this.shown&&this.fConfirmCallback&&this.fConfirmCallback(!0),this.closeCommand()},C.prototype.noClick=function(){this.fConfirmCallback&&this.fConfirmCallback(!1),this.closeCommand()},C.prototype.onEscHandler=function(){this.noClick()},E.prototype.popupTemplate=function(){return"Popups_AccountCreatePopupViewModel"},E.prototype.init=function(){this.isFirstStep(!0),this.friendlyName(""),this.email(""),this.incomingMailLogin(""),this.incomingLoginFocused(!1),this.incomingMailPassword(""),this.outgoingMailLogin(""),this.outgoingMailPassword(""),this.outServerFocused(!1),this.clearServers()},E.prototype.clearServers=function(){this.incomingMailPort(143),this.incomingMailServer(""),this.outgoingMailPort(25),this.outgoingMailServer(""),this.useSmtpAuthentication(!0)},E.prototype.onShow=function(){this.emailFocus(!0),this.init()},E.prototype.onFirstSaveClick=function(){if(this.isEmptyFirstFields())this.loading(!1);else{var e={Action:"EmailDomainData",Email:this.email()};this.loading(!0),Ci.Ajax.send(e,this.onEmailDomainDataResponse,this) }},E.prototype.onSecondSaveClick=function(){if(this.isEmptySecondFields())this.loading(!1);else{var e={Action:"AccountCreate",AccountID:this.editedAccountId(),FriendlyName:this.friendlyName(),Email:this.email(),IncomingMailLogin:this.incomingMailLogin(),IncomingMailPassword:this.incomingMailPassword(),IncomingMailServer:this.incomingMailServer(),IncomingMailPort:parseInt(this.incomingMailPort(),10),OutgoingMailServer:this.outgoingMailServer(),OutgoingMailLogin:this.outgoingMailLogin(),OutgoingMailPassword:this.outgoingMailPassword(),OutgoingMailPort:parseInt(this.outgoingMailPort(),10),OutgoingMailAuth:this.useSmtpAuthentication()?2:0};this.loading(!0),Ci.Ajax.send(e,this.onAccountCreateResponse,this)}},E.prototype.onSaveClick=function(){this.loading()||(this.isFirstStep()?this.onFirstSaveClick():this.onSecondSaveClick())},E.prototype.onCancelClick=function(){this.closeCommand(),this.init()},E.prototype.onEmailDomainDataResponse=function(e){this.incomingMailLogin(this.email()),e.Result?(this.incomingMailPort(e.Result.IncomingMailPort),this.incomingMailServer(e.Result.IncomingMailServer),this.outgoingMailPort(e.Result.OutgoingMailPort),this.outgoingMailServer(e.Result.OutgoingMailServer),this.onSecondSaveClick()):(this.loading(!1),this.isFirstStep(!1),this.incomingLoginFocused(!0))},E.prototype.onAccountCreateResponse=function(e,t){if(this.loading(!1),e.Result){var i=new $,s=parseInt(e.Result.IdAccount,10);i.init(s,t.Email,t.FriendlyName),i.updateExtended(t),i.setExtensions(e.Result.Extensions),Ti.Accounts.addAccount(i),this.closeCommand()}else Ci.Api.showErrorByCode(e,Si.i18n("WARNING/CREATING_ACCOUNT_ERROR"))},E.prototype.isEmptyFirstFields=function(){switch(""){case this.email():return this.emailFocus(!0),!0;case this.incomingMailPassword():return this.incomingMailFocus(!0),!0;default:return!1}},E.prototype.isEmptySecondFields=function(){switch(""){case this.email():return this.emailFocus(!0),!0;case this.incomingMailLogin():return this.incomingLoginFocused(!0),!0;case this.incomingMailServer():return this.incomingServerFocused(!0),!0;case this.outgoingMailServer():return this.outServerFocused(!0),!0;default:return!1}},T.prototype.popupTemplate=function(){return"Popups_AccountCreateIdentityPopupViewModel"},T.prototype.onShow=function(e){var t=Ti.Accounts.getAccount(e),i=new tt;i.accountId(e),i.email(t.email()),this.oIdentityPropertiesViewModel.populate(i),this.oIdentityPropertiesViewModel.friendlyNameHasFocus(!0)},T.prototype.cancel=function(){this.closeCommand()},F.prototype.popupTemplate=function(){return"Popups_FetcherAddPopupViewModel"},F.prototype.onShow=function(){this.incomingMailServer(""),this.incomingMailPort(110),this.incomingMailLogin(""),this.incomingMailPassword(""),this.folder(""),this.outgoingMailServer(""),this.outgoingMailPort(25),this.leaveMessagesOnServer(!0)},F.prototype.onSaveClick=function(){if(this.isEmptyRequiredFields())Ci.Api.showError(Si.i18n("WARNING/FETCHER_CREATE_ERROR"));else{var e={Action:"FetcherCreate",AccountID:this.defaultAccountId(),Folder:this.folder(),IncomingMailServer:this.incomingMailServer(),IncomingMailPort:parseInt(this.incomingMailPort(),10),IncomingMailLogin:this.incomingMailLogin(),IncomingMailPassword:""===this.incomingMailPassword()?"******":this.incomingMailPassword(),LeaveMessagesOnServer:this.leaveMessagesOnServer()?1:0};this.loading(!0),Ci.Ajax.send(e,this.onAddFetcherResponse,this)}},F.prototype.onAddFetcherResponse=function(e){this.loading(!1),e.Result?(Ti.Accounts.populateFetchers(),this.closeCommand()):Ci.Api.showErrorByCode(e)},F.prototype.onCancelClick=function(){this.newFolderCreating()||this.closeCommand()},F.prototype.onEscHandler=function(){this.onCancelClick()},F.prototype.isEmptyRequiredFields=function(){switch(""){case this.incomingMailServer():return this.serverIsSelected(!0),!0;case this.incomingMailLogin():return this.loginIsSelected(!0),!0;case this.incomingMailPassword():return this.passwordIsSelected(!0),!0;default:return!1}},F.prototype.onAddNewFolderClick=function(){this.newFolderCreating(!0),Ci.Screens.showPopup(w,[_.bind(this.chooseFolderInList,this)])},F.prototype.chooseFolderInList=function(e,t){var i=this.folderList().delimiter(),s=[];""!==e&&""!==t&&_.each(this.options(),_.bind(function(o){e===o.name&&(s=o.fullName.split(i),s.pop(),t===s.join(i)&&this.folder(o.fullName))},this)),this.newFolderCreating(!1)},I.prototype.onShow=function(){var e=Ci.MailCache.editedFolderList();this.sentFolderFullName(e.sentFolderFullName()),this.draftsFolderFullName(e.draftsFolderFullName()),this.allowSpamFolderEditing()&&this.spamFolderFullName(e.spamFolderFullName()),this.trashFolderFullName(e.trashFolderFullName()),this.options(this.folders().getOptions(Si.i18n("SETTINGS/ACCOUNT_FOLDERS_NO_USAGE_ASSIGNED"),!1,!1,!1))},I.prototype.popupTemplate=function(){return"Popups_FolderSystemPopupViewModel"},I.prototype.onResponseSetupSystemFolders=function(e){e.Result===!1&&(Ci.Api.showErrorByCode(e,Si.i18n("ACCOUNT_FOLDERS_ERROR_SETUP_SPECIAL_FOLDERS")),Ci.MailCache.getFolderList(Ti.Accounts.editedId()))},I.prototype.onOKClick=function(){var e=this.folders(),t=!1,i=null;this.sentFolderFullName()!==e.sentFolderFullName()&&(e.sentFolderFullName(this.sentFolderFullName()),t=!0),this.draftsFolderFullName()!==e.draftsFolderFullName()&&(e.draftsFolderFullName(this.draftsFolderFullName()),t=!0),this.allowSpamFolderEditing()&&this.spamFolderFullName()!==e.spamFolderFullName()&&(e.spamFolderFullName(this.spamFolderFullName()),t=!0),this.trashFolderFullName()!==e.trashFolderFullName()&&(e.trashFolderFullName(this.trashFolderFullName()),t=!0),t&&(i={Action:"SetupSystemFolders",AccountID:Ti.Accounts.editedId(),Sent:e.sentFolderFullName(),Drafts:e.draftsFolderFullName(),Trash:e.trashFolderFullName(),Spam:e.spamFolderFullName()},Ci.Ajax.send(i,this.onResponseSetupSystemFolders,this)),this.closeCommand()},I.prototype.onCancelClick=function(){this.closeCommand()},I.prototype.onEscHandler=function(){this.onCancelClick()},w.prototype.popupTemplate=function(){return"Popups_FolderCreatePopupViewModel"},w.prototype.onShow=function(e){this.fCallback=e,this.folderName(""),this.parentFolder(""),this.folderNameFocus(!0)},w.prototype.onResponseFolderCreate=function(e){e.Result?Ci.MailCache.getFolderList(Ti.Accounts.editedId()):(this.loading(!1),Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ACCOUNT_FOLDERS_CANT_CREATE_FOLDER")))},w.prototype.onOKClick=function(){var e=""===this.parentFolder()?this.namespace():this.parentFolder(),t={Action:"FolderCreate",AccountID:Ti.Accounts.editedId(),FolderNameInUtf8:this.folderName(),FolderParentFullNameRaw:e,Delimiter:this.folders().delimiter()};this.loading(!0),Ci.Ajax.send(t,this.onResponseFolderCreate,this)},w.prototype.onCancelClick=function(){this.loading()||(this.fCallback&&this.fCallback("",""),this.closeCommand())},w.prototype.onEscHandler=function(){this.onCancelClick()},P.prototype.onShow=function(e){this.isHelpdesk(e),this.init()},P.prototype.popupTemplate=function(){return"Popups_ChangePasswordPopupViewModel"},P.prototype.init=function(){this.currentPassword(""),this.newPassword(""),this.confirmPassword("")},P.prototype.onResponse=function(e){e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ACCOUNT_PROPERTIES_NEW_PASSWORD_UPDATE_ERROR")):(Ci.Api.showReport(Si.i18n("SETTINGS/ACCOUNT_PROPERTIES_CHANGE_PASSWORD_SUCCESS")),this.closeCommand(),this.init())},P.prototype.onOKClick=function(){var e=null;this.confirmPassword()!==this.newPassword()?Ci.Api.showError(Si.i18n("WARNING/PASSWORDS_DO_NOT_MATCH")):this.newPassword().length<Ti.App.PasswordMinLength?Ci.Api.showError(Si.i18n("WARNING/PASSWORDS_MIN_LENGTH_ERROR")):!Ti.App.PasswordMustBeComplex||this.newPassword().match(/([0-9])/)&&this.newPassword().match(/([!,%,&,@,#,$,^,*,?,_,~])/)?this.isHelpdesk()?(e={Action:"HelpdeskUpdateUserPassword",CurrentPassword:this.currentPassword(),NewPassword:this.newPassword()},Ci.Ajax.sendExt(e,this.onResponse,this)):(e={Action:"UpdateAccountPassword",AccountID:Ti.Accounts.editedId(),CurrentIncomingMailPassword:this.currentPassword(),NewIncomingMailPassword:this.newPassword()},Ci.Ajax.send(e,this.onResponse,this)):Ci.Api.showError(Si.i18n("WARNING/PASSWORD_MUST_BE_COMPLEX"))},P.prototype.onCancelClick=function(){this.closeCommand()},M.prototype.onShow=function(e){this.folderName(""),this.folderName.focus(!0),this.folderName.error(""),Si.isFunc(e)&&(this.fCallback=e)},M.prototype.popupTemplate=function(){return"Popups_FileStorage_FolderCreatePopupViewModel"},M.prototype.onOKClick=function(){if(this.folderName.error(""),this.fCallback){var e=this.fCallback(this.folderName());e?this.folderName.error(""+e):this.closeCommand()}else this.closeCommand()},M.prototype.onCancelClick=function(){this.closeCommand()},R.prototype.onShow=function(e){this.link(""),this.linkFocus(!0),Si.isFunc(e)&&(this.fCallback=e),this.checkTimer=setTimeout(_.bind(this.checkUrl,this),2e3)},R.prototype.popupTemplate=function(){return"Popups_FileStorage_LinkCreatePopupViewModel"},R.prototype.checkUrl=function(){clearTimeout(this.checkTimer),this.link()!==this.linkPrev()&&(this.linkPrev(this.link()),Ci.Ajax.send({Action:"CheckUrl",Url:this.link()},this.onCheckUrlResponse,this)),this.checkTimer=setTimeout(_.bind(this.checkUrl,this),1e3)},R.prototype.onCheckUrlResponse=function(e){var t=new it;e.Result?(t.isPopupItem(!0),t.linkUrl(this.link()),t.fileName(e.Result.Name),t.size(e.Result.Size),t.allowDownload(!1),e.Result.Thumb&&(t.thumb(!0),t.thumbnailSrc(e.Result.Thumb)),this.fileItem(t),this.urlChecked(!0)):this.urlChecked(!1)},R.prototype.executeSave=function(){this.fCallback&&(this.fCallback(this.fileItem()),this.link(""),this.linkPrev(""),this.urlChecked(!1)),clearTimeout(this.checkTimer),this.closeCommand()},R.prototype.onCancelClick=function(){this.link(""),this.linkPrev(""),this.urlChecked(!1),clearTimeout(this.checkTimer),this.closeCommand()},R.prototype.onEscHandler=function(){this.onCancelClick()},D.prototype.onShow=function(e,t){this.item=e,this.item.nameForEdit(this.item.fileName()),this.name(this.item.nameForEdit()),this.name.focus(!0),this.name.error(""),Si.isFunc(t)&&(this.fCallback=t)},D.prototype.popupTemplate=function(){return"Popups_FileStorage_RenamePopupViewModel"},D.prototype.onOKClick=function(){if(this.name.error(""),this.fCallback){this.item.nameForEdit(this.name());var e=this.fCallback(this.item);e?this.name.error(""+e):this.closeCommand()}else this.closeCommand()},D.prototype.onCancelClick=function(){this.closeCommand()},N.prototype.onShow=function(e){this.item=e,this.pub(""),Ci.Ajax.send({Action:"FilesCreatePublicLink",Account:Ti.Accounts.defaultId(),Type:e.storageType(),Path:e.path(),Name:e.fileName(),Size:e.size(),IsFolder:e.isFolder()?"1":"0"},this.onFilesCreatePublicLinkResponse,this)},N.prototype.onFilesCreatePublicLinkResponse=function(e){e.Result&&(this.pub(e.Result),this.pubFocus(!0),this.item.shared(!0))},N.prototype.popupTemplate=function(){return"Popups_FileStorage_SharePopupViewModel"},N.prototype.onOKClick=function(){this.closeCommand()},N.prototype.onFilesDeletePublicLinkResponse=function(){this.closeCommand()},N.prototype.onCancelSharingClick=function(){this.item&&(Ci.Ajax.send({Action:"FilesDeletePublicLink",Account:Ti.Accounts.defaultId(),Type:this.item.storageType(),Path:this.item.path(),Name:this.item.fileName()},this.onFilesDeletePublicLinkResponse,this),this.item.shared(!1))},k.prototype.onShow=function(e){Si.isFunc(e)&&(this.fCallback=e),this.fileStorageViewModel.onShow()},k.prototype.onApplyBindings=function(e){this.fileStorageViewModel.onApplyBindings(e)},k.prototype.popupTemplate=function(){return"Popups_FileStorage_FileStoragePopupViewModel"},k.prototype.onSelectClick=function(){var e=this.fileStorageViewModel.selector.listCheckedAndSelected(),t=_.filter(e,function(e){return!e.isFolder()},this);this.fCallback&&this.fCallback(t),this.closeCommand()},k.prototype.onCancelClick=function(){this.closeCommand()},L.prototype.clearFields=function(){this.calendarName(""),this.calendarDescription(""),this.selectedColor(this.colors[0]),this.calendarId(null)},L.prototype.onShow=function(e,t,i){this.clearFields(),Si.isFunc(e)&&(this.fCallback=e),Si.isUnd(t)||(this.colors(t),this.selectedColor(t[0])),Si.isUnd(i)?this.popupTitle(Si.i18n("CALENDAR/TITLE_CREATE_CALENDAR")):(this.popupTitle(Si.i18n(i.name()?"CALENDAR/TITLE_EDIT_CALENDAR":"CALENDAR/TITLE_CREATE_CALENDAR")),this.calendarName(i.name?i.name():""),this.calendarDescription(i.description?i.description():""),this.selectedColor(i.color?i.color():""),this.calendarId(i.id?i.id:null))},L.prototype.popupTemplate=function(){return"Popups_Calendar_CalendarPopupViewModel"},L.prototype.onSaveClick=function(){""===this.calendarName()?Ci.Screens.showPopup(A,[Si.i18n("CALENDAR/WARNING_BLANK_CALENDAR_NAME")]):(this.fCallback&&(this.fCallback(this.calendarName(),this.calendarDescription(),this.selectedColor(),this.calendarId()),this.clearFields()),this.closeCommand())},L.prototype.onCancelClick=function(){this.closeCommand()},O.prototype.onShow=function(e,t){Si.isFunc(e)&&(this.fCallback=e),Si.isUnd(t)||(this.color(t.color?t.color():""),this.calendarId(t.id?t.id:""))},O.prototype.popupTemplate=function(){return"Popups_Calendar_ImportPopupViewModel"},O.prototype.onFileImportStart=function(){this.importing(!0)},O.prototype.onFileImportComplete=function(){this.importing(!1),this.fCallback(),this.closeCommand()},O.prototype.onApplyBindings=function(t){var i=this;this.oJua=new Jua({action:"?/Upload/Calendars/",name:"jua-uploader",queueSize:1,clickElement:e("#jue_import_button",t),disableAjaxUpload:!1,disableDragAndDrop:!0,disableMultiple:!0,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()},AdditionalData:function(){return JSON.stringify({CalendarID:i.calendarId()})}}}),this.oJua.on("onStart",_.bind(this.onFileImportStart,this)).on("onComplete",_.bind(this.onFileImportComplete,this)),this.allowDragNDrop(this.oJua.isDragAndDropSupported())},O.prototype.onCancelClick=function(){this.closeCommand()},x.prototype.onShow=function(e,t){Si.isFunc(e)&&(this.fCallback=e),Si.isUnd(t)||(this.selectedColor(t.color()),this.calendarId(t.id),this.calendarUrl(t.davUrl()+t.url()),this.exportUrl(t.exportUrl()),this.icsLink(t.davUrl()+t.url()+"?export"),this.isPublic(t.isPublic()),this.shares(t.shares().slice(0)),this.oldShares(t.shares().slice(0)),this.owner(t.owner()),this.sharedToAll(t.isSharedToAll()),this.sharedToAllAccess(t.sharedToAllAccess))},x.prototype.popupTemplate=function(){return"Popups_Calendar_SharePopupViewModel"},x.prototype.onSaveClick=function(){this.fCallback&&this.fCallback(this.calendarId(),this.isPublic(),this.shares(),this.sharedToAll(),this.sharedToAllAccess()),this.closePopup()},x.prototype.onCancelClick=function(){this.shares(this.oldShares()),this.closePopup()},x.prototype.onEscHandler=function(){this.onCancelClick()},x.prototype.closePopup=function(){this.cleanAll(),this.closeCommand()},x.prototype.cleanAll=function(){this.newShare(""),this.newShareAccess(vi.CalendarAccess.Read),this.shareToAllAccess=i.observable(vi.CalendarAccess.Read),this.shareAutocompleteItem(null),this.canAdd(!1)},x.prototype.addShare=function(){var e=this.shareAutocompleteItem()?this.shareAutocompleteItem().email:this.newShare();this.canAdd()?(this.shares.push({name:this.shareAutocompleteItem()?this.shareAutocompleteItem().name:"",email:e,access:this.newShareAccess()}),this.cleanAll()):(this.whomAnimate(e),this.recivedAnim(!0))},x.prototype.removeShare=function(e){this.shares.remove(e)},x.prototype.autocompleteCallback=function(e,t){var i={Action:"ContactSuggestions",Search:e,GlobalOnly:"1"};this.shareAutocompleteItem(null),e=Si.trim(e),""!==e?Ci.Ajax.send(i,function(e){var i=[];e&&e.Result&&e.Result&&e.Result.List&&(i=_.map(e.Result.List,function(e){return e&&e.Email&&e.Email!==this.owner()?e.Name&&0<Si.trim(e.Name).length?e.ForSharedToAll?{value:e.Name,name:e.Name,email:e.Email,frequency:e.Frequency}:{value:'"'+e.Name+'" <'+e.Email+">",name:e.Name,email:e.Email,frequency:e.Frequency}:{value:e.Email,name:"",email:e.Email,frequency:e.Frequency}:null},this),i=_.sortBy(_.compact(i),function(e){return e.frequency}).reverse(),this.newShareList(i),this.setGlobal(this.newShare(),i)),t(i)},this):t([])},x.prototype.setGlobal=function(e,t){var i=_.any(t,function(t){return t.email===e},this),s=_.any(this.shares(),function(t){return t.email===e},this);this.canAdd(i&&!s)},x.prototype.itsMe=function(e){return e===this.defaultAccount.email()},U.prototype.onShow=function(e,t){Si.isFunc(e)&&(this.fCallback=e),Si.isUnd(t)||(this.selectedColor(t.color()),this.calendarId(t.id),this.calendarUrl(t.davUrl()+t.url()),this.exportUrl(t.exportUrl()),this.icsLink(t.davUrl()+t.url()+"?export"),this.isPublic(t.isPublic()),this.pubUrl(t.pubUrl()),this.exportUrl(t.exportUrl()))},U.prototype.popupTemplate=function(){return"Popups_Calendar_GetLinkPopupViewModel"},U.prototype.onCancelClick=function(){this.fCallback&&this.fCallback(this.calendarId(),this.isPublic()),this.closeCommand()},U.prototype.onEscHandler=function(){this.onCancelClick()},H.prototype.createDatePickerObject=function(t,i){e(t).datepicker({showOtherMonths:!0,selectOtherMonths:!0,monthNames:Si.getMonthNamesArray(),dayNamesMin:Si.i18n("DATETIME/DAY_NAMES_MIN").split(" "),firstDay:Ti.User.CalendarWeekStartsOn,showOn:"both",buttonText:"",buttonImage:"skins/Default/images/calendar-icon.png",buttonImageOnly:!0,dateFormat:this.dateFormatDatePicker,onSelect:i}),e(t).mousedown(function(){e("#ui-datepicker-div").toggle()})},H.prototype.initializeDatePickers=function(){this.createDatePickerObject(this.startDom(),this.selectStartDate.bind(this)),this.createDatePickerObject(this.endDom(),this.selectEndDate.bind(this)),this.createDatePickerObject(this.repeatEndDom(),Si.emptyFunction()),this.startDom().datepicker("option","dateFormat",this.dateFormatDatePicker),this.endDom().datepicker("option","dateFormat",this.dateFormatDatePicker),this.repeatEndDom().datepicker("option","dateFormat",this.dateFormatDatePicker)},H.prototype.onShow=function(e){var t=this.defaultAccount,i=t?t.email():"",s=t?t.friendlyName():"",o=e.End.clone(),n="";this.FCMoment=e.FCMoment,this.isMyEvent(i===(e.Owner||i)),this.callbackSave=e.CallbackSave,this.callbackDelete=e.CallbackDelete,this.callbackAttendeeActionDecline=e.CallbackAttendeeActionDecline,this.timeFormatMoment=e.TimeFormat,this.dateFormatMoment=Si.getDateFormatForMoment(e.DateFormat),this.dateFormatDatePicker=Si.getDateFormatForDatePicker(e.DateFormat),this.ampmTimeFormat(Ti.User.defaultTimeFormat()!==vi.TimeFormat.F24),this.initializeDatePickers(),this.allDay(e.AllDay),this.startDate(e.Start.format(this.dateFormatMoment)),this.startDom().datepicker("setDate",e.Start.toDate()),this.startTime(e.Start.format(this.timeFormatMoment)),e.End&&this.allDay()&&o.subtract(1,"days"),this.endDate(o?o.format(this.dateFormatMoment):this.startDate()),this.endDom().datepicker("setDate",o?o.toDate():e.Start.toDate()),this.endTime(o?o.format(this.timeFormatMoment):this.startTime()),this.calendars=e.Calendars,this.calendars&&this.calendarsList(_.filter(this.calendars.collection(),function(e){return e.isEditable()})),this.selectedCalendarId(e.SelectedCalendar),this.selectedCalendarId.valueHasMutated(),this.calendarId(e.SelectedCalendar),this.editableSwitch(this.selectedCalendarIsShared(),this.selectedCalendarIsEditable(),this.isMyEvent()),this.changeCalendarColor(this.selectedCalendarId()),this.id(e.ID||null),this.uid(e.Uid||null),this.recurrenceId(e.RecurrenceId||null),this.subject(e.Subject||""),this.location(e.Location||""),this.description(e.Description||""),this.allEvents(e.AllEvents||vi.CalendarEditRecurrenceEvent.AllEvents),this.populateAlarms(e.Alarms),this.appointment(e.Appointment),this.attendees(e.Attendees||[]),Ti.Accounts&&(n=Ti.Accounts.getAttendee(_.map(this.attendees(),function(e){return e.email},this))),this.setCurrentAttenderStatus(n,e.Attendees||[]),this.owner(e.Owner||i),this.ownerName(e.OwnerName||(this.isMyEvent()?s:"")),this.guestAutocomplete(""),this.excluded(e.Excluded||!1),this.repeatRuleParse(e.RRule||null),null===this.id()&&this.subjectFocus(!0),this.autosizeTrigger.notifySubscribers(!0),this.modified=!1,this.isAppointmentButtonsVisible(this.appointment()&&this.selectedCalendarIsEditable()&&_.find(this.attendees(),function(e){return e.email===i}))},H.prototype.popupTemplate=function(){return"Popups_Calendar_EventPopupViewModel"},H.prototype.changeCalendarColor=function(e){if(Si.isFunc(this.calendars.getCalendarById)){var t=this.calendars.getCalendarById(e);t&&(this.calendarColor(""),this.calendarColor(t.color()))}},H.prototype.onSaveClick=function(){if(""===this.subject())Ci.Screens.showPopup(A,[Si.i18n("CALENDAR/WARNING_EVENT_BLANK_SUBJECT"),_.bind(function(){this.subjectFocus(!0)},this)]);else{if(this.callbackSave){var e=this.repeatPeriod(),t="",i=null,s=0,o=0,n=moment(this.getDateTime(this.startDom(),this.startTime())),r=moment(this.getDateTime(this.endDom(),this.endTime())),a={calendarId:this.calendarId(),newCalendarId:this.selectedCalendarId(),id:this.id(),uid:this.uid(),recurrenceId:this.recurrenceId(),allEvents:this.allEvents(),subject:this.subject(),title:Si.getTitleForEvent(this.subject()),start:n,allDay:this.allDay(),location:this.location(),description:this.description(),alarms:this.getAlarmsArray(this.displayedAlarms()),attendees:this.attendees(),owner:this.owner(),modified:this.modified};this.allDay()&&r.add(1,"days"),a.end=r,e&&(t=this.repeatEndDom().datepicker("getDate"),i=t?this.getUnixTimestamp(t):null,s=this.repeatInterval(),o=this.repeatWeekNum(),e===vi.CalendarRepeatPeriod.Daily?a.rrule={byDays:[],count:null,end:2,interval:1,period:e,until:i,weekNum:null}:e===vi.CalendarRepeatPeriod.Weekly?(this.setDayOfWeek(),a.rrule={byDays:this.getDays(),count:null,end:2,interval:s,period:e,until:i,weekNum:null}):e===vi.CalendarRepeatPeriod.Monthly?a.rrule={byDays:[],count:null,end:0,interval:1,period:e,until:null,weekNum:null}:e===vi.CalendarRepeatPeriod.Yearly&&(a.rrule={byDays:[],count:null,end:0,interval:1,period:e,until:null,weekNum:null})),this.callbackSave(a)}this.closePopup()}},H.prototype.onEscHandler=function(){_.delay(_.bind(this.closePopup,this),100)},H.prototype.closePopup=function(){this.hideAll(),this.cleanAll(),this.closeCommand()},H.prototype.hideAll=function(){this.dateEdit(!1),this.repeatEdit(!1),this.guestsEdit(!1)},H.prototype.cleanAll=function(){this.subject(""),this.description(""),this.location(""),this.isRepeat(!1),this.allDay(!1),this.repeatPeriod(0),this.repeatInterval(1),this.repeatCount(null),this.repeatWeekNum(null),this.startDate(""),this.startTime(""),this.endDate(""),this.endTime(""),this.repeatEndDate(""),this.displayedAlarms([]),this.weekMO(!1),this.weekTU(!1),this.weekWE(!1),this.weekTH(!1),this.weekFR(!1),this.weekSA(!1),this.weekSU(!1),this.attendees([]),this.selectedCalendarId(""),this.attendees([])},H.prototype.onDeleteClick=function(){if(this.callbackDelete){var e={calendarId:this.selectedCalendarId(),id:this.id(),uid:this.uid(),recurrenceId:this.recurrenceId(),allEvents:this.allEvents(),subject:this.subject(),title:Si.getTitleForEvent(this.subject()),start:moment(this.getDateTime(this.startDom(),this.startTime())),end:moment(this.getDateTime(this.endDom(),this.endTime())),allDay:this.allDay(),location:this.location(),description:this.description()};this.callbackDelete(e)}this.closePopup()},H.prototype.showDates=function(e,t){t.stopPropagation(),this.dateEdit(!this.dateEdit())},H.prototype.showGuests=function(){if(this.attendees().length>0){var e=Si.i18n("CALENDAR/CONFIRM_CLOSE_ATTENDEERS"),t=_.bind(function(e){e&&(this.guestsEdit(!1),this.guestEmailFocus(!1),this.attendees([]))},this);Ci.Screens.showPopup(C,[e,t])}else this.guestsEdit(!this.guestsEdit()),this.guestEmailFocus(!this.guestEmailFocus())},H.prototype.onAddGuestClick=function(){var e=this.guestAutocompleteItem(),t=this.guestAutocomplete(),i=e||{name:"",email:t},s=_.any(this.attendees(),function(e){return e.email===i.email});""===i.email?Ci.Api.showError(Si.i18n("CALENDAR/EVENT_ERROR_ENTER_EMAIL")):i.email===this.owner()?this.recivedAnim(!0):s?this.recivedAnim(!0):this.attendees.push({status:0,name:i.name,email:i.email}),this.whomAnimate(i.email),this.guestAutocomplete("")},H.prototype.populateAlarms=function(e){e?(this.alarmOptions(this.getDisplayedAlarms(_.union(this.defaultAlarms(),e))),this.displayedAlarms(this.getDisplayedAlarms(e))):this.alarmOptions(this.getDisplayedAlarms(this.defaultAlarms()))},H.prototype.getDisplayedAlarms=function(e){var t,s,o=[];return e&&_.each(e,function(e){t=this["alarm"+e]=i.observable(e),t.subscribe(function(){this.disableAlarms()},this),s=e>0&&60>e?Si.i18n("CALENDAR/ALARM_MINUTES_PLURAL",{COUNT:e},null,e):e>=60&&1440>e?Si.i18n("CALENDAR/ALARM_HOURS_PLURAL",{COUNT:e/60},null,e/60):e>=1440&&10080>e?Si.i18n("CALENDAR/ALARM_DAYS_PLURAL",{COUNT:e/1440},null,e/1440):Si.i18n("CALENDAR/ALARM_WEEKS_PLURAL",{COUNT:e/10080},null,e/10080),o.push({value:e,alarm:t,text:s,isDisabled:!1})},this),_.sortBy(o,function(e){return e.value})},H.prototype.getDisplayedPeriods=function(){return[{label:Si.i18n("CALENDAR/EVENT_REPEAT_NEVER"),value:0},{label:Si.i18n("CALENDAR/EVENT_REPEAT_DAILY"),value:1},{label:Si.i18n("CALENDAR/EVENT_REPEAT_WEEKLY"),value:2},{label:Si.i18n("CALENDAR/EVENT_REPEAT_MONTHLY"),value:3},{label:Si.i18n("CALENDAR/EVENT_REPEAT_YEARLY"),value:4}]},H.prototype.getDisplayedIntervals=function(){for(var e=1,t=[];30>=e;e++)t.push({label:e+Si.i18n("th"),value:e});return t},H.prototype.getAlarmsArray=function(e){var t=[];return _.each(e,function(e){t.push(e.alarm())},this),_.sortBy(t,function(e){return-e})},H.prototype.addFirstAlarm=function(){if(this.displayedAlarms().length){var e=Si.i18n("CALENDAR/CONFIRM_CLOSE_ALARMS"),t=_.bind(function(e){e&&this.displayedAlarms.removeAll()},this);Ci.Screens.showPopup(C,[e,t])}else this.displayedAlarms(this.getDisplayedAlarms([this.alarmOptions()[0].value]))},H.prototype.addAlarm=function(){var e,t,s=0;t=_.sortBy(this.displayedAlarms(),function(e){return e.alarm()}),_.each(t,function(e){var t=e.alarm();5!==t&&5>=s?s=5:10!==t&&10>=s?s=10:15!==t&&15>=s?s=15:30!==t&&30>=s?s=30:1440!==t&&1440>=s&&(s=1440)}),e=this.getDisplayedAlarms([s])[0],this["alarm"+s]=i.observable(s),this.displayedAlarms.push(e)},H.prototype.removeAlarm=function(e){this.displayedAlarms.remove(e)},H.prototype.removeGuest=function(e){this.attendees.remove(e)},H.prototype.disableAlarms=function(){_.each(this.alarmOptions(),function(e){e.isDisabled=_.any(this.displayedAlarms(),function(t){return t.alarm()===e.value})},this),this.alarmOptions.valueHasMutated()},H.prototype.autocompleteCallback=function(e,t){var i={Action:"ContactSuggestions",Search:e,GlobalOnly:"0"};this.guestAutocompleteItem(null),e=Si.trim(e),""!==e?Ci.Ajax.send(i,function(e){var i=[];e&&e.Result&&e.Result&&e.Result.List&&(i=_.map(e.Result.List,function(e){return e&&e.Email&&e.Email!==this.owner()?e.Name&&0<Si.trim(e.Name).length?{value:'"'+e.Name+'" <'+e.Email+">",name:e.Name,email:e.Email,frequency:e.Frequency}:{value:e.Email,name:"",email:e.Email,frequency:e.Frequency}:null},this),i=_.sortBy(_.compact(i),function(e){return e.frequency}).reverse()),t(i)},this):t([])},H.prototype.repeatRuleParse=function(e){var t=this.allEvents();this.repeatEndDom().datepicker("option","minDate",this.getDateTime(this.endDom())),e&&t===vi.CalendarEditRecurrenceEvent.AllEvents&&(e.until&&this.datepickerSetDate(this.repeatEndDom(),new Date(1e3*e.until)),e.byDays.length&&_.each(e.byDays,function(e){this["week"+e](!0)},this),this.repeatPeriod(e.period),this.repeatInterval(e.interval),this.repeatCount(e.count),this.repeatWeekNum(e.weekNum))},H.prototype.getDays=function(){var e=[];return this.weekMO()&&e.push("MO"),this.weekTU()&&e.push("TU"),this.weekWE()&&e.push("WE"),this.weekTH()&&e.push("TH"),this.weekFR()&&e.push("FR"),this.weekSA()&&e.push("SA"),this.weekSU()&&e.push("SU"),e},H.prototype.onMainPanelClick=function(){this.dateEdit()&&this.dateEdit(!1)},H.prototype.onKeydown=function(e,t){(t.keyCode===vi.Key.Enter||t.keyCode===vi.Key.Esc)&&t.preventDefault()},H.prototype.onKeyup=function(e,t){"event_subject"!==t.target.id&&"event_location"!==t.target.id||t.keyCode!==vi.Key.Enter||this.onSaveClick()},H.prototype.onPaste=function(e,t,i){var s=i().replace(/[\r\n\t]+/gm," ");i(s)},H.prototype.selectStartDate=function(){if(this.startDate()&&this.endDate()){var e=this.dateFormatMoment,t=this.timeFormatMoment,i=this.FCMoment||moment,s=this.getDateTime(this.startDom(),this.startTime()),o=this.getDateTime(this.endDom(),this.endTime()),n=this.getUnixTimestamp(s),r=this.getUnixTimestamp(o),a=i(s),l=i(o),h=a.format(e),c=a.format(t),u=l.format(e),d=l.format(t);this.isEvOneDay(h===u),this.isEvOneTime(c===d),n>r&&(this.datepickerSetDate(this.endDom(),s),this.endDate(h),this.endTime(c),this.isEvOneDay(!0),this.isEvOneTime(!0)),this.startDate(h),this.startTime(c),this.yearlyDate(a.format(this.getPartOfDate(this.dateFormatMoment.slice(0,-5)))),this.monthlyDate(a.format(this.getPartOfDate(this.dateFormatMoment.slice(0,2))))}},H.prototype.selectEndDate=function(){if(this.endDate()&&this.startDate()){var e=this.dateFormatMoment,t=this.timeFormatMoment,i=this.FCMoment||moment,s=this.getDateTime(this.endDom(),this.endTime()),o=this.getDateTime(this.startDom(),this.startTime()),n=this.getUnixTimestamp(s),r=this.getUnixTimestamp(o),a=i(s),l=i(o),h=a.format(e),c=a.format(t),u=l.format(e),d=l.format(t);this.isEvOneDay(h===u),this.isEvOneTime(c===d),r>n&&(this.datepickerSetDate(this.startDom(),s),this.startDate(h),this.startTime(c),this.isEvOneDay(!0),this.isEvOneTime(!0)),this.endDate(h),this.endTime(c),this.repeatEndDom().datepicker("option","minDate",s),this.isRepeat()||this.datepickerSetDate(this.repeatEndDom(),a.add("days",7).toDate())}},H.prototype.getUnixTimestamp=function(e){return moment(e).unix()},H.prototype.getDateTime=function(e,t){t=moment(t,"h:mm a").format("HH:mm");var i=e.datepicker("getDate"),s=t?t.split(":"):[];return 2===s.length&&(i.setHours(s[0]),i.setMinutes(s[1])),i},H.prototype.datepickerSetDate=function(e,t){e.datepicker("setDate",t)},H.prototype.getPartOfDate=function(e){var t="MM/DD";switch(e){case"MM/DD":t="MM/DD";break;case"DD/MM":t="DD/MM";break;case"DD MMMM":t="DD MMMM";break;case"DD":t="DD"}return t},H.prototype.setActualTime=function(){var e=moment();e.minutes(e.minutes()>30?60:30),e.seconds(0),e.milliseconds(0),this.startTime(e.format(this.timeFormatMoment)),this.endTime(e.add("minutes",30).format(this.timeFormatMoment))},H.prototype.onAppointmentActionResponse=function(e){e.Result||Ci.Api.showErrorByCode(e,Si.i18n("WARNING/UNKNOWN_ERROR"))},H.prototype.doAppointmentAction=function(e){var t=vi.IcalConfigInt.NeedsAction,i=this.attendees(),s=Ti.Accounts?Ti.Accounts.getAttendee(_.map(this.attendees(),function(e){return e.email},this)):"",o=_.find(this.attendees(),function(e){return e.email===s},this),n=this.calendars.getCalendarById(this.selectedCalendarId()),r={Action:"AppointmentAction",AppointmentAction:e,CalendarId:this.selectedCalendarId(),EventId:this.uid(),Attendee:s};if(o){switch(e){case vi.IcalConfig.Accepted:t=vi.IcalConfigInt.Accepted,Ci.CalendarCache.markIcalAccepted(this.uid());break;case vi.IcalConfig.Tentative:t=vi.IcalConfigInt.Tentative,Ci.CalendarCache.markIcalTentative(this.uid());break;case vi.IcalConfig.Declined:t=vi.IcalConfigInt.Declined,Ci.CalendarCache.markIcalNonexistent(this.uid())}Ci.Ajax.send(r,this.onAppointmentActionResponse,this),o.status=t,this.attendees([]),this.attendees(i),this.setCurrentAttenderStatus(o.email,this.attendees()),e===vi.IcalConfig.Declined&&n&&this.callbackAttendeeActionDecline&&Si.isFunc(this.callbackAttendeeActionDecline)&&(this.callbackAttendeeActionDecline(n,this.id()),this.closePopup())}},H.prototype.editableSwitch=function(e,t,i){this.isEditable(e&&t&&i||!e&&t&&i||e&&t&&!i),this.isEditableReminders(t)},H.prototype.setCurrentAttenderStatus=function(e,t){var i=_.find(t,function(t){return t.email===e});this.attenderStatus(i?i.status:0)},H.prototype.getAttenderTextStatus=function(e){switch(e){case 0:e="pending"; break;case 1:e="accepted";break;case 2:e="declined";break;case 3:e="tentative"}return e},H.prototype.setDayOfWeek=function(){if(this.repeatPeriod()===vi.CalendarRepeatPeriod.Weekly&&!this.getDays().length){var e=this.getDateTime(this.startDom()).getUTCDay();switch(e){case 0:this.weekMO(!0);break;case 1:this.weekTU(!0);break;case 2:this.weekWE(!0);break;case 3:this.weekTH(!0);break;case 4:this.weekFR(!0);break;case 5:this.weekSA(!0);break;case 6:this.weekSU(!0)}}},H.prototype.getDisplayedTimes=function(e){var t=[];switch(e){case"HH:mm":t=[{text:"00:00",value:"00:00"},{text:"00:30",value:"00:30"},{text:"01:00",value:"01:00"},{text:"01:30",value:"01:30"},{text:"02:00",value:"02:00"},{text:"02:30",value:"02:30"},{text:"03:00",value:"03:00"},{text:"03:30",value:"03:30"},{text:"04:00",value:"04:00"},{text:"04:30",value:"04:30"},{text:"05:00",value:"05:00"},{text:"05:30",value:"05:30"},{text:"06:00",value:"06:00"},{text:"06:30",value:"06:30"},{text:"07:00",value:"07:00"},{text:"07:30",value:"07:30"},{text:"08:00",value:"08:00"},{text:"08:30",value:"08:30"},{text:"09:00",value:"09:00"},{text:"09:30",value:"09:30"},{text:"10:00",value:"10:00"},{text:"10:30",value:"10:30"},{text:"11:00",value:"11:00"},{text:"11:30",value:"11:30"},{text:"12:00",value:"12:00"},{text:"12:30",value:"12:30"},{text:"13:00",value:"13:00"},{text:"13:30",value:"13:30"},{text:"14:00",value:"14:00"},{text:"14:30",value:"14:30"},{text:"15:00",value:"15:00"},{text:"15:30",value:"15:30"},{text:"16:00",value:"16:00"},{text:"16:30",value:"16:30"},{text:"17:00",value:"17:00"},{text:"17:30",value:"17:30"},{text:"18:00",value:"18:00"},{text:"18:30",value:"18:30"},{text:"19:00",value:"19:00"},{text:"19:30",value:"19:30"},{text:"20:00",value:"20:00"},{text:"20:30",value:"20:30"},{text:"21:00",value:"21:00"},{text:"21:30",value:"21:30"},{text:"22:00",value:"22:00"},{text:"22:30",value:"22:30"},{text:"23:00",value:"23:00"},{text:"23:30",value:"23:30"}];break;case"hh:mm A":t=[{text:"12:00 AM",value:"12:00 AM"},{text:"12:30 AM",value:"12:30 AM"},{text:"01:00 AM",value:"01:00 AM"},{text:"01:30 AM",value:"01:30 AM"},{text:"02:00 AM",value:"02:00 AM"},{text:"02:30 AM",value:"02:30 AM"},{text:"03:00 AM",value:"03:00 AM"},{text:"03:30 AM",value:"03:30 AM"},{text:"04:00 AM",value:"04:00 AM"},{text:"04:30 AM",value:"04:30 AM"},{text:"05:00 AM",value:"05:00 AM"},{text:"05:30 AM",value:"05:30 AM"},{text:"06:00 AM",value:"06:00 AM"},{text:"06:30 AM",value:"06:30 AM"},{text:"07:00 AM",value:"07:00 AM"},{text:"07:30 AM",value:"07:30 AM"},{text:"08:00 AM",value:"08:00 AM"},{text:"08:30 AM",value:"08:30 AM"},{text:"09:00 AM",value:"09:00 AM"},{text:"09:30 AM",value:"09:30 AM"},{text:"10:00 AM",value:"10:00 AM"},{text:"10:30 AM",value:"10:30 AM"},{text:"11:00 AM",value:"11:00 AM"},{text:"11:30 AM",value:"11:30 AM"},{text:"12:00 PM",value:"12:00 PM"},{text:"12:30 PM",value:"12:30 PM"},{text:"01:00 PM",value:"01:00 PM"},{text:"01:30 PM",value:"01:30 PM"},{text:"02:00 PM",value:"02:00 PM"},{text:"02:30 PM",value:"02:30 PM"},{text:"03:00 PM",value:"03:00 PM"},{text:"03:30 PM",value:"03:30 PM"},{text:"04:00 PM",value:"04:00 PM"},{text:"04:30 PM",value:"04:30 PM"},{text:"05:00 PM",value:"05:00 PM"},{text:"05:30 PM",value:"05:30 PM"},{text:"06:00 PM",value:"06:00 PM"},{text:"06:30 PM",value:"06:30 PM"},{text:"07:00 PM",value:"07:00 PM"},{text:"07:30 PM",value:"07:30 PM"},{text:"08:00 PM",value:"08:00 PM"},{text:"08:30 PM",value:"08:30 PM"},{text:"09:00 PM",value:"09:00 PM"},{text:"09:30 PM",value:"09:30 PM"},{text:"10:00 PM",value:"10:00 PM"},{text:"10:30 PM",value:"10:30 PM"},{text:"11:00 PM",value:"11:00 PM"},{text:"11:30 PM",value:"11:30 PM"}]}return t},H.prototype.displayReminderPart=function(e,t){var i="";return i="%REMINDERS%"===e?"Reminders":"Text",t+i},G.prototype.onShow=function(e){Si.isFunc(e)&&(this.fCallback=e)},G.prototype.popupTemplate=function(){return"Popups_Calendar_EditRecurrenceEventPopupViewModel"},G.prototype.onlyThisInstanceButtonClick=function(){this.fCallback&&this.fCallback(vi.CalendarEditRecurrenceEvent.OnlyThisInstance),this.closeCommand()},G.prototype.allEventsButtonClick=function(){this.fCallback&&this.fCallback(vi.CalendarEditRecurrenceEvent.AllEvents),this.closeCommand()},G.prototype.cancelButtonClick=function(){this.fCallback&&this.fCallback(vi.CalendarEditRecurrenceEvent.None),this.closeCommand()},G.prototype.onEscHandler=function(){this.cancelButtonClick()},B.prototype.onShow=function(e){this.fCallback=e.CallbackSave,this.fProceedUploading=e.ProceedUploading,this.calendars=e.Calendars,this.calendarsList(e.EditableCalendars),this.selectedCalendarId(e.DefaultCalendarId),this.changeCalendarColor(this.selectedCalendarId())},B.prototype.popupTemplate=function(){return"Popups_Calendar_CalendarSelectCalendarsPopupViewModel"},B.prototype.onSaveClick=function(){this.fCallback&&this.fCallback(this.selectedCalendarId(),this.fProceedUploading),this.closeCommand()},B.prototype.onCancelClick=function(){this.closeCommand()},B.prototype.changeCalendarColor=function(e){if(Si.isFunc(this.calendars.getCalendarById)){var t=this.calendars.getCalendarById(e);t&&(this.calendarColor(""),this.calendarColor(t.color()))}},V.prototype.popupTemplate=function(){return"Popups_PhonePopupViewModel"},V.prototype.onShow=function(e){this.text(e.text),this.callback=e.Callback||Si.emptyFunction},V.prototype.onCancelClick=function(){this.closeCommand()},V.prototype.onOKClick=function(){this.closeCommand(),this.callback()},V.prototype.answer=function(){this.action(vi.PhoneAction.IncomingConnect)},V.prototype.hangup=function(){this.action(vi.PhoneAction.Online)},j.prototype.onShow=function(e){this.pgp=e,this.emails(Ti.Accounts.getAllFullEmails()),this.selectedEmail(""),this.password(""),this.selectedKeyLength(2048),this.process(!1)},j.prototype.popupTemplate=function(){return"Popups_GenerateOpenPgpKeyPopupViewModel"},j.prototype.generate=function(){this.pgp&&(this.process(!0),_.delay(_.bind(function(){var e=this.pgp.generateKey(this.selectedEmail(),this.password(),this.selectedKeyLength());e&&e.result&&Ci.Api.showReport(Si.i18n("OPENPGP/REPORT_KEY_SUCCESSFULLY_GENERATED")),e&&!e.result?(this.process(!1),Ci.Api.showPgpErrorByCode(e,vi.PgpAction.Generate)):this.closeCommand()},this),50))},K.prototype.onShow=function(e){this.armor(e.getArmor()),this.user(e.getUser()),this.private(e.isPrivate())},K.prototype.popupTemplate=function(){return"Popups_ShowOpenPgpKeyArmorPopupViewModel"},K.prototype.send=function(){""!==this.armor()&&""!==this.downloadLinkFilename()&&(Ci.Routing.goDirectly(Ci.Links.compose(),["data-as-file",this.armor(),this.downloadLinkFilename()]),this.closeCommand())},K.prototype.select=function(){var e=this.domKey()&&1===this.domKey().length?this.domKey()[0]:null,i=null,s=null;e&&t.getSelection&&document.createRange&&(s=document.createRange(),s.setStart(e,0),s.setEnd(e,1),i=t.getSelection(),i.removeAllRanges(),i.addRange(s))},W.prototype.onShow=function(e,t){this.pgp=e,this.keyArmor(t||""),this.keyArmorFocused(!0),this.keys([]),this.hasExistingKeys(!1),""!==this.keyArmor()&&this.checkArmor()},W.prototype.popupTemplate=function(){return"Popups_ImportOpenPgpKeyPopupViewModel"},W.prototype.checkArmor=function(){var e=null,t=[],s=this.pgp,o=!1;""===this.keyArmor()?this.keyArmorFocused(!0):s&&(e=s.getArmorInfo(this.keyArmor()),Si.isNonEmptyArray(e)&&_.each(e,function(e){if(e){var n=s.findKeyByID(e.getId(),e.isPublic()),r=null!==n,a=e.isPublic()?"OPENPGP/PUBLIC_KEY_ADD_INFO":"OPENPGP/PRIVATE_KEY_ADD_INFO";o=o||r,t.push({armor:e.getArmor(),email:e.user,id:e.getId(),addInfo:Si.i18n(a,{LENGTH:e.getBitSize()}),needToImport:i.observable(!r),disabled:r})}}),0===t.length&&Ci.Api.showError(Si.i18n("OPENPGP/ERROR_IMPORT_NO_KEY_FOUNDED")),this.keys(t),this.hasExistingKeys(o))},W.prototype.importKey=function(){var e=null,t=[];this.pgp&&(_.each(this.keys(),function(e){e.needToImport()&&t.push(e.armor)}),t.length>0?(e=this.pgp.importKeys(t.join("")),e&&e.result&&Ci.Api.showReport(Si.i18n("OPENPGP/REPORT_KEY_SUCCESSFULLY_IMPORTED_PLURAL",{},null,t.length)),e&&!e.result&&Ci.Api.showPgpErrorByCode(e,vi.PgpAction.Import,Si.i18n("OPENPGP/ERROR_IMPORT_KEY")),this.closeCommand()):Ci.Api.showError(Si.i18n("OPENPGP/ERROR_IMPORT_NO_KEY_SELECTED")))},q.prototype.onShow=function(e,t,i,s,o,n){this.data(e),this.fromEmail(t),this.emails(i),this.okCallback=o,this.cancelCallback=n,this.sign(!0),this.password(""),this.encrypt(!s),this.signAndSend(s)},q.prototype.popupTemplate=function(){return"Popups_OpenPgpEncryptPopupViewModel"},q.prototype.executeSignEncrypt=function(){var e=_.bind(function(e){e&&this.signEncrypt(e)},this);Ci.Api.pgp(e,Ti.User.IdUser)},q.prototype.signEncrypt=function(e){var t=this.data(),i=this.sign()?this.fromEmail():"",s=this.emails(),o=this.sign()?this.password():"",n=null,r="",a="";this.encrypt()?0===s.length?Ci.Api.showError(Si.i18n("OPENPGP/ERROR_TO_ENCRYPT_SPECIFY_RECIPIENTS")):this.sign()?(a=vi.PgpAction.EncryptSign,r=Si.i18n("OPENPGP/REPORT_MESSAGE_SIGNED_ENCRYPTED_SUCCSESSFULLY"),n=e.signAndEncrypt(t,i,s,o)):(a=vi.PgpAction.Encrypt,r=Si.i18n("OPENPGP/REPORT_MESSAGE_ENCRYPTED_SUCCSESSFULLY"),n=e.encrypt(t,s)):this.sign()&&(a=vi.PgpAction.Sign,r=Si.i18n("OPENPGP/REPORT_MESSAGE_SIGNED_SUCCSESSFULLY"),n=e.sign(t,i,o)),n&&(n.result?(this.closeCommand(),this.okCallback&&(this.signAndSend()||Ci.Api.showReport(r),this.okCallback(n.result,this.encrypt()))):Ci.Api.showPgpErrorByCode(n,a))},q.prototype.cancel=function(){this.cancelCallback&&this.cancelCallback(),this.closeCommand()},q.prototype.onEscHandler=function(){this.cancel()},Y.prototype.onShow=function(e){var i=null;Si.isFunc(e)&&(this.fCallback=e),this.pickerApiLoaded&&this.googleApiLoaded&&(i=t.gapi.auth.getToken(),!i||_.isEmpty(i)||i.error?this.doGoogleAuth():this.createPicker())},Y.prototype.onApplyBindings=function(){this.allowGoogle&&Si.loadScript("https://apis.google.com/js/api.js?onload=onGoogleApiLoad",_.bind(this.onGoogleApiLoad,this),null,"onGoogleApiLoad")},Y.prototype.popupTemplate=function(){return"Popups_GooglePickerPopupViewModel"},Y.prototype.onEscHandler=function(){this.onCancelClick()},Y.prototype.onCancelClick=function(){this.closeCommand(),this.pickerApiLoaded&&this.picker&&this.picker.setVisible(!1)},Y.prototype.onGoogleApiLoad=function(){this.googleApiLoaded=!0,t.gapi.load("auth",{callback:_.bind(this.doGoogleAuth,this)}),t.gapi.load("picker",{callback:_.bind(this.onPickerApiLoad,this)})},Y.prototype.doGoogleAuth=function(){var e=t.gapi.auth.getToken();(!e||_.isEmpty(e)||e&&e.error)&&t.gapi.auth.init(_.bind(this.checkGoogleAuth,this,!0))},Y.prototype.checkGoogleAuth=function(e){this.checkTimer=t.setTimeout(_.bind(this.ckeckPickerCreate,this),5e3),t.gapi.auth.authorize({client_id:this.googleClientId,scope:["https://www.googleapis.com/auth/drive"],immediate:!!e},_.bind(this.handleGoogleAuthResult,this))},Y.prototype.handleGoogleAuthResult=function(e){e&&(e.error?"immediate_failed"===e.error&&(t.clearTimeout(this.checkTimer),this.checkGoogleAuth(!1)):this.createPicker())},Y.prototype.onPickerApiLoad=function(){this.pickerApiLoaded=!0},Y.prototype.ckeckPickerCreate=function(){t.clearTimeout(this.checkTimer),this.pickerCreated||(this.closeCommand(),Ci.Api.showError(Si.i18n("COMPOSE/ERROR_GOOGLE_PICKER_POPUP")))},Y.prototype.createPicker=function(){var e=null,i=t.gapi.auth.getToken(),s=this;this.pickerApiLoaded&&i&&!i.error&&(e=(new t.google.picker.DocsView).setIncludeFolders(!0),this.picker=(new t.google.picker.PickerBuilder).addView(e).setOAuthToken(i.access_token).setDeveloperKey(s.googleKey).setOrigin(t.location.protocol+"//"+t.location.host).setCallback(_.bind(s.pickerCallback,s,i.access_token)).enableFeature(t.google.picker.Feature.NAV_HIDDEN).enableFeature(t.google.picker.Feature.MULTISELECT_ENABLED).setLocale(Ti.User.DefaultLanguageShort).build(),this.picker.setVisible(!0),this.picker.A.style.zIndex=2e3,this.pickerCreated=!0)},Y.prototype.pickerCallback=function(e,i){i[t.google.picker.Response.ACTION]===t.google.picker.Action.PICKED?(this.fCallback&&this.fCallback(i[t.google.picker.Response.DOCUMENTS],e),this.closeCommand()):i[t.google.picker.Response.ACTION]===t.google.picker.Action.CANCEL&&this.closeCommand()},z.prototype.parse=function(e){this.AllowWebMail=!!e.AllowWebMail,this.AllowUsersChangeInterfaceSettings=!!e.AllowUsersChangeInterfaceSettings,this.AllowUsersChangeEmailSettings=!!e.AllowUsersChangeEmailSettings,this.AllowUsersAddNewAccounts=Si.isUnd(e.AllowUsersAddNewAccounts)?this.AllowUsersChangeEmailSettings:!!e.AllowUsersAddNewAccounts,this.SiteName=Si.pString(e.SiteName),this.Languages=e.Languages,this.Themes=e.Themes,this.DateFormats=e.DateFormats,this.AttachmentSizeLimit=Si.pInt(e.AttachmentSizeLimit),this.ImageUploadSizeLimit=Si.pInt(e.ImageUploadSizeLimit),this.FileSizeLimit=Si.pInt(e.FileSizeLimit),this.AutoSave=!!e.AutoSave,this.IdleSessionTimeout=60*Si.pInt(e.IdleSessionTimeout)*1e3,this.AllowInsertImage=!!e.AllowInsertImage,this.AllowBodySize=!!e.AllowBodySize,this.MaxBodySize=Si.pInt(e.MaxBodySize),this.MaxSubjectSize=Si.pInt(e.MaxSubjectSize),this.AllowPrefetch=!!e.AllowPrefetch,this.LoginFormType=Si.pInt(e.LoginFormType),this.LoginSignMeType=Si.pInt(e.LoginSignMeType),this.LoginAtDomainValue=Si.pString(e.LoginAtDomainValue),this.AllowRegistration=!!e.AllowRegistration,this.AllowPasswordReset=!!e.AllowPasswordReset,this.RegistrationDomains=e.RegistrationDomains,this.RegistrationQuestions=_.without(e.RegistrationQuestions,""),this.DemoWebMail=!!e.DemoWebMail,this.DemoWebMailLogin=Si.pString(e.DemoWebMailLogin),this.DemoWebMailPassword=Si.pString(e.DemoWebMailPassword),this.GoogleAnalyticsAccount=e.GoogleAnalyticsAccount,this.ShowQuotaBar=!!e.ShowQuotaBar,this.ServerUseUrlRewrite=!!e.ServerUseUrlRewrite,this.AllowLanguageOnLogin=!Ii&&!!e.AllowLanguageOnLogin,this.FlagsLangSelect=!!e.FlagsLangSelect,this.DefaultLanguage=Si.pString(e.DefaultLanguage),this.LoginDescription=Si.pString(e.LoginDescription),this.CustomLoginUrl=Si.pString(e.CustomLoginUrl),this.CustomLogoutUrl=Si.pString(e.CustomLogoutUrl),this.IosDetectOnLogin=!!e.IosDetectOnLogin,this.AllowContactsSharing=!!e.AllowContactsSharing,""!==e.DefaultLanguageShort&&(this.DefaultLanguageShort=e.DefaultLanguageShort),this.DefaultTab=e.DefaultTab,this.AllowIosProfile=!!e.AllowIosProfile,this.PasswordMinLength=e.PasswordMinLength,this.PasswordMustBeComplex=!!e.PasswordMustBeComplex},Q.prototype.fillDefaultFontName=function(){var e=Si.pString(Ti.HtmlEditorDefaultFontName);""!==e&&(this.DefaultFontName=e)},Q.prototype.fillDefaultFontSize=function(){var e=Si.pInt(Ti.HtmlEditorDefaultFontSize);-1!==Si.inArray(e,[2,3,5,7])&&(this.DefaultFontSize=e)},Q.prototype.getSaveMailInSentItems=function(){var e=!0;switch(this.SaveMail){case vi.SaveMail.Unchecked:e=!1;break;case vi.SaveMail.Checked:case vi.SaveMail.Hidden:e=!0}return e},Q.prototype.getUseSaveMailInSentItems=function(){var e=!1;switch(this.SaveMail){case vi.SaveMail.Unchecked:case vi.SaveMail.Checked:e=!0;break;case vi.SaveMail.Hidden:e=!1}return e},Q.prototype.parse=function(e){var t=null;null!==e&&(this.IdUser=Si.pInt(e.IdUser),this.MailsPerPage=Si.pInt(e.MailsPerPage),this.ContactsPerPage=Si.pInt(e.ContactsPerPage),this.AutoCheckMailInterval=Si.pInt(e.AutoCheckMailInterval),this.DefaultTheme=Si.pString(e.DefaultTheme),this.DefaultLanguage=Si.pString(e.DefaultLanguage),this.DefaultLanguageShort=Si.pString(e.DefaultLanguageShort),this.DefaultDateFormat=Si.pString(e.DefaultDateFormat),this.defaultTimeFormat(Si.pString(e.DefaultTimeFormat)),this.ThreadsEnabled=!!e.ThreadsEnabled,this.useThreads(!!e.UseThreads),this.SaveRepliedToCurrFolder=!!e.SaveRepliedMessagesToCurrentFolder,this.DesktopNotifications=!!e.DesktopNotifications,this.AllowChangeInputDirection=!!e.AllowChangeInputDirection,this.AllowCompose=!!e.AllowCompose,this.AllowReply=!!e.AllowReply,this.AllowForward=!!e.AllowForward,this.SaveMail=Si.pInt(e.SaveMail),this.AllowFetcher=!!e.AllowFetcher,this.OutlookSyncEnable=!!e.OutlookSyncEnable,this.MobileSyncEnable=!!e.MobileSyncEnable,this.ShowPersonalContacts=!!e.ShowPersonalContacts,this.ShowGlobalContacts=!!e.ShowGlobalContacts,this.ShowContacts=this.ShowPersonalContacts||this.ShowGlobalContacts,this.IsFilesSupported=!!e.IsFilesSupported&&!Ii,this.IsFilesSupported=!!e.IsFilesSupported&&!Ii,this.filesEnable(!!e.FilesEnable&&!Ii),this.IsHelpdeskSupported=!!e.IsHelpdeskSupported&&!Ii,this.IsHelpdeskAgent=!!e.IsHelpdeskAgent,this.LastLogin=Si.pInt(e.LastLogin),this.AllowCalendar=!!e.AllowCalendar&&!Ii,this.CalendarSharing=!!e.CalendarSharing,this.CalendarAppointments=!!e.CalendarAppointments,this.IsDemo=!!e.IsDemo,this.AllowVoice=!!e.AllowVoice,this.SipRealm=e.SipRealm,this.SipWebsocketProxyUrl=e.SipWebsocketProxyUrl,this.SipOutboundProxyUrl=e.SipOutboundProxyUrl,this.SipCallerID=e.SipCallerID,this.SipImpi=e.SipImpi,this.SipImpu=e.SipImpu,this.SipPassword=e.SipPassword,this.VoiceProvider=e.VoiceProvider,this.AllowHelpdeskNotifications=e.AllowHelpdeskNotifications,this.IsCollaborationSupported=!!e.IsCollaborationSupported,this.AllowFilesSharing=!!e.AllowFilesSharing,this.enableOpenPgp(!!e.EnableOpenPgp),this.AllowAutosaveInDrafts=!!e.AllowAutosaveInDrafts&&(Ti.App?Ti.App.AutoSave:!1),t=e.Calendar,t&&(this.CalendarShowWeekEnds=!!t.ShowWeekEnds,this.CalendarShowWorkDay=!!t.ShowWorkDay,this.CalendarWorkDayStarts=Si.pInt(t.WorkDayStarts),this.CalendarWorkDayEnds=Si.pInt(t.WorkDayEnds),this.CalendarWeekStartsOn=Si.pInt(t.WeekStartsOn),this.CalendarDefaultTab=Si.pInt(t.DefaultTab)),this.SocialAccounts(e.SocialAccounts))},Q.prototype.updateCommonSettings=function(e,t,i,s,o,n,r,a,l,h,c){var u=this.defaultTimeFormat()!==r;this.MailsPerPage=e,this.ContactsPerPage=t,this.AutoCheckMailInterval=i,Ci.MailCache.setAutocheckmailTimer(),this.DefaultTheme=s,this.DefaultLanguage=o,this.DefaultDateFormat=n,this.defaultTimeFormat(r),this.useThreads("1"===a),this.SaveRepliedToCurrFolder="1"===l,this.AllowChangeInputDirection="1"===c,this.DesktopNotifications="1"===h,u&&Ci.nowMoment.valueHasMutated()},Q.prototype.updateOpenPgpSettings=function(e,t){this.enableOpenPgp("1"===e),this.AllowAutosaveInDrafts="1"===t},Q.prototype.updateCalendarSettings=function(e,t,i,s,o,n){this.CalendarShowWeekEnds=e,this.CalendarShowWorkDay=t,this.CalendarWorkDayStarts=i,this.CalendarWorkDayEnds=s,this.CalendarWeekStartsOn=o,this.CalendarDefaultTab=n},Q.prototype.updateHelpdeskSettings=function(e){this.AllowHelpdeskNotifications=e},Q.prototype.onSyncSettingsResponse=function(e){e.Result?(this.mobileSync(e.Result.Mobile),this.outlookSync(e.Result.Outlook)):Ci.Api.showErrorByCode(e)},Q.prototype.requestSyncSettings=function(){(null===this.mobileSync()||null===this.outlookSync())&&Ci.Ajax.send({Action:"SyncSettings"},this.onSyncSettingsResponse,this)},$.prototype.init=function(e,t,i){this.id(e),this.email(t),this.friendlyName(i)},$.prototype.onQuotaParamsResponse=function(e){e&&e.Result&&_.isArray(e.Result)&&1<e.Result.length&&(this.quota(Si.pInt(e.Result[1])),this.usedSpace(Si.pInt(e.Result[0])),Ci.MailCache.quotaChangeTrigger(!Ci.MailCache.quotaChangeTrigger())),this.quotaRecieved(!0)},$.prototype.updateQuotaParams=function(){var e={Action:"Quota",AccountID:this.id()};Ti.App&&Ti.App.ShowQuotaBar&&Ci.Ajax.send(e,this.onQuotaParamsResponse,this)},$.prototype.parse=function(e,t){var i=new vt;this.init(parseInt(e.AccountID,10),Si.pString(e.Email),Si.pString(e.FriendlyName)),i.parse(this.id(),e.Signature),this.signature(i),this.isCurrent(t===this.id()),this.isEdited(t===this.id())},$.prototype.requestExtensions=function(){if(!this.extensionsRequested()&&Ci.Ajax){var e=t.jstz?t.jstz.determine():null;Ci.Ajax.send({AccountID:this.id(),Action:"IsAuth",ClientTimeZone:e?e.name():""},this.onIsAuthResponse,this)}},$.prototype.onIsAuthResponse=function(e){var t=!!e.Result,i=t?e.Result.Extensions:[];t&&(this.setExtensions(i),this.extensionsRequested(!0))},$.prototype.setExtensions=function(e){_.isArray(e)&&this.extensions(e)},$.prototype.extensionExists=function(e){return-1===_.indexOf(this.extensions(),e)?!1:!0},$.prototype.updateExtended=function(e){e&&(this.isExtended(!0),Si.isNormal(e.FriendlyName)&&this.friendlyName(e.FriendlyName),Si.isNormal(e.IncomingMailLogin)&&this.incomingMailLogin(e.IncomingMailLogin),Si.isNormal(e.IncomingMailPort)&&this.incomingMailPort(e.IncomingMailPort),Si.isNormal(e.IncomingMailServer)&&this.incomingMailServer(e.IncomingMailServer),Si.isNormal(e.IsInternal)&&this.isInternal(e.IsInternal),Si.isNormal(e.IsLinked)&&this.isLinked(e.IsLinked),Si.isNormal(e.IsDefault)&&this.isDefault(e.IsDefault),Si.isNormal(e.OutgoingMailAuth)&&this.outgoingMailAuth(e.OutgoingMailAuth),Si.isNormal(e.OutgoingMailLogin)&&this.outgoingMailLogin(e.OutgoingMailLogin),Si.isNormal(e.OutgoingMailPort)&&this.outgoingMailPort(e.OutgoingMailPort),Si.isNormal(e.OutgoingMailServer)&&this.outgoingMailServer(e.OutgoingMailServer),this.setExtensions(e.Extensions))},$.prototype.changeAccount=function(){Ti.Accounts.changeCurrentAccount(this.id())},$.prototype.getFetcherOrIdentityByEmail=function(e){var t=this.fetchers()?this.fetchers().collection():[],i=null;return i=_.find(t,function(t){return t.email()===e}),i||(i=_.find(this.identities()||[],function(t){return t.email()===e})),i},$.prototype.getFetchersIdentitiesEmails=function(){var e=this.fetchers()?this.fetchers().collection():[],t=this.identities()||[],i=[];return _.each(e,function(e){i.push(e.email())}),_.each(t,function(e){i.push(e.email())}),i},J.prototype.changeCurrentAccount=function(e){var t=this.getCurrent(),i=this.getAccount(e);i&&this.currentId()!==e&&(t.isCurrent(!1),this.currentId(e),i.isCurrent(!0),Ci.Routing.setHash(Ci.Links.inbox()))},J.prototype.changeEditedAccount=function(e){var t=this.getEdited(),i=this.getAccount(e);i&&this.editedId()!==e&&(t.isEdited(!1),this.editedId(e),i.isEdited(!0))},J.prototype.parse=function(e,t){var i=null,s=!1,o=null;_.isArray(t)&&this.collection(_.map(t,function(t){var i=new $;return i.parse(t,e),i.id()===e&&(s=!0),i})),!s&&this.collection.length>0&&(i=this.collection()[0],e=i.id(),s=!0),s&&(this.defaultId(e),this.currentId(e),this.editedId(e)),o=this.getDefault(),o&&_.defer(function(){o.isDefault(!0)})},J.prototype.getAccount=function(e){var t=_.find(this.collection(),function(t){return t.id()===e},this);return t},J.prototype.getCurrent=function(){var e=_.find(this.collection(),function(e){return e.id()===this.currentId()},this);return e},J.prototype.getDefault=function(){var e=_.find(this.collection(),function(e){return e.id()===this.defaultId()},this);return e},J.prototype.getEmail=function(){var e="",t=Ti.Accounts.getCurrent();return t&&(e=t.email()),e},J.prototype.getEdited=function(){var e=_.find(this.collection(),function(e){return e.id()===this.editedId()},this);return e},J.prototype.addAccount=function(e){this.collection.push(e)},J.prototype.deleteAccount=function(e){this.currentId()===e&&this.changeCurrentAccount(this.defaultId()),this.editedId()===e&&this.changeEditedAccount(this.defaultId()),this.collection.remove(function(t){return t.id()===e})},J.prototype.hasAccountWithId=function(e){var t=_.find(this.collection(),function(t){return t.id()===e},this);return!!t},J.prototype.populateFetchersIdentities=function(){this.populateFetchers(),this.populateIdentities()},J.prototype.populateFetchers=function(){Ti.User.AllowFetcher&&Ci.Ajax.send({Action:"FetcherList",AccountID:Ti.Accounts.defaultId()},this.onFetcherListResponse,this)},J.prototype.onFetcherListResponse=function(e){var t=null,i=this.getDefault();Si.isNonEmptyArray(e.Result)&&(t=new Ct,t.parse(Ti.Accounts.defaultId(),e.Result)),i.fetchers(t)},J.prototype.populateIdentities=function(){Ti.AllowIdentities&&Ci.Ajax.send({Action:"GetIdentities"},this.onIdentitiesResponse,this)},J.prototype.onIdentitiesResponse=function(e){var t={};Si.isNonEmptyArray(e.Result)&&_.each(e.Result,function(e){var i=new tt,s=-1;i.parse(e),s=i.accountId(),t[s]||(t[s]=[]),t[s].push(i)}),_.each(this.collection(),function(e){var i=t[e.id()];Si.isNonEmptyArray(i)||(i=[]),e.identities(i)})},J.prototype.populateIdentitiesFromSourceAccount=function(e){e&&_.each(this.collection(),function(t){var i=e.getAccount(t.id());i&&(t.fetchers(i.fetchers()),t.identities(i.identities()),t.signature(i.signature()))})},J.prototype.getAllFullEmails=function(){var e=[];return _.each(this.collection(),function(t){t&&(e.push(t.fullEmail()),t.fetchers()&&Si.isNonEmptyArray(t.fetchers().collection())&&_.each(t.fetchers().collection(),function(t){t.isOutgoingEnabled()&&""!==t.fullEmail()&&e.push(t.fullEmail())}),Si.isNonEmptyArray(t.identities())&&_.each(t.identities(),function(t){e.push(t.fullEmail())}))}),e},J.prototype.getCurrentFetchersAndFiltersFolderNames=function(){var e=this.getCurrent(),t=[];return e&&(e.filters()&&_.each(e.filters().collection(),function(e){t.push(e.folder())},this),e.fetchers()&&_.each(e.fetchers().collection(),function(e){t.push(e.folder())},this)),t},J.prototype.getAttendee=function(e){var t=[],i="";return _.each(this.collection(),function(e){t=e.isCurrent()?_.union(e.email(),e.getFetchersIdentitiesEmails(),t):_.union(t,e.email(),e.getFetchersIdentitiesEmails())}),t=_.uniq(t),_.each(t,_.bind(function(t){if(""===i){var s=_.find(e,function(e){return e===t});s===t&&(i=t)}},this)),i},X.prototype.parse=function(e){null!==e&&(this.sName=Si.pString(e.DisplayName),"string"!=typeof this.sName&&(this.sName=""),this.sEmail=Si.pString(e.Email),"string"!=typeof this.sEmail&&(this.sEmail=""),this.sDisplay=this.sName.length>0?this.sName:this.sEmail,this.setFull())},X.prototype.getEmail=function(){return this.sEmail},X.prototype.getName=function(){return this.sName},X.prototype.getDisplay=function(){return this.sDisplay},X.prototype.setFull=function(){var e="";e=this.sEmail.length>0?this.sName.length>0?this.sName+" <"+this.sEmail+">":this.sEmail:this.sName,this.sFull=e},X.prototype.getFull=function(){return this.sFull},X.prototype.oPopup=null,X.prototype.oTitle=null,X.prototype.bPopupOpened=!1,X.prototype.iCloseTimeoutId=0,X.prototype.mouseoverEvent=function(t,i){this.oPopup&&0!==this.oPopup.length||(this.oPopup=e("div.item_viewer[data-email='"+this.sEmail+"']"),this.oPopup.length>0&&this.oPopup.on("mouseenter",_.bind(this.openPopup,this)).on("mouseleave",_.bind(this.mouseoutEvent,this))),this.oTitle=e(i.currentTarget),this.oPopup.length>0&&this.openPopup(i)},X.prototype.openPopup=function(){this.bPopupOpened=!0,clearTimeout(this.iCloseTimeoutId),setTimeout(_.bind(function(){var i,s,o,n=this.oTitle.offset();this.bPopupOpened&&n.left+n.top!==0&&(i=n.left+10,s=n.top+this.oTitle.height()+6,o=e(t).width()-(i+396),o>0&&(o=0),this.oPopup.addClass("expand").css("top",s+"px").css("left",i+o+"px").appendTo("body"))},this),180)},X.prototype.mouseoutEvent=function(){this.bPopupOpened&&this.oPopup&&this.oTitle&&(this.bPopupOpened=!1,this.iCloseTimeoutId=setTimeout(_.bind(function(){this.bPopupOpened||this.oPopup.removeClass("expand")},this),200))},Z.prototype.parse=function(e){this.aCollection=_.map(e,function(e){var t=new X;return t.parse(e),t})},Z.prototype.addCollection=function(e){_.each(e,function(e){var t=_.find(this.aCollection,function(t){return e.sEmail===t.sEmail});t||this.aCollection.push(e)},this)},Z.prototype.excludeCollection=function(e){_.each(e,function(e){this.aCollection=_.filter(this.aCollection,function(t){return e.sEmail!==t.sEmail})},this)},Z.prototype.getFirstEmail=function(){return this.aCollection.length>0?this.aCollection[0].getEmail():""},Z.prototype.getFirstName=function(){return this.aCollection.length>0?this.aCollection[0].getName():""},Z.prototype.getFirstDisplay=function(){return this.aCollection.length>0?this.aCollection[0].getDisplay():""},Z.prototype.getDisplay=function(e,t){var i=_.map(this.aCollection,function(i){return e&&t===i.sEmail?e:i.getDisplay(e)});return i.join(", ")},Z.prototype.getFull=function(){var e=_.map(this.aCollection,function(e){return e.getFull()});return e.join(", ")},Z.prototype.getEmails=function(){var e=_.map(this.aCollection,function(e){return e.getEmail()});return e},et.prototype.parse=function(e){this.iTimeStampInUTC=e,this.oMoment=moment.unix(this.iTimeStampInUTC)},et.prototype.setDate=function(e,t,i){this.oMoment=moment([e,t,i])},et.prototype.getTimeFormat=function(){return Ti.User.defaultTimeFormat()===vi.TimeFormat.F24?"HH:mm":"hh:mm A"},et.prototype.getFullDate=function(){return this.oMoment?this.oMoment.format("ddd, MMM D, YYYY, "+this.getTimeFormat()):""},et.prototype.getMidDate=function(){return this.getShortDate(!0)},et.prototype.getShortDate=function(e){var t="",i=null;return this.oMoment&&(i=moment(),i.format("L")===this.oMoment.format("L")?t=this.oMoment.format(this.getTimeFormat()):(t=i.clone().subtract("days",1).format("L")===this.oMoment.format("L")?Si.i18n("DATETIME/YESTERDAY"):this.oMoment.format(i.year()===this.oMoment.year()?"MMM D":"MMM D, YYYY"),(Si.isUnd(e)?1:!e)||(t+=", "+this.oMoment.format(this.getTimeFormat())))),t},et.prototype.getDate=function(){return this.oMoment?this.oMoment.format("ddd, MMM D, YYYY"):""},et.prototype.getTime=function(){return this.oMoment?this.oMoment.format(this.getTimeFormat()):""},et.prototype.convertDate=function(e){var t=Si.getDateFormatForMoment(Ti.User.DefaultDateFormat)+" "+this.getTimeFormat();return moment(1e3*e).format(t)},et.prototype.getTimeStampInUTC=function(){return this.iTimeStampInUTC},tt.prototype.parse=function(e){"Object/CIdentity"===e["@Object"]&&(this.enabled(!!e.Enabled),this.email(Si.pString(e.Email)),this.friendlyName(Si.pString(e.FriendlyName)),this.accountId(Si.pInt(e.IdAccount)),this.id(Si.pInt(e.IdIdentity)),this.signature(Si.pString(e.Signature)),this.useSignature(!!e.UseSignature))},it.prototype.dataObjectName="",it.prototype.isVisibleViewLink=function(){return this.uploaded()&&!this.uploadError()&&this.isViewMimeType()},it.prototype.parse=function(e,t){e["@Object"]===this.dataObjectName&&(this.fileName(Si.pString(e.FileName)),this.tempName(Si.pString(e.TempName)),""===this.tempName()&&this.tempName(this.fileName()),this.type(Si.pString(e.MimeType)),this.size(e.EstimatedSize?parseInt(e.EstimatedSize,10):parseInt(e.SizeInBytes,10)),this.content(Si.pString(e.Content)),this.thumb(!!e.Thumb),this.hash(Si.pString(e.Hash)),this.accountId(t),this.allowExpandSubFiles(!!e.Expand),this.iframedView(!!e.Iframed),this.uploadUid(this.hash()),this.uploaded(!0),Si.isFunc(this.additionalParse)&&this.additionalParse(e))},it.prototype.getInThumbQueue=function(e){this.thumbnailSessionUid(e),this.thumb()&&(!this.linked||this.linked&&!this.linked())&&Si.thumbQueue(this.thumbnailSessionUid(),this.thumbnailLink(),this.thumbnailSrc)},it.prototype.downloadFile=function(e){this.allowDownload()&&(e&&e.Api&&e.Api.downloadByUrl||(e=Ci),e&&this.downloadLink().length>0&&"#"!==this.downloadLink()&&e.Api.downloadByUrl(this.downloadLink()))},it.prototype.onExpandAttachmentResponse=function(e){this.subFiles([]),Si.isNonEmptyArray(e.Result)&&(_.each(e.Result,_.bind(function(e){var t=this.getInstance();e["@Object"]=this.dataObjectName,t.parse(e,this.accountId()),this.subFiles.push(t)},this)),this.subFilesLoaded(!0),this.subFilesCollapsed(!0)),this.subFilesStartedLoading(!1)},it.prototype.expandFile=function(){this.subFilesLoaded()?this.subFilesCollapsed(!0):(this.subFilesStartedLoading(!0),Ci.Ajax.send({Action:"ExpandAttachment",RawKey:this.hash()},this.onExpandAttachmentResponse,this))},it.prototype.collapseFile=function(){this.subFilesCollapsed(!1)},it.prototype.getInstance=function(){return new it},it.prototype.importFile=function(){var e=this.content(),t=_.bind(function(t){t&&Ci.Screens.showPopup(W,[t,e])},this);Ci.Api.pgp(t,Ti.User.IdUser)},it.prototype.viewFile=function(){this.viewCommonFile()},it.prototype.viewCommonFile=function(){var e=null,t=Si.getAppPath()+this.viewLink();this.visibleViewLink()&&this.viewLink().length>0&&"#"!==this.viewLink()&&(this.isLink()&&(t=this.linkUrl()),e=this.iframedView()?Si.WindowOpener.openTab(t):Si.WindowOpener.open(t,t,!1),e&&e.focus())},it.prototype.eventDragStart=function(e,t){var i=t.originalEvent||t;return e&&i&&i.dataTransfer&&i.dataTransfer.setData&&i.dataTransfer.setData("DownloadURL",this.generateTransferDownloadUrl()),!0 },it.prototype.generateTransferDownloadUrl=function(){var e=this.downloadLink();return"http"!==e.substr(0,4)&&(e=t.location.protocol+"//"+t.location.host+t.location.pathname+e),this.type()+":"+this.fileName()+":"+e},it.prototype.onUploadSelect=function(e,t){this.fileName(t.FileName),this.type(t.Type),this.size(Si.pInt(t.Size)),this.uploadUid(e),this.uploaded(!1),this.visibleSpinner(!1),this.statusText(""),this.progressPercent(0),this.visibleProgress(!1)},it.prototype.onUploadStart=function(){this.visibleSpinner(!0),this.visibleProgress(!0)},it.prototype.onUploadProgress=function(e,t){t>0&&(this.progressPercent(Math.ceil(e/t*100)),this.visibleProgress(!0))},it.prototype.onUploadComplete=function(e,t,i){var s=!t||!i||i.Error||!1,o=Si.i18n(i&&"size"===i.Error?"COMPOSE/UPLOAD_ERROR_SIZE":"COMPOSE/UPLOAD_ERROR_UNKNOWN");this.visibleSpinner(!1),this.progressPercent(0),this.visibleProgress(!1),this.uploaded(!0),this.uploadError(s),this.statusText(s?o:Si.i18n("COMPOSE/UPLOAD_COMPLETE")),s||(this.fillDataAfterUploadComplete(i,e),setTimeout(function(e){return function(){e.statusText("")}}(this),3e3))},it.prototype.fillDataAfterUploadComplete=function(){},it.prototype.onImageLoad=function(){this.thumb()&&!this.thumbnailLoaded()&&(this.thumbnailLoaded(!0),Si.thumbQueue(this.thumbnailSessionUid()))},Si.extend(st,it),st.prototype.dataObjectName="Object/CApiMailAttachment",st.prototype.getInstance=function(){return new st},st.prototype.getCopy=function(){var e=new st;return e.copyProperties(this),e},st.prototype.copyProperties=function(e){this.fileName(e.fileName()),this.tempName(e.tempName()),this.size(e.size()),this.accountId(e.accountId()),this.hash(e.hash()),this.type(e.type()),this.cid(e.cid()),this.contentLocation(e.contentLocation()),this.inline(e.inline()),this.linked(e.linked()),this.thumb(e.thumb()),this.thumbnailSrc(e.thumbnailSrc()),this.thumbnailLoaded(e.thumbnailLoaded()),this.statusText(e.statusText()),this.uploaded(e.uploaded()),this.iframedView(e.iframedView())},st.prototype.isVisibleViewLink=function(){return this.uploaded()&&!this.uploadError()&&(this.isViewMimeType()||this.isMessageType())},st.prototype.additionalParse=function(e){this.mimePartIndex(Si.pString(e.MimePartIndex)),this.cid(Si.pString(e.CID)),this.contentLocation(Si.pString(e.ContentLocation)),this.inline(!!e.IsInline),this.linked(!!e.IsLinked)},st.prototype.setMessageData=function(e,t){this.folderName(e),this.messageUid(t)},st.prototype.onMessageResponse=function(e){var t=e.Result,i=new rt;t&&this.oNewWindow&&(i.parse(t,e.AccountID,!1,!0),this.messagePart(i),this.messagePart().viewMessage(this.oNewWindow),this.oNewWindow=void 0)},st.prototype.viewFile=function(){this.isMessageType()?this.viewMessageFile():this.viewCommonFile()},st.prototype.viewMessageFile=function(){var t=null,i='<div style="margin: 30px; text-align: center; font: normal 14px Tahoma;">'+Si.i18n("MAIN/LOADING")+"</div>";t=Si.WindowOpener.open("",this.fileName()),t&&(this.messagePart()?this.messagePart().viewMessage(t):(e(t.document.body).html(i),this.oNewWindow=t,Ci.Ajax.send({Action:"Message",Folder:this.folderName(),Uid:this.messageUid(),Rfc822MimeIndex:this.mimePartIndex()},this.onMessageResponse,this)),t.focus())},st.prototype.viewCommonFile=function(){var e=null,t=Si.getAppPath()+this.viewLink();this.visibleViewLink()&&this.viewLink().length>0&&"#"!==this.viewLink()&&(t=Si.getAppPath()+this.viewLink(),e=this.iframedView()?Si.WindowOpener.openTab(t):Si.WindowOpener.open(t,t,!1),e&&e.focus())},st.prototype.fillDataAfterUploadComplete=function(e,t){this.cid(t),this.tempName(e.Result.Attachment.TempName),this.type(e.Result.Attachment.MimeType),this.size(e.Result.Attachment.Size),this.hash(e.Result.Attachment.Hash),this.iframedView(e.Result.Attachment.Iframed),this.accountId(e.AccountID)},st.prototype.parseFromUpload=function(e,t){this.fileName(e.Name.toString()),this.tempName(e.TempName?e.TempName.toString():this.fileName()),this.type(e.MimeType.toString()),this.size(parseInt(e.Size,10)),this.hash(e.Hash),this.accountId(t),this.uploadUid(this.hash()),this.uploaded(!0),this.uploadStarted(!1)},st.prototype.errorFromUpload=function(){this.uploaded(!0),this.uploadError(!0),this.uploadStarted(!1),this.statusText(Si.i18n("COMPOSE/UPLOAD_ERROR_UNKNOWN"))},ot.prototype.getMessageByUid=function(e){return this.oMessages[e]},ot.prototype.getFlaggedMessageUids=function(){var e=[];return _.each(this.oMessages,function(t){t.flagged()&&e.push(t.uid())}),e},ot.prototype.setMessageUnflaggedByUid=function(e){var t=this.oMessages[e];t&&t.flagged(!1)},ot.prototype.hideThreadMessages=function(e){_.each(e.threadUids(),function(e){var t=this.oMessages[e];t&&(t.deleted()||(t.threadShowAnimation(!1),t.threadHideAnimation(!0),setTimeout(function(){t.threadHideAnimation(!1)},1e3)))},this)},ot.prototype.getThreadMessages=function(e){var t=[],i=[],s=[],o=0,n=null,r=50;return _.each(e.threadUids(),function(a){if(o<e.threadCountForLoad()){var l=this.oMessages[a];l?l.deleted()||(l.markAsThreadPart(r,e.uid()),t.push(l),s.push(l.uid()),o++,n=l):(i.push(a),s.push(a),o++)}else s.push(a)},this),e.threadLoading()||this.loadThreadMessages(i),e.changeThreadUids(s,t.length),n&&t.length<e.threadUids().length&&n.showNextLoadingLink(_.bind(e.increaseThreadCountForLoad,e)),this.addThreadUidsToUidLists(e.uid(),e.threadUids()),t},ot.prototype.computeThreadData=function(e){{var t=0,i=!1,s=[];e.oFrom.getFirstEmail()}_.each(e.threadUids(),function(e){var s=this.oMessages[e];s&&!s.deleted()&&(s.seen()||t++,s.flagged()&&(i=!0))},this),e.threadUnreedCount(t),e.partialFlagged(i),e.threadSenders(s)},ot.prototype.addThreadUidsToUidLists=function(e,t){_.each(this.oUids,function(i){_.each(i,function(i){i.addThreadUids(e,t)})})},ot.prototype.loadThreadMessages=function(e){if(e.length>0){var t={Action:"MessageListByUids",Folder:this.fullName(),Uids:e};Ci.Ajax.send(t,this.onMessageListByUidsResponse,this)}},ot.prototype.getThreadCheckedUidsFromList=function(e){var t=this,i=[];return _.each(e,function(e){e.threadCount()>0&&!e.threadOpened()&&_.each(e.threadUids(),function(e){var s=t.oMessages[e];s&&!s.deleted()&&s.checked()&&i.push(e)})}),i},ot.prototype.parseAndCacheMessage=function(e,t,i){var s=e.Uid.toString(),o=this.oMessages[s]?this.oMessages[s]:new rt;return o.parse(e,this.iAccountId,t,i),this.oMessages[o.uid()]=o,o},ot.prototype.onMessageListByUidsResponse=function(e){var t=e.Result;t&&"Collection/MessageCollection"===t["@Object"]&&(_.each(t["@Collection"],function(e){this.parseAndCacheMessage(e,!0,!0)},this),Ci.MailCache.showOpenedThreads(this.fullName()))},ot.prototype.addRequestedUids=function(e){this.aRequestedUids=_.union(this.aRequestedUids,e)},ot.prototype.hasUidBeenRequested=function(e){return-1!==_.indexOf(this.aRequestedUids,e)},ot.prototype.addRequestedThreadUids=function(e){this.aRequestedThreadUids=_.union(this.aRequestedThreadUids,e)},ot.prototype.hasThreadUidBeenRequested=function(e){return-1!==_.indexOf(this.aRequestedThreadUids,e)},ot.prototype.hasListBeenRequested=function(e){var t=_.where(this.requestedLists,e),i=t.length>0;return i||this.requestedLists.push(e),i},ot.prototype.markMessageReplied=function(e,t){var i=this.oMessages[e];if(i)switch(t){case vi.ReplyType.Reply:case vi.ReplyType.ReplyAll:i.answered(!0);break;case vi.ReplyType.Forward:i.forwarded(!0)}},ot.prototype.removeAllMessages=function(){var e=null;this.oMessages={},this.oUids={},this.messageCount(0),this.unseenMessageCount(0),this.realUnseenMessageCount(0),e=this.getUidList("",""),e.resultCount(0)},ot.prototype.removeAllMessageListsFromCacheIfHasChanges=function(){this.hasChanges()&&(this.oUids={},this.requestedLists=[],this.aRequestedThreadUids=[],this.hasChanges(!1))},ot.prototype.removeFlaggedMessageListsFromCache=function(){_.each(this.oUids,function(e,t){delete this.oUids[t][vi.FolderFilter.Flagged]},this)},ot.prototype.removeUnseenMessageListsFromCache=function(){_.each(this.oUids,function(e,t){delete this.oUids[t][vi.FolderFilter.Unseen]},this)},ot.prototype.setRelevantInformation=function(e,t,i,s,o){var n=this.hasExtendedInfo()&&(this.hash()!==t||this.realUnseenMessageCount()!==s);return this.uidNext(e),this.hash(t),this.hasExtendedInfo()&&o||(this.messageCount(i),this.unseenMessageCount(s),0===s&&this.unseenMessageCount.valueHasMutated()),this.realUnseenMessageCount(s),this.hasExtendedInfo(!0),n&&this.markHasChanges(),this.relevantInformationLastMoment=moment(),n},ot.prototype.markHasChanges=function(){this.hasChanges(!0)},ot.prototype.addMessagesCountsDiff=function(e,t){var i=this.messageCount()+e,s=this.unseenMessageCount()+t;0>i&&(i=0),this.messageCount(i),0>s&&(s=0),s>i&&(s=i),this.unseenMessageCount(s)},ot.prototype.markDeletedByUids=function(e){var t=0,i=0;return _.each(e,function(e){var s=this.oMessages[e];s&&(t++,s.seen()||i++,s.deleted(!0))},this),this.addMessagesCountsDiff(-t,-i),{MinusDiff:t,UnseenMinusDiff:i}},ot.prototype.revertDeleted=function(e){var t=0,i=0;return _.each(e,function(e){var s=this.oMessages[e];s&&s.deleted()&&(t++,s.seen()||i++,s.deleted(!1))},this),this.addMessagesCountsDiff(t,i),{PlusDiff:t,UnseenPlusDiff:i}},ot.prototype.commitDeleted=function(e){_.each(e,_.bind(function(e){delete this.oMessages[e]},this)),_.each(this.oUids,function(t){_.each(t,function(t){t.deleteUids(e)})})},ot.prototype.getUidList=function(e,t){var i=null;return void 0===this.oUids[e]&&(this.oUids[e]={}),void 0===this.oUids[e][t]&&(i=new at,i.search(e),i.filters(t),this.oUids[e][t]=i),this.oUids[e][t]},ot.prototype.parse=function(e,t){var i="",s=Ci.Storage.getData("folderAccordion")||[];return"Object/Folder"===e["@Object"]?(this.parentFullName(t),i=Si.pString(e.Name),this.name(i),this.nameForEdit(i),this.fullName(Si.pString(e.FullNameRaw)),this.fullNameHash(Si.pString(e.FullNameHash)),this.routingHash(Ci.Routing.buildHashFromArray([vi.Screens.Mailbox,this.fullName()])),this.delimiter(e.Delimiter),this.type(e.Type),this.subscribed(e.IsSubscribed),this.selectable(e.IsSelectable),this.existen(e.IsExists),e.Extended&&this.setRelevantInformation(e.Extended.UidNext.toString(),e.Extended.Hash,e.Extended.MessageCount,e.Extended.MessageUnseenCount,!1),_.find(s,function(e){return e===this.name()},this)&&this.expanded(!0),e.SubFolders):null},ot.prototype.onMessageResponse=function(e,t){var i=e.Result,s=null,o=i?i.Uid.toString():t.Uid.toString(),n=this.oMessages[o],r=n?n.selected():!1;i?(n=this.parseAndCacheMessage(i,!1,!1),n&&n.ical()&&n.ical().isReplyType()&&Ci.CalendarCache&&Ci.CalendarCache.calendarChanged(!0)):(r&&(Ci.Api.showErrorByCode(e,Si.i18n("WARNING/UNKNOWN_ERROR")),Ci.Routing.replaceHashWithoutPart("/msg"+o)),n=null),s=this.aResponseHandlers[o],s&&(s.handler.call(s.context,n,o),delete this.aResponseHandlers[o])},ot.prototype.getCompletelyFilledMessage=function(e,t,i){var s=this.oMessages[e],o={Action:"Message",Folder:this.fullName(),Uid:e};e.length>0&&(s&&s.completelyFilled()&&!s.trimmed()?t&&i&&t.call(i,s,e):(t&&i&&(this.aResponseHandlers[e]={handler:t,context:i}),Ci.Ajax.send(o,this.onMessageResponse,this)))},ot.prototype.showExternalPictures=function(e){var t=this.oMessages[e];void 0!==t&&t.showExternalPictures()},ot.prototype.alwaysShowExternalPicturesForSender=function(e){_.each(this.oMessages,function(t){var i=t.oFrom.aCollection;i.length>0&&i[0].sEmail===e&&t.alwaysShowExternalPicturesForSender()},this)},ot.prototype.executeGroupOperation=function(e,t,i){var s=0;_.each(this.oMessages,function(o){t.length>0?_.each(t,function(t){o&&o.uid()===t&&o[e]()!==i&&(o[e](i),s++)}):o[e](i)}),0===t.length&&(s=i?this.unseenMessageCount():this.messageCount()-this.unseenMessageCount()),"seen"===e&&s>0&&(i?this.addMessagesCountsDiff(0,-s):this.addMessagesCountsDiff(0,s),this.markHasChanges())},ot.prototype.emptyFolder=function(){var e=Si.i18n("MAILBOX/CONFIRM_EMPTY_FOLDER"),t=_.bind(this.clearFolder,this);this.enableEmptyFolder()&&Ci.Screens.showPopup(C,[e,t])},ot.prototype.clearFolder=function(e){var t={Action:"FolderClear",Folder:this.fullName()};this.enableEmptyFolder()&&e&&(Ci.Ajax.send(t),this.removeAllMessages(),Ci.MailCache.onClearFolder(this))},ot.prototype.getNameWhithLevel=function(){var e=this.level();return!this.isNamespace()&&e>0&&e--,Si.strRepeat(" ",3*e)+this.name()},ot.prototype.onAccordion=function(e,t){var i=!this.expanded(),s=Ci.Storage.getData("folderAccordion")||[];i?s.push(this.name()):s=_.reject(s,function(e){return e===this.name()},this),Ci.Storage.setData("folderAccordion",s),this.expanded(i),Ci.MailCache.countMessages(this),t.stopPropagation()},ot.prototype.executeUnseenFilter=function(){var e=!1;return this.showUnseenMessages()?(Ci.MailCache.waitForUnseenMessages(!0),e=Ci.Routing.setHash(Ci.Links.mailbox(this.fullName(),1,"","",vi.FolderFilter.Unseen)),e&&Ci.MailCache.changeCurrentMessageList(this.fullName(),1,"",vi.FolderFilter.Unseen),!1):!0},nt.prototype.getFoldersWithoutCountInfo=function(){var e=_.compact(_.map(this.oNamedCollection,function(e,t){return e.canBeSelected()&&!e.hasExtendedInfo()?t:null}));return e},nt.prototype.setCurrentFolder=function(e,t){var i=this.getFolderByFullName(e);null===i&&(i=this.inboxFolder()),null!==i&&(this.currentFolder()&&(this.currentFolder().selected(!1),this.oStarredFolder&&this.oStarredFolder.selected(!1)),this.currentFolder(i),t===vi.FolderFilter.Flagged?this.oStarredFolder&&this.oStarredFolder.selected(!0):this.currentFolder().selected(!0))},nt.prototype.getFolderByType=function(e){switch(e){case vi.FolderTypes.Inbox:return this.inboxFolder();case vi.FolderTypes.Sent:return this.sentFolder();case vi.FolderTypes.Drafts:return this.draftsFolder();case vi.FolderTypes.Trash:return this.trashFolder();case vi.FolderTypes.Spam:return this.spamFolder()}return null},nt.prototype.getFolderByFullName=function(e){var t=this.oNamedCollection[e];return t?t:null},nt.prototype.parse=function(e,t,i){this.iAccountId=e,this.sNamespace=Si.pString(t.Namespace),this.bInitialized(!0),this.sNamespaceFolder=this.sNamespace.length>0?this.sNamespace.substring(0,this.sNamespace.length-1):this.sNamespace,this.expandFolders(Ti.MailExpandFolders&&!Ci.Storage.hasData("folderAccordion")),Ci.Storage.hasData("folderAccordion")||Ci.Storage.setData("folderAccordion",[]),this.collection(this.parseRecursively(t["@Collection"],i))},nt.prototype.parseRecursively=function(e,t,i,s){var o=this,n=[],r=0,a=0,l=null,h="",c=null,u=[],d=!1,p=this.expandFolders(),g=Ti.Accounts.getAccount(this.iAccountId),m=function(){var e=o.getFolderByType(vi.FolderTypes.Spam);g&&g.extensionExists("AllowSpamFolderExtension")||(e.type(vi.FolderTypes.User),o.spamFolder(null))},b=function(){g&&g.extensionsRequested()&&(m(),g.extensionsRequestedSubscription.dispose(),g.extensionsRequestedSubscription=void 0)};if(s=s||"",Si.isUnd(i)&&(i=-1),i++,_.isArray(e)){for(a=e.length;a>r;r++){switch(h=Si.pString(e[r].FullNameRaw),l=t[h],l||(l=new ot),l.iAccountId=this.iAccountId,c=l.parse(e[r],s),p&&null!==c&&(l.expanded(!0),this.expandNames().push(Si.pString(e[r].Name))),d=this.sNamespace===l.fullName()+l.delimiter(),l.isNamespace(d),l.level(i),this.oNamedCollection[l.fullName()]=l,l.type()){case vi.FolderTypes.Inbox:this.inboxFolder(l);break;case vi.FolderTypes.Sent:this.sentFolder(l);break;case vi.FolderTypes.Drafts:this.draftsFolder(l);break;case vi.FolderTypes.Trash:this.trashFolder(l);break;case vi.FolderTypes.Spam:this.spamFolder(l),g.extensionsRequested()?m():g.extensionsRequestedSubscription=g.extensionsRequested.subscribe(b)}n.push(l),null===c&&l.type()===vi.FolderTypes.Inbox?(this.createStarredFolder(l.fullName(),i),this.oStarredFolder&&n.push(this.oStarredFolder)):null!==c&&(u=this.parseRecursively(c["@Collection"],t,i,l.fullName()),l.type()===vi.FolderTypes.Inbox&&(l.isNamespace()?(this.createStarredFolder(l.fullName(),i+1),this.oStarredFolder&&u.unshift(this.oStarredFolder)):(this.createStarredFolder(l.fullName(),i),this.oStarredFolder&&n.push(this.oStarredFolder))),l.subfolders(u))}p&&Ci.Storage.setData("folderAccordion",this.expandNames())}return n},nt.prototype.createStarredFolder=function(e,t){var i=new ot;i.iAccountId=this.iAccountId,i.virtual(!0),i.level(t),i.fullName(e),i.name(Si.i18n("MAIN/FOLDER_STARRED")),i.type(vi.FolderTypes.Starred),i.routingHash(Ci.Routing.buildHashFromArray(Ci.Links.mailbox(i.fullName(),1,"","",vi.FolderFilter.Flagged))),this.oStarredFolder=i},nt.prototype.getOptions=function(e,t,i,s){var o=" ",n=function(e){var r=0,a=0,l=null,h=[];for(Si.isUnd(t)&&(t=!1),Si.isUnd(i)&&(i=!1),Si.isUnd(s)&&(s=!1),r=0,a=e.length;a>r;r++)l=e[r],l.virtual()||(l.type()===vi.FolderTypes.Inbox||!i)&&i||h.push({name:l.name(),fullName:l.fullName(),displayName:new Array(l.level()+1).join(o)+l.name(),translatedDisplayName:new Array(l.level()+1).join(o)+l.displayName(),disable:l.isSystem()&&!t||!s&&!l.canBeSelected()}),h=h.concat(n(l.subfolders()));return h},r=n(this.collection());return""!==e&&r.unshift({name:e,fullName:"",displayName:e,translatedDisplayName:e,disable:!1}),r},nt.prototype.getRecursivelyMessageCount=function(e){var t=0,i=0,s=null,o=0;for(t=0,i=e.length;i>t;t++)s=e[t],s.virtual()||(o+=s.messageCount()+this.getRecursivelyMessageCount(s.subfolders()));return o},nt.prototype.deleteFolder=function(e){var t=function(i){return e&&e.fullName()===i.fullName()?!0:(i.subfolders.remove(t),!1)};this.collection.remove(t)},rt.prototype.viewMessage=function(t){var i=this.getDomText(Si.getAppPath()),s="";this.textBodyForNewWindow(i.html()),s=e(this.domMessageForPrint()).html(),t&&(e(t.document.body).html(s),t.focus(),_.each(this.attachments(),function(i){var s=e(t.document.body).find("[data-hash='download-"+i.hash()+"']");s.on("click",_.bind(i.downloadFile,i,Ci)),s=e(t.document.body).find("[data-hash='view-"+i.hash()+"']"),s.on("click",_.bind(i.viewFile,i))},this))},rt.prototype.fillFromOrToText=function(){var e=Ci.MailCache.getFolderByFullName(this.accountId(),this.folder()),t=Ti.Accounts.getAccount(this.accountId());this.fromOrToText(e.type()===vi.FolderTypes.Drafts||e.type()===vi.FolderTypes.Sent?this.oTo.getDisplay(Si.i18n("MESSAGE/ME_RECIPIENT"),t.email()):this.oFrom.getDisplay(Si.i18n("MESSAGE/ME_SENDER"),t.email()))},rt.prototype.changeThreadUids=function(e,t){this.threadUids(e),this.threadLoading(t<Math.min(this.threadUids().length,this.threadCountForLoad()))},rt.prototype.showNextLoadingLink=function(e){this.threadNextLoadingLinkVisible()&&(this.threadNextLoadingVisible(!0),this.threadFunctionLoadNext=e)},rt.prototype.increaseThreadCountForLoad=function(){this.threadCountForLoad(this.threadCountForLoad()+5),Ci.MailCache.showOpenedThreads(this.folder())},rt.prototype.loadNextMessages=function(){this.threadFunctionLoadNext&&(this.threadFunctionLoadNext(),this.threadNextLoadingLinkVisible(!1),this.threadFunctionLoadNext=null)},rt.prototype.markAsThreadPart=function(e,t){var i=this;this.threadPart(!0),this.threadParentUid(t),this.threadUids([]),this.threadNextLoadingVisible(!1),this.threadNextLoadingLinkVisible(!0),this.threadFunctionLoadNext=null,this.threadHideAnimation(!1),setTimeout(function(){i.threadShowAnimation(!0)},e)},rt.prototype.parse=function(e,t,i,s){var o=null,n=null,r="",a="";s&&this.threadPart(i),this.threadPart()||this.threadParentUid(""),"Object/MessageListItem"===e["@Object"]&&(this.seen(!!e.IsSeen),this.flagged(!!e.IsFlagged),this.answered(!!e.IsAnswered),this.forwarded(!!e.IsForwarded),e.Custom&&(this.Custom=e.Custom)),("Object/Message"===e["@Object"]||"Object/MessageListItem"===e["@Object"])&&(this.accountId(t),this.folder(e.Folder),this.uid(Si.pString(e.Uid)),this.subject(Si.pString(e.Subject)),this.messageId(Si.pString(e.MessageId)),this.size(e.Size),this.textSize(e.TextSize),this.oDateModel.parse(e.TimeStampInUTC),this.oFrom.parse(e.From),this.oTo.parse(e.To),this.fillFromOrToText(),this.oCc.parse(e.Cc),this.oBcc.parse(e.Bcc),this.oSender.parse(e.Sender),this.oReplyTo.parse(e.ReplyTo),this.fullDate(this.oDateModel.getFullDate()),this.fullFrom(this.oFrom.getFull()),this.to(this.oTo.getFull()),this.cc(this.oCc.getFull()),this.bcc(this.oBcc.getFull()),this.hasAttachments(!!e.HasAttachments),this.hasIcalAttachment(!!e.HasIcalAttachment),this.hasVcardAttachment(!!e.HasVcardAttachment),"Object/MessageListItem"===e["@Object"]&&s&&this.threadUids(_.map(e.Threads,function(e){return e.toString()},this)),this.importance(e.Priority),_.isArray(e.DraftInfo)&&this.draftInfo(e.DraftInfo),this.sensitivity(e.Sensitivity),this.hash(Si.pString(e.Hash)),"Object/Message"===e["@Object"]&&(this.trimmed(e.Trimmed),this.trimmedTextSize(e.TrimmedTextSize),this.inReplyTo(e.InReplyTo),this.references(e.References),this.readingConfirmation(e.ReadingConfirmation),r=Si.pString(e.Html),a=Si.pString(e.Plain),""!==r?(this.text(r),this.isPlain(!1)):(this.textRaw(e.PlainRaw),-1!==this.textRaw().indexOf("-----BEGIN PGP MESSAGE-----")?(this.text("<pre>"+Si.encodeHtml(this.textRaw())+"</pre>"),this.encryptedMessage(!0)):-1!==this.textRaw().indexOf("-----BEGIN PGP SIGNED MESSAGE-----")?(this.text("<pre>"+Si.encodeHtml(this.textRaw())+"</pre>"),this.signedMessage(!0)):this.text(""!==a?"<div>"+a+"</div>":""),this.isPlain(!0)),this.$text=null,this.isExternalsShown(!1),this.rtl(e.Rtl),this.hasExternals(!!e.HasExternals),this.foundedCids(e.FoundedCIDs),this.parseAttachments(e.Attachments,t),this.safety(e.Safety),this.sourceHeaders(e.Headers),null!==e.ICAL&&(o=new lt,o.parse(e.ICAL,Ti.Accounts.getAttendee(this.oTo.getEmails())),this.ical(o)),null!==e.VCARD&&(n=new ht,n.parse(e.VCARD),this.vcard(n)),this.completelyFilled(!0)),this.updateMomentDate())},rt.prototype.updateMomentDate=function(){this.date(this.oDateModel.getShortDate(moment().clone().subtract("days",1).format("L")===moment.unix(this.oDateModel.getTimeStampInUTC()).format("L")))},rt.prototype.getDomText=function(t,i){var s=this.$text;return t=t||"",(null===this.$text||""!==t)&&(this.completelyFilled()?(this.$text=e(this.text()),this.showInlinePictures(t),this.safety()===!0&&this.alwaysShowExternalPicturesForSender(),i&&this.isExternalsShown()&&this.showExternalPictures(),s=this.$text):s=e("")),s.clone()},rt.prototype.getConvertedHtml=function(e,t){var i=this.getDomText(e,t);return i.length>0?i.wrap("<p>").parent().html():""},rt.prototype.parseAttachments=function(e,t){if(_.isArray(e)){var i=Date.now().toString();this.attachments(_.map(e,function(e){var s=new st;return s.parse(e,t),s.getInThumbQueue(i),s.setMessageData(this.folder(),this.uid()),s},this))}},rt.prototype.parseAddressArray=function(e){var t=[];return _.isArray(e)&&(t=_.map(e,function(e){var t=new X;return t.parse(e),t})),t},rt.prototype.findAttachmentByCid=function(e){return _.find(this.attachments(),function(t){return t.cid()===e})},rt.prototype.findAttachmentByContentLocation=function(e){return _.find(this.attachments(),function(t){return t.contentLocation()===e})},rt.prototype.showInlinePictures=function(t){var i=this;this.foundedCids().length>0&&(e("[data-x-src-cid]",this.$text).each(function(){var s=e(this).attr("data-x-src-cid"),o=i.findAttachmentByCid(s);o&&o.viewLink().length>0&&e(this).attr("src",t+o.viewLink())}),e("[data-x-style-cid]",this.$text).each(function(){var t="",s=e(this).attr("data-x-style-cid-name"),o=e(this).attr("data-x-style-cid"),n=i.findAttachmentByCid(o);n&&n.viewLink().length>0&&""!==s&&(t=Si.trim(e(this).attr("style")),t=""===t?"":";"===t.substr(-1)?t+" ":t+"; ",e(this).attr("style",t+s+": url('"+n.viewLink()+"')"))})),e("[data-x-src-location]",this.$text).each(function(){var s=e(this).attr("data-x-src-location"),o=i.findAttachmentByContentLocation(s);o||(o=i.findAttachmentByCid(s)),o&&o.viewLink().length>0&&e(this).attr("src",t+o.viewLink())})},rt.prototype.showExternalPictures=function(){e("[data-x-src]",this.$text).each(function(){e(this).attr("src",e(this).attr("data-x-src")).removeAttr("data-x-src")}),e("[data-x-style-url]",this.$text).each(function(){var t=Si.trim(e(this).attr("style"));t=""===t?"":";"===t.substr(-1)?t+" ":t+"; ",e(this).attr("style",t+e(this).attr("data-x-style-url")).removeAttr("data-x-style-url")}),this.isExternalsShown(!0)},rt.prototype.alwaysShowExternalPicturesForSender=function(){this.completelyFilled()&&(this.isExternalsAlwaysShown(!0),this.isExternalsShown()||this.showExternalPictures())},rt.prototype.openThread=function(){if(this.threadCountVisible()){var e=this.folder();this.threadOpened(!this.threadOpened()),this.threadOpened()?Ci.MailCache.showOpenedThreads(e):(Ci.MailCache.hideThreads(this),setTimeout(function(){Ci.MailCache.showOpenedThreads(e)},500))}},rt.prototype.downloadAllAttachments=function(){if(""!==this.allAttachmentsHash)Ci.Api.downloadByUrl(Si.getDownloadLinkByHash(this.accountId(),this.allAttachmentsHash));else{var e=_.filter(this.attachments(),function(e){return!e.linked()}),t=_.map(e,function(e){return e.hash()});Ci.Ajax.send({Action:"MessageZipAttachments",Hashes:t},this.onMessageZipAttachments,this)}},rt.prototype.onMessageZipAttachments=function(e){e.Result&&(this.allAttachmentsHash=e.Result,Ci.Api.downloadByUrl(Si.getDownloadLinkByHash(this.accountId(),this.allAttachmentsHash)))},rt.prototype.saveAttachmentsToFiles=function(){var e=_.filter(this.attachments(),function(e){return!e.linked()}),t=_.map(e,function(e){return e.hash()});Ci.filesRecievedAnim(!0),Ci.Ajax.send({Action:"MessageAttachmentsSaveToFiles",Attachments:t},this.onMessageAttachmentsSaveToFilesResponse,this)},rt.prototype.onMessageAttachmentsSaveToFilesResponse=function(e,t){var i=0,s=t.Attachments.length;e.Result&&_.each(t.Attachments,function(t){void 0!==e.Result[t]&&i++}),0===i?Ci.Api.showError(Si.i18n("MESSAGE/ERROR_ATTACHMENTS_SAVED_TO_FILES")):s>i?Ci.Api.showError(Si.i18n("MESSAGE/WARNING_ATTACHMENTS_SAVED_TO_FILES",{SAVED_COUNT:i,TOTAL_COUNT:s})):Ci.Api.showReport(Si.i18n("MESSAGE/REPORT_ATTACHMENTS_SAVED_TO_FILES"))},rt.prototype.downloadAllAttachmentsSeparately=function(){_.each(this.attachments(),function(e){e.linked()||e.downloadFile(Ci)})},rt.prototype.toJSON=function(){return{uid:this.uid(),accountId:this.accountId(),to:this.to(),subject:this.subject(),threadPart:this.threadPart(),threadUids:this.threadUids(),threadOpened:this.threadOpened()}},at.prototype.addThreadUids=function(e,t){-1!==_.indexOf(this.collection(),e)&&(this.threadUids[e]=t)},at.prototype.setUidsAndCount=function(e){"Collection/MessageCollection"===e["@Object"]&&(_.each(e.Uids,function(t,i){this.collection()[i+e.Offset]=t.toString()},this),this.resultCount(e.MessageResultCount))},at.prototype.getUidsForOffset=function(e,t){for(var i=0,s=this.collection().length,o="",n=0,r=[],a=null;s>i;i++)i>=e&&n<Ti.User.MailsPerPage&&(o=this.collection()[i],a=t[o],(a&&!a.deleted()||void 0===o)&&(n++,void 0!==o&&r.push(o)));return r},at.prototype.deleteUids=function(e){for(var t=0,i=this.collection().length,s="",o=[],n=0;i>t;t++)s=this.collection()[t],-1===_.indexOf(e,s)?o.push(s):n++;this.collection(o),this.resultCount(this.resultCount()-n)},lt.prototype.fillDecisions=function(){var e=Ti.Accounts.getCurrent(),t=e?e.email():"";switch(this.cancelDecision(Si.i18n("MESSAGE/APPOINTMENT_CANCELED",{SENDER:t})),this.icalConfig()){case vi.IcalConfig.Accepted:this.replyDecision(Si.i18n("MESSAGE/APPOINTMENT_ACCEPTED",{SENDER:t}));break;case vi.IcalConfig.Declined:this.replyDecision(Si.i18n("MESSAGE/APPOINTMENT_DECLINED",{SENDER:t}));break;case vi.IcalConfig.Tentative:this.replyDecision(Si.i18n("MESSAGE/APPOINTMENT_TENTATIVELY_ACCEPTED",{SENDER:t}))}},lt.prototype.parse=function(e,t){var i="";e&&"Object/CApiMailIcs"===e["@Object"]&&(i=Si.pString(e.Description),this.uid(Si.pString(e.Uid)),this.file(Si.pString(e.File)),this.attendee(Si.pString(e.Attendee)||t),this.type(e.Type),this.location(Si.pString(e.Location)),this.description(i.replace(/\r/g,"").replace(/\n/g,"<br />")),this.when(Si.pString(e.When)),this.calendarId(Si.pString(e.CalendarId)),this.selectedCalendarId(Si.pString(e.CalendarId)),Ci.CalendarCache.addIcal(this))},lt.prototype.acceptAppointment=function(){this.calendarId(this.selectedCalendarId()),this.changeAndSaveConfig(vi.IcalConfig.Accepted)},lt.prototype.tentativeAppointment=function(){this.calendarId(this.selectedCalendarId()),this.changeAndSaveConfig(vi.IcalConfig.Tentative)},lt.prototype.declineAppointment=function(){this.calendarId(""),this.selectedCalendarId(""),this.changeAndSaveConfig(vi.IcalConfig.Declined)},lt.prototype.changeAndSaveConfig=function(e){this.icalConfig()!==e&&(this.icalConfig()===e||e===vi.IcalConfig.Declined&&this.icalConfig()===vi.IcalConfig.NeedsAction||Ci.CalendarCache.recivedAnim(!0),this.changeConfig(e),this.doAppointmentAction())},lt.prototype.changeConfig=function(e){this.type(this.icalType()+"-"+e),Ti.SingleMode&&t.opener?t.opener.App.CalendarCache.markIcalTypeByFile(this.file(),this.type(),this.cancelDecision(),this.replyDecision(),this.calendarId(),this.selectedCalendarId()):Ci.CalendarCache.markIcalTypeByFile(this.file(),this.type(),this.cancelDecision(),this.replyDecision(),this.calendarId(),this.selectedCalendarId())},lt.prototype.onAppointmentActionResponse=function(e){e.Result?Ci.CalendarCache&&Ci.CalendarCache.calendarChanged(!0):Ci.Api.showErrorByCode(e,Si.i18n("WARNING/UNKNOWN_ERROR"))},lt.prototype.doAppointmentAction=function(){var e={Action:"AppointmentAction",AppointmentAction:this.icalConfig(),CalendarId:this.selectedCalendarId(),File:this.file(),Attendee:this.attendee()};Ci.Ajax.send(e,this.onAppointmentActionResponse,this)},lt.prototype.onAddEventResponse=function(e){e.Result?(e.Result.Uid&&this.uid(e.Result.Uid),Ci.CalendarCache&&Ci.CalendarCache.calendarChanged(!0)):Ci.Api.showErrorByCode(e)},lt.prototype.addEvent=function(){var e={Action:"SaveIcs",CalendarId:this.selectedCalendarId(),File:this.file()};Ci.Ajax.send(e,this.onAddEventResponse,this),this.isJustSaved(!0),this.calendarId(this.selectedCalendarId()),setTimeout(_.bind(function(){this.isJustSaved(!1)},this),2e4),Ci.CalendarCache.recivedAnim(!0)},lt.prototype.onEventDelete=function(){this.calendarId(""),this.selectedCalendarId(""),this.changeConfig(vi.IcalConfig.NeedsAction)},lt.prototype.onEventTentative=function(){this.changeConfig(vi.IcalConfig.Tentative)},lt.prototype.onEventAccept=function(){this.changeConfig(vi.IcalConfig.Accepted)},lt.prototype.firstCalendarName=function(){return this.calendars()[0]?this.calendars()[0].name:""},lt.prototype.updateAttendeeStatus=function(e){if(this.icalType()===vi.IcalType.Cancel||this.icalType()===vi.IcalType.Reply){var t={Action:"UpdateAttendeeStatus",File:this.file(),FromEmail:e};Ci.Ajax.send(t,this.onUpdateAttendeeStatusResponse,this)}},lt.prototype.onUpdateAttendeeStatusResponse=function(e){e.Result&&Ci.CalendarCache&&(Ci.CalendarCache.recivedAnim(!0),Ci.CalendarCache.calendarChanged(!0))},ht.prototype.parse=function(e){e&&"Object/CApiMailVcard"===e["@Object"]&&(this.uid(Si.pString(e.Uid)),this.file(Si.pString(e.File)),this.name(Si.pString(e.Name)),this.email(Si.pString(e.Email)),this.isExists(!!e.Exists),Ci.ContactsCache.addVcard(this))},ht.prototype.onAddContactResponse=function(e){e&&e.Result&&e.Result.Uid&&this.uid(e.Result.Uid)},ht.prototype.addContact=function(){var e={Action:"SaveVcf",File:this.file()};Ci.Ajax.send(e,this.onAddContactResponse,this),this.isJustSaved(!0),this.isExists(!0),setTimeout(_.bind(function(){this.isJustSaved(!1)},this),2e4),Ci.ContactsCache.recivedAnim(!0),Ti.SingleMode&&t.opener?t.opener.App.ContactsCache.markVcardExistentByFile(this.file()):Ci.ContactsCache.markVcardExistentByFile(this.file())},ct.birthdayMonths=Si.getMonthNamesArray(),ct.birthdayMonthSelect=[{text:Si.i18n("DATETIME/MONTH"),value:"0"},{text:ct.birthdayMonths[0],value:"1"},{text:ct.birthdayMonths[1],value:"2"},{text:ct.birthdayMonths[2],value:"3"},{text:ct.birthdayMonths[3],value:"4"},{text:ct.birthdayMonths[4],value:"5"},{text:ct.birthdayMonths[5],value:"6"},{text:ct.birthdayMonths[6],value:"7"},{text:ct.birthdayMonths[7],value:"8"},{text:ct.birthdayMonths[8],value:"9"},{text:ct.birthdayMonths[9],value:"10"},{text:ct.birthdayMonths[10],value:"11"},{text:ct.birthdayMonths[11],value:"12"}],ct.birthdayYearSelect=[{text:Si.i18n("DATETIME/YEAR"),value:"0"}],ct.prototype.getSendMailLink=function(e){var t=this.getFullEmail(e),i=Ci.Links.composeWithToField(t),s=Ci.Routing.buildHashFromArray(i); return s},ct.prototype.clear=function(){this.isNew(!1),this.readOnly(!1),this.idContact(""),this.idUser(""),this.global(!1),this.itsMe(!1),this.edited(!1),this.extented(!1),this.personalCollapsed(!1),this.businessCollapsed(!1),this.otherCollapsed(!1),this.groupsCollapsed(!1),this.displayName(""),this.firstName(""),this.lastName(""),this.nickName(""),this.skype(""),this.facebook(""),this.primaryEmail(this.sEmailDefaultType),this.primaryPhone(this.sPhoneDefaultType),this.primaryAddress(this.sAddressDefaultType),this.personalEmail(""),this.personalStreetAddress(""),this.personalCity(""),this.personalState(""),this.personalZipCode(""),this.personalCountry(""),this.personalWeb(""),this.personalFax(""),this.personalPhone(""),this.personalMobile(""),this.businessEmail(""),this.businessCompany(""),this.businessDepartment(""),this.businessJob(""),this.businessOffice(""),this.businessStreetAddress(""),this.businessCity(""),this.businessState(""),this.businessZipCode(""),this.businessCountry(""),this.businessWeb(""),this.businessFax(""),this.businessPhone(""),this.otherEmail(""),this.otherBirthdayMonth("0"),this.otherBirthdayDay("0"),this.otherBirthdayYear("0"),this.otherNotes(""),this.etag(""),this.sharedToAll(!1),this.groups([])},ct.prototype.switchToNew=function(){this.clear(),this.edited(!0),this.extented(!1),this.isNew(!0),Ii||this.displayNameFocused(!0)},ct.prototype.switchToView=function(){this.edited(!1),this.extented(!1)},ct.prototype.toObject=function(){var e={ContactId:this.idContact(),PrimaryEmail:this.primaryEmail(),PrimaryPhone:this.primaryPhone(),PrimaryAddress:this.primaryAddress(),UseFriendlyName:"1",Title:"",FullName:this.displayName(),FirstName:this.firstName(),LastName:this.lastName(),NickName:this.nickName(),Global:this.global()?"1":"0",ItsMe:this.itsMe()?"1":"0",Skype:this.skype(),Facebook:this.facebook(),HomeEmail:this.personalEmail(),HomeStreet:this.personalStreetAddress(),HomeCity:this.personalCity(),HomeState:this.personalState(),HomeZip:this.personalZipCode(),HomeCountry:this.personalCountry(),HomeFax:this.personalFax(),HomePhone:this.personalPhone(),HomeMobile:this.personalMobile(),HomeWeb:this.personalWeb(),BusinessEmail:this.businessEmail(),BusinessCompany:this.businessCompany(),BusinessJobTitle:this.businessJob(),BusinessDepartment:this.businessDepartment(),BusinessOffice:this.businessOffice(),BusinessStreet:this.businessStreetAddress(),BusinessCity:this.businessCity(),BusinessState:this.businessState(),BusinessZip:this.businessZipCode(),BusinessCountry:this.businessCountry(),BusinessFax:this.businessFax(),BusinessPhone:this.businessPhone(),BusinessWeb:this.businessWeb(),OtherEmail:this.otherEmail(),Notes:this.otherNotes(),ETag:this.etag(),BirthdayDay:this.otherBirthdayDay(),BirthdayMonth:this.otherBirthdayMonth(),BirthdayYear:this.otherBirthdayYear(),SharedToAll:this.sharedToAll()?"1":"0",GroupsIds:this.groups()};return e},ct.prototype.parse=function(e){if(e&&"Object/CContact"===e["@Object"]){var t=0,i=0,s=0,o=[];switch(this.idContact(Si.pExport(e,"IdContact","").toString()),this.idUser(Si.pExport(e,"IdUser","").toString()),this.global(!!Si.pExport(e,"Global",!1)),this.itsMe(!!Si.pExport(e,"ItsMe",!1)),this.readOnly(!!Si.pExport(e,"ReadOnly",!1)),this.displayName(Si.pExport(e,"FullName","")),this.firstName(Si.pExport(e,"FirstName","")),this.lastName(Si.pExport(e,"LastName","")),this.nickName(Si.pExport(e,"NickName","")),this.skype(Si.pExport(e,"Skype","")),this.facebook(Si.pExport(e,"Facebook","")),t=Si.pInt(Si.pExport(e,"PrimaryEmail",0))){case 1:t=vi.ContactEmailType.Business;break;case 2:t=vi.ContactEmailType.Other;break;default:case 0:t=vi.ContactEmailType.Personal}switch(this.primaryEmail(t),i=Si.pInt(Si.pExport(e,"PrimaryPhone",0))){case 2:i=vi.ContactPhoneType.Business;break;case 1:i=vi.ContactPhoneType.Personal;break;default:case 0:i=vi.ContactPhoneType.Mobile}switch(this.primaryPhone(i),s=Si.pInt(Si.pExport(e,"PrimaryAddress",0))){case 1:s=vi.ContactAddressType.Business;break;default:case 0:s=vi.ContactAddressType.Personal}this.primaryAddress(s),this.personalEmail(Si.pExport(e,"HomeEmail","")),this.personalStreetAddress(Si.pExport(e,"HomeStreet","")),this.personalCity(Si.pExport(e,"HomeCity","")),this.personalState(Si.pExport(e,"HomeState","")),this.personalZipCode(Si.pExport(e,"HomeZip","")),this.personalCountry(Si.pExport(e,"HomeCountry","")),this.personalWeb(Si.pExport(e,"HomeWeb","")),this.personalFax(Si.pExport(e,"HomeFax","")),this.personalPhone(Si.pExport(e,"HomePhone","")),this.personalMobile(Si.pExport(e,"HomeMobile","")),this.businessEmail(Si.pExport(e,"BusinessEmail","")),this.businessCompany(Si.pExport(e,"BusinessCompany","")),this.businessDepartment(Si.pExport(e,"BusinessDepartment","")),this.businessJob(Si.pExport(e,"BusinessJobTitle","")),this.businessOffice(Si.pExport(e,"BusinessOffice","")),this.businessStreetAddress(Si.pExport(e,"BusinessStreet","")),this.businessCity(Si.pExport(e,"BusinessCity","")),this.businessState(Si.pExport(e,"BusinessState","")),this.businessZipCode(Si.pExport(e,"BusinessZip","")),this.businessCountry(Si.pExport(e,"BusinessCountry","")),this.businessWeb(Si.pExport(e,"BusinessWeb","")),this.businessFax(Si.pExport(e,"BusinessFax","")),this.businessPhone(Si.pExport(e,"BusinessPhone","")),this.otherEmail(Si.pExport(e,"OtherEmail","")),this.otherBirthdayMonth(Si.pExport(e,"BirthdayMonth","0").toString()),this.otherBirthdayDay(Si.pExport(e,"BirthdayDay","0").toString()),this.otherBirthdayYear(Si.pExport(e,"BirthdayYear","0").toString()),this.otherNotes(Si.pExport(e,"Notes","")),this.etag(Si.pExport(e,"ETag","")),this.sharedToAll(!!Si.pExport(e,"SharedToAll",!1)),o=Si.pExport(e,"GroupsIds",[]),_.isArray(o)&&this.groups(o)}},ct.prototype.getFullEmail=function(e){var t=e;return""!==this.displayName()&&(t=""!==e?'"'+this.displayName()+'" <'+e+">":this.displayName()),t},ct.prototype.getEmailsString=function(){return _.uniq(_.without([this.email(),this.personalEmail(),this.businessEmail(),this.otherEmail()],"")).join(",")},ct.prototype.viewAllMails=function(){Ci.MailCache.searchMessagesInInbox("email:"+this.getEmailsString())},ct.prototype.sendThisContact=function(){Ci.Routing.goDirectly(Ci.Links.compose(),["vcard",this])},ct.prototype.isStrLink=function(e){return/^http/.test(e)},ct.prototype.onCallClick=function(e){Ci.Phone.call(e)},ct.prototype.viewAllMailsWithContact=function(){var e=this.getEmailsString();Ti.SingleMode&&t.opener&&t.opener.App?(t.opener.App.MailCache.searchMessagesInCurrentFolder("email:"+e),t.opener.focus(),t.close()):Ci.MailCache.searchMessagesInCurrentFolder("email:"+e)},ut.prototype.clear=function(){this.isNew(!1),this.idGroup(""),this.idUser(""),this.name(""),this.nameFocused(!1),this.edited(!1),this.isOrganization(!1),this.email(""),this.country(""),this.city(""),this.company(""),this.fax(""),this.phone(""),this.state(""),this.street(""),this.web(""),this.zip(""),this.events([])},ut.prototype.populate=function(e){this.isNew(e.isNew()),this.idGroup(e.idGroup()),this.idUser(e.idUser()),this.name(e.name()),this.nameFocused(e.nameFocused()),this.edited(e.edited()),this.isOrganization(e.isOrganization()),this.email(e.email()),this.country(e.country()),this.city(e.city()),this.company(e.company()),this.fax(e.fax()),this.phone(e.phone()),this.state(e.state()),this.street(e.street()),this.web(e.web()),this.zip(e.zip())},ut.prototype.switchToNew=function(){this.clear(),this.edited(!0),this.isNew(!0),Ii||this.nameFocused(!0)},ut.prototype.switchToView=function(){this.edited(!1)},ut.prototype.toObject=function(){return{GroupId:this.idGroup(),Name:this.name(),IsOrganization:this.isOrganization()?"1":"0",Email:this.email(),Country:this.country(),City:this.city(),Company:this.company(),Fax:this.fax(),Phone:this.phone(),State:this.state(),Street:this.street(),Web:this.web(),Zip:this.zip()}},dt.prototype.parse=function(e){e&&"Object/CContactListItem"===Si.pExport(e,"@Object","")&&(this.sId=Si.pString(e.Id),this.sName=Si.pString(e.Name),this.sEmail=Si.pString(e.Email),this.bIsGroup=!!e.IsGroup,this.bIsOrganization=!!e.IsOrganization,this.bReadOnly=!!e.ReadOnly,this.bItsMe=!!e.ItsMe,this.bGlobal=!!e.Global,this.bSharedToAll=!!e.SharedToAll)},dt.prototype.IsGroup=function(){return this.bIsGroup},dt.prototype.Global=function(){return this.bGlobal},dt.prototype.ReadOnly=function(){return this.bReadOnly},dt.prototype.ItsMe=function(){return this.bItsMe},dt.prototype.Id=function(){return this.sId},dt.prototype.Name=function(){return this.sName},dt.prototype.Email=function(){return this.sEmail},dt.prototype.EmailAndName=function(){return this.sName&&this.sEmail&&0<this.sName.length&&0<this.sEmail.length?'"'+this.sName+'" <'+this.sEmail+">":this.sEmail},dt.prototype.IsSharedToAll=function(){return this.bSharedToAll},dt.prototype.IsOrganization=function(){return this.bIsOrganization},pt.prototype.parse=function(e){this.id=Si.pString(e.Id),this.cTag=e.CTag,this.name(Si.pString(e.Name)),this.description(Si.pString(e.Description)),this.owner(Si.pString(e.Owner)),this.active(Ci.Storage.hasData(this.id)?Ci.Storage.getData(this.id):!0),this.isDefault=!!e.IsDefault,this.access(e.Access),this.isShared(!!e.Shared),this.isSharedToAll(!!e.SharedToAll),this.sharedToAllAccess=e.SharedToAllAccess,this.isPublic(!!e.IsPublic);var t=Si.pString(e.Color);this.color(t),this.url(Si.pString(e.Url)),this.davUrl(Si.pString(e.ServerUrl)),this.exportUrl(Si.getAppPath()+"?/Raw/Calendars/0/"+Si.pString(e.ExportHash)),this.pubUrl(Si.getAppPath()+"?calendar-pub="+Si.pString(e.PubHash)),this.shares(e.Shares||[]),_.each(e.Events,function(e){this.addEvent(e)},this)},pt.prototype.eventExists=function(e){return _.find(this.events(),function(t){return e===t.id})},pt.prototype.updateEvent=function(e){var t=!1;return e&&(this.removeEvent(e.id),this.addEvent(e)),t},pt.prototype.addEvent=function(e){e&&!this.eventExists(e.id)&&this.events.push(this.parseEvent(e))},pt.prototype.getEvent=function(e){return _.find(this.events(),function(t){return t.id===e},this)},pt.prototype.getEvents=function(e,t){var i=_.filter(this.events(),function(i){return moment.utc(i.start).unix()>=e.unix()&&moment.utc(i.end).unix()<=t.unix()||moment.utc(i.start).unix()<=e.unix()&&moment.utc(i.end).unix()>=t.unix()},this);return Si.isUnd(i)&&(i=[]),i},pt.prototype.removeEvent=function(e){this.events(_.filter(this.events(),function(t){return t.id!==e},this))},pt.prototype.removeEventByUid=function(e,t){Si.isUnd(t)&&(t=!1),this.events(_.filter(this.events(),function(i){return!(i.uid===e||t&&i.excluded)},this))},pt.prototype.removeEvents=function(){this.events([])},pt.prototype.expungeEvents=function(e,t,i){var s=[];_.each(this.getEvents(moment.unix(t),moment.unix(i)),function(t){_.include(e,t.id)||s.push(t.id)},this),this.events(_.filter(this.events(),function(e){return!_.include(s,e.id)},this))},pt.prototype.isEditable=function(){return this.access()!==vi.CalendarAccess.Read},pt.prototype.isOwner=function(){return this.account&&this.account.email()===this.owner()},pt.prototype.parseEvent=function(e){if(e.title=Si.getTitleForEvent(e.subject),e.editable=e.appointment?!1:!0,e.backgroundColor=e.borderColor=this.color(),!_.isArray(e.className)){var t=e.className;e.className=[t]}return this.access()===vi.CalendarAccess.Read?e.className.push("fc-event-readonly"):e.className=_.filter(e.className,function(e){return"fc-event-readonly"!==e}),e.rrule&&!e.excluded?e.className.push("fc-event-repeat"):e.className=_.filter(e.className,function(e){return"fc-event-repeat"!==e}),Si.isNonEmptyArray(e.attendees)?e.className.push("fc-event-appointment"):e.className=_.filter(e.className,function(e){return"fc-event-appointment"!==e}),e},pt.prototype.reloadEvents=function(){this.events(_.map(this.events(),function(e){return this.parseEvent(e)},this))},pt.prototype.canShare=function(){return!this.isShared()||this.isShared()&&this.access()===vi.CalendarAccess.Write||this.isOwner()},gt.prototype.pickCurrentCalendar=function(e){var t=_.find(this.collection(),function(e){return e.active()&&e.access()===vi.CalendarAccess.Write},this);this.currentCal()&&this.currentCal().active()||(e&&e.active()?this.currentCal(e):!this.defaultCal()||!this.defaultCal().active()&&t?t&&this.currentCal(t):this.currentCal(this.defaultCal()))},gt.prototype.hideOtherCalendars=function(e){_.each(this.collection(),function(t){t.active(t.id===e)},this)},gt.prototype.getCalendarById=function(e){var t=_.find(this.collection(),function(t){return t.id===e},this);return t},gt.prototype.getEvents=function(e,t){var i=[],s=[];return _.each(this.collection(),function(o){o&&o.active()&&(s=Si.isUnd(e)||Si.isUnd(t)?o.events():o.getEvents(e,t),i=_.union(i,s))},this),i},gt.prototype.parseCalendar=function(e){var t=new pt;return t.parse(e),t},gt.prototype.parseAndAddCalendar=function(e){var t=0,i=null,s=this.parseCalendar(e);return s.active.subscribe(function(e){this.parentOnCalendarActiveChange(s);var t=s.active()?s:this.defaultCal();this.pickCurrentCalendar(t),Ci.Storage.setData(s.id,e)},this),s.isDefault&&this.defaultCal(s),t=this.calendarExists(s.id),t||0===t?(i=this.getCalendarById(s.id),s.events(i.events()),this.collection.splice(t,1,s)):this.collection.push(s),this.sort(),s},gt.prototype.calendarExists=function(e){var t=_.indexOf(_.map(this.collection(),function(e){return e.id}),e);return 0>t?!1:t},gt.prototype.removeCalendar=function(e){this.collection(_.filter(this.collection(),function(t){return t.id!==e},this))},gt.prototype.clearCollection=function(){this.collection.removeAll()},gt.prototype.getColors=function(){return _.map(this.collection(),function(e){return e.color().toLowerCase()},this)},gt.prototype.setDefault=function(e){_.each(this.collection(),function(t){t.id!==e?(t.isDefault=!0,this.defaultCal(t)):t.isDefault=!1},this)},gt.prototype.sort=function(){var e=_.sortBy(this.collection(),function(e){return e.name()});this.collection(_.sortBy(e,function(e){return e.isShared()}))},gt.prototype.expunge=function(e){this.collection(_.filter(this.collection(),function(t){return _.include(e,t.id)},this))},Si.extend(mt,it),mt.prototype.getInstance=function(){return new mt},mt.prototype.parse=function(e,t){var i=new et;this.isFolder(!!e.IsFolder),this.isLink(!!e.IsLink),this.fileName(Si.pString(e.Name)),this.id(Si.pString(e.Id)),this.path(Si.pString(e.Path)),this.fullPath(Si.pString(e.FullPath)),this.storageType(Si.pInt(e.Type)),this.shared(!!e.Shared),this.isExternal(!!e.IsExternal),this.iframedView(!!e.Iframed),this.isLink()&&(this.linkUrl(Si.pString(e.LinkUrl)),this.linkType(Si.pInt(e.LinkType))),this.isFolder()||(this.size(Si.pInt(e.Size)),i.parse(e.LastModified),this.lastModified(i.getShortDate()),this.owner(Si.pString(e.Owner)),this.thumb(!!e.Thumb),this.thumbnailExternalLink(Si.pString(e.ThumbnailLink)),this.hash(Si.pString(e.Hash)),this.publicHash(t)),this.thumb()&&""===this.thumbnailExternalLink()&&Si.thumbQueue(this.thumbnailSessionUid(),this.thumbnailLink(),this.thumbnailSrc),this.content(Si.pString(e.Content))},mt.prototype.onUploadSelectOwn=function(e,t,i,s,o,n){var r=new et,a=new Date;this.onUploadSelect(e,t),r.parse(a.getTime()/1e3),this.fileName(i),this.lastModified(r.getShortDate()),this.owner(s),this.path(o),this.storageType(n)},bt.prototype.parse=function(e){if(this.Id=e.IdHelpdeskPost,this.IdThread=e.IdHelpdeskThread,this.IdOwner=e.IdOwner,this.bThreadOwner=e.IsThreadOwner,this.sFrom=Si.isNonEmptyArray(e.Owner)?e.Owner[1]||e.Owner[0]||"":"",this.sDate=et.prototype.convertDate(e.Created),this.iType=e.Type,this.bSysType=e.SystemType,this.sText=Si.pString(e.Text),this.itsMe(e.ItsMe),e.Attachments){var t=0,i=0,s=null,o=[],n=Date.now().toString();for(i=e.Attachments.length;i>t;t++)e.Attachments[t]&&"Object/CHelpdeskAttachment"===Si.pExport(e.Attachments[t],"@Object","")&&(s=new yt,s.parse(e.Attachments[t]),s.getInThumbQueue(n),o.push(s));this.attachments(o)}},ft.prototype.parse=function(e){this.Id=e.IdHelpdeskThread,this.ThreadHash=Si.pString(e.ThreadHash),this.IdOwner=e.IdOwner,this.ItsMe=!!e.ItsMe,this.sSubject=Si.pString(e.Subject),this.time(Si.pInt(e.Updated)),this.aOwner=Si.isNonEmptyArray(e.Owner)?e.Owner:["",""],this.sEmail=this.aOwner[0]||"",this.sName=this.aOwner[1]||"",this.sFrom=this.sName||this.sEmail,this.sFromFull=Si.trim(""===this.sName?this.sEmail:this.sName+(""!==this.sEmail?" ("+this.sEmail+")":"")),this.postsCount(e.PostCount),this.state(e.Type),this.unseen(!e.IsRead)},ft.prototype.Name=function(){return this.sName},ft.prototype.Email=function(){return this.sEmail},ft.prototype.updateMomentDate=function(){this.time.valueHasMutated()},Si.extend(yt,it),yt.prototype.dataObjectName="Object/CHelpdeskAttachment",yt.prototype.getInstance=function(){return new yt},yt.prototype.fillDataAfterUploadComplete=function(e){this.tempName(e.Result.HelpdeskFile.TempName),this.type(e.Result.HelpdeskFile.MimeType),this.hash(e.Result.HelpdeskFile.Hash)},vt.prototype.parse=function(e,t){this.iAccountId=e,this.options(parseInt(t.Options,10)),this.signature(t.Signature)},St.prototype.parse=function(e,t){this.iAccountId=e,this.enable=!!t.Enable,this.subject=Si.pString(t.Subject),this.message=Si.pString(t.Message)},Ct.prototype.parse=function(e,t){this.accountId=e;var i=[],s=0,o=0,n=null,r=null;if(_.isArray(t))for(o=t.length;o>s;s++)r=t[s],n=new At,n.id(r.IdFetcher),n.accountId(r.IdAccount),n.isEnabled(r.IsEnabled),n.isLocked(r.IsLocked),n.email(r.Email),n.userName(r.Name),n.folder(r.Folder),n.signatureOptions(!!r.SignatureOptions),n.signature(r.Signature),n.incomingMailServer(r.IncomingMailServer),n.incomingMailPort(r.IncomingMailPort),n.incomingMailLogin(r.IncomingMailLogin),n.leaveMessagesOnServer(r.LeaveMessagesOnServer),n.isOutgoingEnabled(r.IsOutgoingEnabled),n.outgoingMailServer(r.OutgoingMailServer),n.outgoingMailPort(r.OutgoingMailPort),n.outgoingMailAuth(r.OutgoingMailAuth),i.push(n);this.collection(i)},Ct.prototype.getFetcher=function(e){var t=null,i=0,s=0,o=this.collection();for(s=o.length;s>i;i++)o[i].id()===e&&(t=o[i]);return t},Et.prototype.parse=function(e,t){this.iAccountId=e,this.enable=!!t.Enable,this.email=Si.pString(t.Email)},Tt.prototype.parse=function(e,t){var i=0,s=t.length,o=null;if(this.iAccountId=e,_.isArray(t))for(s=t.length;s>i;i++)o=new Ft(e),o.parse(t[i]),this.collection.push(o)},Ft.prototype.parse=function(e){this.enable(!!e.Enable),this.field(Si.pInt(e.Field)),this.condition(Si.pInt(e.Condition)),this.filter(Si.pString(e.Filter)),this.action(Si.pInt(e.Action)),this.folder(Si.pString(e.FolderFullName)),this.commit()},Ft.prototype.revert=function(){this.enable.revert(),this.field.revert(),this.condition.revert(),this.filter.revert(),this.action.revert(),this.folder.revert()},Ft.prototype.commit=function(){this.enable.commit(),this.field.commit(),this.condition.commit(),this.filter.commit(),this.action.commit(),this.folder.commit()},Ft.prototype.toString=function(){var e=[this.enable(),this.field(),this.condition(),this.filter(),this.action(),this.folder()];return e.join(":")},It.prototype.showLoading=function(e){this.loadingMessage(e&&""!==e?e:Si.i18n("MAIN/LOADING")),this.loadingVisible(!0),_.defer(_.bind(function(){this.loadingHidden(!1)},this))},It.prototype.hideLoading=function(){this.loadingHidden(!0),setTimeout(_.bind(function(){this.loadingHidden()&&this.loadingVisible(!1)},this),this.iAnimationDuration)},It.prototype.showReport=function(e,t){var i=this;t=t||this.iReportDuration,e&&""!==e?(this.reportMessage(e),this.reportVisible(!0),_.defer(function(){i.reportHidden(!1)}),clearTimeout(this.iReportTimeout),this.iReportTimeout=setTimeout(function(){i.reportHidden(!0),setTimeout(function(){i.reportHidden()&&i.reportVisible(!1)},this.iAnimationDuration)},t)):(this.reportHidden(!0),this.reportVisible(!1))},It.prototype.showError=function(e,t,i,s){e&&""!==e?(this.gray(!!s),this.errorMessage(e),this.isHtmlError(t),this.errorVisible(!0),_.defer(_.bind(function(){this.errorHidden(!1)},this)),clearTimeout(this.iErrorTimeout),i||(this.iErrorTimeout=setTimeout(_.bind(function(){this.selfHideError()},this),this.iErrorDuration))):this.selfHideError()},It.prototype.selfHideError=function(){this.errorHidden(!0),setTimeout(_.bind(function(){this.errorHidden()&&this.errorVisible(!1)},this),this.iAnimationDuration)},It.prototype.hideError=function(e){e=Si.isUnd(e)?!1:!!e,e===this.gray()&&this.selfHideError()},wt.prototype.onRoute=function(){this.changeCurrentAccount()},wt.prototype.changeCurrentAccount=function(){this.email(Ti.Accounts.getEmail())},wt.prototype.logout=function(){Ci.logout()},wt.prototype.switchToFullVersion=function(){Ci.Ajax.send({Action:"SetMobile",Mobile:0},function(){t.location.reload()},this)},_.extend(Pt.prototype,wt.prototype),Mt.prototype.hotKeysBind=function(){e(document).on("keydown",e.proxy(function(e){if(this.shown&&!Si.isTextFieldFocused()){var t=e.keyCode;e.ctrlKey&&t===vi.Key.Left?this.clickPreviousPage():e.ctrlKey&&t===vi.Key.Right&&this.clickNextPage()}},this))},Mt.prototype.hide=function(){this.shown=!1},Mt.prototype.show=function(){this.shown=!0},Mt.prototype.clear=function(){this.currentPage(1),this.count(0)},Mt.prototype.setCount=function(e){this.count(e),this.currentPage()>this.pagesCount()&&this.currentPage(this.pagesCount())},Mt.prototype.setPage=function(e,t){this.perPage(t),this.currentPage(e>this.pagesCount()?this.pagesCount():e)},Mt.prototype.clickPage=function(e){var t=e.number;1>t&&(t=1),t>this.pagesCount()&&(t=this.pagesCount()),this.currentPage(t)},Mt.prototype.clickFirstPage=function(){this.currentPage(1)},Mt.prototype.clickPreviousPage=function(){var e=this.currentPage()-1;1>e&&(e=1),this.currentPage(e)},Mt.prototype.clickNextPage=function(){var e=this.currentPage()+1;e>this.pagesCount()&&(e=this.pagesCount()),this.currentPage(e)},Mt.prototype.clickLastPage=function(){this.currentPage(this.pagesCount())},Rt.prototype.init=function(){e(document.body).on("click",_.bind(function(){this.closeAllPopups()},this)),e(this.colorPickerDropdownDom()).on("click",function(e){e.stopPropagation()}),e(this.insertLinkDropdownDom()).on("click",function(e){e.stopPropagation()}),e(this.insertImageDropdownDom()).on("click",function(e){e.stopPropagation()}),this.initEditorUploader()},Rt.prototype.correctFontFromSettings=function(){var e=this.sDefaultFont,t=!1;_.each(this.aFonts,function(i){i.toLowerCase()===e.toLowerCase()&&(e=i,t=!0)}),t?this.sDefaultFont=e:this.aFonts.push(e)},Rt.prototype.showLinkPopup=function(t){var i=e(this.workareaDom()),s=i.position(),o=t.position(),n=t.height();this.linkHref(t.attr("href")||t.text()),this.linkPopupLeft(Math.round(o.left+s.left)),this.linkPopupTop(Math.round(o.top+n+s.top)),this.visibleLinkPopup(!0)},Rt.prototype.hideLinkPopup=function(){this.visibleLinkPopup(!1)},Rt.prototype.showChangeLink=function(){this.visibleLinkHref(!0),this.hideLinkPopup()},Rt.prototype.changeLink=function(){this.oCrea.changeLink(this.linkHref()),this.hideChangeLink()},Rt.prototype.hideChangeLink=function(){this.visibleLinkHref(!1)},Rt.prototype.showImagePopup=function(t,i){var s=e(this.workareaDom()),o=s.position(),n=s.offset();this.imagePopupLeft(Math.round(i.pageX+o.left-n.left)),this.imagePopupTop(Math.round(i.pageY+o.top-n.top)),this.visibleImagePopup(!0)},Rt.prototype.hideImagePopup=function(){this.visibleImagePopup(!1)},Rt.prototype.resizeImage=function(e){var t={width:"auto",height:"auto"};switch(e){case vi.HtmlEditorImageSizes.Small:t.width="300px";break;case vi.HtmlEditorImageSizes.Medium:t.width="600px";break;case vi.HtmlEditorImageSizes.Large:t.width="1200px";break;case vi.HtmlEditorImageSizes.Original:t.width="auto"}this.oCrea.changeCurrentImage(t),this.visibleImagePopup(!1)},Rt.prototype.onImageOver=function(t){if("IMG"===t.target.nodeName&&!this.visibleImagePopup()){this.imageSelected(!0),this.tooltipText(Si.i18n("HTMLEDITOR/CLICK_TO_EDIT_IMAGE"));var i=this,s=e(this.workareaDom());s.bind("mousemove.image",function(e){var t=s.position(),o=s.offset();i.tooltipPopupTop(Math.round(e.pageY+t.top-o.top)),i.tooltipPopupLeft(Math.round(e.pageX+t.left-o.left))})}return!0},Rt.prototype.onImageOut=function(){if(this.imageSelected()){this.imageSelected(!1);var t=e(this.workareaDom());t.unbind("mousemove.image")}return!0},Rt.prototype.initCrea=function(e,t,i){this.oCrea||(this.init(),this.oCrea=new Crea({creaId:this.creaId,fontNameArray:this.aFonts,defaultFontName:this.sDefaultFont,defaultFontSize:this.iDefaultSize,isRtl:Si.isRTL(),enableDrop:!1,onCursorMove:_.bind(this.setFontValuesFromText,this),onFocus:_.bind(this.onCreaFocus,this),onBlur:_.bind(this.onCreaBlur,this),onUrlIn:_.bind(this.showLinkPopup,this),onUrlOut:_.bind(this.hideLinkPopup,this),onImageSelect:_.bind(this.showImagePopup,this),onImageBlur:_.bind(this.hideImagePopup,this),onItemOver:_.bind(this.onImageOver,this),onItemOut:_.bind(this.onImageOut,this),openInsertLinkDialog:_.bind(this.insertLink,this)}),this.oCrea.start(this.isEnable())),this.oCrea.setTabIndex(i),this.oCrea.clearUndoRedo(),this.setText(e,t),this.setFontValuesFromText(),this.uploadedImagePathes([]),this.selectedFont(this.sDefaultFont),this.selectedSize(this.iDefaultSize)},Rt.prototype.setFocus=function(){this.oCrea&&this.oCrea.setFocus(!1)},Rt.prototype.changeSignatureContent=function(e,t){this.oCrea&&this.oCrea.changeSignatureContent(e,t)},Rt.prototype.setFontValuesFromText=function(){this.lockFontSubscribing(!0),this.selectedFont(this.oCrea.getFontName()),this.selectedSize(this.oCrea.getFontSizeInNumber()),this.lockFontSubscribing(!1)},Rt.prototype.isUndoAvailable=function(){return this.oCrea?this.oCrea.isUndoAvailable():!1},Rt.prototype.getPlainText=function(){return this.oCrea?this.oCrea.getPlainText():""},Rt.prototype.getText=function(e){return this.oCrea?this.oCrea.getText(e):""},Rt.prototype.setText=function(e,t){this.oCrea&&(t?this.oCrea.setPlainText(e):this.oCrea.setText(e),this.inactive.valueHasMutated())},Rt.prototype.undoAndClearRedo=function(){this.oCrea&&(this.oCrea.undo(),this.oCrea.clearRedo())},Rt.prototype.getNotDefaultText=function(){var e=this.getText();return this.removeAllTags(e)!==Si.i18n("HTMLEDITOR/SIGNATURE_PLACEHOLDER")?e:""},Rt.prototype.removeAllTags=function(e){return e.replace(/<style>.*<\/style>/g,"").replace(/<[^>]*>/g,"")},Rt.prototype.setActivitySource=function(e){this.activitySource=e,null!==this.activitySourceSubscription&&this.activitySourceSubscription.dispose(),this.activitySourceSubscription=this.activitySource.subscribe(function(){this.inactive(0===Si.pInt(this.activitySource()))},this),this.inactive(0===Si.pInt(this.activitySource()))},Rt.prototype.onCreaFocus=function(){this.oCrea&&(this.closeAllPopups(),this.activitySource(1),this.textFocused(!0))},Rt.prototype.onCreaBlur=function(){this.oCrea&&this.textFocused(!1)},Rt.prototype.closeAllPopups=function(){this.visibleInsertLinkPopup(!1),this.visibleInsertImagePopup(!1),this.visibleFontColorPopup(!1)},Rt.prototype.insertHtml=function(e){this.oCrea&&(this.oCrea.isFocused()||this.oCrea.setFocus(!0),this.oCrea.insertHtml(e,!1))},Rt.prototype.insertLink=function(){this.visibleInsertLinkPopup()||(this.linkForInsert(this.getMailtoLink(this.oCrea.getSelectedText())),this.closeAllPopups(),this.visibleInsertLinkPopup(!0),this.linkFocused(!0))},Rt.prototype.insertLinkFromPopup=function(e,t){this.linkForInsert().length>0&&(this.linkForInsert(this.getMailtoLink(this.linkForInsert())),this.oCrea.insertLink(this.linkForInsert())),this.closeInsertLinkPopup(e,t)},Rt.prototype.closeInsertLinkPopup=function(e,t){this.visibleInsertLinkPopup(!1),t&&t.stopPropagation()},Rt.prototype.textColor=function(){this.closeAllPopups(),this.visibleFontColorPopup(!0),this.oFontColorPicker.onShow(),this.oBackColorPicker.onShow()},Rt.prototype.colorToHex=function(e){if("#"===e.substr(0,1))return e;for(var t=/(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(e),i=parseInt(t[2],10),s=parseInt(t[3],10),o=parseInt(t[4],10),n=o|s<<8|i<<16,r=n.toString(16);r.length<6;)r="0"+r;return t[1]+"#"+r},Rt.prototype.setTextColorFromPopup=function(e){this.oCrea.textColor(this.colorToHex(e)),this.visibleFontColorPopup(!1)},Rt.prototype.setBackColorFromPopup=function(e){this.oCrea.backgroundColor(this.colorToHex(e)),this.visibleFontColorPopup(!1)},Rt.prototype.insertImage=function(){return this.allowInsertImage()&&!this.visibleInsertImagePopup()&&(this.imagePathFromWeb(""),this.closeAllPopups(),this.visibleInsertImagePopup(!0),this.initUploader()),!0},Rt.prototype.insertWebImageFromPopup=function(e,t){this.allowInsertImage()&&this.imagePathFromWeb().length>0&&this.oCrea.insertImage(this.imagePathFromWeb()),this.closeInsertImagePopup(e,t)},Rt.prototype.insertComputerImageFromPopup=function(t,i){var s=Si.getViewLinkByHash(Ti.Accounts.currentId(),i.Hash),o=!1;this.allowInsertImage()&&s.length>0&&(o=this.oCrea.insertImage(s),o&&(e(this.oCrea.$editableArea).find('img[src="'+s+'"]').attr("data-x-src-cid",t),i.CID=t,this.uploadedImagePathes.push(i))),this.closeInsertImagePopup()},Rt.prototype.closeInsertImagePopup=function(e,t){this.visibleInsertImagePopup(!1),t&&t.stopPropagation()},Rt.prototype.initUploader=function(){this.imageUploaderButton()&&!this.oJua&&(this.oJua=new Jua({action:"?/Upload/Attachment/",name:"jua-uploader",queueSize:2,clickElement:this.imageUploaderButton(),disableMultiple:!0,disableAjaxUpload:!1,disableDragAndDrop:!0,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()}}}),this.bInsertImageAsBase64?this.oJua.on("onSelect",_.bind(this.onEditorDrop,this)):this.oJua.on("onSelect",_.bind(this.onFileUploadSelect,this)).on("onComplete",_.bind(this.onFileUploadComplete,this)))},Rt.prototype.initEditorUploader=function(){if(Ti.App.AllowInsertImage&&this.uploaderAreaDom()&&!this.editorUploader){var e=null,t=null;this.oParent&&this.oParent.composeUploaderDragOver&&this.oParent.onFileUploadProgress&&this.oParent.onFileUploadStart&&this.oParent.onFileUploadComplete?(e=_.bind(function(){this.editorUploaderBodyDragOver(!0),this.oParent.composeUploaderDragOver(!0)},this),t=_.bind(function(){this.editorUploaderBodyDragOver(!1),this.oParent.composeUploaderDragOver(!1)},this),this.editorUploader=new Jua({action:"?/Upload/Attachment/",name:"jua-uploader",queueSize:1,dragAndDropElement:this.bAllowImageDragAndDrop?this.uploaderAreaDom():null,disableMultiple:!0,disableAjaxUpload:!1,disableDragAndDrop:!this.bAllowImageDragAndDrop,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()}}}),this.editorUploader.on("onDragEnter",_.bind(this.oParent.composeUploaderDragOver,this.oParent,!0)).on("onDragLeave",_.bind(this.oParent.composeUploaderDragOver,this.oParent,!1)).on("onBodyDragEnter",e).on("onBodyDragLeave",t).on("onProgress",_.bind(this.oParent.onFileUploadProgress,this.oParent)).on("onSelect",_.bind(this.onEditorDrop,this)).on("onStart",_.bind(this.oParent.onFileUploadStart,this.oParent)).on("onComplete",_.bind(this.oParent.onFileUploadComplete,this.oParent))):(e=_.bind(this.editorUploaderBodyDragOver,this,!0),t=_.bind(this.editorUploaderBodyDragOver,this,!1),this.editorUploader=new Jua({queueSize:1,dragAndDropElement:this.bAllowImageDragAndDrop?this.uploaderAreaDom():null,disableMultiple:!0,disableAjaxUpload:!1,disableDragAndDrop:!this.bAllowImageDragAndDrop}),this.editorUploader.on("onBodyDragEnter",e).on("onBodyDragLeave",t).on("onSelect",_.bind(this.onEditorDrop,this)))}},Rt.prototype.onEditorDrop=function(e,i){var s=null,o=null,n=this,r=!1,a=Math.random().toString();if(i&&i.File&&i.File.type)if(Ti.App.AllowInsertImage&&0===i.File.type.indexOf("image/"))o=i.File,Ti.App.ImageUploadSizeLimit>0&&o.size>Ti.App.ImageUploadSizeLimit?Ci.Screens.showPopup(A,[Si.i18n("COMPOSE/UPLOAD_ERROR_SIZE")]):(s=new t.FileReader,r=this.oCrea.isFocused(),r||this.oCrea.setFocus(!0),this.oCrea.insertHtml('<img id="'+o.name+"_"+a+'" src="skins/Default/images/wait.gif" />',!0),r||this.oCrea.fixFirefoxCursorBug(),s.onload=function(e){n.oCrea.$editableArea.find('img[id="'+o.name+"_"+a+'"]').attr("src",e.target.result),n.oCrea.editableSave()},s.readAsDataURL(o));else{if(this.oParent&&this.oParent.onFileUploadSelect)return this.oParent.onFileUploadSelect(e,i),!0;Ci.browser.ie10AndAbove||Ci.Screens.showPopup(A,[Si.i18n("HTMLEDITOR/UPLOAD_ERROR_NOT_IMAGE")]) }return!1},Rt.prototype.isFileImage=function(t){if("string"==typeof t.Type)return-1!==t.Type.indexOf("image");var i=t.FileName.lastIndexOf("."),s=t.FileName.substr(i+1),o=["jpg","jpeg","gif","tif","tiff","png"];return-1!==e.inArray(s,o)},Rt.prototype.onFileUploadSelect=function(e,t){return this.isFileImage(t)?(this.closeInsertImagePopup(),!0):(Ci.Screens.showPopup(A,[Si.i18n("HTMLEDITOR/UPLOAD_ERROR_NOT_IMAGE")]),!1)},Rt.prototype.onFileUploadComplete=function(e,t,i){var s="";i&&i.Result?i.Result.Error?(s=Si.i18n("size"===i.Result.Error?"COMPOSE/UPLOAD_ERROR_SIZE":"COMPOSE/UPLOAD_ERROR_UNKNOWN"),Ci.Screens.showPopup(A,[s])):(this.oCrea.setFocus(!0),this.insertComputerImageFromPopup(e,i.Result.Attachment)):Ci.Screens.showPopup(A,[Si.i18n("COMPOSE/UPLOAD_ERROR_UNKNOWN")])},Rt.prototype.getMailtoLink=function(e){return Si.isCorrectEmail(e)?"mailto:"+e:e},Dt.prototype.onShow=function(){e(this.colorPickerDom()).find("span.color-item").on("click",function(t){return function(){t.setColorFromPopup(e(this).data("color"))}}(this))},Dt.prototype.setColorFromPopup=function(e){this.pickHandler.call(this.pickContext,e)},_t.prototype.answer=function(){this.action(vi.PhoneAction.IncomingConnect)},_t.prototype.multiAction=function(){var e=this.action();e===vi.PhoneAction.OfflineActive?this.action(vi.PhoneAction.Offline):e===vi.PhoneAction.Online?(this.action(vi.PhoneAction.OnlineActive),this.getLogs(),_.delay(_.bind(function(){this.inputFocus(!0)},this),500)):e===vi.PhoneAction.OnlineActive&&this.validateNumber()?(this.phone&&(this.phone.phoneToCall(this.input()),this.action(vi.PhoneAction.Outgoing)),this.inputFocus(!1)):e!==vi.PhoneAction.OnlineActive||this.validateNumber()?(e===vi.PhoneAction.Outgoing||e===vi.PhoneAction.Incoming||e===vi.PhoneAction.OutgoingConnect||e===vi.PhoneAction.IncomingConnect)&&(this.action(vi.PhoneAction.Online),this.dropdownShow(!1)):(this.action(vi.PhoneAction.Online),this.dropdownShow(!1))},_t.prototype.autocompleteCallback=function(e,t){var i={Action:"ContactSuggestions",Search:e,PhoneOnly:"1"};this.phoneAutocompleteItem(null),e=Si.trim(e),""!==e&&Ci.Ajax.send(i,function(e){var i=[];e&&e.Result&&e.Result.List&&(_.each(e.Result.List,function(e){_.each(e.Phones,function(t){i.push({label:""!==e.Name?e.Name+" <"+e.Email+">":e.Email,value:t,frequency:e.Frequency})},this)},this),i=_.sortBy(_.compact(i),function(e){return-e.frequency})),t(i)},this)},_t.prototype.validateNumber=function(){return/^[^a-zA-Z\u00BF-\u1FFF\u2C00-\uD7FF]+$/g.test(this.input())},_t.prototype.onLogItem=function(e){this.input(e.phoneToCall),this.dropdownShow(!1)},_t.prototype.getLogs=function(){this.spinner(!0),this.logs([]),this.logsToShow([]),this.phone.getLogs(this.onLogsResponse,this)},_t.prototype.onLogsResponse=function(e){e&&e.Result&&(this.logs([]),_.each(e.Result,function(e){e.phoneToCall=this.phone.getCleanedPhone("incoming"===e.UserDirection?e.From:e.To),e.phoneToShow=e.UserDisplayName?e.UserDisplayName:e.phoneToCall,e.phoneToShow&&this.logs.push(e)},this),this.logs(_.sortBy(this.logs(),function(e){return-Date.parse(e.StartTime)}).slice(0,100)),this.seeMore()),this.spinner(!1)},_t.prototype.seeMore=function(){this.logsToShow(this.logs().slice(0,this.logsToShow().length+10))},_t.prototype.timer=function(){var e=0,t=0,i=0,s=function(e){var t=e.toString();return 1===t.length?t="0"+t:t};return function(o){"start"===o?(t=0,i=0,e=setInterval(_.bind(function(){60===t&&(t=0,i++),this.report(Si.i18n("PHONE/PASSED_TIME")+" "+s(i)+":"+s(t)),t++},this),1e3)):"stop"===o&&clearInterval(e)}}(),Nt.prototype.__name="CWrapLoginViewModel",Nt.prototype.onShow=function(){this.oLoginViewModel.onShow&&this.oLoginViewModel.onShow()},Nt.prototype.onApplyBindings=function(){this.oLoginViewModel.onApplyBindings&&this.oLoginViewModel.onApplyBindings()},Nt.prototype.changeLanguage=function(e){e&&this.allowLanguages()&&(this.currentLanguage(e),this.oLoginViewModel.changingLanguage(!0),Ci.Ajax.send({Action:"LoginLanguageUpdate",Language:e},function(){t.location.reload()},this))},kt.prototype.__name="CLoginViewModel",kt.prototype.onApplyBindings=function(){wi.addClass("non-adjustable-valign")},kt.prototype.onShow=function(){this.fillFields()},kt.prototype.fillFields=function(){_.delay(_.bind(function(){this.focusFields()},this),1)},kt.prototype.focusFields=function(){this.emailVisible()&&""===this.email()?this.emailFocus(!0):this.loginVisible()&&""===this.login()&&this.loginFocus(!0)},kt.prototype.signIn=function(){e(".check_autocomplete_input").trigger("input").trigger("change").trigger("keydown");var t=this.loginFormType(),i=this.email(),s=this.login(),o=this.password();this.loading()||this.changingLanguage()||""===Si.trim(o)||!(vi.LoginFormType.Login===t&&""!==Si.trim(s)||vi.LoginFormType.Email===t&&""!==Si.trim(i)||vi.LoginFormType.Both===t&&""!==Si.trim(i))?this.shake(!0):this.sendRequest()},kt.prototype.onResponse=function(e){!1===e.Result?(this.loading(!1),this.shake(!0),Ci.Api.showErrorByCode(e,Si.i18n("WARNING/LOGIN_PASS_INCORRECT"))):t.location.reload()},kt.prototype.sendRequest=function(){var e={Action:"Login",Email:this.emailVisible()?this.email():"",IncLogin:this.loginVisible()?this.login():"",IncPassword:this.password(),SignMe:this.signMe()?"1":"0"};this.loading(!0),Ci.Ajax.send(e,this.onResponse,this)},Lt.prototype.__name="CForgotViewModel",Lt.prototype.executeGetQuestion=function(){var e={Action:"GetForgotAccountQuestion",Email:this.email()};this.gettingQuestion(!0),Ci.Ajax.send(e,this.onGetQuestionResponse,this)},Lt.prototype.onGetQuestionResponse=function(e){var t="";this.gettingQuestion(!1),!1===e.Result?Ci.Api.showErrorByCode(e,Si.i18n("LOGIN/ERROR_GETTING_QUESTION")):(t=Si.pString(e.Result.Question),""===t?Ci.Api.showError(Si.i18n("LOGIN/ERROR_PASSWORD_RESET_NOT_AVAILABLE")):(this.question(t),this.visibleEmailForm(!1),this.visibleQuestionForm(!0),this.visiblePasswordForm(!1)))},Lt.prototype.executeValidateAnswer=function(){var e={Action:"ValidateForgotAccountQuestion",Email:this.email(),Question:this.question(),Answer:this.answer()};this.validatingAnswer(!0),Ci.Ajax.send(e,this.onValidateAnswerResponse,this)},Lt.prototype.onValidateAnswerResponse=function(e){this.validatingAnswer(!1),!1===e.Result?Ci.Api.showErrorByCode(e,Si.i18n("LOGIN/ERROR_WRONG_ANSWER")):(this.visibleEmailForm(!1),this.visibleQuestionForm(!1),this.visiblePasswordForm(!0))},Lt.prototype.executeChangePassword=function(){if(this.password()!==this.confirmPassword())Ci.Api.showError(Si.i18n("WARNING/PASSWORDS_DO_NOT_MATCH"));else{var e={Action:"ChangeForgotAccountPassword",Email:this.email(),Question:this.question(),Answer:this.answer(),Password:this.password()};this.changingPassword(!0),Ci.Ajax.send(e,this.onChangePasswordResponse,this)}},Lt.prototype.onChangePasswordResponse=function(e){this.changingPassword(!1),!1===e.Result?Ci.Api.showErrorByCode(e,Si.i18n("LOGIN/ERROR_RESETTING_PASSWORD")):(this.gotoForgot(!1),Ci.Api.showReport(Si.i18n("LOGIN/REPORT_PASSWORD_CHANGED")))},Ot.prototype.__name="CRegisterViewModel",Ot.prototype.registerAccount=function(){if(this.password()!==this.confirmPassword())Ci.Api.showError(Si.i18n("WARNING/PASSWORDS_DO_NOT_MATCH"));else{var e={Action:"RegisterAccount",Name:this.name(),Email:this.login()+"@"+this.selectedDomain(),Password:this.password(),Question:this.allowQuestionPart?this.visibleYourQuestion()?this.yourQuestion():this.question():"",Answer:this.allowQuestionPart?this.answer():""};this.loading(!0),Ci.Ajax.send(e,this.onResponse,this)}},Ot.prototype.onResponse=function(e){!1===e.Result?(this.loading(!1),Ci.Api.showErrorByCode(e,Si.i18n("WARNING/LOGIN_PASS_INCORRECT"))):t.location.reload()},Ut.prototype.createDatePickerObject=function(t){e(t).datepicker({showOtherMonths:!0,selectOtherMonths:!0,monthNames:Si.getMonthNamesArray(),dayNamesMin:Si.i18n("DATETIME/DAY_NAMES_MIN").split(" "),firstDay:Ti.User.CalendarWeekStartsOn,showOn:"focus",dateFormat:this.dateFormatDatePicker}),e(t).mousedown(function(){e("#ui-datepicker-div").toggle()})},Ut.prototype.changeRoutingForMessageList=function(e,t,i,s,o){var n=Ci.Routing.setHash(Ci.Links.mailbox(e,t,i,s,o));n&&s.length>0&&this.search()===s&&this.listChangedThrottle(!this.listChangedThrottle())},Ut.prototype.onEnterPress=function(e){e.openThread()},Ut.prototype.onMessageDblClick=function(e){var t=this.folderList().getFolderByFullName(e.folder());t.type()===vi.FolderTypes.Drafts?Ci.Routing.setHash(Ci.Links.composeFromMessage("drafts",e.folder(),e.uid())):this.openMessageInNewWindowBinded(e)},Ut.prototype.onFolderListSubscribe=function(){this.setCurrentFolder(),this.requestMessageList()},Ut.prototype.onShow=function(){this.selector.useKeyboardKeys(!0),this.oPageSwitcher.show(),this.oJua&&this.oJua.setDragAndDropEnabledStatus(!0)},Ut.prototype.onHide=function(){this.selector.useKeyboardKeys(!1),this.oPageSwitcher.hide(),this.oJua&&this.oJua.setDragAndDropEnabledStatus(!1)},Ut.prototype.onRoute=function(e){var t=Ci.Links.parseMailbox(e),i=this.currentPage()!==t.Page||this.folderFullName()!==t.Folder||this.filters()!==t.Filters||t.Filters===vi.FolderFilter.Unseen&&Ci.MailCache.waitForUnseenMessages()||this.search()!==t.Search,s=Ti.User.MailsPerPage!==this.oPageSwitcher.perPage();this.pageSwitcherLocked(!0),this.folderFullName()!==t.Folder||this.search()!==t.Search||this.filters()!==t.Filters?this.oPageSwitcher.clear():this.oPageSwitcher.setPage(t.Page,Ti.User.MailsPerPage),this.pageSwitcherLocked(!1),t.Page!==this.oPageSwitcher.currentPage()&&Ci.Routing.replaceHash(Ci.Links.mailbox(t.Folder,this.oPageSwitcher.currentPage(),t.Uid,t.Search,t.Filters)),this.currentPage(this.oPageSwitcher.currentPage()),this.folderFullName(t.Folder),this.filters(t.Filters),this.search(t.Search),this.searchInput(this.search()),this.searchSpan.notifySubscribers(),this.setCurrentFolder(),(i||s||0===this.collection().length)&&(t.Filters===vi.FolderFilter.Unseen&&Ci.MailCache.waitForUnseenMessages(!0),this.requestMessageList()),this.highlightTrigger.notifySubscribers(!0)},Ut.prototype.setCurrentFolder=function(){this.folderList().setCurrentFolder(this.folderFullName(),this.filters())},Ut.prototype.requestMessageList=function(){var e=this.folderList().currentFolderFullName(),t=this.oPageSwitcher.currentPage();e.length>0?Ci.MailCache.changeCurrentMessageList(e,t,this.search(),this.filters()):Ci.MailCache.checkCurrentFolderList()},Ut.prototype.calculateSearchStringFromAdvancedForm=function(){var t=this.searchInputFrom(),i=this.searchInputTo(),s=this.searchInputSubject(),o=this.searchInputText(),n=this.searchAttachmentsCheckbox(),r=(this.searchAttachments(),this.searchDateStart()),a=this.searchDateEnd(),l=[],h=function(t){return t=e.trim(t).replace(/"/g,'\\"'),(-1<t.indexOf(" ")||-1<t.indexOf('"'))&&(t='"'+t+'"'),t};return""!==t&&l.push("from:"+h(t)),""!==i&&l.push("to:"+h(i)),""!==s&&l.push("subject:"+h(s)),""!==o&&l.push("text:"+h(o)),n&&l.push("has:attachments"),(""!==r||""!==a)&&l.push("date:"+h(r)+"/"+h(a)),l.join(" ")},Ut.prototype.onSearchClick=function(){var e=this.folderList().currentFolderFullName(),t=1,i=this.searchInput();this.bAdvancedSearch()&&(i=this.calculateSearchStringFromAdvancedForm(),this.searchInput(i),this.bAdvancedSearch(!1)),this.changeRoutingForMessageList(e,t,"",i,this.filters())},Ut.prototype.onRetryClick=function(){this.requestMessageList()},Ut.prototype.onClearSearchClick=function(){var e=this.folderList().currentFolderFullName(),t=this.currentMessage()?this.currentMessage().uid():"",i="",s=1;this.clearAdvancedSearch(),this.changeRoutingForMessageList(e,s,t,i,this.filters())},Ut.prototype.onClearFilterClick=function(){var e=this.folderList().currentFolderFullName(),t=this.currentMessage()?this.currentMessage().uid():"",i="",s=1,o="";this.clearAdvancedSearch(),this.changeRoutingForMessageList(e,s,t,i,o)},Ut.prototype.onStopSearchClick=function(){this.onClearSearchClick()},Ut.prototype.routeForMessage=function(e){if(null!==e){var t=this.folderList().currentFolder(),i=this.folderList().currentFolderFullName(),s=this.oPageSwitcher.currentPage(),o=e.uid(),n=this.search();""!==o&&(Ii&&t.type()===vi.FolderTypes.Drafts?Ci.Routing.setHash(Ci.Links.composeFromMessage("drafts",e.folder(),e.uid())):(this.changeRoutingForMessageList(i,s,o,n,this.filters()),Ii&&Ci.MailCache.currentMessage()&&o===Ci.MailCache.currentMessage().uid()&&Ci.MailCache.currentMessage.valueHasMutated()))}},Ut.prototype.onApplyBindings=function(t){var s=this,o=_.bind(function(e){e&&e.stopPropagation&&e.stopPropagation()},this);e(".message_list",t).on("click",function(){s.isFocused(!1)}).on("click",".message_sub_list .item .flag",function(e){s.onFlagClick(i.dataFor(this)),e&&e.stopPropagation&&e.stopPropagation()}).on("dblclick",".message_sub_list .item .flag",o).on("click",".message_sub_list .item .thread",o).on("dblclick",".message_sub_list .item .thread",o),this.selector.initOnApplyBindings(".message_sub_list .item",".message_sub_list .item.selected",".message_sub_list .item .custom_checkbox",e(".message_list",t),e(".message_list_scroll.scroll-inner",t)),this.initUploader()},Ut.prototype.onFlagClick=function(e){Ci.MailCache.executeGroupOperation("MessageSetFlagged",[e.uid()],"flagged",!e.flagged())},Ut.prototype.executeMarkAsRead=function(){Ci.MailCache.executeGroupOperation("MessageSetSeen",this.checkedOrSelectedUids(),"seen",!0)},Ut.prototype.executeMarkAsUnread=function(){Ci.MailCache.executeGroupOperation("MessageSetSeen",this.checkedOrSelectedUids(),"seen",!1)},Ut.prototype.executeMarkAllRead=function(){Ci.MailCache.executeGroupOperation("MessageSetAllSeen",[],"seen",!0)},Ut.prototype.executeMoveToFolder=function(e){Ci.MailCache.moveMessagesToFolder(e,this.checkedOrSelectedUids())},Ut.prototype.executeCopyToFolder=function(e){Ci.MailCache.copyMessagesToFolder(e,this.checkedOrSelectedUids())},Ut.prototype.onDeletePress=function(e){var t=_.map(e,function(e){return e.uid()});t.length>0&&this.deleteMessages(t)},Ut.prototype.executeDelete=function(){this.deleteMessages(this.checkedOrSelectedUids())},Ut.prototype.deleteMessages=function(e){var t=this.folderList().currentFolderFullName(),i=this.folderList().trashFolder(),s=i&&t===i.fullName(),o=this.folderList().spamFolder(),n=o&&t===o.fullName(),r=function(t){t&&Ci.MailCache.deleteMessages(e)};n?Ci.MailCache.deleteMessages(e):s?Ci.Screens.showPopup(C,[Si.i18n("MAILBOX/CONFIRM_MESSAGES_DELETE"),r]):i?Ci.MailCache.moveMessagesToFolder(i.fullName(),this.checkedOrSelectedUids()):i||Ci.Screens.showPopup(C,[Si.i18n("MAILBOX/CONFIRM_MESSAGES_DELETE_NO_TRASH_FOLDER"),r])},Ut.prototype.executeSpam=function(){var e=this.folderList().spamFolderFullName();this.folderList().currentFolderFullName()!==e&&Ci.MailCache.moveMessagesToFolder(e,this.checkedOrSelectedUids())},Ut.prototype.executeNotSpam=function(){var e=this.folderList().inboxFolder();e&&this.folderList().currentFolderFullName()!==e.fullName()&&Ci.MailCache.moveMessagesToFolder(e.fullName(),this.checkedOrSelectedUids())},Ut.prototype.clearAdvancedSearch=function(){this.searchInputFrom(""),this.searchInputTo(""),this.searchInputSubject(""),this.searchInputText(""),this.bAdvancedSearch(!1),this.searchAttachmentsCheckbox(!1),this.searchAttachments(""),this.searchDateStart(""),this.searchDateEnd("")},Ut.prototype.onAdvancedSearchClick=function(){this.bAdvancedSearch(!this.bAdvancedSearch())},Ut.prototype.calculateSearchStringForDescription=function(){return'<span class="part">'+Si.encodeHtml(this.search())+"</span>"},Ut.prototype.initUploader=function(){var e=this;this.uploaderArea()&&(this.oJua=new Jua({action:"?/Upload/Message/",name:"jua-uploader",queueSize:2,dragAndDropElement:this.uploaderArea(),disableAjaxUpload:this.isPublic,disableFolderDragAndDrop:this.isPublic,disableDragAndDrop:this.isPublic,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()},AdditionalData:function(){return JSON.stringify({Folder:e.folderFullName()})}}}),this.oJua.on("onDrop",_.bind(this.onMessageDrop,this)).on("onComplete",_.bind(this.onMessageUploadComplete,this)).on("onBodyDragEnter",_.bind(this.bDragActive,this,!0)).on("onBodyDragLeave",_.bind(this.bDragActive,this,!1)))},Ut.prototype.onMessageDrop=function(e){e&&e.File&&e.File.type&&0===e.File.type.indexOf("message/")||Ci.Api.showError(Si.i18n("MAILBOX/ERROR_UPLOAD_EML"))},Ut.prototype.onMessageUploadComplete=function(e,t,i){var s=!t||!i||i.Error||!1;s?Ci.Api.showError(Si.i18n("MAILBOX/ERROR_UPLOAD_EML")):Ci.MailCache.executeCheckMail()},Ht.prototype.resizeDblClick=function(t,i){""!==i.target.className&&i.target.className.search(/add_contact|icon|link|title|subject|link|date/)&&(i.preventDefault(),i.stopPropagation?i.stopPropagation():i.cancelBubble=!0,Si.removeSelection(),this.jqPanelHelper||(this.jqPanelHelper=e(".MailLayout .panel_helper")),this.jqPanelHelper.trigger("resize",[5,"min",!0]))},Ht.prototype.notifySender=function(){this.currentMessage()&&""!==this.currentMessage().readingConfirmation()&&(Ci.Ajax.send({Action:"MessageSendConfirmation",Confirmation:this.currentMessage().readingConfirmation(),Subject:Si.i18n("MESSAGE/RETURN_RECEIPT_MAIL_SUBJECT"),Text:Si.i18n("MESSAGE/RETURN_RECEIPT_MAIL_TEXT",{EMAIL:Ti.Accounts.getEmail(),SUBJECT:this.subject()}),ConfirmFolder:this.currentMessage().folder(),ConfirmUid:this.currentMessage().uid()}),this.currentMessage().readingConfirmation(""))},Ht.prototype.onMessagesSubscribe=function(){!this.currentMessage()&&this.uid().length>0&&Ci.MailCache.setCurrentMessage(this.uid(),this.folder())},Ht.prototype.onCurrentMessageSubscribe=function(){var i=null,s=null,o=this.currentMessage(),n=o?Ti.Accounts.getAccount(o.accountId()):null;if(this.singleMode()&&t.opener&&t.opener.oReplyDataFromViewPane?(this.replyText(t.opener.oReplyDataFromViewPane.ReplyText),this.replyDraftUid(t.opener.oReplyDataFromViewPane.ReplyDraftUid),t.opener.oReplyDataFromViewPane=null):o&&o.uid()===this.displayedMessageUid()||(this.replyText(""),this.replyDraftUid("")),o&&this.uid()===o.uid()){if(this.subject(o.subject()),this.importance(o.importance()),this.from(o.oFrom.getDisplay()),this.fromEmail(o.oFrom.getFirstEmail()),this.fullFrom(o.oFrom.getFull()),this.oFromAddr(o.oFrom.aCollection.length>0?o.oFrom.aCollection[0]:null),this.to(o.oTo.getFull()),this.aToAddr(o.oTo.aCollection),this.cc(o.oCc.getFull()),this.aCcAddr(o.oCc.aCollection),this.bcc(o.oBcc.getFull()),this.aBccAddr(o.oBcc.aCollection),this.currentAccountEmail(n.email()),this.aAllRecipients(_.uniq(_.union(this.aToAddr(),this.aCcAddr(),this.aBccAddr()))),this.mobileApp||this.requestContactsByEmail(_.union(o.oFrom.aCollection,this.aAllRecipients())),this.midDate(o.oDateModel.getMidDate()),this.fullDate(o.oDateModel.getFullDate()),this.isLoading(""!==o.uid()&&!o.completelyFilled()),this.setMessageBody(),this.rtlMessage(o.rtl()),this.singleMode()){var r=[],a=Date.now().toString();_.each(o.attachments(),_.bind(function(e){var t=new st;t.copyProperties(e),t.getInThumbQueue(a),r.push(t)},this)),this.attachments(r)}else this.attachments(o.attachments());if(null!==this.ical()&&this.ical().animation(!1),i=o.ical(),i&&this.singleMode()&&(i=this.getIcalCopy(i)),this.ical(i),null!==this.ical()&&(_.defer(_.bind(function(){null!==this.ical()&&this.ical().animation(!0)},this)),this.ical().updateAttendeeStatus(this.fromEmail())),s=o.vcard(),s&&this.singleMode()&&(s=this.getVcardCopy(s)),this.vcard(s),!o.completelyFilled()||o.trimmed()){var l=o.completelyFilled()?o.trimmed:o.completelyFilled;this.singleMode()?o.completelyFilledSingleModeSubscription=l.subscribe(this.onCurrentMessageSubscribe,this):o.completelyFilledSubscription=l.subscribe(this.onCurrentMessageSubscribe,this)}else o.completelyFilledSubscription?(o.completelyFilledSubscription.dispose(),o.completelyFilledSubscription=void 0):o.completelyFilledSingleModeSubscription&&(o.completelyFilledSingleModeSubscription.dispose(),o.completelyFilledSingleModeSubscription=void 0)}else this.isLoading(!1),e(this.domTextBody()).empty().data("displayed-message-uid",""),this.displayedMessageUid(""),this.rtlMessage(!1),this.attachments([]),this.visiblePicturesControl(!1),this.visibleShowPicturesLink(!1),this.ical(null),this.vcard(null),this.decryptPassword(""),this.visibleDecryptControl(!1),this.visibleVerifyControl(!1)},Ht.prototype.updateMomentDate=function(){var e=this.currentMessage();e&&e.oDateModel&&(this.midDate(e.oDateModel.getMidDate()),this.fullDate(e.oDateModel.getFullDate()))},Ht.prototype.fromMouseoverEvent=function(e,t){this.oFromAddr()&&this.oFromAddr().mouseoverEvent(e,t)},Ht.prototype.fromMouseoutEvent=function(e,t){this.oFromAddr()&&this.oFromAddr().mouseoutEvent(e,t)},Ht.prototype.requestContactsByEmail=function(e){_.each(e,_.bind(function(e){Ci.ContactsCache.getContactByEmail(e.sEmail,this.onContactResponse,this)},this))},Ht.prototype.onContactResponse=function(e,t){e&&(this.recipientsContacts.push(e),this.recipientsContacts(_.uniq(this.recipientsContacts()))),_.each(_.union([this.oFromAddr()],this.aAllRecipients()),function(i){i&&i.sEmail===t&&(i.loaded(!0),e&&i.founded(!0))})},Ht.prototype.getVcardCopy=function(e){var t=new ht;return t.uid(e.uid()),t.file(e.file()),t.name(e.name()),t.email(e.email()),t.isExists(e.isExists()),t.isJustSaved(e.isJustSaved()),t},Ht.prototype.getIcalCopy=function(e){var t=new lt;return t.uid(e.uid()),t.file(e.file()),t.attendee(e.attendee()),t.type(e.type()),t.cancelDecision(e.cancelDecision()),t.replyDecision(e.replyDecision()),t.isJustSaved(e.isJustSaved()),t.location(e.location()),t.description(e.description()),t.when(e.when()),t.calendarId(e.calendarId()),t.selectedCalendarId(e.selectedCalendarId()),t.calendars(e.calendars()),t.animation(e.animation()),t},Ht.prototype.setMessageBody=function(){if(this.currentMessage()){var t=this.currentMessage(),i=t.text(),s=i.length,o=5e6,n=e(this.domTextBody()),r=[];this.textBody(i),_.defer(_.bind(function(){if(this.currentMessage()){var e=this.currentMessage();n.data("displayed-message-uid")===e.uid()&&(r=this.getBlockquotesStatus()),n.empty(),e.isPlain()||s>o?(n.html(i),this.visiblePicturesControl(!1)):(n.append(e.getDomText().html()),this.visiblePicturesControl(e.hasExternals()&&!e.isExternalsAlwaysShown()),this.visibleShowPicturesLink(!e.isExternalsShown()),this.doHidingBlockquotes(r)),this.decryptPassword(""),this.visibleDecryptControl(Ti.User.enableOpenPgp()&&e.encryptedMessage()),this.visibleVerifyControl(Ti.User.enableOpenPgp()&&e.signedMessage()),n.data("displayed-message-uid",e.uid()),this.displayedMessageUid(e.uid())}},this))}},Ht.prototype.getBlockquotesStatus=function(){var t=[];return e(e("blockquote",e(this.domTextBody())).get()).each(function(){var i=e(this);i.hasClass("blockquote_before_toggle")&&t.push(i.hasClass("collapsed"))}),t},Ht.prototype.doHidingBlockquotes=function(t){var i=120,s=80,o=0;e(e("blockquote",e(this.domTextBody())).get()).each(function(){var n=e(this),r=n.parents("blockquote"),a=e('<span class="blockquote_toggle"></span>').html(Si.i18n("MESSAGE/SHOW_QUOTED_TEXT")),l=!0;0===r.length&&n.height()>i&&(n.addClass("blockquote_before_toggle").after(a).wrapInner('<div class="blockquote_content"></div>'),a.bind("click",function(){l?(n.height("auto"),a.html(Si.i18n("MESSAGE/HIDE_QUOTED_TEXT")),l=!1):(n.height(s),a.html(Si.i18n("MESSAGE/SHOW_QUOTED_TEXT")),l=!0),n.toggleClass("collapsed",l)}),o<t.length&&(l=t[o],o++),n.height(l?s:"auto").toggleClass("collapsed",l))})},Ht.prototype.onRoute=function(e){var t=Ci.Links.parseMailbox(e);""!==this.replyText()&&this.uid()!==t.Uid&&this.saveReplyMessage(!1),this.uid(t.Uid),this.folder(t.Folder),Ci.MailCache.setCurrentMessage(this.uid(),this.folder()),this.contentHasFocus(!0)},Ht.prototype.showPictures=function(){Ci.MailCache.showExternalPictures(!1),this.visibleShowPicturesLink(!1),this.setMessageBody()},Ht.prototype.alwaysShowPictures=function(){var e=this.currentMessage()?this.currentMessage().oFrom.getFirstEmail():"";e.length>0&&Ci.Ajax.send({Action:"EmailSafety",Email:e}),Ci.MailCache.showExternalPictures(!0),this.visiblePicturesControl(!1),this.setMessageBody()},Ht.prototype.showDetails=function(){this.detailsVisible(!0)},Ht.prototype.hideDetails=function(){this.detailsVisible(!1)},Ht.prototype.openInNewWindow=function(){this.openMessageInNewWindowBinded(this.currentMessage())},Ht.prototype.addToContacts=function(e,t){this.processed()||(this.processed(!0),Ci.ContactsCache.addToContacts(t,e,this.onAddToContactsResponse,this))},Ht.prototype.onAddToContactsResponse=function(e,t){e.Result&&""!==t.HomeEmail&&(Ci.Api.showReport(Si.i18n("CONTACTS/REPORT_CONTACT_SUCCESSFULLY_ADDED")),Ci.ContactsCache.clearInfoAboutEmail(t.HomeEmail),Ci.ContactsCache.getContactByEmail(t.HomeEmail,this.onContactResponse,this)),this.processed(!1)},Ht.prototype.getReplyHtmlText=function(){return'<div style="font-family: '+this.defaultFontName+'; font-size: 16px">'+Ci.MessageSender.getHtmlFromText(this.replyText())+"</div>"},Ht.prototype.executeReplyOrForward=function(e){this.currentMessage()&&(Ci.MessageSender.setReplyData(this.getReplyHtmlText(),this.replyDraftUid()),this.replyText(""),this.replyDraftUid(""),Ci.Routing.setHash(Ci.Links.composeFromMessage(e,this.currentMessage().folder(),this.currentMessage().uid())))},Ht.prototype.executeDeleteMessage=function(){this.singleMode()&&this.currentMessage()&&t.opener&&t.opener.App&&t.opener.App.MailCache?(t.opener.App.MailCache.deleteMessages([this.currentMessage().uid()]),t.close()):this.mobileApp&&this.currentMessage()&&Ci.MailCache.deleteMessages([this.currentMessage().uid()])},Ht.prototype.executePrevMessage=function(){this.isEnablePrevMessage()&&this.moveToSingleMessageView(this.prevMessageUid())},Ht.prototype.executeNextMessage=function(){this.isEnableNextMessage()&&this.moveToSingleMessageView(this.nextMessageUid())},Ht.prototype.moveToSingleMessageView=function(e){var t=Ci.MailCache.folderList().currentFolderFullName(),i=[vi.Screens.SingleMessageView,t,"msg"+e];Ci.Routing.setHash(i)},Ht.prototype.executeReply=function(){this.executeReplyOrForward(vi.ReplyType.Reply)},Ht.prototype.executeReplyAll=function(){this.executeReplyOrForward(vi.ReplyType.ReplyAll)},Ht.prototype.executeResend=function(){this.executeReplyOrForward(vi.ReplyType.Resend)},Ht.prototype.executeForward=function(){this.executeReplyOrForward(vi.ReplyType.Forward)},Ht.prototype.executePrint=function(){var t=this.currentMessage(),i=t?Si.WindowOpener.open("",this.subject()+"-print"):null,s="";t&&i&&(this.textBodyForNewWindow(t.getConvertedHtml(Si.getAppPath(),!0)),s=e(this.domMessageForPrint()).html(),e(i.document.body).html(s),i.print())},Ht.prototype.executeSave=function(){this.currentMessage()&&Ci.Api.downloadByUrl(this.currentMessage().downloadLink())},Ht.prototype.executeSaveAsPdf=function(){if(this.currentMessage()){var t=this.currentMessage().getDomText(),i=this.currentMessage().accountId(),s=function(e){try{var t=document.createElement("canvas"),i=null;t.width=e.width,t.height=e.height,i=t.getContext("2d"),i.drawImage(e,0,0),e.src=t.toDataURL("image/png")}catch(s){}};e("img[data-x-src-cid]",t).each(function(){s(this)}),Ci.Ajax.send({Action:"PdfFromHtml",Subject:this.subject(),Html:t.html()},function(e){e&&e.Result&&e.Result.Hash?Ci.Api.downloadByUrl(Si.getDownloadLinkByHash(i,e.Result.Hash)):Ci.Api.showError(Si.i18n("WARNING/CREATING_PDF_ERROR"))},this)}},Ht.prototype.changeAddMenuVisibility=function(){var e=!this.visibleAddMenu();this.visibleAddMenu(e)},Ht.prototype.onMessageSendOrSaveResponse=function(e,t){var i=Ci.MessageSender.onMessageSendOrSaveResponse(e,t);switch(i.Action){case"MessageSend":this.replySendingStarted(!1),i.Result&&this.replyText("");break;case"MessageSave":i.Result&&this.replyDraftUid(i.NewUid),this.replySavingStarted(!1),this.replyAutoSavingStarted(!1)}},Ht.prototype.executeSendQuickReplyCommand=function(){this.isEnableSendQuickReply()&&(this.replySendingStarted(!0),this.requiresPostponedSending(this.replyAutoSavingStarted()),Ci.MessageSender.sendReplyMessage("MessageSend",this.getReplyHtmlText(),this.replyDraftUid(),this.onMessageSendOrSaveResponse,this,this.requiresPostponedSending()),this.replyTextFocus(!1))},Ht.prototype.executeSaveQuickReply=function(){this.saveReplyMessage(!1)},Ht.prototype.saveReplyMessage=function(e){this.isEnableSaveQuickReply()&&(e?this.replyAutoSavingStarted(!0):this.replySavingStarted(!0),Ci.MessageSender.sendReplyMessage("MessageSave",this.getReplyHtmlText(),this.replyDraftUid(),this.onMessageSendOrSaveResponse,this))},Ht.prototype.stopAutosaveTimer=function(){t.clearTimeout(this.autoSaveTimer)},Ht.prototype.startAutosaveTimer=function(){if(this.isEnableSaveQuickReply()){var e=_.bind(this.saveReplyMessage,this,!0);this.stopAutosaveTimer(),Ti.User.AllowAutosaveInDrafts&&(this.autoSaveTimer=t.setTimeout(e,1e3*Ti.App.AutoSaveIntervalSeconds))}},Ht.prototype.downloadAllAttachments=function(){this.currentMessage()&&this.currentMessage().downloadAllAttachments()},Ht.prototype.saveAttachmentsToFiles=function(){this.currentMessage()&&this.currentMessage().saveAttachmentsToFiles()},Ht.prototype.downloadAllAttachmentsSeparately=function(){this.currentMessage()&&this.currentMessage().downloadAllAttachmentsSeparately()},Ht.prototype.onApplyBindings=function(t){Ci.registerSessionTimeoutFunction(_.bind(function(){""!==this.replyText()&&this.saveReplyMessage(!1)},this)),e(t).on("mousedown","a",function(t){if(t&&3!==t.which){var i=e(this).attr("href");if(i&&"mailto:"===i.toString().toLowerCase().substr(0,7))return Ci.Api.openComposeMessage(i.toString().substr(7)),!1}return!0}),this.hotKeysBind()},Ht.prototype.hotKeysBind=function(){e(document).on("keydown",e.proxy(function(e){var t=Ci.Screens.currentScreen()===vi.Screens.Mailbox&&e&&!e.ctrlKey&&!e.shiftKey&&!Si.isTextFieldFocused()&&this.isEnableReply();t&&e.keyCode===vi.Key.q?(e.preventDefault(),this.replyTextFocus(!0)):t&&e.keyCode===vi.Key.r&&this.executeReply()},this))},Ht.prototype.showSourceHeaders=function(){var t=this.currentMessage(),i=t&&t.completelyFilled()?Si.WindowOpener.open("",this.subject()+"-headers"):null;i&&e(i.document.body).html("<pre>"+Si.encodeHtml(t.sourceHeaders())+"</pre>")},Ht.prototype.onDecryptMessageClick=function(){this.currentMessage()&&this.currentMessage().encryptedMessage()&&this.decryptVerifyMessage(!1)},Ht.prototype.onVerifyMessageClick=function(){this.currentMessage()&&this.currentMessage().signedMessage()&&this.decryptVerifyMessage(!0)},Ht.prototype.decryptVerifyMessage=function(e){var t=_.bind(function(t){var i=this.currentMessage();t&&i&&(e&&i.signedMessage()?this.verifyMessage(t):i.encryptedMessage()&&this.decryptMessage(t))},this);Ci.Api.pgp(t,Ti.User.IdUser)},Ht.prototype.decryptMessage=function(e){var t=this.currentMessage(),i=t.textRaw(),s=Ti.Accounts.getEmail(),o=t.oFrom.getFirstEmail(),n=this.decryptPassword(),r=e.decryptAndVerify(i,s,o,n),a=!1;r&&r.result&&!r.errors&&(t.text("<pre>"+Si.encodeHtml(r.result)+"</pre>"),t.$text=null,t.encryptedMessage(!1),this.decryptPassword(""),this.visibleDecryptControl(!1),this.setMessageBody(),Ci.Api.showReport(r.notices?Si.i18n("OPENPGP/REPORT_MESSAGE_SUCCESSFULLY_DECRYPTED"):Si.i18n("OPENPGP/REPORT_MESSAGE_SUCCESSFULLY_DECRYPTED_AND_VERIFIED"))),r&&(r.errors||r.notices)&&(a=Ci.Api.showPgpErrorByCode(r,vi.PgpAction.DecryptVerify),a&&Ci.Api.showReport(Si.i18n("OPENPGP/REPORT_MESSAGE_SUCCESSFULLY_DECRYPTED_AND_NOT_SIGNED")))},Ht.prototype.verifyMessage=function(e){var t=this.currentMessage(),i=t.textRaw(),s=t.oFrom.getFirstEmail(),o=e.verify(i,s);o&&o.result&&!o.errors&&!o.notices&&(t.text("<pre>"+Si.encodeHtml(o.result)+"</pre>"),t.$text=null,t.signedMessage(!1),this.visibleVerifyControl(!1),this.setMessageBody(),Ci.Api.showReport(Si.i18n("OPENPGP/REPORT_MESSAGE_SUCCESSFULLY_VERIFIED"))),o&&(o.errors||o.notices)&&Ci.Api.showPgpErrorByCode(o,vi.PgpAction.Verify)},Ht.prototype.testFunction=function(){Ci.Api.pgp(function(){})},Gt.prototype.executeCheckMail=function(){Ci.MailCache.checkMessageFlags(),Ci.MailCache.executeCheckMail()},Gt.prototype.openMessageInNewWindow=function(e){var i=this.folderList().getFolderByFullName(e.folder()),s=i.type()===vi.FolderTypes.Drafts;!this.oMessagePane.currentMessage()||this.oMessagePane.currentMessage().uid()!==e.uid()||""===this.oMessagePane.replyText()&&""===this.oMessagePane.replyDraftUid()||(t.oReplyDataFromViewPane={ReplyText:this.oMessagePane.replyText(),ReplyDraftUid:this.oMessagePane.replyDraftUid()},this.oMessagePane.replyText(""),this.oMessagePane.replyDraftUid("")),Si.WindowOpener.openMessage(e,s) },Gt.prototype.gotoFolderList=function(){this.changeSelectedPanel(vi.MobilePanel.Groups)},Gt.prototype.gotoMessageList=function(){return this.changeSelectedPanel(vi.MobilePanel.Items),!0},Gt.prototype.gotoMessagePane=function(){Ci.MailCache.currentMessage()?this.changeSelectedPanel(vi.MobilePanel.View):this.gotoMessageList()},Gt.prototype.changeSelectedPanel=function(e){this.mobileApp&&this.selectedPanel()!==e&&this.selectedPanel(e)},Gt.prototype.resizeDblClick=function(t,i){i.preventDefault(),i.stopPropagation?i.stopPropagation():i.cancelBubble=!0,Si.removeSelection(),this.jqPanelHelper||(this.jqPanelHelper=e(".MailLayout .panel_helper")),this.jqPanelHelper.trigger("resize",[600,"max"])},Gt.prototype.onRoute=function(e){this.oMessageList.onRoute(e),this.oMessagePane.onRoute(e)},Gt.prototype.onShow=function(){this.oMessageList.onShow()},Gt.prototype.onHide=function(){this.oMessageList.onHide()},Gt.prototype.onApplyBindings=function(){var t=this;this.oMessageList.onApplyBindings(this.$viewModel),this.oMessagePane.onApplyBindings(this.$viewModel),e(this.domFolderList()).on("click","span.folder",function(i){i.ctrlKey?t.oMessageList.executeCopyToFolder(e(this).data("folder")):t.oMessageList.executeMoveToFolder(e(this).data("folder"))}),this.hotKeysBind()},Gt.prototype.hotKeysBind=function(){e(document).on("keydown",e.proxy(function(e){var i=e.keyCode,s=e&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!Si.isTextFieldFocused()&&Ci.Screens.currentScreen()===vi.Screens.Mailbox,o=this.oMessageList,n=o.collection()[0],r=n&&Ci.MailCache.currentMessage()&&n.uid()===Ci.MailCache.currentMessage().uid();s&&i===vi.Key.s||s&&r&&i===vi.Key.Up?(e.preventDefault(),this.searchFocus()):o.isFocused()&&e&&i===vi.Key.Down&&n?(e.preventDefault(),o.isFocused(!1),o.routeForMessage(n)):s&&i===vi.Key.n&&(t.location.href="#compose")},this))},Gt.prototype.dragAndDropHelper=function(t){t&&t.checked(!0);var i=Si.draggableMessages(),s=this.oMessageList.checkedOrSelectedUids(),o=s.length;return i.data("p7-message-list-folder",this.folderList().currentFolderFullName()),i.data("p7-message-list-uids",s),e(".count-text",i).text(Si.i18n("MAILBOX/DRAG_TEXT_PLURAL",{COUNT:o},null,o)),i},Gt.prototype.messagesDrop=function(e,t,i){if(e){var s=i&&i.helper?i.helper:null,o=s?s.data("p7-message-list-folder"):"",n=s?s.data("p7-message-list-uids"):null;""!==o&&null!==n&&(Si.uiDropHelperAnim(t,i),t.ctrlKey?this.oMessageList.executeCopyToFolder(e.fullName()):this.oMessageList.executeMoveToFolder(e.fullName()))}},Gt.prototype.searchFocus=function(){this.oMessageList.selector.useKeyboardKeys()&&!Si.isTextFieldFocused()&&this.oMessageList.isFocused(!0)},Gt.prototype.backToList=function(){Ci.Routing.setPreviousHash()},Gt.prototype.onVolumerClick=function(e,t){t.stopPropagation()},Bt.prototype.__name="CComposeViewModel",Bt.prototype.changeSelectedFetcherOrIdentity=function(e){e?e.id()!==(this.selectedFetcherOrIdentity()&&this.selectedFetcherOrIdentity().id())&&this.selectedFetcherOrIdentity(e):null!==this.selectedFetcherOrIdentity()&&this.selectedFetcherOrIdentity(null)},Bt.prototype.isEnableSending=function(){var e=0===this.toAddr().length&&0===this.ccAddr().length&&0===this.bccAddr().length,t=0!==this.folderList().iAccountId;return t&&!this.sending()&&!e&&this.allAttachmentsUploaded()},Bt.prototype.isEnableSaving=function(){var e=this.folderList()&&0!==this.folderList().iAccountId;return this.shown()&&e&&!this.sending()&&!this.saving()},Bt.prototype.onApplyBindings=function(){Ci.registerSessionTimeoutFunction(_.bind(this.executeSave,this,!1));var t=_.bind(function(e,t){this.autocompleteCallback(e.term,t)},this);this.allowDropbox&&Si.loadScript("https://www.dropbox.com/static/api/2/dropins.js",null,{id:"dropboxjs","data-app-key":this.dropboxKey}),this.initUploader(),e(this.toAddrDom()).inputosaurus({width:"auto",parseOnBlur:!0,autoCompleteSource:t,change:_.bind(function(e){this.lockToAddr(!0),this.setRecipient(this.toAddr,e.target.value),this.lockToAddr(!1)},this),copy:_.bind(function(e){this.inputosaurusBuffer=e},this),paste:_.bind(function(){var e=this.inputosaurusBuffer||"";return this.inputosaurusBuffer="",e},this),mobileDevice:Ri}),e(this.ccAddrDom()).inputosaurus({width:"auto",parseOnBlur:!0,autoCompleteSource:t,change:_.bind(function(e){this.lockCcAddr(!0),this.setRecipient(this.ccAddr,e.target.value),this.lockCcAddr(!1)},this),copy:_.bind(function(e){this.inputosaurusBuffer=e},this),paste:_.bind(function(){var e=this.inputosaurusBuffer||"";return this.inputosaurusBuffer="",e},this),mobileDevice:Ri}),e(this.bccAddrDom()).inputosaurus({width:"auto",parseOnBlur:!0,autoCompleteSource:t,change:_.bind(function(e){this.lockBccAddr(!0),this.setRecipient(this.bccAddr,e.target.value),this.lockBccAddr(!1)},this),copy:_.bind(function(e){this.inputosaurusBuffer=e},this),paste:_.bind(function(){var e=this.inputosaurusBuffer||"";return this.inputosaurusBuffer="",e},this),mobileDevice:Ri}),this.hotKeysBind()},Bt.prototype.hotKeysBind=function(){e(document).on("keydown",e.proxy(function(e){if(e&&e.ctrlKey&&!e.altKey&&!e.shiftKey){var t=e.keyCode,i=Ci.Screens.currentScreen(),s=i===vi.Screens.Compose||i===vi.Screens.SingleCompose,o=s&&e&&e.ctrlKey,n=this.editableArea(),r=vi.Key;!n&&this.oHtmlEditor.oCrea&&this.editableArea(this.oHtmlEditor.oCrea.$editableArea[0]),o&&t===r.s?(e.preventDefault(),e.returnValue=!1,this.isEnableSaving()&&this.saveCommand()):o&&t===r.Enter&&""!==this.toAddr()&&this.sendCommand()}},this))},Bt.prototype.getMessageOnRoute=function(){var e=this.routeParams(),t="",i="";""!==this.routeType()&&3===e.length&&(t=e[1],i=e[2],Ci.MailCache.getMessage(t,i,this.onMessageResponse,this)),this.routeParams([])},Bt.prototype.onShow=function(){this.useSaveMailInSentItems(Ti.User.getUseSaveMailInSentItems()),this.saveMailInSentItems(Ti.User.getSaveMailInSentItems()),this.oHtmlEditor.initCrea(this.textBody(),this.plainText(),"7"),this.commitedTextBody(this.oHtmlEditor.getText()),this.shown(!0),this.backToListOnSendOrSave(!1),this.startAutosaveTimer(),this.focusAfterFilling(),wi.addClass("screen-compose"),this.oJua&&this.oJua.setDragAndDropEnabledStatus(!0),this.getSocialAccounts()},Bt.prototype.onRoute=function(e){var i="",s={};switch(this.plainText(!1),this.pgpSecured(!1),this.pgpEncrypted(!1),this.fromDrafts(!1),this.changeSenderAccountId(Ti.Accounts.currentId()),this.bUploadStatus=!1,t.clearTimeout(this.iUploadAttachmentsTimer),this.messageUploadAttachmentsStarted(!1),this.draftUid(""),this.draftInfo.removeAll(),this.setDataFromMessage(new rt),this.isDraftsCleared(!1),this.routeType(e.length>0?e[0]:""),this.routeType()){case vi.ReplyType.Reply:case vi.ReplyType.ReplyAll:case vi.ReplyType.Resend:case vi.ReplyType.Forward:case"drafts":this.routeParams(e),0!==this.folderList().iAccountId&&this.getMessageOnRoute();break;default:i=Ci.MessageSender.getSignatureText(this.senderAccountId(),null,!0),Ti.SingleMode&&t.opener&&t.opener.oMessageParametersFromCompose?(this.setMessageDataInSingleMode(t.opener.oMessageParametersFromCompose),t.opener.oMessageParametersFromCompose=void 0):""!==i&&this.textBody("<br /><br />"+i+"<br />"),"to"===this.routeType()&&2===e.length&&(s=Ci.Links.parseToAddr(e[1]),this.setRecipient(this.toAddr,s.to),s.hasMailto&&(this.subject(s.subject),this.setRecipient(this.ccAddr,s.cc),this.setRecipient(this.bccAddr,s.bcc),this.textBody(s.body))),"vcard"===this.routeType()&&2===e.length&&this.addContactAsAttachment(e[1]),"file"===this.routeType()&&2===e.length&&this.addFilesAsAttachment(e[1]),"data-as-file"===this.routeType()&&3===e.length&&this.addDataAsAttachment(e[1],e[2])}this.visibleCc(""!==this.ccAddr()),this.visibleBcc(""!==this.bccAddr()),this.commit(),this.focusAfterFilling(),this.allowFiles(Ti.User.IsFilesSupported&&Ti.User.filesEnable())},Bt.prototype.focusAfterFilling=function(){0===this.toAddr().length?(this.toAddrFocused(!0),this.toAddrFocused.valueHasMutated()):0===this.subject().length?this.subjectFocused(!0):this.oHtmlEditor.setFocus()},Bt.prototype.beforeHide=function(e){var t=Si.i18n("COMPOSE/CONFIRM_DISCARD_CHANGES"),i=_.bind(function(t){t&&Si.isFunc(e)?(this.commit(),e()):Ci.Routing.historyBackWithoutParsing(vi.Screens.Compose)},this);!this.isChanged()||this.isEmpty()||this.sending()||this.saving()?Si.isFunc(e)&&e():Ci.Screens.showPopup(C,[t,i])},Bt.prototype.onHide=function(){this.isChanged()&&!this.isEmpty()&&this.executeSave(!0),this.shown(!1),this.stopAutosaveTimer(),this.toAddrFocused(!1),this.ccAddrFocused(!1),this.bccAddrFocused(!1),this.subjectFocused(!1),this.oHtmlEditor.closeAllPopups(),this.oHtmlEditor.visibleLinkPopup(!1),this.messageUploadAttachmentsStarted(!1),wi.removeClass("screen-compose").removeClass("screen-compose-cc").removeClass("screen-compose-bcc").removeClass("screen-compose-attachments"),this.oJua&&this.oJua.setDragAndDropEnabledStatus(!1)},Bt.prototype.sendingAndSavingSubscription=function(){(this.sending()||this.saving())&&this.stopAutosaveTimer(),this.sending()||this.saving()||this.startAutosaveTimer()},Bt.prototype.stopAutosaveTimer=function(){t.clearTimeout(this.autoSaveTimer)},Bt.prototype.startAutosaveTimer=function(){if(this.shown()&&!this.pgpSecured()){var e=_.bind(this.executeSave,this,!0);this.stopAutosaveTimer(),Ti.User.AllowAutosaveInDrafts&&(this.autoSaveTimer=t.setTimeout(e,1e3*Ti.App.AutoSaveIntervalSeconds))}},Bt.prototype.setRecipient=function(e,t){e()===t?e.valueHasMutated():e(t)},Bt.prototype.onMessageResponse=function(e){var t=null,i=null,s=e.oTo.aCollection.concat(e.oCc.aCollection),o=!1;if(null===e)this.setDataFromMessage(new rt);else{switch(i=Ci.MessageSender.getFetcherOrIdentityByRecipients(s,e.accountId()),o=Ci.MessageSender.isFetcherOrIdentitySameAsChiefAccount(this.senderAccountId()),this.routeType()){case vi.ReplyType.Reply:case vi.ReplyType.ReplyAll:i&&!o&&this.changeSelectedFetcherOrIdentity(i),t=Ci.MessageSender.getReplyDataFromMessage(e,this.routeType(),this.senderAccountId(),i,!0),this.draftInfo(t.DraftInfo),this.draftUid(t.DraftUid),this.setRecipient(this.toAddr,t.To),this.setRecipient(this.ccAddr,t.Cc),this.setRecipient(this.bccAddr,t.Bcc),this.subject(t.Subject),this.textBody(t.Text),this.attachments(t.Attachments),this.inReplyTo(t.InReplyTo),this.references(t.References);break;case vi.ReplyType.Forward:t=Ci.MessageSender.getReplyDataFromMessage(e,this.routeType(),this.senderAccountId(),i,!0),this.draftInfo(t.DraftInfo),this.draftUid(t.DraftUid),this.setRecipient(this.toAddr,t.To),this.setRecipient(this.ccAddr,t.Cc),this.subject(t.Subject),this.textBody(t.Text),this.attachments(t.Attachments),this.inReplyTo(t.InReplyTo),this.references(t.References);break;case vi.ReplyType.Resend:this.setDataFromMessage(e);break;case"drafts":e.subject().substring(0,3)!==Si.i18n("COMPOSE/FORWARD_PREFIX")&&this.changeSelectedFetcherOrIdentity(i),this.draftUid(e.uid()),this.setDataFromMessage(e),this.fromDrafts(!0)}this.routeType("")}this.attachments().length>0&&this.requestAttachmentsTempName(),this.visibleCc(""!==this.ccAddr()),this.visibleBcc(""!==this.bccAddr()),this.commit(),this.focusAfterFilling()},Bt.prototype.changeSenderAccountId=function(e,t,i){Ti.Accounts.hasAccountWithId(e)?this.senderAccountId(e):Ti.Accounts.hasAccountWithId(this.senderAccountId())||this.senderAccountId(Ti.Accounts.currentId()),this.fillSenderList(t,i)},Bt.prototype.fillSenderList=function(e,t){var i=[],s=Ti.Accounts.getAccount(this.senderAccountId());s&&(i.push({fullEmail:s.fullEmail(),id:""}),s.fetchers()?_.each(s.fetchers().collection(),function(e){var t=e.fullEmail();e.isOutgoingEnabled()&&t.length>0&&i.push({fullEmail:t,id:"fetcher"+e.id()})},this):s.fetchersSubscribtion||(s.fetchersSubscribtion=s.fetchers.subscribe(function(){this.fillSenderList(e,t)},this)),_.isArray(s.identities())?_.each(s.identities(),function(e){e.enabled()&&i.push({fullEmail:e.fullEmail(),id:Si.pString(e.id())})},this):s.identitiesSubscribtion||(s.identitiesSubscribtion=s.identities.subscribe(function(){this.fillSenderList(e,t)},this))),this.senderList(i.length>0?i:[]),e&&""!==e?this.changeSelectedSenderByEmail(e):this.changeSelectedFetcherOrIdentity(t||null)},Bt.prototype.changeSelectedSenderByEmail=function(e){var t=Ti.Accounts.getAccount(this.senderAccountId()),i=t?t.getFetcherOrIdentityByEmail(e):null;i&&i.id()&&t.email()!==e&&this.changeSelectedFetcherOrIdentity(i)},Bt.prototype.setDataFromMessage=function(e){var t="",i=!1,s=!1;e.isPlain()?(i=-1!==e.textRaw().indexOf("-----BEGIN PGP MESSAGE-----"),s=-1!==e.textRaw().indexOf("-----BEGIN PGP SIGNED MESSAGE-----"),s||i?(t=e.textRaw(),this.pgpSecured(!0),this.pgpEncrypted(i)):t=e.textRaw()):t=e.getConvertedHtml(),this.draftInfo(e.draftInfo()),this.inReplyTo(e.inReplyTo()),this.references(e.references()),this.setRecipient(this.toAddr,e.oTo.getFull()),this.setRecipient(this.ccAddr,e.oCc.getFull()),this.setRecipient(this.bccAddr,e.oBcc.getFull()),this.subject(e.subject()),this.attachments(e.attachments()),this.plainText(e.isPlain()),this.textBody(t),this.selectedImportance(e.importance()),this.selectedSensitivity(e.sensitivity()),this.readingConfirmation(e.readingConfirmation()),this.changeSenderAccountId(e.accountId(),e.oFrom.getFirstEmail())},Bt.prototype.addDataAsAttachment=function(e,t){var i="data-as-attachment-"+Math.random(),s={Action:"DataAsAttachmentUpload",Data:e,FileName:t,Hash:i},o=new st;this.subject(t.substr(0,t.length-4)),o.fileName(t),o.hash(i),o.uploadStarted(!0),this.attachments.push(o),this.messageUploadAttachmentsStarted(!0),Ci.Ajax.send(s,this.onDataAsAttachmentUpload,this)},Bt.prototype.onDataAsAttachmentUpload=function(e,t){var i=e.Result,s=t.Hash,o=_.find(this.attachments(),function(e){return e.hash()===s});this.messageUploadAttachmentsStarted(!1),o&&(i&&i.Attachment?o.parseFromUpload(i.Attachment,e.AccountID):o.errorFromUpload())},Bt.prototype.addFilesAsAttachment=function(e){var t=null,i=[],s=null;_.each(e,function(e){t=new st,t.fileName(e.fileName()),t.hash(e.hash()),t.thumb(e.thumb()),t.uploadStarted(!0),this.attachments.push(t),i.push(e.hash())},this),i.length>0&&(s={Action:"FilesUpload",Hashes:i},this.messageUploadAttachmentsStarted(!0),Ci.Ajax.send(s,this.onFilesUpload,this))},Bt.prototype.onFilesUpload=function(t,i){var s=t.Result,o=i.Hashes,n=Date.now().toString();this.messageUploadAttachmentsStarted(!1),e.isArray(s)?_.each(s,function(e){var i=_.find(this.attachments(),function(t){return t.hash()===e.Hash});i&&(i.parseFromUpload(e,t.AccountID),i.hash(e.NewHash),i.getInThumbQueue(n))},this):_.each(o,function(e){var t=_.find(this.attachments(),function(t){return t.hash()===e});t&&t.errorFromUpload()},this)},Bt.prototype.addContactAsAttachment=function(e){var t=new st,i=null;e&&(t.fileName("contact-"+e.idContact()+".vcf"),t.uploadStarted(!0),this.attachments.push(t),i={Action:"ContactVCardUpload",ContactId:e.idContact(),Global:e.global()?"1":"0",Name:t.fileName()},this.messageUploadAttachmentsStarted(!0),Ci.Ajax.send(i,this.onContactVCardUpload,this))},Bt.prototype.onContactVCardUpload=function(e,t){var i=e.Result,s=null;this.messageUploadAttachmentsStarted(!1),i?(s=_.find(this.attachments(),function(e){return e.fileName()===i.Name&&e.uploadStarted()}),s&&s.parseFromUpload(i,e.AccountID)):(s=_.find(this.attachments(),function(e){return e.fileName()===t.Name&&e.uploadStarted()}),s&&s.errorFromUpload())},Bt.prototype.requestAttachmentsTempName=function(){var e=_.map(this.attachments(),function(e){return e.uploadUid(e.hash()),e.uploadStarted(!0),e.hash()}),t={Action:"MessageUploadAttachments",Attachments:e};e.length>0&&(this.messageUploadAttachmentsStarted(!0),Ci.Ajax.send(t,this.onMessageUploadAttachmentsResponse,this))},Bt.prototype.onMessageUploadAttachmentsResponse=function(e,t){var i=t.Attachments;this.messageUploadAttachmentsStarted(!1),e.Result?_.each(e.Result,_.bind(this.setAttachTepmNameByHash,this)):(_.each(i,function(e){var t=_.find(this.attachments(),function(t){return t.hash()===e});t&&t.errorFromUpload()},this),Ci.Api.showError(Si.i18n("COMPOSE/UPLOAD_ERROR_REPLY_ATTACHMENTS")))},Bt.prototype.setAttachTepmNameByHash=function(e,t){_.each(this.attachments(),function(i){i.hash()===e&&(i.tempName(t),i.uploadStarted(!1))})},Bt.prototype.setMessageDataInSingleMode=function(e){this.draftInfo(e.draftInfo),this.draftUid(e.draftUid),this.inReplyTo(e.inReplyTo),this.references(e.references),this.setRecipient(this.toAddr,e.toAddr),this.setRecipient(this.ccAddr,e.ccAddr),this.setRecipient(this.bccAddr,e.bccAddr),this.subject(e.subject),this.attachments(_.map(e.attachments,function(e){var t=new st;return t.parse(e,this.senderAccountId()),t},this)),this.textBody(e.textBody),this.selectedImportance(e.selectedImportance),this.selectedSensitivity(e.selectedSensitivity),this.readingConfirmation(e.readingConfirmation),this.changeSenderAccountId(e.senderAccountId,"",e.selectedFetcherOrIdentity)},Bt.prototype.isEmpty=function(){var e=Si.trim(this.toAddr()),t=Si.trim(this.ccAddr()),i=Si.trim(this.bccAddr()),s=Si.trim(this.subject()),o=this.oHtmlEditor.getText(),n=Si.trim(o.replace(/<br *\/{0,1}>/gi,"\n").replace(/<[^>]*>/g,"").replace(/ /g," "));return""===e&&""===t&&""===i&&""===s&&0===this.attachments().length&&""===n},Bt.prototype.commit=function(){this.toAddr.commit(),this.ccAddr.commit(),this.bccAddr.commit(),this.subject.commit(),this.commitedTextBody(this.oHtmlEditor.getText()),this.attachmentsChanged(!1)},Bt.prototype.isChanged=function(){var t=""===e(this.toAddrDom()).inputosaurus("getNotParsedValue"),i=""===e(this.ccAddrDom()).inputosaurus("getNotParsedValue"),s=""===e(this.bccAddrDom()).inputosaurus("getNotParsedValue");return this.toAddr.changed()||!t||this.ccAddr.changed()||!i||this.bccAddr.changed()||!s||this.subject.changed()||this.commitedTextBody()!==this.oHtmlEditor.getText()||this.attachmentsChanged()},Bt.prototype.executeBackToList=function(){Ti.SingleMode?t.close():this.shown()&&Ci.Routing.setPreviousHash(),this.backToListOnSendOrSave(!1)},Bt.prototype.onFileUploadSelect=function(e,t){var i,s=Si.i18n("COMPOSE/UPLOAD_ERROR_FILENAME_SIZE",{FILENAME:t.FileName,MAXSIZE:Si.friendlySize(Ti.App.AttachmentSizeLimit)});return Ti.App.AttachmentSizeLimit>0&&t.Size>Ti.App.AttachmentSizeLimit?(Ci.Screens.showPopup(A,[s]),!1):(i=new st,i.onUploadSelect(e,t),this.attachments.push(i),!0)},Bt.prototype.getAttachmentByUid=function(e){return _.find(this.attachments(),function(t){return t.uploadUid()===e})},Bt.prototype.onFileUploadStart=function(e){var t=this.getAttachmentByUid(e);t&&t.onUploadStart()},Bt.prototype.onFileUploadProgress=function(e,t,i){var s=this.getAttachmentByUid(e);s&&s.onUploadProgress(t,i)},Bt.prototype.onFileUploadComplete=function(e,t,i){var s=this.getAttachmentByUid(e),o=Date.now().toString();s&&(s.onUploadComplete(e,t,i),"image"===s.type().substr(0,5)&&(s.thumb(!0),s.getInThumbQueue(o)))},Bt.prototype.onFileRemove=function(e){var t=this.getAttachmentByUid(e);this.oJua&&this.oJua.cancel(e),this.attachments.remove(t)},Bt.prototype.initUploader=function(){this.composeUploaderButton()&&(this.oJua=new Jua({action:"?/Upload/Attachment/",name:"jua-uploader",queueSize:2,clickElement:this.composeUploaderButton(),dragAndDropElement:this.composeUploaderDropPlace(),disableAjaxUpload:!1,disableFolderDragAndDrop:!1,disableDragAndDrop:!1,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()}}}),this.oJua.on("onDragEnter",_.bind(this.composeUploaderDragOver,this,!0)).on("onDragLeave",_.bind(this.composeUploaderDragOver,this,!1)).on("onBodyDragEnter",_.bind(this.composeUploaderBodyDragOver,this,!0)).on("onBodyDragLeave",_.bind(this.composeUploaderBodyDragOver,this,!1)).on("onProgress",_.bind(this.onFileUploadProgress,this)).on("onSelect",_.bind(this.onFileUploadSelect,this)).on("onStart",_.bind(this.onFileUploadStart,this)).on("onComplete",_.bind(this.onFileUploadComplete,this)),this.allowDragNDrop(this.oJua.isDragAndDropSupported()))},Bt.prototype.getSendSaveParameters=function(e){var t=Ci.MessageSender.convertAttachmentsForSending(this.attachments());return _.each(this.oHtmlEditor.uploadedImagePathes(),function(e){t[e.TempName]=[e.Name,e.CID,"1","1"]}),{AccountID:this.senderAccountId(),FetcherID:this.selectedFetcherOrIdentity()&&this.selectedFetcherOrIdentity().FETCHER?this.selectedFetcherOrIdentity().id():"",IdentityID:this.selectedFetcherOrIdentity()&&!this.selectedFetcherOrIdentity().FETCHER?this.selectedFetcherOrIdentity().id():"",DraftInfo:this.draftInfo(),DraftUid:this.draftUid(),To:this.toAddr(),Cc:this.ccAddr(),Bcc:this.bccAddr(),Subject:this.subject(),Text:this.plainText()?this.oHtmlEditor.getPlainText():this.oHtmlEditor.getText(e),IsHtml:this.plainText()?"0":"1",Importance:this.selectedImportance(),Sensivity:this.selectedSensitivity(),ReadingConfirmation:this.readingConfirmation()?"1":"0",Attachments:t,InReplyTo:this.inReplyTo(),References:this.references()}},Bt.prototype.onMessageSendOrSaveResponse=function(e,t){var i=Ci.MessageSender.onMessageSendOrSaveResponse(e,t);switch(this.commit(),i.Action){case"MessageSave":i.Result&&i.NewUid&&this.draftUid(i.NewUid),this.saving(!1);break;case"MessageSend":i.Result&&(Ci.MailCache.deletedDraftMessageUid(this.draftUid()),this.backToListOnSendOrSave()&&this.executeBackToList()),this.sending(!1)}},Bt.prototype.verifyDataForSending=function(){var e=Si.getIncorrectEmailsFromAddressString(this.toAddr()),t=Si.getIncorrectEmailsFromAddressString(this.ccAddr()),i=Si.getIncorrectEmailsFromAddressString(this.bccAddr()),s=_.union(e,t,i),o=Si.i18n("COMPOSE/WARNING_INPUT_CORRECT_EMAILS")+s.join(", ");return s.length>0?(Ci.Screens.showPopup(A,[o]),!1):!0},Bt.prototype.executeSend=function(e){var t=e===!0;this.isEnableSending()&&this.verifyDataForSending()&&(!t&&this.enableOpenPgp()&&Ti.User.AutosignOutgoingEmails&&!this.pgpSecured()?this.openPgpPopup(!0):(this.sending(!0),this.requiresPostponedSending(!this.allowStartSending()),Ci.MessageSender.send("MessageSend",this.getSendSaveParameters(!0),this.saveMailInSentItems(),!0,this.onMessageSendOrSaveResponse,this,this.requiresPostponedSending())),this.backToListOnSendOrSave(!0))},Bt.prototype.executeSaveCommand=function(){this.executeSave(!1)},Bt.prototype.executeSave=function(e){var t=Si.i18n("OPENPGP/CONFIRM_SAVE_ENCRYPTED_DRAFT"),i=Si.i18n("COMPOSE/TOOL_SAVE"),s=_.bind(function(t){t&&(this.saving(!0),Ci.MessageSender.send("MessageSave",this.getSendSaveParameters(!1),this.saveMailInSentItems(),!e,this.onMessageSendOrSaveResponse,this))},this);this.isEnableSaving()&&(!e||this.isChanged()?!e&&this.pgpSecured()?Ci.Screens.showPopup(C,[t,s,"",i]):s(!0):e&&this.startAutosaveTimer(),this.backToListOnSendOrSave(!0))},Bt.prototype.changeBccVisibility=function(){this.visibleBcc(!this.visibleBcc()),this.visibleBcc()?this.bccAddrFocused(!0):this.toAddrFocused(!0)},Bt.prototype.changeCcVisibility=function(){this.visibleCc(!this.visibleCc()),this.visibleCc()?this.ccAddrFocused(!0):this.toAddrFocused(!0)},Bt.prototype.getMessageDataForSingleMode=function(){var e=_.map(this.attachments(),function(e){return{"@Object":"Object/CApiMailAttachment",FileName:e.fileName(),TempName:e.tempName(),MimeType:e.type(),MimePartIndex:e.mimePartIndex(),EstimatedSize:e.size(),CID:e.cid(),ContentLocation:e.contentLocation(),IsInline:e.inline(),IsLinked:e.linked(),Hash:e.hash()}});return{draftInfo:this.draftInfo(),draftUid:this.draftUid(),inReplyTo:this.inReplyTo(),references:this.references(),senderAccountId:this.senderAccountId(),selectedFetcherOrIdentity:this.selectedFetcherOrIdentity(),toAddr:this.toAddr(),ccAddr:this.ccAddr(),bccAddr:this.bccAddr(),subject:this.subject(),attachments:e,textBody:this.oHtmlEditor.getText(),selectedImportance:this.selectedImportance(),selectedSensitivity:this.selectedSensitivity(),readingConfirmation:this.readingConfirmation()}},Bt.prototype.openInNewWindow=function(){t.oMessageParametersFromCompose=this.getMessageDataForSingleMode(),Si.WindowOpener.openTab("#"+vi.Screens.SingleCompose),this.commit(),this.executeBackToList()},Bt.prototype.autocompleteCallback=function(e,t){var i={Action:"ContactSuggestions",Search:e};e=Si.trim(e),""!==e?Ci.Ajax.send(i,function(e){var i=[];e&&e.Result&&e.Result&&e.Result.List&&(i=_.map(e.Result.List,function(e){var t="",i=e.Email;return e.IsGroup?t=e.Name&&0<Si.trim(e.Name).length?'"'+e.Name+'" ('+e.Email+")":"("+e.Email+")":e.Name&&0<Si.trim(e.Name).length?(t='"'+e.Name+'" <'+e.Email+">",i=t):t=e.Email,{label:t,value:i,frequency:e.Frequency}}),i=_.compact(i)),t(i)},this):t([])},Bt.prototype.onShowFilesPopupClick=function(){var e=_.bind(this.addFilesAsAttachment,this);Ci.Screens.showPopup(k,[e])},Bt.prototype.onShowGoogleDriveClick=function(){Ci.Screens.showPopup(Y,[_.bind(this.googlePickerCallback,this)])},Bt.prototype.googlePickerCallback=function(e,t){var i=null,s=[],o={},n=this;_.each(e,function(e){i=(new st).fileName(e.name).hash(e.id).size(e.sizeBytes).uploadStarted(!0).type(e.mimeType),"image"===i.type().substr(0,5)&&i.thumb(!0),n.attachments.push(i),s.push(e.id)},this),o={Action:"FilesUploadByLink",Links:s,LinksAsIds:!0,AccessToken:t},this.messageUploadAttachmentsStarted(!0),Ci.Ajax.send(o,this.onFilesUpload,this)},Bt.prototype.onShowDropBoxClick=function(){var e=null,i=[],s={},o=this,n={success:function(t){_.each(t,function(t){e=(new st).fileName(t.name).hash(t.link).size(t.bytes).uploadStarted(!0).thumb(!!t.thumbnailLink),o.attachments.push(e),i.push(t.link)},o),s={Action:"FilesUploadByLink",Links:i},o.messageUploadAttachmentsStarted(!0),Ci.Ajax.send(s,o.onFilesUpload,o)},cancel:function(){},linkType:"direct",multiselect:!0};this.allowDropbox&&t.Dropbox&&t.Dropbox.choose(n)},Bt.prototype.confirmOpenPgp=function(){var e=Si.i18n("OPENPGP/CONFIRM_HTML_TO_PLAIN_FORMATTING"),t=_.bind(function(e){e&&this.openPgpPopup(!1)},this);this.notInlineAttachments().length>0&&(e+="\r\n\r\n"+Si.i18n("OPENPGP/CONFIRM_HTML_TO_PLAIN_ATTACHMENTS")),Ci.Screens.showPopup(C,[e,t])},Bt.prototype.openPgpPopup=function(e){var t=this.oHtmlEditor.getPlainText(),i=_.bind(function(t,i){e||(this.stopAutosaveTimer(),this.executeSave(!0)),this.plainText(!0),this.textBody(t),this.pgpSecured(!0),this.pgpEncrypted(i),e&&this.executeSend(!0)},this),s=_.bind(function(){e&&this.executeSend(!0)},this);Ci.Screens.showPopup(q,[t,Ti.Accounts.getEmail(),this.recipientEmails(),e,i,s])},Bt.prototype.undoPgp=function(){var e=this.textBody(),t=[];this.pgpSecured()&&(this.plainText(!1),this.fromDrafts()&&!this.pgpEncrypted()?(t=e.split("-----BEGIN PGP SIGNED MESSAGE-----"),2===t.length&&(e=t[1]),t=e.split("-----BEGIN PGP SIGNATURE-----"),2===t.length&&(e=t[0]),t=e.split("\r\n\r\n"),t.length>0&&(t.shift(),e=t.join("\r\n\r\n")),e="<div>"+e.replace(/\r\n/gi,"<br />")+"</div>",this.textBody(e)):this.oHtmlEditor.undoAndClearRedo(),this.pgpSecured(!1),this.pgpEncrypted(!1))},Bt.prototype.getSocialAccounts=function(){this.googleConnected(!1),this.dropboxConnected(!1),_.each(Ti.User.SocialAccounts(),function(e){"Object/CSocial"===e["@Object"]&&(e.Type===vi.SocialType.Google?this.googleConnected(!0):e.Type===vi.SocialType.Dropbox&&this.dropboxConnected(!0))},this)},Vt.prototype.onFileImportStart=function(){this.importing(!0)},Vt.prototype.onFileImportComplete=function(e,t,i){if(this.importing(!1),this.oParent.requestContactList(),t&&i&&i.Result){var s=Si.pInt(i.Result.ImportedCount);s>0?Ci.Api.showReport(Si.i18n("CONTACTS/CONTACT_IMPORT_HINT_PLURAL",{NUM:s},null,s)):Ci.Api.showError(Si.i18n("WARNING/CONTACTS_IMPORT_NO_CONTACTS"))}else Ci.Api.showError(Si.i18n("WARNING/CONTACTS_IMPORT_ERROR"))},Vt.prototype.onApplyBindings=function(t){this.oJua=new Jua({action:"?/Upload/Contacts/",name:"jua-uploader",queueSize:1,clickElement:e("#jue_import_button",t),disableAjaxUpload:!1,disableDragAndDrop:!0,disableMultiple:!0,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()}}}),this.oJua.on("onStart",_.bind(this.onFileImportStart,this)).on("onComplete",_.bind(this.onFileImportComplete,this))},jt.prototype.groupDropdownToggle=function(e){this.currentGroupDropdown(e)},jt.prototype.gotoGroupList=function(){this.changeSelectedPanel(vi.MobilePanel.Groups)},jt.prototype.gotoContactList=function(){return this.changeSelectedPanel(vi.MobilePanel.Items),!0},jt.prototype.gotoViewPane=function(){this.changeSelectedPanel(vi.MobilePanel.View)},jt.prototype.backToContactList=function(){var e=this.selectedGroupType(),t=e===vi.ContactsGroupListType.SubGroup?this.currentGroupId():"";Ci.Routing.setHash(Ci.Links.contacts(e,t,this.search(),this.oPageSwitcher.currentPage()))},jt.prototype.changeSelectedPanel=function(e){this.mobileApp&&this.selectedPanel(e)},jt.prototype.executeSave=function(e){var t={},i=[];e===this.selectedItem()&&this.selectedItem().canBeSave()?e instanceof ct&&!e.readOnly()?(_.each(this.groupFullCollection(),function(e){e&&e.checked()&&i.push(e.Id())}),e.groups(i),t=e.toObject(),t.Action=e.isNew()?"ContactCreate":"ContactUpdate",t.SharedToAll=e.isNew()?vi.ContactsGroupListType.SharedToAll===this.selectedGroupType()?"1":"0":e.sharedToAll()?"1":"0",e.edited()&&e.edited(!1),e.isNew()&&this.selectedItem(null),(this.selectedGroupType()===vi.ContactsGroupListType.Global||this.selectedGroupType()===vi.ContactsGroupListType.All)&&this.recivedAnimUnshare(!0),Ci.Ajax.send(t,this.onContactCreateResponse,this)):e instanceof ut&&!e.readOnly()&&(t=e.toObject(),t.Action=e.isNew()?"GroupCreate":"GroupUpdate",this.gotoGroupList(),e.edited()&&e.edited(!1),e.isNew()&&!this.mobileApp&&this.selectedItem(null),Ci.Ajax.send(t,this.onGroupCreateResponse,this)):Ci.Api.showError(Si.i18n("CONTACTS/ERROR_EMPTY_CONTACT"))},jt.prototype.executeNewContact=function(){if(this.showPersonalContacts()){var e=this.selectedGroupInList();this.oContactModel.switchToNew(),this.oContactModel.groups(e?[e.Id()]:[]),this.selectedItem(this.oContactModel),this.selector.itemSelected(null),this.gotoViewPane()}},jt.prototype.executeNewGroup=function(){this.oGroupModel.switchToNew(),this.selectedItem(this.oGroupModel),this.selector.itemSelected(null),this.gotoViewPane()},jt.prototype.executeDelete=function(){var e=_.filter(this.selector.listCheckedOrSelected(),function(e){return!e.ReadOnly()}),t=e.length,i=Si.i18n("CONTACTS/CONFIRM_DELETE_CONTACT_PLURAL",{},null,t),s=_.bind(function(t){t&&this.deleteContacts(e)},this);Ci.Screens.showPopup(C,[i,s])},jt.prototype.deleteContacts=function(e){var t=this,i=this.selectedContact(),s=_.map(e,function(e){return e.Id()});0<s.length&&(_.each(e,function(e){e&&(Ci.ContactsCache.clearInfoAboutEmail(e.Email()),!i||e.IsGroup()||e.ReadOnly()||i.readOnly()||i.idContact()!==e.Id()||(i=null,this.selectedContact(null)))},this),_.each(this.collection(),function(t){-1<Si.inArray(t,e)&&t.deleted(!0)}),_.delay(function(){t.collection.remove(function(e){return e.deleted()})},500),Ci.Ajax.send({Action:"ContactDelete",ContactsId:s.join(","),SharedToAll:vi.ContactsGroupListType.SharedToAll===this.selectedGroupType()?"1":"0"},this.requestContactList,this),Ci.ContactsCache.markVcardsNonexistentByUid(s))},jt.prototype.executeRemoveFromGroup=function(){var e=this,t=this.selectedGroupInList(),i=this.selector.listCheckedOrSelected(),s=_.map(i,function(e){return e.ReadOnly()?"":e.Id()});s=_.compact(s),t&&0<s.length&&(_.each(this.collection(),function(e){-1<Si.inArray(e,i)&&e.deleted(!0)}),_.delay(function(){e.collection.remove(function(e){return e.deleted()})},500),Ci.Ajax.send({Action:"RemoveContactsFromGroup",GroupId:t.Id(),ContactsId:s.join(",")},this.requestContactList,this))},jt.prototype.executeImport=function(){this.selectedItem(null),this.oContactImportViewModel.visibility(!0),this.selector.itemSelected(null),this.selectedGroupType(vi.ContactsGroupListType.Personal),this.gotoViewPane()},jt.prototype.executeCSVExport=function(){Ci.Api.downloadByUrl(Si.getExportContactsLink("csv"))},jt.prototype.executeVCFExport=function(){Ci.Api.downloadByUrl(Si.getExportContactsLink("vcf"))},jt.prototype.executeCancel=function(){var e=this.selectedItem();e&&(e instanceof ct&&!e.readOnly()?e.isNew()?this.selectedItem(null):e.edited()&&e.edited(!1):e instanceof ut&&!e.readOnly()&&(e.isNew()?this.selectedItem(null):e.edited()&&(this.selectedItem(this.selectedOldItem()),e.edited(!1)),this.gotoGroupList())),this.oContactImportViewModel.visibility(!1) },jt.prototype.executeAddContactsToGroup=function(e,t){e&&_.isArray(t)&&0<t.length&&(e.recivedAnim(!0),Ci.Ajax.send({Action:"AddContactsToGroup",GroupId:e.Id(),ContactsId:t},this.onAddContactsToGroupResponse,this))},jt.prototype.executeAddContactsToGroupId=function(e,t){e&&_.isArray(t)&&0<t.length&&Ci.Ajax.send({Action:"AddContactsToGroup",GroupId:e,ContactsId:t},this.onAddContactsToGroupResponse,this)},jt.prototype.onAddContactsToGroupResponse=function(){this.requestContactList(),this.selector.itemSelected()&&this.requestContact(this.selector.itemSelected().sId)},jt.prototype.executeAddSelectedContactsToGroup=function(e){var t=this.selector.listCheckedOrSelected(),i=[];e&&_.isArray(t)&&0<t.length&&_.each(t,function(e){e&&!e.IsGroup()&&i.push([e.Id(),e.Global()?"1":"0"])},this),this.executeAddContactsToGroup(e,i)},jt.prototype.groupsInContactView=function(e){var t=[],i=[];return e&&!e.groupsIsEmpty()&&(i=e.groups(),t=_.filter(this.groupFullCollection(),function(e){return 0<=Si.inArray(e.Id(),i)})),t},jt.prototype.onShow=function(){this.selector.useKeyboardKeys(!0),this.oPageSwitcher.show(),this.oPageSwitcher.perPage(Ti.User.ContactsPerPage)},jt.prototype.onHide=function(){this.selector.listCheckedOrSelected(!1),this.selector.useKeyboardKeys(!1),this.selectedItem(null),this.oPageSwitcher.hide()},jt.prototype.onApplyBindings=function(){this.selector.initOnApplyBindings(".contact_sub_list .item",".contact_sub_list .selected.item",".contact_sub_list .item .custom_checkbox",e(".contact_list",this.$viewModel),e(".contact_list_scroll.scroll-inner",this.$viewModel));var t=this;this.$viewModel.on("click",".content .item.add_to .dropdown_helper .item",function(){e(this).hasClass("new-group")?t.executeNewGroup():t.executeAddSelectedContactsToGroup(i.dataFor(this))}),this.showPersonalContacts(!!Ti.User.ShowPersonalContacts),this.showGlobalContacts(!!Ti.User.ShowGlobalContacts),this.showSharedToAllContacts(!!Ti.App.AllowContactsSharing),this.selectedGroupType.valueHasMutated(),this.oContactImportViewModel.onApplyBindings(this.$viewModel),this.requestGroupFullList(),this.hotKeysBind()},jt.prototype.hotKeysBind=function(){var t=!1;e(document).on("keydown",_.bind(function(e){var i=e.keyCode,s=this.collection()[0],o=this.isSearchFocused(),n=!1,r=Ci.Screens.currentScreen()===vi.Screens.Contacts;r&&!Si.isTextFieldFocused()&&!o&&e&&i===vi.Key.s?(e.preventDefault(),this.searchFocus()):s&&(n=s.selected(),s&&o&&e&&i===vi.Key.Down?(this.isSearchFocused(!1),this.selector.itemSelected(s),t=!0):!o&&t&&n&&e&&i===vi.Key.Up?(this.isSearchFocused(!0),this.selector.itemSelected(!1),t=!1):n?t=!0:n||(t=!1))},this))},jt.prototype.requestContactList=function(){this.loadingList(!0),Ci.Ajax.send({Action:vi.ContactsGroupListType.Global===this.selectedGroupType()?"GlobalContactList":"ContactList",Offset:(this.oPageSwitcher.currentPage()-1)*Ti.User.ContactsPerPage,Limit:Ti.User.ContactsPerPage,SortField:this.sortType(),SortOrder:this.sortOrder()?"1":"0",Search:this.search(),GroupId:this.selectedGroupInList()?this.selectedGroupInList().Id():"",SharedToAll:vi.ContactsGroupListType.SharedToAll===this.selectedGroupType()?"1":"0",All:vi.ContactsGroupListType.All===this.selectedGroupType()?"1":"0"},this.onContactListResponse,this)},jt.prototype.requestGroupFullList=function(){Ci.Ajax.send({Action:"GroupFullList"},this.onGroupListResponse,this)},jt.prototype.requestContact=function(e){this.loadingViewPane(!0);var t=_.find(this.collection(),function(t){return t.sId===e});t&&(this.selector.itemSelected(t),Ci.Ajax.send({Action:t.Global()?"GlobalContact":"Contact",ContactId:t.Id(),SharedToAll:t.IsSharedToAll()?"1":"0"},this.onContactResponse,this))},jt.prototype.requestContactById=function(e,t){this.loadingViewPane(!0),e&&Ci.Ajax.send({Action:t?"GlobalContact":"Contact",ContactId:e},this.onContactResponse,this)},jt.prototype.editGroup=function(e){var t=new ut;t.populate(e),this.selectedOldItem(t),e.edited(!0)},jt.prototype.changeGroupType=function(e){Ci.Routing.setHash(Ci.Links.contacts(e))},jt.prototype.onViewGroupClick=function(e){Ci.Routing.setHash(Ci.Links.contacts(vi.ContactsGroupListType.SubGroup,e.Id()))},jt.prototype.onRoute=function(e){var t=Ci.Links.parseContacts(e),i=[vi.ContactsGroupListType.Personal,vi.ContactsGroupListType.SharedToAll,vi.ContactsGroupListType.Global,vi.ContactsGroupListType.All],s=this.selectedGroupType()===vi.ContactsGroupListType.SubGroup?this.currentGroupId():"",o=this.selectedGroupType()!==t.Type||s!==t.GroupId||this.search()!==t.Search,n=!0,r=!1;this.pageSwitcherLocked(!0),o?this.oPageSwitcher.clear():this.oPageSwitcher.setPage(t.Page,Ti.User.ContactsPerPage),this.pageSwitcherLocked(!1),t.Page!==this.oPageSwitcher.currentPage()&&Ci.Routing.replaceHash(Ci.Links.contacts(t.Type,t.GroupId,t.Search,this.oPageSwitcher.currentPage())),this.currentPage()!==t.Page&&(this.currentPage(t.Page),r=!0),-1!==Si.inArray(t.Type,i)?this.selectedGroupType(t.Type):s!==t.GroupId&&(n=this.viewGroup(t.GroupId),n?r=!1:Ci.Routing.replaceHash(Ci.Links.contacts())),this.search()!==t.Search&&(this.search(t.Search),r=!0),this.contactUidForRequest(""),t.Uid?0===this.collection().length?this.contactUidForRequest(t.Uid):this.requestContact(t.Uid):(this.selector.itemSelected(null),this.gotoContactList()),r&&this.requestContactList()},jt.prototype.viewGroup=function(e){var t=_.find(this.groupFullCollection(),function(t){return t&&t.Id()===e});return t&&(this.oGroupModel.clear(),t.IsOrganization()?this.requestGroup(t):this.oGroupModel.idGroup(t.Id()).name(t.Name()),this.selectedGroupInList(t),this.selectedItem(this.oGroupModel),this.selector.itemSelected(null),this.selector.listCheckedOrSelected(!1),Ci.Ajax.send({Action:"GroupEvents",GroupId:e},this.onGroupEventsResponse,this)),!!t},jt.prototype.deleteGroup=function(e){e&&(Ci.Ajax.send({Action:"GroupDelete",GroupId:e},this.requestGroupFullList,this),this.selectedGroupType(vi.ContactsGroupListType.Personal),this.groupFullCollection.remove(function(t){return t&&t.Id()===e}))},jt.prototype.mailGroup=function(e){e&&Ci.Ajax.send({Action:"ContactList",Offset:0,Limit:99,SortField:vi.ContactSortType.Email,SortOrder:"1",GroupId:e.idGroup()},function(e){if(e&&e.Result&&e.Result.List){var t=0,i=0,s=[],o=null,n=[],r=e.Result.List;for(i=r.length;i>t;t++)r[t]&&"Object/CContactListItem"===Si.pExport(r[t],"@Object","")&&(o=new dt,o.parse(r[t]),n.push(o));s=_.map(n,function(e){return e.EmailAndName()}),s=_.compact(s),Ci.Api.openComposeMessage(s.join(", "))}},this)},jt.prototype.dragAndDropHelper=function(t){t&&t.checked(!0);var i=this.selector.itemSelected(),s=Si.draggableMessages(),o=this.selector.listCheckedOrSelected().length,n=o>0?_.map(this.selector.listCheckedOrSelected(),function(e){return[e.Id(),e.Global()?"1":"0"]}):[];return i&&!i.checked()&&i.checked(!0),s.data("p7-contatcs-type",this.selectedGroupType()),s.data("p7-contatcs-uids",n),e(".count-text",s).text(Si.i18n("CONTACTS/DRAG_TEXT_PLURAL",{COUNT:o},null,o)),s},jt.prototype.contactsDrop=function(e,t,i){if(e){var s=i&&i.helper?i.helper:null,o=s?s.data("p7-contatcs-uids"):null;null!==o&&(Si.uiDropHelperAnim(t,i),this.executeAddContactsToGroup(e,o))}},jt.prototype.contactsDropToGroupType=function(e,t,i){var s=i&&i.helper?i.helper:null,o=s?s.data("p7-contatcs-type"):null,n=s?s.data("p7-contatcs-uids"):null;e!==o&&null!==o&&null!==n&&(Si.uiDropHelperAnim(t,i),this.executeShare())},jt.prototype.searchFocus=function(){this.selector.useKeyboardKeys()&&!Si.isTextFieldFocused()&&this.isSearchFocused(!0)},jt.prototype.onContactDblClick=function(){var e=this.selectedContact();e&&Ci.Api.openComposeMessage(e.email())},jt.prototype.onClearSearchClick=function(){this.searchInput(""),this.searchSubmitCommand()},jt.prototype.onContactResponse=function(e){if(e&&e.Action&&e.Result){var t=new ct,i=this.selector.itemSelected();t.parse(e.Result),i&&i.Id()===t.idContact()&&this.selectedItem(t)}},jt.prototype.onContactCreateResponse=function(e){e&&e.Action&&e.Result&&(Ci.Api.showReport(Si.i18n("ContactCreate"===e.Action?"CONTACTS/REPORT_CONTACT_SUCCESSFULLY_ADDED":"CONTACTS/REPORT_CONTACT_SUCCESSFULLY_UPDATED")),this.requestContactList())},jt.prototype.onContactListResponse=function(e){if(e&&e.Action&&e.Result){var t=0,i=0,s=[],o="GlobalContactList"===e.Action,n=this.selector.itemSelected(),r=null,a=this.selector.listChecked(),l=a&&0<a.length?_.map(a,function(e){return e.Id()}):[],h=null;for(i=e.Result.List.length;i>t;t++)e.Result.List[t]&&"Object/CContactListItem"===Si.pExport(e.Result.List[t],"@Object","")&&(h=new dt,h.parse(e.Result.List[t],o),s.push(h));n&&(r=_.find(s,function(e){return n.Id()===e.Id()})),l&&0<l.length&&_.each(s,function(e){e.checked(-1<Si.inArray(e.Id(),l))}),this.collection(s),this.loadingList(!1),this.oPageSwitcher.setCount(Si.pInt(e.Result.ContactCount)),r&&this.selector.itemSelected(r),this.selectedGroupContactsList(e.Result.List)}},jt.prototype.viewAllMails=function(){var e=this.selectedGroupContactsList(),t="email:";e&&(_.each(e,function(e){_.each(e.Emails,function(e){t=t+e+","})}),Ci.MailCache.searchMessagesInInbox(t))},jt.prototype.onGroupListResponse=function(e){if(e&&e.Action&&e.Result){var t=0,i=0,s=[],o=_.find(this.groupFullCollection(),function(e){return e.selected()}),n=null;for(this.groupFullCollection(s),i=e.Result.length;i>t;t++)e.Result[t]&&"Object/CContactListItem"===Si.pExport(e.Result[t],"@Object","")&&(n=new dt,n.parse(e.Result[t]),n.IsGroup()&&(o&&o.Id()===n.Id()&&this.selectedGroupInList(n),s.push(n)));this.groupFullCollection(s)}},jt.prototype.onGroupCreateResponse=function(e){if(e&&e.Action&&e.Result){var t=_.map(this.selector.listChecked(),function(e){return[e.Id(),e.Global()?"1":"0"]});this.executeAddContactsToGroupId(e.Result.IdGroup,t),this.mobileApp||(this.selectedItem(null),this.selector.itemSelected(null)),Ci.Api.showReport(Si.i18n("CONTACTS/REPORT_GROUP_SUCCESSFULLY_ADDED")),this.requestContactList(),this.requestGroupFullList()}},jt.prototype.executeShare=function(){var e=this,t=this.selector.listCheckedOrSelected(),i=this.selectedContact(),s=_.map(t,function(e){return e.ReadOnly()?"":e.Id()});s=_.compact(s),0<s.length&&(_.each(t,function(e){e&&(Ci.ContactsCache.clearInfoAboutEmail(e.Email()),!i||e.IsGroup()||e.ReadOnly()||i.readOnly()||i.idContact()!==e.Id()||(i=null,this.selectedContact(null)))},this),_.each(this.collection(),function(e){-1<Si.inArray(e,t)&&e.deleted(!0)}),_.delay(function(){e.collection.remove(function(e){return e.deleted()})},500),vi.ContactsGroupListType.SharedToAll===this.selectedGroupType()?this.recivedAnimUnshare(!0):this.recivedAnimShare(!0),Ci.Ajax.send({Action:"ContactUpdateSharedToAll",ContactsId:s.join(","),SharedToAll:vi.ContactsGroupListType.SharedToAll===this.selectedGroupType()?"1":"0"},this.onContactUpdateSharedToAllResponse,this))},jt.prototype.onContactUpdateSharedToAllResponse=function(){},jt.prototype.requestGroup=function(e){this.loadingViewPane(!0),e&&Ci.Ajax.send({Action:"Group",GroupId:e.Id()},this.onGroupResponse,this)},jt.prototype.onGroupResponse=function(e){if(e&&e.Action&&e.Result){var t=e.Result;this.oGroupModel.idGroup(t.IdGroup).name(t.Name).isOrganization(t.IsOrganization).company(t.Company).country(t.Country).state(t.State).city(t.City).street(t.Street).zip(t.Zip).phone(t.Phone).fax(t.Fax).email(t.Email).web(t.Web)}},jt.prototype.onGroupEventsResponse=function(e){if(e&&e.Action&&e.Result){var t=e.Result;this.oGroupModel.events(t)}},jt.prototype.reload=function(){this.requestContactList()},Kt.prototype.onHide=function(e){var t=null,i=this.tab();this.confirmSaving(i),t=this.getCurrentViewModel(),t&&Si.isFunc(t.onHide)&&t.onHide(e),wi.removeClass("non-adjustable")},Kt.prototype.onApplyBindings=function(){_.each(this.aTabs,function(e){e&&Si.isFunc(e.onApplyBindings)&&e.onApplyBindings()})},Kt.prototype.onShow=function(e){var t=this.getCurrentViewModel();t&&Si.isFunc(t.onShow)&&t.onShow(e),wi.addClass("non-adjustable")},Kt.prototype.viewTab=function(e){var t=this.getViewModel(vi.SettingsTab.Common),i=t?vi.SettingsTab.Common:vi.SettingsTab.EmailAccounts,s=this.getViewModel(e),o=-1===Si.inArray(e,vi.SettingsTab);e=s&&o?e:i,this.tab(e)},Kt.prototype.onRoute=function(e){var t=null,i=this.tab();i=_.isArray(e)&&e.length>0?e[0]:vi.SettingsTab.Common,this.tab()!==i&&(t=this.getCurrentViewModel(),t&&Si.isFunc(t.onHide)&&t.onHide(e),this.confirmSaving(this.tab())),this.viewTab(i),t=this.getCurrentViewModel(),t&&Si.isFunc(t.onRoute)&&t.onRoute(e)},Kt.prototype.confirmSaving=function(e){var t=this.getViewModel(e),i=Si.i18n("SETTINGS/CONFIRM_SETTINGS_SAVE"),s=_.bind(function(e){t&&(e?t.onSaveClick&&t.onSaveClick():t.init&&t.init())},this);t&&Si.isFunc(t.isChanged)&&t.isChanged()&&Ci.Screens.showPopup(C,[i,s])},Kt.prototype.getViewModel=function(e){return _.find(this.aTabs,function(t){return t.TabName===e})},Kt.prototype.getCurrentViewModel=function(){return this.getViewModel(this.tab())},Kt.prototype.showTab=function(e){Ci.Routing.setHash([vi.Screens.Settings,e])},Kt.prototype.onResponseFolderChanges=function(e){e.Result||(Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")),Ci.MailCache.getFolderList(Ti.Accounts.editedId()))},Kt.prototype.onResponseFolderRename=function(e,t){t&&t.Result?t&&e&&t.Result&&!Si.isUnd(t.Result.FullName)&&(e.fullName(t.Result.FullName),e.fullNameHash(t.Result.FullNameHash)):(Ci.Api.showErrorByCode(t,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")),Ci.MailCache.getFolderList(Ti.Accounts.editedId()))},Kt.prototype.deleteFolder=function(e,t,i){var s={Action:"FolderDelete",AccountID:Ti.Accounts.editedId(),Folder:e.fullName()};i&&t&&e&&(t.remove(function(t){return e.fullName()===t.fullName()?!0:!1}),Ci.Ajax.send(s,this.onResponseFolderChanges,this))},Kt.prototype.onSubscribeFolderClick=function(e){var t={Action:"FolderSubscribe",AccountID:Ti.Accounts.editedId(),Folder:e.fullName(),SetAction:e.subscribed()?0:1};e&&e.canSubscribe()&&(e.subscribed(!e.subscribed()),Ci.Ajax.send(t,this.onResponseFolderChanges,this))},Kt.prototype.onDeleteFolderClick=function(e,t){var i=Si.i18n("SETTINGS/ACCOUNT_FOLDERS_CONFIRMATION_DELETE"),s=this.getCollectionFromParent(t),o=_.bind(this.deleteFolder,this,e,s),n=this.getViewModel(vi.SettingsTab.EmailAccounts);e&&e.canDelete()?Ci.Screens.showPopup(C,[i,o]):n&&n.oAccountFolders.highlighted(!0)},Kt.prototype.folderEditOnEnter=function(e){if(e.name()!==e.nameForEdit()){var t={Action:"FolderRename",AccountID:Ti.Accounts.editedId(),PrevFolderFullNameRaw:e.fullName(),NewFolderNameInUtf8:e.nameForEdit()};Ci.Ajax.send(t,_.bind(this.onResponseFolderRename,this,e),this),e.name(e.nameForEdit())}e.edited(!1)},Kt.prototype.folderEditOnEsc=function(e){e.edited(!1)},Kt.prototype.getCollectionFromParent=function(e){return e.subfolders?e.subfolders:e.collection},Kt.prototype.canMoveFolderUp=function(e,t,i){var s=this.getCollectionFromParent(i),o=s()[t-1],n="";return t>0&&o&&(n=s()[t-1].fullName()),0!==t&&e&&e.fullName()!==Ci.MailCache.editedFolderList().inboxFolderFullName()&&Ci.MailCache.editedFolderList().inboxFolderFullName()!==n},Kt.prototype.canMoveFolderDown=function(e,t,i){var s=this.getCollectionFromParent(i);return t!==s().length-1&&e.fullName()!==Ci.MailCache.editedFolderList().inboxFolderFullName()},Kt.prototype.moveFolderUp=function(e,t,i){var s=this.getCollectionFromParent(i);this.canMoveFolderUp(e,t,i)&&s&&(s.splice(t,1),s.splice(t-1,0,e),this.folderListOrderUpdateDebounce())},Kt.prototype.moveFolderDown=function(e,t,i){var s=this.getCollectionFromParent(i);this.canMoveFolderDown(e,t,i)&&s&&(s.splice(t,1),s.splice(t+1,0,e),this.folderListOrderUpdateDebounce())},Kt.prototype.afterSortableFolderMove=function(){this.folderListOrderUpdateDebounce()},Kt.prototype.folderListOrderUpdate=function(){var e=Ci.MailCache.editedFolderList().getOptions("",!1,!1,!1),t={Action:"FolderListOrderUpdate",AccountID:Ti.Accounts.editedId(),FolderList:_.compact(_.map(e,function(e){return e&&e.fullName?e.fullName:null}))};Ci.Ajax.send(t,this.onResponseFolderChanges,this)},Wt.prototype.TemplateName="Settings_CommonSettingsViewModel",Wt.prototype.TabName=vi.SettingsTab.Common,Wt.prototype.TabTitle=Si.i18n("SETTINGS/TAB_COMMON"),Wt.prototype.onApplyBindings=function(){this.init(),this.updateFirstState()},Wt.prototype.setMessagesPerPage=function(e){var t=this.rangeOfNumbers;-1===_.indexOf(t,e)&&(t=_.sortBy(_.union(t,[e]),function(e){return e},this)),this.messagesPerPageValues(t),this.messagesPerPage(e)},Wt.prototype.setContactsPerPage=function(e){var t=this.rangeOfNumbers;-1===_.indexOf(t,e)&&(t=_.sortBy(_.union(t,[e]),function(e){return e},this)),this.contactsPerPageValues(t),this.contactsPerPage(e)},Wt.prototype.init=function(){this.selectedSkin(Ti.User.DefaultTheme),this.selectedLanguage(Ti.User.DefaultLanguage),this.setMessagesPerPage(Ti.User.MailsPerPage),this.setContactsPerPage(Ti.User.ContactsPerPage),this.autocheckmailInterval(Ti.User.AutoCheckMailInterval),this.timeFormat(Ti.User.defaultTimeFormat()),this.dateFormat(Ti.User.DefaultDateFormat),this.useThreads(Ti.User.useThreads()),this.saveRepliedToCurrFolder(Ti.User.SaveRepliedToCurrFolder),this.allowChangeInputDirection(Ti.User.AllowChangeInputDirection),this.desktopNotifications(Ti.User.DesktopNotifications)},Wt.prototype.getState=function(){var e=[this.selectedSkin(),this.selectedLanguage(),this.messagesPerPage(),this.contactsPerPage(),this.autocheckmailInterval(),this.timeFormat(),this.dateFormat(),this.useThreads(),this.saveRepliedToCurrFolder(),this.allowChangeInputDirection(),this.desktopNotifications()];return e.join(":")},Wt.prototype.updateFirstState=function(){this.firstState=this.getState()},Wt.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},Wt.prototype.onResponse=function(e,i){var s=!1;this.loading(!1),e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):(Ci.CalendarCache.calendarSettingsChanged(!0),s=i.DefaultTheme!==Ti.User.DefaultTheme||i.DefaultLanguage!==Ti.User.DefaultLanguage,s?t.location.reload():(this.setMessagesPerPage(i.MailsPerPage),this.setContactsPerPage(i.ContactsPerPage),Ti.User.updateCommonSettings(i.MailsPerPage,i.ContactsPerPage,i.AutoCheckMailInterval,i.DefaultTheme,i.DefaultLanguage,i.DefaultDateFormat,i.DefaultTimeFormat,i.UseThreads,i.SaveRepliedMessagesToCurrentFolder,i.DesktopNotifications,i.AllowChangeInputDirection),Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY"))))},Wt.prototype.onSaveClick=function(){var e={Action:"UpdateUserSettings",MailsPerPage:Si.pInt(this.messagesPerPage()),ContactsPerPage:Si.pInt(this.contactsPerPage()),AutoCheckMailInterval:Si.pInt(this.autocheckmailInterval()),DefaultTheme:this.selectedSkin(),DefaultLanguage:this.selectedLanguage(),DefaultDateFormat:this.dateFormat(),DefaultTimeFormat:this.timeFormat(),UseThreads:this.useThreads()?"1":"0",SaveRepliedMessagesToCurrentFolder:this.saveRepliedToCurrFolder()?"1":"0",AllowChangeInputDirection:this.allowChangeInputDirection()?"1":"0",DesktopNotifications:this.desktopNotifications()?"1":"0"};this.loading(!0),this.updateFirstState(),Ci.Ajax.send(e,this.onResponse,this)},Wt.prototype.registerMailto=function(){Si.registerMailto()},qt.prototype.TemplateName="Settings_EmailAccountsSettingsViewModel",qt.prototype.TabName=vi.SettingsTab.EmailAccounts,qt.prototype.TabTitle=Si.i18n("SETTINGS/TAB_EMAIL_ACCOUNTS"),qt.prototype.isChanged=function(){return!1},qt.prototype.onRoute=function(e){var t=Ti.Accounts.getEdited();t&&(_.isArray(e)&&e.length>1?this.changeCurrentTab(e[1]):this.changeAccount(this.editedAccountId()))},qt.prototype.confirmSaving=function(e,t){var i=this.getViewModel(e),s=Si.i18n("SETTINGS/CONFIRM_SETTINGS_SAVE"),o=_.bind(function(e){i&&(e?Si.isFunc(i.onSaveClick)&&i.onSaveClick():(Si.isFunc(i.revert)&&i.revert(),i.updateFirstState())),Si.isFunc(t)&&t()},this);i&&Si.isFunc(i.isChanged)&&i.isChanged()?Ci.Screens.showPopup(C,[s,o]):Si.isFunc(t)&&t()},qt.prototype.onHide=function(){var e=this.getCurrentViewModel();this.confirmSaving(this.tab()),e&&Si.isFunc(e.onHide)&&e.onHide()},qt.prototype.changeCurrentTab=function(e){var t=Ti.Accounts.getEdited(),i=null,s=this.isTabAllowed(e,t),o=_.bind(function(){this.tab()!==e&&(i=this.getCurrentViewModel(),i&&Si.isFunc(i.onHide)&&i.onHide()),this.tab(e),i=this.getCurrentViewModel(),i&&Si.isFunc(i.onShow)&&i.onShow(t)},this);t&&(s?this.confirmSaving(this.tab(),o):this.tab()===e?(this.tab(vi.AccountSettingsTab.Properties),Ci.Routing.replaceHash([vi.Screens.Settings,vi.SettingsTab.EmailAccounts,vi.AccountSettingsTab.Properties]),this.editedFetcherId(null),this.editedIdentityId(null)):Ci.Routing.replaceHash([vi.Screens.Settings,vi.SettingsTab.EmailAccounts,this.tab()]))},qt.prototype.allowedChangeTabAfterConfirm=function(){},qt.prototype.getViewModel=function(e){switch(e){case vi.AccountSettingsTab.Folders:return this.oAccountFolders;case vi.AccountSettingsTab.Filters:return this.oAccountFilters;case vi.AccountSettingsTab.Forward:return this.oAccountForward;case vi.AccountSettingsTab.Signature:return this.oAccountSignature;case vi.AccountSettingsTab.Autoresponder:return this.oAccountAutoresponder;case vi.AccountSettingsTab.FetcherInc:return this.oFetcherIncoming;case vi.AccountSettingsTab.FetcherOut:return this.oFetcherOutgoing;case vi.AccountSettingsTab.FetcherSig:return this.oFetcherSignature;case vi.AccountSettingsTab.IdentityProperties:return this.oIdentityProperties;case vi.AccountSettingsTab.IdentitySignature:return this.oIdentityProperties;default:case vi.AccountSettingsTab.Properties:return this.oAccountProperties}},qt.prototype.getCurrentViewModel=function(){return this.getViewModel(this.tab())},qt.prototype.isTabAllowed=function(e,t){var i=[vi.AccountSettingsTab.Properties,vi.AccountSettingsTab.Signature,vi.AccountSettingsTab.Folders,vi.AccountSettingsTab.FetcherInc,vi.AccountSettingsTab.FetcherOut,vi.AccountSettingsTab.FetcherSig];return t.extensionExists("AllowSieveFiltersExtension")&&i.push(vi.AccountSettingsTab.Filters),t.extensionExists("AllowForwardExtension")&&i.push(vi.AccountSettingsTab.Forward),t.extensionExists("AllowAutoresponderExtension")&&i.push(vi.AccountSettingsTab.Autoresponder),Ti.AllowIdentities&&this.editedIdentityId()&&(i.push(vi.AccountSettingsTab.IdentityProperties),i.push(vi.AccountSettingsTab.IdentitySignature)),-1!==Si.inArray(e,i)},qt.prototype.onTabClick=function(e){Ci.Routing.setHash([vi.Screens.Settings,vi.SettingsTab.EmailAccounts,e])},qt.prototype.onResponseAccountDelete=function(e,i){e.Result?(Ti.Accounts.deleteAccount(i.AccountIDToDelete),this.changeAccount(this.editedAccountId()),this.defaultAccountId()===i.AccountIDToDelete&&(Ci.Routing.setHash([]),t.location.reload())):Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED"))},qt.prototype.deleteAccount=function(e,t){var i={Action:"AccountDelete",AccountIDToDelete:e};t&&Ci.Ajax.send(i,this.onResponseAccountDelete,this)},qt.prototype.onAccountDelete=function(e){var t=_.bind(this.deleteAccount,this,e),i=Ti.Accounts.getAccount(e);this.allowUsersChangeInterfaceSettings&&Ci.Screens.showPopup(C,[i.removeConfirmation(),t,i.email()])},qt.prototype.onEditedAccountDelete=function(){this.onAccountDelete(this.editedAccountId())},qt.prototype.onAccountAdd=function(){Ci.Screens.showPopup(E,[])},qt.prototype.changeAccount=function(e){var t=null,i={Action:"AccountSettings",AccountID:e};(this.isFetcherTab(this.tab())||this.isIdentityTab(this.tab()))&&this.onTabClick(vi.AccountSettingsTab.Properties),this.confirmSaving(this.tab()),t=Ti.Accounts.getAccount(e),!Si.isUnd(t)&&t.isExtended()?this.populate(t):Ci.Ajax.send(i,this.onAccountSettingsResponse,this),this.editedFetcherId(null),this.editedIdentityId(null)},qt.prototype.onAccountSettingsResponse=function(e,t){if(e.Result){var i=Ti.Accounts.getAccount(t.AccountID);Si.isUnd(i)||(i.updateExtended(e.Result),this.populate(i))}else Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED"))},qt.prototype.populate=function(e){this.allowAutoresponderExtension(e.extensionExists("AllowAutoresponderExtension")),this.allowForwardExtension(e.extensionExists("AllowForwardExtension")),this.allowSieveFiltersExtension(e.extensionExists("AllowSieveFiltersExtension")),Ti.Accounts.changeEditedAccount(e.id()),this.changeCurrentTab(this.tab())},qt.prototype.onIdentityAdd=function(e,t){t.stopPropagation(),Ci.Screens.showPopup(T,[e])},qt.prototype.onFetcherAdd=function(){Ci.Screens.showPopup(F,[])},qt.prototype.fetcherDelete=function(e,t){var i={Action:"FetcherDelete",FetcherID:e};t&&Ci.Ajax.send(i,this.onFetcherDeleteResponse,this)},qt.prototype.onFetcherDeleteClick=function(e){var t=Si.i18n("WARNING/FETCHER_DELETE_WARNING"),i=_.bind(this.fetcherDelete,this,e.idFetcher()),s=e.incomingMailServer();Ci.Screens.showPopup(C,[t,i,s])},qt.prototype.onFetcherDeleteResponse=function(e){e.Result?(Ti.Accounts.populateFetchers(),this.editedFetcherId(null)):Ci.Api.showErrorByCode(e.ErrorCode,Si.i18n("WARNING/FETCHER_DELETING_ERROR"))},qt.prototype.onChangeFetcher=function(e){var t=this.defaultAccount.fetchers().getFetcher(e);this.fetcher(t),this.isFetcherTab(this.tab())||this.onTabClick(vi.AccountSettingsTab.FetcherInc),this.confirmSaving(this.tab()),this.oFetcherIncoming.populate(t),this.oFetcherOutgoing.populate(t),this.oFetcherSignature.populate(t),this.editedFetcherId(t.id()),this.editedIdentityId(null)},qt.prototype.isFetcherTab=function(e){return-1!==Si.inArray(e,[vi.AccountSettingsTab.FetcherInc,vi.AccountSettingsTab.FetcherOut,vi.AccountSettingsTab.FetcherSig])},qt.prototype.onChangeIdentity=function(e){this.onTabClick(vi.AccountSettingsTab.IdentityProperties),this.confirmSaving(this.tab()),this.oIdentityProperties.populate(e),this.editedIdentityId(e.id()),this.editedFetcherId(null)},qt.prototype.isIdentityTab=function(e){return-1!==Si.inArray(e,[vi.AccountSettingsTab.IdentityProperties,vi.AccountSettingsTab.IdentitySignature])},qt.prototype.onRemoveIdentity=function(){this.editedIdentityId(null),this.changeCurrentTab(this.tab())},Yt.prototype.TemplateName="Settings_CalendarSettingsViewModel",Yt.prototype.TabName=vi.SettingsTab.Calendar,Yt.prototype.TabTitle=Si.i18n("SETTINGS/TAB_CALENDAR"),Yt.prototype.init=function(){this.showWeekends(Ti.User.CalendarShowWeekEnds),this.selectedWorkdayStarts(Ti.User.CalendarWorkDayStarts),this.selectedWorkdayEnds(Ti.User.CalendarWorkDayEnds),this.showWorkday(Ti.User.CalendarShowWorkDay),this.weekStartsOn(Ti.User.CalendarWeekStartsOn),this.defaultTab(Ti.User.CalendarDefaultTab)},Yt.prototype.getState=function(){var e=[this.showWeekends(),this.selectedWorkdayStarts(),this.selectedWorkdayEnds(),this.showWorkday(),this.weekStartsOn(),this.defaultTab()];return e.join(":")},Yt.prototype.updateFirstState=function(){this.firstState=this.getState()},Yt.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},Yt.prototype.onResponse=function(e,t){this.loading(!1),e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_CALENDAR_SETTINGS_SAVING_FAILED")):(Ci.CalendarCache.calendarSettingsChanged(!0),Ti.User.updateCalendarSettings(t.ShowWeekEnds,t.ShowWorkDay,t.WorkDayStarts,t.WorkDayEnds,t.WeekStartsOn,t.DefaultTab),Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")))},Yt.prototype.onSaveClick=function(){var e={Action:"UpdateUserSettings",ShowWeekEnds:this.showWeekends()?1:0,ShowWorkDay:this.showWorkday()?1:0,WorkDayStarts:parseInt(this.selectedWorkdayStarts(),10),WorkDayEnds:parseInt(this.selectedWorkdayEnds(),10),WeekStartsOn:parseInt(this.weekStartsOn(),10),DefaultTab:parseInt(this.defaultTab(),10)};this.loading(!0),this.updateFirstState(),Ci.Ajax.send(e,this.onResponse,this)},Yt.prototype.getDisplayedTimes=function(e){var t=[];switch(e){case"HH:mm":t=[{text:"01:00",value:"1"},{text:"02:00",value:"2"},{text:"03:00",value:"3"},{text:"04:00",value:"4"},{text:"05:00",value:"5"},{text:"06:00",value:"6"},{text:"07:00",value:"7"},{text:"08:00",value:"8"},{text:"09:00",value:"9"},{text:"10:00",value:"10"},{text:"11:00",value:"11"},{text:"12:00",value:"12"},{text:"13:00",value:"13"},{text:"14:00",value:"14"},{text:"15:00",value:"15"},{text:"16:00",value:"16"},{text:"17:00",value:"17"},{text:"18:00",value:"18"},{text:"19:00",value:"19"},{text:"20:00",value:"20"},{text:"21:00",value:"21"},{text:"22:00",value:"22"},{text:"23:00",value:"23"},{text:"00:00",value:"24"}];break;case"hh:mm A":t=[{text:"01:00 AM",value:"1"},{text:"02:00 AM",value:"2"},{text:"03:00 AM",value:"3"},{text:"04:00 AM",value:"4"},{text:"05:00 AM",value:"5"},{text:"06:00 AM",value:"6"},{text:"07:00 AM",value:"7"},{text:"08:00 AM",value:"8"},{text:"09:00 AM",value:"9"},{text:"10:00 AM",value:"10"},{text:"11:00 AM",value:"11"},{text:"12:00 PM",value:"12"},{text:"01:00 PM",value:"13"},{text:"02:00 PM",value:"14"},{text:"03:00 PM",value:"15"},{text:"04:00 PM",value:"16"},{text:"05:00 PM",value:"17"},{text:"06:00 PM",value:"18"},{text:"07:00 PM",value:"19"},{text:"08:00 PM",value:"20"},{text:"09:00 PM",value:"21"},{text:"10:00 PM",value:"22"},{text:"11:00 PM",value:"23"},{text:"12:00 AM",value:"24"}]}return t},zt.prototype.TemplateName="Settings_MobileSyncSettingsViewModel",zt.prototype.TabName=vi.SettingsTab.MobileSync,zt.prototype.TabTitle=Si.i18n("SETTINGS/TAB_MOBILE_SYNC"),zt.prototype.onRoute=function(){Ti.User.requestSyncSettings()},zt.prototype.onMobileSyncSubscribe=function(){this.enableDav(Ti.User.MobileSyncEnable&&this.mobileSync()&&this.mobileSync().EnableDav),this.enableDav()&&(this.davLogin(this.mobileSync().Dav.Login),this.davServer(this.mobileSync().Dav.Server),this.davCalendars(this.mobileSync().Dav.Calendars),this.davPersonalContactsUrl(this.mobileSync().Dav.PersonalContactsUrl),this.davCollectedAddressesUrl(this.mobileSync().Dav.CollectedAddressesUrl),this.davGlobalAddressBookUrl(this.mobileSync().Dav.GlobalAddressBookUrl),this.davSharedWithAllUrl(this.mobileSync().Dav.SharedWithAllUrl))},Qt.prototype.TemplateName="Settings_OutLookSyncSettingsViewModel",Qt.prototype.TabName=vi.SettingsTab.OutLookSync,Qt.prototype.TabTitle=Si.i18n("SETTINGS/TAB_OUTLOOK_SYNC"),Qt.prototype.onRoute=function(){Ti.User.requestSyncSettings()},Qt.prototype.onOutlookSyncSubscribe=function(){Ti.User.OutlookSyncEnable&&(this.visibleOutlookSync(!0),this.outlookSync()&&this.server(this.outlookSync().Server))},$t.prototype.TemplateName="Settings_PgpSettingsViewModel",$t.prototype.TabName=vi.SettingsTab.Pgp,$t.prototype.TabTitle=Si.i18n("SETTINGS/TAB_OPENPGP"),$t.prototype.init=function(){this.enableOpenPgp(Ti.User.enableOpenPgp()),this.allowAutosaveInDrafts(Ti.User.AllowAutosaveInDrafts),this.autosignOutgoingEmails(Ti.User.AutosignOutgoingEmails)},$t.prototype.getState=function(){var e=[this.enableOpenPgp(),this.allowAutosaveInDrafts(),this.autosignOutgoingEmails()];return e.join(":")},$t.prototype.updateFirstState=function(){this.firstState=this.getState()},$t.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},$t.prototype.onRoute=function(){var e=_.bind(function(e){e&&(this.pgp=e,this.keys(this.pgp.getKeys()),this.pgp.getKeysObservable().subscribe(function(){this.keys(this.pgp.getKeys())},this)),this.pgpLoaded(!0)},this);Ci.Api.pgp(e,Ti.User.IdUser)},$t.prototype.importKey=function(){this.pgp&&Ci.Screens.showPopup(W,[this.pgp])},$t.prototype.generateNewKey=function(){this.pgp&&Ci.Screens.showPopup(j,[this.pgp])},$t.prototype.removeOpenPgpKey=function(e){var t="",i=_.bind(function(t){if(t){var i=this.pgp.deleteKey(e);i.result||Ci.Api.showError(Si.i18n("OPENPGP/ERROR_DELETE_KEY"))}},this);this.pgp&&e&&(t=Si.i18n("OPENPGP/CONFIRM_DELETE_KEY",{KEYEMAIL:e.getEmail()}),Ci.Screens.showPopup(C,[t,i]))},$t.prototype.showArmor=function(e){this.pgp&&Ci.Screens.showPopup(K,[e])},$t.prototype.onResponse=function(e,t){this.loading(!1),e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):(Ti.User.updateOpenPgpSettings(t.EnableOpenPgp,t.AllowAutosaveInDrafts,t.AutosignOutgoingEmails),Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")))},$t.prototype.onSaveClick=function(){var e={Action:"UpdateUserSettings",EnableOpenPgp:this.enableOpenPgp()?"1":"0",AllowAutosaveInDrafts:this.allowAutosaveInDrafts()?"1":"0",AutosignOutgoingEmails:this.autosignOutgoingEmails()?"1":"0"}; this.loading(!0),this.updateFirstState(),Ci.Ajax.send(e,this.onResponse,this)},Jt.prototype.onShow=function(e){this.account(e),this.populate()},Jt.prototype.getState=function(){var e=[this.friendlyName(),this.email(),this.incomingMailLogin(),this.incomingMailPort(),this.incomingMailServer(),this.outgoingMailLogin(),this.outgoingMailPort(),this.outgoingMailServer(),this.useSmtpAuthentication()];return e.join(":")},Jt.prototype.updateFirstState=function(){this.firstState=this.getState()},Jt.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},Jt.prototype.populate=function(){var e=this.account();e?(this.allowChangePassword(e.extensionExists("AllowChangePasswordExtension")),this.isInternal(e.isInternal()),this.isLinked(e.isLinked()),this.isDefault(e.isDefault()),this.removeHint(e.removeHint()),this.useSmtpAuthentication(2===Si.pInt(e.outgoingMailAuth())?!0:!1),this.friendlyName(e.friendlyName()),this.email(e.email()),this.incomingMailLogin(e.incomingMailLogin()),this.incomingMailServer(e.incomingMailServer()),this.incomingMailPort(e.incomingMailPort()),this.outgoingMailServer(e.outgoingMailServer()),this.outgoingMailLogin(e.outgoingMailLogin()),this.outgoingMailPort(e.outgoingMailPort()),this.updateFirstState()):(this.allowChangePassword(!1),this.isLinked(!0),this.useSmtpAuthentication(!0),this.friendlyName(""),this.email(""),this.incomingMailLogin(""),this.incomingMailServer(""),this.incomingMailPort(143),this.outgoingMailServer(""),this.outgoingMailLogin(""),this.outgoingMailPort(25))},Jt.prototype.onResponse=function(e,t){if(this.loading(!1),e.Result){var i=Si.pInt(e.AccountID),s=i>0?Ti.Accounts.getAccount(i):null;s&&(s.updateExtended(t),Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")))}else Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED"))},Jt.prototype.prepareParameters=function(){var e={Action:"UpdateAccountSettings",AccountID:this.account().id(),FriendlyName:this.friendlyName(),Email:this.email(),IncomingMailLogin:this.incomingMailLogin(),IncomingMailServer:this.incomingMailServer(),IncomingMailPort:Si.pInt(this.incomingMailPort()),OutgoingMailServer:this.outgoingMailServer(),OutgoingMailLogin:this.outgoingMailLogin(),OutgoingMailPort:Si.pInt(this.outgoingMailPort()),OutgoingMailAuth:this.useSmtpAuthentication()?2:0,IncomingMailPassword:this.incomingMailPassword()};return e},Jt.prototype.saveData=function(e){this.updateFirstState(),Ci.Ajax.send(e,this.onResponse,this)},Jt.prototype.onSaveClick=function(){this.account()&&(this.loading(!0),this.saveData(this.prepareParameters()))},Jt.prototype.onChangePasswordClick=function(){Ci.Screens.showPopup(P,[!1])},Xt.prototype.onHide=function(){var e=Ti.Accounts.editedId();_.delay(function(){Ci.MailCache.getFolderList(e)},3e3)},Xt.prototype.isChanged=function(){return!1},Xt.prototype.onAddNewFolderClick=function(){Ci.Screens.showPopup(w)},Xt.prototype.onSystemFoldersClick=function(){Ci.Screens.showPopup(I)},Zt.prototype.__name="CAccountSignatureViewModel",Zt.prototype.onShow=function(e){this.account(e),this.oHtmlEditor.initCrea(this.signature(),!1,""),this.oHtmlEditor.setActivitySource(this.useSignature),this.enableImageDragNDrop(this.oHtmlEditor.editorUploader.isDragAndDropSupported()&&!Ci.browser.ie10AndAbove),this.updateFirstState()},Zt.prototype.getState=function(){var e=[this.type(),this.useSignature(),this.oHtmlEditor.getText()];return e.join(":")},Zt.prototype.updateFirstState=function(){this.firstState=this.getState()},Zt.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},Zt.prototype.getSignature=function(){if(this.account())if(null!==this.account().signature())this.type(this.account().signature().type()),this.useSignature(this.account().signature().options()),this.signature(this.account().signature().signature()),this.updateFirstState();else{var e={Action:"AccountSignature",AccountID:this.account().id()};Ci.Ajax.send(e,this.onSignatureResponse,this)}},Zt.prototype.onSignatureResponse=function(e){var t=null,i=parseInt(e.AccountID,10);e.Result?this.account()&&i===this.account().id()&&(t=new vt,t.parse(i,e.Result),this.account().signature(t),this.type(this.account().signature().type()),this.useSignature(this.account().signature().options()),this.signature(this.account().signature().signature()),this.updateFirstState()):Ci.Api.showErrorByCode(e)},Zt.prototype.prepareParameters=function(){var e={Action:"UpdateAccountSignature",AccountID:this.account().id(),Type:this.type()?1:0,Options:this.useSignature(),Signature:this.signature()};return e},Zt.prototype.saveData=function(e){this.updateFirstState(),Ci.Ajax.send(e,this.onResponse,this)},Zt.prototype.onSaveClick=function(){this.account()&&(this.loading(!0),this.signature(this.oHtmlEditor.getNotDefaultText()),this.account().signature().type(this.type()),this.account().signature().options(this.useSignature()),this.account().signature().signature(this.signature()),this.saveData(this.prepareParameters()))},Zt.prototype.onResponse=function(e){this.loading(!1),e.Result?Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")):Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED"))},ei.prototype.onShow=function(e){this.account(e)},ei.prototype.getState=function(){return[this.enable(),this.email()].join(":")},ei.prototype.updateFirstState=function(){this.firstState=this.getState()},ei.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState},ei.prototype.prepareParameters=function(){return{Action:"UpdateForward",AccountID:this.account().id(),Enable:this.enable()?"1":"0",Email:this.email()}},ei.prototype.saveData=function(e){this.updateFirstState(),Ci.Ajax.send(e,this.onUpdateForwardResponse,this)},ei.prototype.onSaveClick=function(){if(this.account()){var e=this,t=this.account().forward(),i=function(){t&&(t.enable=e.enable(),t.email=e.email()),e.loading(!0),e.saveData(e.prepareParameters())};this.enable()&&""===this.email()?this.emailFocus(!0):this.enable()&&""!==this.email()&&Si.getIncorrectEmailsFromAddressString(this.email()).length?Ci.Screens.showPopup(A,[Si.i18n("COMPOSE/WARNING_INPUT_CORRECT_EMAILS")+" "+this.email()]):i()}},ei.prototype.getForward=function(){if(this.account())if(null!==this.account().forward())this.enable(this.account().forward().enable),this.email(this.account().forward().email),this.firstState=this.getState();else{var e={Action:"GetForward",AccountID:this.account().id()};this.loading(!0),this.updateFirstState(),Ci.Ajax.send(e,this.onGetForwardResponse,this)}},ei.prototype.onGetForwardResponse=function(e,t){if(this.loading(!1),t&&t.Action){if(e&&e.Result&&e.AccountID&&this.account()){var i=null,s=new Et,o=Si.pInt(e.AccountID);o&&(i=Ti.Accounts.getAccount(o),i&&(s.parse(o,e.Result),i.forward(s),this.enable(i.forward().enable),this.email(i.forward().email),this.updateFirstState(),o===this.account().id()&&this.getForward()))}}else Ci.Api.showError(Si.i18n("WARNING/UNKNOWN_ERROR"))},ei.prototype.onUpdateForwardResponse=function(e,t){this.loading(!1),t&&t.Action?e&&e.Result?Ci.Api.showReport(Si.i18n("SETTINGS/ACCOUNT_FORWARD_SUCCESS_REPORT")):Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):Ci.Api.showError(Si.i18n("WARNING/UNKNOWN_ERROR"))},ti.prototype.onShow=function(e){this.account(e)},ti.prototype.getState=function(){var e=[this.enable(),this.subject(),this.message()];return e.join(":")},ti.prototype.updateFirstState=function(){this.firstState=this.getState()},ti.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},ti.prototype.prepareParameters=function(){var e={Action:"UpdateAutoresponder",AccountID:this.account().id(),Enable:this.enable()?"1":"0",Subject:this.subject(),Message:this.message()};return e},ti.prototype.saveData=function(e){this.updateFirstState(),Ci.Ajax.send(e,this.onUpdateAutoresponder,this)},ti.prototype.onSaveClick=function(){if(this.account()){var e=this.account().autoresponder();e&&(e.enable=this.enable(),e.subject=this.subject(),e.message=this.message()),this.loading(!0),this.saveData(this.prepareParameters())}},ti.prototype.getAutoresponder=function(){if(this.account())if(null!==this.account().autoresponder())this.enable(this.account().autoresponder().enable),this.subject(this.account().autoresponder().subject),this.message(this.account().autoresponder().message),this.updateFirstState();else{var e={Action:"GetAutoresponder",AccountID:this.account().id()};this.loading(!0),Ci.Ajax.send(e,this.onGetAutoresponderResponse,this)}},ti.prototype.onGetAutoresponderResponse=function(e,t){if(this.loading(!1),t&&t.Action){if(e&&e.Result&&e.AccountID&&this.account()){var i=null,s=new St,o=Si.pInt(e.AccountID);o&&(i=Ti.Accounts.getAccount(o),i&&(s.parse(o,e.Result),i.autoresponder(s),o===this.account().id()&&this.getAutoresponder()))}}else Ci.Api.showError(Si.i18n("WARNING/UNKNOWN_ERROR"))},ti.prototype.onUpdateAutoresponder=function(e,t){this.loading(!1),t&&t.Action?e&&e.Result?Ci.Api.showReport(Si.i18n("SETTINGS/ACCOUNT_AUTORESPONDER_SUCCESS_REPORT")):Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):Ci.Api.showError(Si.i18n("WARNING/UNKNOWN_ERROR"))},ii.prototype.onShow=function(e){this.account(e),this.getFilters()},ii.prototype.onHide=function(){this.collection([]),this.updateFirstState()},ii.prototype.revert=function(){_.each(this.collection(),function(e){e.revert()})},ii.prototype.commit=function(){_.each(this.collection(),function(e){e.commit()})},ii.prototype.getState=function(){var e=":",t=_.map(this.collection(),function(e){return e.toString()},this);return t.length>0&&(e=t.join(":")),e},ii.prototype.updateFirstState=function(){this.firstState=this.getState()},ii.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState},ii.prototype.prepareParameters=function(){var e=_.map(this.collection(),function(e){return{Enable:e.enable()?"1":"0",Field:e.field(),Filter:e.filter(),Condition:e.condition(),Action:e.action(),FolderFullName:e.folder()}}),t={Action:"UpdateSieveFilters",AccountID:this.account().id(),Filters:e};return t},ii.prototype.saveData=function(e){var t=_.some(this.collection(),function(e){return""===e.filter()||"3"===Si.pString(e.action())&&""===e.folder()});t?Ci.Api.showError(Si.i18n("SETTINGS/ERROR_FILTERS_FIELDS_FILL")):(this.saving(!0),this.commit(),this.updateFirstState(),Ci.Ajax.send(e,this.onUpdateFiltersResponse,this))},ii.prototype.onSaveClick=function(){this.account()&&this.saveData(this.prepareParameters())},ii.prototype.getFilters=function(){if(this.account())if(null!==this.account().filters())this.account().id()===this.folderList().iAccountId?(this.collection(this.account().filters().collection()),this.updateFirstState(),this.loading(!1)):this.loading(!0);else{var e={Action:"GetSieveFilters",AccountID:this.account().id()};this.loading(!0),Ci.Ajax.send(e,this.onGetFiltersResponse,this)}},ii.prototype.deleteFilter=function(e){this.collection.remove(e)},ii.prototype.addFilter=function(){if(this.account()){var e=new Ft(this.account().id());this.collection.push(e)}},ii.prototype.displayFilterPart=function(e,t){var i="";return i="%FIELD%"===e?"Field":"%CONDITION%"===e?"Condition":"%STRING%"===e?"String":"%ACTION%"===e?"Action":"%FOLDER%"===e?"Folder":"%DEPENDED"===e.substr(0,9)?"DependedText":"Text",t+i},ii.prototype.getDependedText=function(e){return e=Si.pString(e),e&&(e=e.replace(/%/g,"").split("=")[1]||""),e},ii.prototype.getDependedField=function(e,t){return e=Si.pString(e),e&&(e=e.replace(/[=](.*)/g,"").split("-")[1]||"",e=e.toLowerCase()),Si.isUnd(t[e])?!1:t[e]()},ii.prototype.onGetFiltersResponse=function(e,t){if(this.loading(!1),t&&t.Action){if(e&&e.Result&&e.AccountID&&this.account()){var i=null,s=new Tt,o=Si.pInt(e.AccountID);o&&(i=Ti.Accounts.getAccount(o),i&&(s.parse(o,e.Result),i.filters(s),o===this.account().id()&&this.getFilters()))}}else Ci.Api.showError(Si.i18n("WARNING/UNKNOWN_ERROR"))},ii.prototype.onUpdateFiltersResponse=function(e,t){this.saving(!1),t&&t.Action?e&&e.Result?Ci.Api.showReport(Si.i18n("SETTINGS/ACCOUNT_FILTERS_SUCCESS_REPORT")):Ci.Api.showError(Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):Ci.Api.showError(Si.i18n("WARNING/UNKNOWN_ERROR"))},si.prototype.onSaveClick=function(){if(this.isEmptyRequiredFields())Ci.Api.showError(Si.i18n("WARNING/FETCHER_CREATE_ERROR"));else{var e={Action:"FetcherUpdate",AccountID:this.defaultAccountId(),FetcherID:this.idFetcher(),IsEnabled:this.isEnabled()?1:0,Folder:this.folder(),IncomingMailPassword:""===this.incomingMailPassword()?"******":this.incomingMailPassword(),LeaveMessagesOnServer:this.leaveMessagesOnServer()?1:0};this.loading(!0),Ci.Ajax.send(e,this.onSaveFetcherResponse,this)}},si.prototype.onSaveFetcherResponse=function(e){this.loading(!1),e.Result?(Ti.Accounts.populateFetchers(),Ci.Api.showReport(Si.i18n("SETTINGS/ACCOUNT_FETCHER_SUCCESSFULLY_SAVED"))):Ci.Api.showErrorByCode(e,Si.i18n("WARNING/UNKNOWN_ERROR"))},si.prototype.populate=function(e){e&&(this.fetcher(e),this.idFetcher(e.id()),this.isEnabled(e.isEnabled()),this.folder(e.folder()),this.incomingMailServer(e.incomingMailServer()),this.incomingMailPort(e.incomingMailPort()),this.incomingMailLogin(e.incomingMailLogin()),this.incomingMailPassword("******"),this.leaveMessagesOnServer(e.leaveMessagesOnServer()))},si.prototype.isEmptyRequiredFields=function(){switch(""){case this.incomingMailServer():return this.serverIsSelected(!0),!0;case this.incomingMailLogin():return this.loginIsSelected(!0),!0;case this.incomingMailPassword():return this.passwordIsSelected(!0),!0;default:return!1}},oi.prototype.onSaveClick=function(){if(this.outgoingMailAuth()&&this.isEmptyRequiredFields())Ci.Api.showError(Si.i18n("WARNING/FETCHER_CREATE_ERROR"));else{var e={Action:"FetcherUpdate",AccountID:this.defaultAccountId(),FetcherID:this.idFetcher(),Email:this.email(),Name:this.userName(),IsOutgoingEnabled:this.isOutgoingEnabled()?1:0,OutgoingMailServer:this.outgoingMailServer(),OutgoingMailPort:parseInt(this.outgoingMailPort(),10),OutgoingMailAuth:this.outgoingMailAuth()?1:0};this.loading(!0),Ci.Ajax.send(e,this.onSaveFetcherResponse,this)}},oi.prototype.onSaveFetcherResponse=function(e){this.loading(!1),e.Result?(Ti.Accounts.populateFetchers(),Ci.Api.showReport(Si.i18n("SETTINGS/ACCOUNT_FETCHER_SUCCESSFULLY_SAVED"))):Ci.Api.showErrorByCode(e,Si.i18n("WARNING/UNKNOWN_ERROR"))},oi.prototype.populate=function(e){e&&(this.fetcher(e),this.idFetcher(e.id()),this.isEnabled(e.isEnabled()),this.email(e.email()),this.userName(e.userName()),this.isOutgoingEnabled(e.isOutgoingEnabled()),this.outgoingMailServer(e.outgoingMailServer()),this.outgoingMailPort(e.outgoingMailPort()),this.outgoingMailAuth(e.outgoingMailAuth()))},oi.prototype.isEmptyRequiredFields=function(){return this.isOutgoingEnabled()&&""===this.outgoingMailServer()?(this.serverIsSelected(!0),!0):!1},ni.prototype.__name="CFetcherSignatureViewModel",ni.prototype.onSaveClick=function(){var e={Action:"FetcherUpdate",AccountID:this.defaultAccountId(),FetcherID:this.idFetcher(),SignatureOptions:this.useSignature(),Signature:this.oHtmlEditor.getText()};this.loading(!0),Ci.Ajax.send(e,this.onSaveFetcherResponse,this)},ni.prototype.onSaveFetcherResponse=function(e){this.loading(!1),e.Result?(Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")),Ti.Accounts.populateFetchers()):Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED"))},ni.prototype.populate=function(e){e&&(this.fetcher(e),this.idFetcher(e.id()),this.signature(e.signature()),this.useSignature(e.signatureOptions()))},ni.prototype.getState=function(){var e=[this.type(),this.useSignature(),this.oHtmlEditor.getText()];return e.join(":")},ni.prototype.updateFirstState=function(){this.firstState=this.getState()},ni.prototype.onShow=function(){this.oHtmlEditor.initCrea(this.signature(),!1,""),this.oHtmlEditor.setActivitySource(this.useSignature),this.enableImageDragNDrop(this.oHtmlEditor.editorUploader.isDragAndDropSupported()&&!Ci.browser.ie10AndAbove),this.updateFirstState()},ri.prototype.TemplateName="Settings_HelpdeskSettingsViewModel",ri.prototype.TabName=vi.SettingsTab.Helpdesk,ri.prototype.TabTitle=Si.i18n("SETTINGS/TAB_HELPDESK"),ri.prototype.onShow=function(){this.allowNotifications(Ti.User.AllowHelpdeskNotifications)},ri.prototype.onResponse=function(e){this.loading(!1),e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):(Ti.User.updateHelpdeskSettings(this.allowNotifications()),Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")))},ri.prototype.onSaveClick=function(){var e={Action:"UpdateHelpdeskUserSettings",AllowHelpdeskNotifications:this.allowNotifications()?"1":"0"};this.loading(!0),Ci.Ajax.send(e,this.onResponse,this)},ai.prototype.TemplateName="Settings_ServicesSettingsViewModel",ai.prototype.TabName=vi.SettingsTab.Services,ai.prototype.TabTitle=Si.i18n("SETTINGS/TAB_SERVICES"),ai.prototype.getState=function(){var e=[this.enableFiles()];return e.join(":")},ai.prototype.updateFirstState=function(){this.firstState=this.getState()},ai.prototype.isChanged=function(){return this.firstState&&this.getState()!==this.firstState?!0:!1},ai.prototype.init=function(){this.enableFiles(Ti.User.filesEnable())},ai.prototype.onApplyBindings=function(){t.servicesSettingsViewModelCallback=_.bind(function(e,t){if(t)switch(e){case"google":this.getSocialAccount(vi.SocialType.Google),this.googleConnected(!this.googleConnected());break;case"dropbox":this.getSocialAccount(vi.SocialType.Dropbox),this.dropboxConnected(!this.dropboxConnected())}},this)},ai.prototype.onGoogleApiLoad=function(){this.googleApiLoaded(!0)},ai.prototype.onShow=function(){},ai.prototype.onRoute=function(){(this.allowGoogle||this.allowDropbox)&&this.getSocialAccounts()},ai.prototype.onDropboxSignInClick=function(){this.dropboxConnected()?this.onSocialSignOutClick("dropbox"):this.onSocialSignInClick("dropbox")},ai.prototype.onGoogleSignInClick=function(){this.googleConnected()?this.onSocialSignOutClick("google"):this.onSocialSignInClick("google")},ai.prototype.onSocialSignInClick=function(t){var i=null;e.cookie("SocialRedirect","settings"),i=Si.WindowOpener.open(Si.getAppPath()+"?"+t,t)},ai.prototype.addSocialAccount=function(e){Ti.User.SocialAccounts.push(e)},ai.prototype.deleteSocialAccount=function(e){Ti.User.SocialAccounts(_.filter(Ti.User.SocialAccounts(),function(t){return"Object/CSocial"===t["@Object"]&&t.Type!==e},this))},ai.prototype.onSocialSignOutClick=function(e){var t=0;switch(e){case"google":this.deleteSocialAccount(vi.SocialType.Google),t=vi.SocialType.Google,this.googleConnected(!1);break;case"dropbox":this.deleteSocialAccount(vi.SocialType.Dropbox),t=vi.SocialType.Dropbox,this.dropboxConnected(!1)}Ci.Ajax.send({Action:"SocialAccountDelete",Type:t},this.onSocialAccountDeleteResponse,this)},ai.prototype.onSocialAccountDeleteResponse=function(e,t){var i=e.Result;t.Type===vi.SocialType.Google?this.googleConnected(i!==!1?!1:!this.googleConnected()):t.Type===vi.SocialType.Dropbox&&this.dropboxConnected(i!==!1?!1:!this.dropboxConnected())},ai.prototype.onSaveClick=function(){var e={Action:"UpdateUserSettings",FilesEnable:this.enableFiles()?"1":"0"};this.loading(!0),this.updateFirstState(),Ci.Ajax.send(e,this.onResponse,this)},ai.prototype.onResponse=function(e){this.loading(!1),e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ERROR_SETTINGS_SAVING_FAILED")):(Ti.User.filesEnable(this.enableFiles()),Ci.Api.showReport(Si.i18n("SETTINGS/COMMON_REPORT_UPDATED_SUCCESSFULLY")))},ai.prototype.getSocialAccounts=function(){this.googleConnected(!1),this.dropboxConnected(!1),_.each(Ti.User.SocialAccounts(),function(e){"Object/CSocial"===e["@Object"]&&(e.Type===vi.SocialType.Google?this.googleConnected(!0):e.Type===vi.SocialType.Dropbox&&this.dropboxConnected(!0))},this)},ai.prototype.getSocialAccount=function(e){Ci.Ajax.send({Action:"SocialAccount",Type:e},this.onSocialAccountResponse,this)},ai.prototype.onSocialAccountResponse=function(e){var t=e.Result;t&&"Object/CSocial"===t["@Object"]&&(this.deleteSocialAccount(t.Type),this.addSocialAccount(t))},li.prototype.__name="CIdentityPropertiesViewModel",li.prototype.onShow=function(){this.oHtmlEditor.initCrea(this.signature(),!1,""),this.oHtmlEditor.setActivitySource(this.useSignature),this.enableImageDragNDrop(this.oHtmlEditor.editorUploader.isDragAndDropSupported()&&!Ci.browser.ie10AndAbove)},li.prototype.onSaveClick=function(){if(""===this.email())Ci.Api.showError(Si.i18n("WARNING/IDENTITY_CREATE_ERROR"));else{this.signature(this.oHtmlEditor.getNotDefaultText());var e=this.bCreate?"CreateIdentity":"UpdateIdentity",t={Action:e,AccountID:this.identity().accountId(),Enabled:this.enabled()?1:0,Email:this.email(),Signature:this.signature(),UseSignature:this.useSignature(),FriendlyName:this.friendlyName()};this.bCreate||(t.IdIdentity=this.identity().id()),this.loading(!0),Ci.Ajax.send(t,this.onUpdateIdentityResponse,this)}},li.prototype.onUpdateIdentityResponse=function(e){this.loading(!1),e.Result?(Ti.Accounts.populateIdentities(),this.bCreate&&this.oParent.closeCommand()):Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ACCOUNTS_IDENTITY_ADDING_ERROR"))},li.prototype.populate=function(e){e&&(this.identity(e),this.enabled(e.enabled()),this.email(e.email()),this.friendlyName(e.friendlyName()),this.signature(e.signature()),this.useSignature(e.useSignature()?1:0))},li.prototype.remove=function(){var e={Action:"DeleteIdentity",AccountID:this.identity().accountId(),IdIdentity:this.identity().id()};Ci.Ajax.send(e,this.onDeleteIdentityResponse,this),this.bCreate||this.oParent.onRemoveIdentity()},li.prototype.onDeleteIdentityResponse=function(e){e.Result||Ci.Api.showErrorByCode(e,Si.i18n("SETTINGS/ACCOUNTS_IDENTITY_DELETING_ERROR")),Ti.Accounts.populateIdentities()},li.prototype.cancel=function(){this.bCreate&&this.oParent.cancel()},hi.prototype.getFCObject=function(){return this.$calendarGrid.fullCalendar("getCalendar")},hi.prototype.getDateFromCurrentView=function(e){var t=this.$calendarGrid.fullCalendar("getView"),i=t&&t[e]?t[e]:null;return i&&"end"===e&&"agendaDay"===t.name&&i.add(1,"d"),i&&i.unix?t[e].unix():0},hi.prototype.eventsSource=function(e,t,i,s){s(this.calendars.getEvents(e,t))},hi.prototype.initFullCalendar=function(){this.$calendarGrid.fullCalendar(this.fullcalendarOptions)},hi.prototype.applyCalendarSettings=function(){this.timeFormat=Ti.User.defaultTimeFormat()===vi.TimeFormat.F24?"HH:mm":"hh:mm A",this.dateFormat=Ti.User.DefaultDateFormat,this.calendarGridDom().removeClass("fc-show-weekends"),Ti.User.CalendarShowWeekEnds&&this.calendarGridDom().addClass("fc-show-weekends"),this.fullcalendarOptions.timeFormat=this.timeFormat,this.fullcalendarOptions.axisFormat=this.timeFormat,this.fullcalendarOptions.defaultView=this.defaultViewName(),this.fullcalendarOptions.lang=moment.lang(),this.applyFirstDay(),this.$calendarGrid.fullCalendar("destroy"),this.$calendarGrid.fullCalendar(this.fullcalendarOptions),this.changeView(this.defaultViewName())},hi.prototype.applyFirstDay=function(){var e=[],t="",i="";switch(Ti.Auth&&(this.fullcalendarOptions.firstDay=Ti.User.CalendarWeekStartsOn),_.each(this.aDayNames,function(t){e.push(t)}),this.fullcalendarOptions.firstDay){case 1:i=e.shift(),e.push(i);break;case 6:t=e.pop(),e.unshift(t)}this.$datePicker.datepicker("option","firstDay",this.fullcalendarOptions.firstDay)},hi.prototype.initDatePicker=function(){this.$datePicker.datepicker({showOtherMonths:!0,selectOtherMonths:!0,monthNames:Si.getMonthNamesArray(),dayNamesMin:Si.i18n("DATETIME/DAY_NAMES_MIN").split(" "),onChangeMonthYear:_.bind(this.changeMonthYearFromDatePicker,this),onSelect:_.bind(this.selectDateFromDatePicker,this),beforeShowDay:_.bind(this.getDayDescription,this)})},hi.prototype.onApplyBindings=function(){this.$calendarGrid=e(this.calendarGridDom()),this.$datePicker=e(this.datePickerDom()),this.isPublic||this.initUploader()},hi.prototype.onShow=function(){this.initialized()||(this.initDatePicker(),this.applyCalendarSettings(),this.highlightWeekInDayPicker(),this.initialized(!0)),Ci.CalendarCache?(Ci.CalendarCache.calendarSettingsChanged()||Ci.CalendarCache.calendarChanged())&&(Ci.CalendarCache.calendarSettingsChanged()&&this.applyCalendarSettings(),Ci.CalendarCache.calendarSettingsChanged(!1),Ci.CalendarCache.calendarChanged(!1),this.getCalendars()):this.isPublic&&this.$calendarGrid.fullCalendar("render"),this.refetchEvents()},hi.prototype.setTimeline=function(){var t=(this.$calendarGrid.fullCalendar("getView"),new Date),i=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=new Date(this.todayDate.getFullYear(),this.todayDate.getMonth(),this.todayDate.getDate()),o=null,n=null,r=0,a=0,l=0;i>s&&(this.execCommand("today"),this.todayDate=this.$calendarGrid.fullCalendar("getDate").toDate(),this.$calendarGrid.fullCalendar("render")),o=e(".fc-slats:visible").parent(),n=o.children(".timeline"),0===n.length&&(n=e("<hr>").addClass("timeline"),o.prepend(n)),n.css("left",e("td .fc-axis").width()+10),n.show(),r=60*t.getHours()*60+60*t.getMinutes()+t.getSeconds(),a=r/86400,l=Math.floor(o.height()*a),n.css("top",l+"px")},hi.prototype.viewRenderCallback=function(i){var s,o=null,n="01/01/1971 ";this.changeDate(),this.loaded||this.initResizing(),"undefined"!=typeof s&&t.clearInterval(s),s=t.setInterval(_.bind(function(){this.setTimeline()},this),6e4);try{this.setTimeline()}catch(r){}"month"!==i.name&&Ti.User.CalendarShowWorkDay&&e(".fc-slats tr").each(function(){e("tr .fc-time span").each(function(){var t=e(this).eq(0).text(),i=""!==t?Date.parse(n+t):o,s=Date.parse(n+Ti.User.CalendarWorkDayStarts+":00"),r=Date.parse(n+Ti.User.CalendarWorkDayEnds+":00");o=i,(s>i||i>=r)&&(e(this).parent().parent().addClass("fc-non-working-time"),e(this).parent().parent().next().addClass("fc-non-working-time"))})}),this.activateCustomScrollInDayAndWeekView()},hi.prototype.collectBusyDays=function(){var e=[],t=null,i=null,s=0,o=0;_.each(this.calendars.getEvents(),function(n){for(t=moment(n.start),i=n.end?moment(n.end):null,n.allDay&&i&&i.subtract(1,"days"),s=i?i.diff(t,"days"):0,o=0;s>=o;o++)e.push(t.clone().add("days",o).toDate())},this),this.busyDays(e)},hi.prototype.refreshDatePicker=function(){var e=this;_.defer(function(){e.collectBusyDays(),e.$datePicker.datepicker("refresh"),e.highlightWeekInDayPicker()})},hi.prototype.getDayDescription=function(e){var t=!0,i=_.find(this.busyDays(),function(t){return t.getDate()===e.getDate()&&t.getMonth()===e.getMonth()&&t.getYear()===e.getYear()},this),s=i?"day_with_events":"",o="";return[t,s,o]},hi.prototype.initResizing=function(){var i=_.throttle(_.bind(this.resize,this),50);e(t).bind("resize",function(e){(e.target===this||Ci.browser.ie8AndBelow)&&i()}),i()},hi.prototype.resize=function(){var e=this.$calendarGrid.parent();e&&this.$calendarGrid.fullCalendar("option","height",e.height()),this.dayNamesResize()},hi.prototype.dayNamesResize=function(){if("month"===this.selectedView()){var t=e("div.weekday-header-item"),i=e("tr.fc-first td.fc-day"),s=e(i[0]).width(),o=0;if(7===t.length&&7===i.length&&0!==s)for(;7>o;o++)e(t[o]).width(s)}},hi.prototype.changeMonthYearFromDatePicker=function(e,t){if(this.changeFullCalendarDate){var i=this.$calendarGrid.fullCalendar("getDate");i.month(t-1).year(e),this.$calendarGrid.fullCalendar("gotoDate",i)}},hi.prototype.selectDateFromDatePicker=function(e){var t=this.getFCObject().moment(e);this.$calendarGrid.fullCalendar("gotoDate",t),_.defer(_.bind(this.highlightWeekInDayPicker,this))},hi.prototype.highlightWeekInDayPicker=function(){var e=this.$datePicker.find("td.ui-datepicker-current-day"),t=e.parent(),i=this.$datePicker.find("table.ui-datepicker-calendar"),s=this.$calendarGrid.fullCalendar("getView");switch(s.name){case"agendaDay":i.addClass("highlight_day").removeClass("highlight_week");break;case"agendaWeek":i.removeClass("highlight_day").addClass("highlight_week");break;default:i.removeClass("highlight_day").removeClass("highlight_week")}t.addClass("current_week")},hi.prototype.changeDateTitle=function(){var e=this.$calendarGrid.fullCalendar("getDate"),t=this.$calendarGrid.fullCalendar("getView"),i=e.format("MMMM YYYY"),s=t.intervalStart,o=t.intervalEnd?t.intervalEnd.add("days",-1):null;switch(t.name){case"agendaDay":i=e.format("MMMM D, YYYY");break;case"agendaWeek":s&&o&&(i=s.format("MMMM D, YYYY")+" - "+o.format("MMMM D, YYYY"))}this.dateTitle(i)},hi.prototype.changeDate=function(){this.changeDateInDatePicker(),this.changeDateTitle(),this.getTimeLimits(),this.getCalendars()},hi.prototype.changeDateInDatePicker=function(){var e=this.$calendarGrid.fullCalendar("getDate");this.changeFullCalendarDate=!1,this.$datePicker.datepicker("setDate",e.local().toDate()),this.changeFullCalendarDate=!0,this.highlightWeekInDayPicker()},hi.prototype.activateCustomScrollInDayAndWeekView=function(){if(!Ri){var t=this.$calendarGrid.fullCalendar("getView"),s="month"===t.name?"day":"time",o=e(".fc-"+s+"-grid-container"),n=e("<div></div>");o.parent().append(n),o.appendTo(n),n.hasClass("scroll-wrap")||(n.attr("data-bind","customScrollbar: {x: false, y: true}"),o.css({overflow:"hidden"}).addClass("scroll-inner"),i.applyBindings({},n[0]))}},hi.prototype.execCommand=function(e,t){t?this.$calendarGrid.fullCalendar(e,t):this.$calendarGrid.fullCalendar(e)},hi.prototype.displayToday=function(){this.execCommand("today")},hi.prototype.displayPrev=function(){this.execCommand("prev")},hi.prototype.displayNext=function(){this.execCommand("next")},hi.prototype.changeView=function(e){this.selectedView(e),this.$calendarGrid.fullCalendar("changeView",e)},hi.prototype.setAutoReloadTimer=function(){var e=this;clearTimeout(this.iAutoReloadTimer),Ti.User.AutoCheckMailInterval>0&&(this.iAutoReloadTimer=setTimeout(function(){e.getCalendars()},60*Ti.User.AutoCheckMailInterval*1e3))},hi.prototype.reloadAll=function(){this.needsToReload=!0,this.getCalendars()},hi.prototype.getTimeLimits=function(){var e=this.getDateFromCurrentView("start"),t=this.getDateFromCurrentView("end");this.startDateTime=e,this.endDateTime=t,this.needsToReload=!0},hi.prototype.getCalendars=function(){this.checkStarted(!0),this.setCalendarGridVisibility(),Ci.Ajax.abortRequestByActionName("CalendarList"),Ci.Ajax.sendExt({Action:"CalendarList",IsPublic:this.isPublic?1:0,PublicCalendarId:this.publicCalendarId},this.onCalendarsResponse,this)},hi.prototype.onCalendarsResponse=function(e){var t=[],i=[],s=null,o=null;e.Result?(this.loaded=!0,e.Result=_.sortBy(e.Result,function(e){return!e.isDefault}),_.each(e.Result,function(e){s=this.calendars.parseCalendar(e),t.push(s.id),o=this.calendars.getCalendarById(s.id),(!o||s&&o&&o.cTag!==s.cTag)&&(s=this.calendars.parseAndAddCalendar(e),s&&(this.isPublic&&(Ci.setTitle(s.name()),this.publicCalendarName(s.name())),i.push(s.id)))},this),0===this.calendars.count()&&this.isPublic&&this.needsToReload&&(Ci.setTitle(Si.i18n("CALENDAR/NO_CALENDAR_FOUND")),Ci.Api.showErrorByCode(0,Si.i18n("CALENDAR/NO_CALENDAR_FOUND"))),this.needsToReload=!1,this.calendars.expunge(t),_.each(t,function(e){s=this.calendars.getCalendarById(e),s&&s.eventsCount()>0&&s.reloadEvents()},this),this.getEvents(t)):(this.setCalendarGridVisibility(),this.checkStarted(!1))},hi.prototype.getEvents=function(e){e.length>0?(Ci.Ajax.abortRequestByActionName("EventList"),Ci.Ajax.sendExt({Action:"EventList",CalendarIds:JSON.stringify(e),Start:this.startDateTime,End:this.endDateTime,IsPublic:this.isPublic?1:0,TimezoneOffset:moment().zone(),Timezone:t.jstz?t.jstz.determine().name():""},this.onEventsResponse,this)):(this.setAutoReloadTimer(),this.checkStarted(!1))},hi.prototype.onEventsResponse=function(e,t){var i=null,s=t.CalendarIds?JSON.parse(t.CalendarIds):[],o=[];e.Result&&(_.each(e.Result,function(e){if(i=this.calendars.getCalendarById(e.calendarId)){o.push(e.id);var t=i.eventExists(e.id);Si.isUnd(t)?i.addEvent(e):t.lastModified!==e.lastModified&&i.updateEvent(e)}},this),_.each(s,function(e){i=this.calendars.getCalendarById(e),i&&i.eventsCount()>0&&i.active()&&i.expungeEvents(o,this.startDateTime,this.endDateTime) },this),this.refreshView()),this.setAutoReloadTimer(),this.checkStarted(!1)},hi.prototype.setCalendarGridVisibility=function(){this.$calendarGrid.css("visibility","").find(".fc-view div").first().css("visibility","")},hi.prototype.getUnusedColor=function(){var e=_.difference(this.colors,this.calendars.getColors());return e.length>0?e[0]:this.colors[0]},hi.prototype.openCreateCalendarForm=function(){if(!this.isPublic){var e=new pt;e.color(this.getUnusedColor()),Ci.Screens.showPopup(L,[_.bind(this.createCalendar,this),this.colors,e])}},hi.prototype.createCalendar=function(e,t,i){this.isPublic||Ci.Ajax.send({Name:e,Description:t,Color:i,Action:"CalendarCreate"},this.onCalendarCreateResponse,this)},hi.prototype.onCalendarCreateResponse=function(e){e.Result&&(this.calendars.parseAndAddCalendar(e.Result),this.calendars.sort())},hi.prototype.openImportCalendarForm=function(e){this.isPublic||Ci.Screens.showPopup(O,[_.bind(this.reloadAll,this),e])},hi.prototype.openUpdateCalendarForm=function(e){this.isPublic||Ci.Screens.showPopup(L,[_.bind(this.updateCalendar,this),this.colors,e])},hi.prototype.updateCalendar=function(e,t,i,s){this.isPublic||Ci.Ajax.send({Name:e,Description:t,Color:i,Id:s,Action:"CalendarUpdate"},this.onCalendarUpdateResponse,this)},hi.prototype.onCalendarUpdateResponse=function(e,t){var i=null;e.Result&&(i=this.calendars.getCalendarById(t.Id),i&&(i.name(t.Name),i.description(t.Description),i.color(t.Color),this.refetchEvents()))},hi.prototype.updateCalendarColor=function(e,t){this.isPublic||Ci.Ajax.send({Color:e,Id:t,Action:"CalendarUpdateColor"},this.onCalendarUpdateColorResponse,this)},hi.prototype.onCalendarUpdateColorResponse=function(e,t){if(e.Result){var i=this.calendars.getCalendarById(t.Id);i&&(i.color(t.Color),this.refetchEvents())}},hi.prototype.openGetLinkCalendarForm=function(e){this.isPublic||Ci.Screens.showPopup(U,[_.bind(this.publicCalendar,this),e])},hi.prototype.openShareCalendarForm=function(e){this.isPublic||Ci.Screens.showPopup(x,[_.bind(this.shareCalendar,this),e])},hi.prototype.shareCalendar=function(e,t,i,s,o){this.isPublic||Ci.Ajax.send({Action:"CalendarShareUpdate",Id:e,IsPublic:t?1:0,Shares:JSON.stringify(i),ShareToAll:s?1:0,ShareToAllAccess:o},this.onCalendarShareUpdateResponse,this)},hi.prototype.onCalendarShareUpdateResponse=function(e,t){if(e.Result){var i=this.calendars.getCalendarById(t.Id);i&&(i.shares(JSON.parse(t.Shares)),1===t.ShareToAll?(i.isShared(!0),i.isSharedToAll(!0),i.sharedToAllAccess=t.ShareToAllAccess):i.isSharedToAll(!1))}},hi.prototype.publicCalendar=function(e,t){this.isPublic||Ci.Ajax.send({Action:"CalendarPublicUpdate",Id:e,IsPublic:t?1:0},this.onCalendarPublicUpdateResponse,this)},hi.prototype.onCalendarPublicUpdateResponse=function(e,t){if(e.Result){var i=this.calendars.getCalendarById(t.Id);i&&i.isPublic(t.IsPublic)}},hi.prototype.deleteCalendar=function(e){var t=this.calendars.getCalendarById(e),i=t?Si.i18n("CALENDAR/CONFIRM_REMOVE_CALENDAR",{CALENDARNAME:t.name()}):"",s=_.bind(function(t){t&&Ci.Ajax.send({Id:e,Action:"CalendarDelete"},this.onCalendarDeleteResponse,this)},this);!this.isPublic&&t&&Ci.Screens.showPopup(C,[i,s])},hi.prototype.onCalendarDeleteResponse=function(e,t){if(e.Result){var i=this.calendars.getCalendarById(t.Id);i&&!i.isDefault&&(this.calendars.currentCal().id===i.id&&this.calendars.currentCal(null),this.calendars.removeCalendar(i.id),this.refetchEvents())}},hi.prototype.onEventDragStart=function(){this.dragEventTrigger=!0,this.refreshDatePicker()},hi.prototype.onEventDragStop=function(){var e=this;this.dragEventTrigger=!1,this.delayOnEventResult&&this.delayOnEventResultData&&0<this.delayOnEventResultData.length?(this.delayOnEventResult=!1,_.each(this.delayOnEventResultData,function(t){e.onEventActionResponse(t[0],t[1],!1)}),this.delayOnEventResultData=[],this.refreshView()):this.refreshDatePicker()},hi.prototype.onEventResizeStart=function(){this.dragEventTrigger=!0},hi.prototype.onEventResizeStop=function(){var e=this;this.dragEventTrigger=!1,this.delayOnEventResult&&this.delayOnEventResultData&&0<this.delayOnEventResultData.length?(this.delayOnEventResult=!1,_.each(this.delayOnEventResultData,function(t){e.onEventActionResponse(t[0],t[1],!1)}),this.delayOnEventResultData=[],this.refreshView()):this.refreshDatePicker()},hi.prototype.createEventInCurrentCalendar=function(){this.createEventToday(this.calendars.currentCal())},hi.prototype.createEventInCalendar=function(e){this.createEventToday(this.calendars.getCalendarById(e))},hi.prototype.createEventToday=function(e){var t=this.getFCObject().moment();t.minutes()>30?t.add("minutes",60-t.minutes()):t.minutes(30),t.seconds(0).milliseconds(0),this.openEventPopup(e,t,t.clone().add("minutes",30),!1)},hi.prototype.getParamsFromEventData=function(e){return{id:e.id,uid:e.uid,calendarId:e.calendarId,newCalendarId:Si.isUnd(e.newCalendarId)?e.calendarId:e.newCalendarId,subject:e.subject,allDay:e.allDay?1:0,location:e.location,description:e.description,alarms:e.alarms?JSON.stringify(e.alarms):"[]",attendees:e.attendees?JSON.stringify(e.attendees):"[]",owner:e.owner,recurrenceId:e.recurrenceId,excluded:e.excluded,allEvents:e.allEvents,modified:e.modified?1:0,start:e.start.local().toDate(),end:e.end.local().toDate(),startTS:e.start.unix(),endTS:(e.end,e.end.unix()),rrule:e.rrule?JSON.stringify(e.rrule):null}},hi.prototype.getEventDataFromParams=function(e){var t=e;return t.alarms=e.alarms?JSON.parse(e.alarms):[],t.attendees=e.attendees?JSON.parse(e.attendees):[],e.rrule&&(t.rrule=JSON.parse(e.rrule)),t},hi.prototype.createEventFromGrid=function(e,t){var i=!e.hasTime();this.openEventPopup(this.calendars.currentCal(),e.local(),t.local(),i)},hi.prototype.openEventPopup=function(e,t,i,s){this.isPublic||Ci.Screens.showPopup(H,[{CallbackSave:_.bind(this.createEvent,this),CallbackDelete:_.bind(this.deleteEvent,this),FCMoment:this.getFCObject().moment,Calendars:this.calendars,SelectedCalendar:e.id,Start:t,End:i,AllDay:s,TimeFormat:this.timeFormat,DateFormat:this.dateFormat,CallbackAttendeeActionDecline:_.bind(this.attendeeActionDecline,this)}])},hi.prototype.createEvent=function(e){var t=this.getParamsFromEventData(e);this.isPublic||(t.calendarId=e.newCalendarId,t.selectStart=this.getDateFromCurrentView("start"),t.selectEnd=this.getDateFromCurrentView("end"),t.Action="EventCreate",Ci.Ajax.send(t,this.onEventActionResponseWithSubThrottle,this))},hi.prototype.eventClickCallback=function(e){var t=_.bind(function(t){var i={ID:e.id,Uid:e.uid,RecurrenceId:e.recurrenceId,Calendars:this.calendars,SelectedCalendar:e.calendarId,AllDay:e.allDay,Location:e.location,Description:e.description,Subject:e.subject,Alarms:e.alarms,Attendees:e.attendees,RRule:e.rrule?e.rrule:null,Excluded:e.excluded?e.excluded:!1,Owner:e.owner,Appointment:e.appointment,OwnerName:e.ownerName,TimeFormat:this.timeFormat,DateFormat:this.dateFormat,AllEvents:t,CallbackSave:_.bind(this.updateEvent,this),CallbackDelete:_.bind(this.deleteEvent,this),CallbackAttendeeActionDecline:_.bind(this.attendeeActionDecline,this)};t!==vi.CalendarEditRecurrenceEvent.None&&(t===vi.CalendarEditRecurrenceEvent.AllEvents&&e.rrule?(i.Start=moment.unix(e.rrule.startBase),i.End=moment.unix(e.rrule.endBase)):(i.Start=e.start.clone(),i.Start=i.Start.local(),i.End=e.end.clone(),i.End=i.End.local()),Ci.Screens.showPopup(H,[i]))},this);e.rrule?e.excluded?t(vi.CalendarEditRecurrenceEvent.OnlyThisInstance):Ci.Screens.showPopup(G,[t]):t(vi.CalendarEditRecurrenceEvent.AllEvents)},hi.prototype.eventAction=function(e,t,i){var s=this.calendars.getCalendarById(t.calendarId);s.access()===vi.CalendarAccess.Read?i&&i():this.isPublic||(i&&(this.revertFunction=i),t.Action=e,Ci.Ajax.send(t,this.onEventActionResponseWithSubThrottle,this))},hi.prototype.updateEvent=function(e){var t=this.getParamsFromEventData(e);t.selectStart=this.getDateFromCurrentView("start"),t.selectEnd=this.getDateFromCurrentView("end"),e.modified&&(this.calendars.setDefault(e.newCalendarId),this.eventAction("EventUpdate",t))},hi.prototype.moveEvent=function(e,t,i){var s=this.getParamsFromEventData(e);s.selectStart=this.getDateFromCurrentView("start"),s.selectEnd=this.getDateFromCurrentView("end"),this.isPublic||(s.rrule?i(!1):(s.allEvents=vi.CalendarEditRecurrenceEvent.AllEvents,this.eventAction("EventUpdate",s,i)))},hi.prototype.resizeEvent=function(e,t,i){var s=this.getParamsFromEventData(e),o=_.bind(function(e){e!==vi.CalendarEditRecurrenceEvent.None?(s.allEvents=e,this.eventAction("EventUpdate",s,i)):i()},this);s.selectStart=this.getDateFromCurrentView("start"),s.selectEnd=this.getDateFromCurrentView("end"),e.rrule?s.excluded?o(vi.CalendarEditRecurrenceEvent.OnlyThisInstance):Ci.Screens.showPopup(G,[o]):o(vi.CalendarEditRecurrenceEvent.AllEvents)},hi.prototype.deleteEvent=function(e){this.eventAction("EventDelete",this.getParamsFromEventData(e))},hi.prototype.onEventActionResponseWithSubThrottle=function(e,t){this.dragEventTrigger?(this.delayOnEventResult=!0,this.delayOnEventResultData.push([e,t])):this.onEventActionResponse(e,t)},hi.prototype.onEventActionResponse=function(t,i,s){var o=this.calendars.getCalendarById(i.calendarId),n=null,r=null;s=Si.isUnd(s)?!0:!!s,t&&t.Result&&!Si.isUnd(o)?"EventCreate"===i.Action||"EventUpdate"===i.Action?(this.customscrollTop(parseInt(e(".calendar .scroll-inner").scrollTop(),10)),r=o.getEvent(i.id),(Si.isUnd(r)||Si.isUnd(r.rrule))&&!i.rrule||i.allEvents!==vi.CalendarEditRecurrenceEvent.AllEvents?o.removeEvent(i.id):o.removeEventByUid(i.uid,!0),i.newCalendarId&&i.newCalendarId!==i.calendarId&&(o=this.calendars.getCalendarById(i.newCalendarId)),_.each(t.Result.Events,function(e){o.addEvent(e)},this),o.cTag=t.Result.CTag,o.active()||o.active(!0),s&&this.refreshView(),this.customscrollTop.valueHasMutated(),this.calendars.currentCal(o)):"EventDelete"===i.Action?(o.cTag=t.Result,i.allEvents===vi.CalendarEditRecurrenceEvent.OnlyThisInstance?o.removeEvent(i.id):o.removeEventByUid(i.uid),s&&this.refreshView()):"EventBase"===i.Action&&(n=t.Result,Ci.Screens.showPopup(H,[{CallbackSave:_.bind(this.updateEvent,this),CallbackDelete:_.bind(this.deleteEvent,this),ID:n.id,Uid:n.uid,RecurrenceId:n.recurrenceId,Calendars:this.calendars,SelectedCalendar:n.calendarId,Start:moment(1e3*n.start),End:moment(1e3*n.end),AllDay:n.allDay,Location:n.location,Description:n.description,Subject:n.subject,Alarms:n.alarms,Attendees:n.attendees,RRule:n.rrule?n.rrule:null,Excluded:n.excluded?n.excluded:!1,Owner:n.owner,Appointment:n.appointment,TimeFormat:this.timeFormat,DateFormat:this.dateFormat,AllEvents:vi.CalendarEditRecurrenceEvent.AllEvents}])):"EventUpdate"!==i.Action||t.Result||1155!==Si.pInt(t.ErrorCode)?this.revertFunction&&this.revertFunction():this.revertFunction=null,this.revertFunction=null},hi.prototype.attendeeActionDecline=function(e,t){e.removeEvent(t),this.refreshView()},hi.prototype.refetchEvents=function(){this.$calendarGrid.fullCalendar("refetchEvents")},hi.prototype.refreshViewSingle=function(){this.refetchEvents(),this.refreshDatePicker()},hi.prototype.refreshView=function(){},hi.prototype.onDrop=function(e,t,i){var s=_.filter(this.calendars.collection(),function(e){return e.isEditable()});s.length>1?Ci.Screens.showPopup(B,[{CallbackSave:_.bind(this.uploadToSelectedCalendar,this),ProceedUploading:i,Calendars:this.calendars,EditableCalendars:s,DefaultCalendarId:this.defaultCalendarId()}]):this.uploadToSelectedCalendar(this.defaultCalendarId(),i)},hi.prototype.onUploadComplete=function(){this.reloadAll()},hi.prototype.initUploader=function(){var e=this;this.uploaderArea()&&(this.oJua=new Jua({action:"?/Upload/Calendars/",name:"jua-uploader",queueSize:2,dragAndDropElement:this.uploaderArea(),disableAjaxUpload:!1,disableFolderDragAndDrop:!1,disableDragAndDrop:!1,disableAutoUploadOnDrop:!0,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()},AdditionalData:function(){return JSON.stringify({CalendarID:e.uploadCalendarId()})}}}),this.oJua.on("onDrop",_.bind(this.onDrop,this)).on("onBodyDragEnter",_.bind(this.bDragActive,this,!0)).on("onBodyDragLeave",_.bind(this.bDragActive,this,!1)).on("onComplete",_.bind(this.onUploadComplete,this)))},hi.prototype.uploadToSelectedCalendar=function(e,t){this.uploadCalendarId(e),this.checkStarted(!0),t()},ci.prototype.__name="CFileStorageViewModel",ci.prototype.onApplyBindings=function(t){this.selector.initOnApplyBindings(".items_sub_list .item",".items_sub_list .selected.item",".items_sub_list .item .custom_checkbox",e(".panel.files .items_list",t),e(".panel.files .items_list .files_scroll.scroll-inner",t)),this.initUploader(),this.hotKeysBind()},ci.prototype.hotKeysBind=function(){var t=Ci.Screens.currentScreen()===vi.Screens.FileStorage;e(document).on("keydown",_.bind(function(e){t&&e&&e.keyCode===vi.Key.s&&this.selector.useKeyboardKeys()&&!Si.isTextFieldFocused()&&(e.preventDefault(),this.isSearchFocused(!0))},this))},ci.prototype.initUploader=function(){var e=this;this.uploaderButton()&&this.uploaderArea()&&(this.oJua=new Jua({action:"?/Upload/File/",name:"jua-uploader",queueSize:2,clickElement:this.uploaderButton(),dragAndDropElement:this.uploaderArea(),disableAjaxUpload:this.isPublic?!0:!1,disableFolderDragAndDrop:this.isPublic?!0:!1,disableDragAndDrop:this.isPublic?!0:!1,hidden:{Token:function(){return Ti.Token},AccountID:function(){return Ti.Accounts.currentId()},AdditionalData:function(t){return JSON.stringify({Type:e.storageType(),SubPath:t&&!Si.isUnd(t.Folder)?t.Folder:"",Path:e.dropPath()})}}}),this.oJua.on("onProgress",_.bind(this.onFileUploadProgress,this)).on("onSelect",_.bind(this.onFileUploadSelect,this)).on("onStart",_.bind(this.onFileUploadStart,this)).on("onDrop",_.bind(this.onDrop,this)).on("onComplete",_.bind(this.onFileUploadComplete,this)).on("onBodyDragEnter",_.bind(this.bDragActive,this,!0)).on("onBodyDragLeave",_.bind(this.bDragActive,this,!1)))},ci.prototype.onFileUploadSelect=function(e,t){if(Ti.App.FileSizeLimit>0&&t.Size/1048576>Ti.App.FileSizeLimit)return Ci.Screens.showPopup(A,[Si.i18n("FILESTORAGE/ERROR_SIZE_LIMIT",{SIZE:Ti.App.FileSizeLimit})]),!1;if(""===this.searchPattern()){var i=new mt,s=t.FileName,o=Si.getFileExtension(s),n=Si.getFileNameWithoutExtension(s),r=0,a=Ti.Accounts.getDefault();for(""!==o&&(o="."+o);!Si.isUnd(this.getFileByName(s));)s=n+"_"+r+o,r++;i.onUploadSelectOwn(e,t,s,a.email(),this.path(),this.storageType()),this.uploadingFiles.push(i)}},ci.prototype.onFileUploadStart=function(e){var t=this.getUploadFileByUid(e);t&&t.onUploadStart()},ci.prototype.onFileUploadProgress=function(e,t,i){if(""===this.searchPattern()){var s=this.getUploadFileByUid(e);s&&s.onUploadProgress(t,i)}},ci.prototype.onFileUploadComplete=function(e,t,i){if(""===this.searchPattern()){var s=this.getUploadFileByUid(e);s&&(s.onUploadComplete(e,t,i),this.deleteUploadFileByUid(e),s.uploadError()?(this.uploadError(!0),Ci.Api.showError(s.statusText())):(this.files.push(s),0===this.uploadingFiles().length&&Ci.Api.showReport(Si.i18n("COMPOSE/UPLOAD_COMPLETE")))),this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()),this.searchPattern(),!1)}},ci.prototype.onDrop=function(e,t){if(!this.isPublic)if(t&&t.target&&""===this.searchPattern()){var s=i.dataFor(t.target);s&&s instanceof mt&&s.isFolder()&&this.dropPath(s.fullPath())}else Ci.Api.showReport(Si.i18n("FILESTORAGE/INFO_CANNOT_UPLOAD_SEARCH_RESULT"))},ci.prototype.filesDrop=function(e,t,i){if(!this.isPublic&&e&&t){var s=this,o="",n=e.fullPath(),r=t.ctrlKey?"FilesCopy":"FilesMove",a=[],l=[];(this.path()!==n&&this.storageType()===e.storageType()||this.storageType()!==e.storageType())&&(e.recivedAnim(!0),Si.uiDropHelperAnim(t,i),a=this.selector.listCheckedAndSelected(),l=_.map(a,function(e){return t.ctrlKey||(e.isFolder()?s.deleteFolderByName(e.fileName()):s.deleteFileByName(e.id())),o=e.path(),{Name:e.id(),IsFolder:e.isFolder()}}),Ci.Ajax.send({Action:r,FromType:this.storageType(),ToType:e.storageType(),FromPath:o,ToPath:n,Files:JSON.stringify(l)},this.onFilesMoveResponse,this))}},ci.prototype.onFilesMoveResponse=function(){this.getQuota(this.storageType())},ci.prototype.dragAndDropHelper=function(t){t&&t.checked(!0);var i=Si.draggableMessages(),s=this.selector.listCheckedAndSelected(),o=s.length,n=0,r=0,a="";return _.each(s,function(e){e.isFolder()?r++:n++},this),0!==n&&0!==r?a=Si.i18n("FILESTORAGE/DRAG_ITEMS_TEXT_PLURAL",{COUNT:o},null,o):0===n?a=Si.i18n("FILESTORAGE/DRAG_FOLDERS_TEXT_PLURAL",{COUNT:r},null,r):0===r&&(a=Si.i18n("FILESTORAGE/DRAG_TEXT_PLURAL",{COUNT:n},null,n)),e(".count-text",i).text(a),i},ci.prototype.onItemDelete=function(){this.executeDelete()},ci.prototype.onEnter=function(e){this.onItemDblClick(e)},ci.prototype.onItemDblClick=function(e){e&&(e.isFolder()?this.getFiles(this.storageType(),e):e.isViewable()?e.viewFile():e.downloadFile())},ci.prototype.onFilesResponse=function(e,t){if(e.Result){var i=[],s=[],o=Date.now().toString();e.Result.Quota&&(this.quota(e.Result.Quota[0]+e.Result.Quota[1]),this.used(e.Result.Quota[0])),_.each(e.Result.Items,function(e){var t=(new mt).allowDrag(!0).allowSelect(!0).allowCheck(!0).allowDelete(!0).allowUpload(!0).allowSharing(!0).allowHeader(!0).allowDownload(!1).isPopupItem(this.isPopup);t.parse(e,this.publicHash),t.getInThumbQueue(o),t.isFolder()?i.push(t):s.push(t)},this),(this.isPublic||t.Type===this.storageType())&&(this.folders(i),this.files(s)),this.loading(!1),this.loadedFiles(!0),clearTimeout(this.timerId)}},ci.prototype.onQuotaResponse=function(e){e.Result&&e.Result.Quota&&(this.quota(e.Result.Quota[0]+e.Result.Quota[1]),this.used(e.Result.Quota[0]))},ci.prototype.onFilesDeleteResponse=function(e){e.Result?this.expungeFileItems():this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()),this.searchPattern())},ci.prototype.executeRename=function(){var e=this.selector.listCheckedAndSelected();!this.isPublic&&e[0]&&Ci.Screens.showPopup(D,[e[0],_.bind(this.renameItem,this)])},ci.prototype.executeDownload=function(){var e=this.selector.listCheckedAndSelected();e[0]&&!e[0].isFolder()&&e[0].downloadFile()},ci.prototype.executeShare=function(){var e=this.selector.listCheckedAndSelected();!this.isPublic&&e[0]&&Ci.Screens.showPopup(N,[e[0]])},ci.prototype.executeSend=function(){var e=this.selector.listCheckedAndSelected(),t=_.filter(e,function(e){return!e.isFolder()},this);t.length>0&&Ci.Routing.goDirectly(Ci.Links.compose(),["file",t])},ci.prototype.onShareIconClick=function(e){e&&Ci.Screens.showPopup(N,[e])},ci.prototype.renameItem=function(e){var t=Si.trim(e.nameForEdit());return Si.validateFileOrFolderName(t)?(Ci.Ajax.send({Action:"FilesRename",Type:this.storageType(),Path:e.path(),Name:e.id(),NewName:t},this.onFilesRenameResponse,this),""):Si.i18n(e.isFolder()?"FILESTORAGE/INVALID_FOLDER_NAME":"FILESTORAGE/INVALID_FILE_NAME")},ci.prototype.onFilesRenameResponse=function(){this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()),this.searchPattern())},ci.prototype.executeDelete=function(){var e=this.selector.listCheckedAndSelected();!this.isPublic&&e&&e.length>0&&Ci.Screens.showPopup(C,[Si.i18n("FILESTORAGE/CONFIRMATION_DELETE"),_.bind(this.deleteItems,this,e)])},ci.prototype.onShow=function(){this.loaded(!0),this.getStorages(),this.selector.useKeyboardKeys(!0),this.oJua&&this.oJua.setDragAndDropEnabledStatus(!0)},ci.prototype.onHide=function(){this.selector.useKeyboardKeys(!1),this.oJua&&this.oJua.setDragAndDropEnabledStatus(!1)},ci.prototype.getQuota=function(e){Ci.Ajax.send({Action:"FilesQuota",Type:e},this.onQuotaResponse,this)},ci.prototype.getStorageByType=function(e){return _.find(this.storages(),function(t){return t.storageType()===e})},ci.prototype.getStorages=function(){this.isPublic?this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex())):(this.getStorageByType(vi.FileStorageType.Personal)||this.storages.push((new mt).isFolder(!0).storageType(vi.FileStorageType.Personal).displayName(Si.i18n("FILESTORAGE/TAB_PERSONAL_FILES"))),this.IsCollaborationSupported&&(this.getStorageByType(vi.FileStorageType.Corporate)||this.storages.push((new mt).isFolder(!0).storageType(vi.FileStorageType.Corporate).displayName(Si.i18n("FILESTORAGE/TAB_CORPORATE_FILES"))),this.AllowFilesSharing&&(this.getStorageByType(vi.FileStorageType.Shared)||this.storages.push((new mt).isFolder(!0).storageType(vi.FileStorageType.Shared).displayName(Si.i18n("FILESTORAGE/TAB_SHARED_FILES"))))),this.isPopup?this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex())):this.getExternalFileStorages())},ci.prototype.getExternalFileStorages=function(){Ci.Ajax.send({Action:"ExternalFileStorages"},this.onExternalStoragesResponse,this)},ci.prototype.onExternalStoragesResponse=function(e){e.Result&&(_.each(e.Result,function(e){this.getStorageByType(e.Type)||this.storages.push((new mt).isExternal(!0).isFolder(!0).storageType(e.Type).displayName(e.DisplayName))},this),this.expungeExternalStorages(_.map(e.Result,function(e){return e.Type},this))),this.getStorageByType(this.storageType())||this.storageType(vi.FileStorageType.Personal),this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()))},ci.prototype.getFiles=function(e,t,i,s){var o=this,n=this.storageType(),r=this.iPathIndex(),a=(new mt).isFolder(!0).storageType(e);return this.isPublic?this.getFilesPub(t):(this.storageType(e),o.loadedFiles(!1),(Si.isUnd(s)||!Si.isUnd(s)&&s)&&(this.timerId=setTimeout(function(){o.loadedFiles()||(o.folders([]),o.files([]),o.loading(!0))},1500)),this.searchPattern(Si.isUnd(i)?"":Si.pString(i)),Si.isUnd(t)||""===t.id()?(this.pathItems.removeAll(),a.displayName(this.rootPath())):a=t,this.pathItems.push(a),this.iPathIndex(this.pathItems().length-1),(r!==this.iPathIndex()||n!==this.storageType())&&(this.folders([]),this.files([])),void Ci.Ajax.sendExt({Action:"Files",Type:e,Path:this.path(),Pattern:this.searchPattern()},this.onFilesResponse,this))},ci.prototype.getFilesPub=function(e){var t=this.iPathIndex(),i=(new mt).isFolder(!0);Si.isUnd(e)||""===e.id()?(this.pathItems.removeAll(),i.displayName(this.rootPath())):i=e,this.pathItems.push(i),this.iPathIndex(this.pathItems().length-1),t!==this.iPathIndex()&&(this.folders([]),this.files([])),Ci.Ajax.sendExt({Action:"FilesPub",Hash:Ti.FileStoragePubHash,Path:this.path()},this.onFilesResponse,this)},ci.prototype.deleteItems=function(e,t){if(t&&0<e.length){var i=_.map(e,function(e){return e.deleted(!0),{Path:e.path(),Name:e.id()}});Ci.Ajax.send({Action:"FilesDelete",Type:this.storageType(),Path:this.path(),Items:JSON.stringify(i)},this.onFilesDeleteResponse,this)}},ci.prototype.getPathItemByIndex=function(e){var t=this.pathItems()[e],i=(new mt).fileName(this.rootPath()).id("");return this.pathItems(this.pathItems().slice(0,e)),t&&!this.isPublic&&(i=t),i},ci.prototype.getFullPathByIndex=function(e){var t=_.map(this.pathItems().slice(0,e),function(e){return e.fileName()});return t.join("/")},ci.prototype.getFileByName=function(e){return _.find(this.files(),function(t){return t.id()===e})},ci.prototype.deleteFileByName=function(e){this.files(_.filter(this.files(),function(t){return t.id()!==e}))},ci.prototype.deleteFolderByName=function(e){this.folders(_.filter(this.folders(),function(t){return t.fileName()!==e}))},ci.prototype.expungeFileItems=function(){this.folders(_.filter(this.folders(),function(e){return!e.deleted()},this)),this.files(_.filter(this.files(),function(e){return!e.deleted()},this))},ci.prototype.expungeExternalStorages=function(e){this.storages(_.filter(this.storages(),function(t){return!t.isExternal()||_.include(e,t.storageType())},this))},ci.prototype.deleteStorageByType=function(e){this.storages(_.filter(this.storages(),function(t){return t.storageType()!==e}))},ci.prototype.getUploadFileByUid=function(e){return _.find(this.uploadingFiles(),function(t){return t.uploadUid()===e})},ci.prototype.deleteUploadFileByUid=function(e){this.uploadingFiles(_.filter(this.uploadingFiles(),function(t){return t.uploadUid()!==e}))},ci.prototype.getUploadingFiles=function(){var e=[],t=this.uploadingFiles(),i=this;return Si.isUnd(t)||(e=_.filter(t,function(e){return e.path()===i.path()&&e.storageType()===i.storageType()})),e},ci.prototype.onCancelUpload=function(e){this.oJua&&this.oJua.cancel(e),this.deleteUploadFileByUid(e)},ci.prototype.onCreateFolderResponse=function(){this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()))},ci.prototype.createFolder=function(e){return e=Si.trim(e),Si.validateFileOrFolderName(e)?(Ci.Ajax.send({Action:"FilesFolderCreate",Type:this.storageType(),Path:this.path(),FolderName:e},this.onCreateFolderResponse,this),""):Si.i18n("FILESTORAGE/INVALID_FOLDER_NAME")},ci.prototype.onCreateFolderClick=function(){Ci.Screens.showPopup(M,[_.bind(this.createFolder,this)])},ci.prototype.onCreateLinkResponse=function(){this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()))},ci.prototype.createLink=function(e){Ci.Ajax.send({Action:"FilesLinkCreate",Type:this.storageType(),Path:this.path(),Link:e.linkUrl(),Name:e.fileName()},this.onCreateLinkResponse,this)},ci.prototype.onCreateLinkClick=function(){var e=_.bind(this.createLink,this);Ci.Screens.showPopup(R,[e])},ci.prototype.onSearch=function(){this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()),this.searchPattern())},ci.prototype.clearSearch=function(){this.getFiles(this.storageType(),this.getPathItemByIndex(this.iPathIndex()))},ui.prototype.requestFromLogin=function(){Ci.Storage.getData("helpdeskQuestion")&&(this.newThreadText(Ci.Storage.getData("helpdeskQuestion")),Ci.Storage.setData("helpdeskQuestion"),this.executeThreadCreate())},ui.prototype.clearQuickReply=function(){this.replyText(""),this.replyTextFocus(!1),this.internalNote(!1),this.uploadedFiles([]),this.isQuickReplyActive(!1)},ui.prototype.onOwnerContactResponse=function(e){e?(this.ownerContact(e),this.ownerExistsInContacts(!0)):(this.ownerContact(new ct),this.ownerExistsInContacts(!1)),this.ownerContactInfoReceived(!0)},ui.prototype.updateOpenerWindow=function(){this.singleMode&&t.opener&&t.opener.App&&t.opener.App.updateHelpdesk()},ui.prototype.deletePost=function(e){if(e&&e.itsMe()){var t=this,i=function(i){i&&Ci.Ajax[t.ajaxSendFunc]({Action:"HelpdeskPostDelete",PostId:e.Id,ThreadId:e.IdThread,IsExt:t.bExtApp?1:0},t.onHelpdeskPostDeleteResponse,t)};Ci.Screens.showPopup(C,[Si.i18n("HELPDESK/CONFIRM_DELETE_THIS_POST"),i])}},ui.prototype.onHelpdeskPostDeleteResponse=function(e){e.Result===!1?Ci.Api.showErrorByCode(e,Si.i18n("HELPDESK/ERROR_COULDNT_DELETE_POST")):Ci.Api.showReport(Si.i18n("HELPDESK/REPORT_POST_HAS_BEEN_DELETED")),this.requestPosts(),this.updateOpenerWindow()},ui.prototype.addToContacts=function(){this.selectedItem()&&Ci.ContactsCache.addToContacts("",this.selectedItem().sEmail,this.onAddToContactsResponse,this)},ui.prototype.iHaveMoreToSay=function(){var e=this;this.isQuickReplyHidden(!1),_.delay(function(){e.replyTextFocus(!0)},300)},ui.prototype.onAddToContactsResponse=function(e,t){e.Result&&this.selectedItem()&&""!==t.HomeEmail&&t.HomeEmail===this.selectedItem().sEmail&&(Ci.Api.showReport(Si.i18n("CONTACTS/REPORT_CONTACT_SUCCESSFULLY_ADDED")),Ci.ContactsCache.clearInfoAboutEmail(this.selectedItem().sEmail),Ci.ContactsCache.getContactByEmail(this.selectedItem().sEmail,this.onOwnerContactResponse,this))},ui.prototype.scrollPostsToBottom=function(){this.scrollToBottomTrigger(!this.scrollToBottomTrigger())},ui.prototype.scrollPostsToTop=function(){this.scrollToTopTrigger(!this.scrollToTopTrigger())},ui.prototype.showClientDetails=function(){this.clientDetailsVisible(!0)},ui.prototype.hideClientDetails=function(){this.clientDetailsVisible(!1)},ui.prototype.startAutocheckmail=function(){var e=this,t=Ti&&Ti.User?Ti.User.AutoCheckMailInterval:1;t>0&&(clearTimeout(this.iAutoCheckTimer),this.iAutoCheckTimer=setTimeout(function(){e.checkCommand()},60*t*1e3))},ui.prototype.onApplyBindings=function(t){this.selector.initOnApplyBindings(".items_sub_list .item",".items_sub_list .selected.item",".items_sub_list .item .custom_checkbox",e(".items_list",t),e(".threads_scroll.scroll-inner",t)),this.initUploader(),e(this.domQuickReply()).on("click",_.bind(function(e){this.isQuickReplyActive(!0),e.stopPropagation()},this)),e(document.body).on("click",_.bind(function(){var e=Ci.Screens.currentScreen()===vi.Screens.Helpdesk;e&&this.isEmptyQuickReplyPane()&&this.isQuickReplyActive(!1)},this)),Ci.registerHelpdeskUpdateFunction&&Ci.registerHelpdeskUpdateFunction(_.bind(this.checkCommand,this)),this.startAutocheckmail(),this.hotKeysBind()},ui.prototype.onShow=function(){this.newThreadButtonWidth.notifySubscribers(),this.selector.useKeyboardKeys(!0),this.oPageSwitcher.show(),this.oPageSwitcher.perPage(this.ThreadsPerPage),this.oPageSwitcher.currentPage(1),this.requestThreadsList()},ui.prototype.onHide=function(){this.selector.useKeyboardKeys(!1),this.selectedItem(null),this.oPageSwitcher.hide()},ui.prototype.requestThreadsList=function(){this.loadingList(!0),this.checkStarted(!0),Ci.Ajax[this.ajaxSendFunc]({Action:"HelpdeskThreadsList",IsExt:this.bExtApp?1:0,Offset:(this.oPageSwitcher.currentPage()-1)*this.ThreadsPerPage,Limit:this.ThreadsPerPage,Filter:this.listFilter(),Search:this.search()},this.onHelpdeskThreadsListResponse,this)},ui.prototype.onHelpdeskThreadsListResponse=function(e){var t=0,i=0,s=this.selectedItem(),o=s?Si.pString(s.Id):"",n=[],r=null,a=null,l=e.Result&&_.isArray(e.Result.List)?e.Result.List:[];if(this.checkStarted(!1),e.Result===!1)Ci.Api.showErrorByCode(e);else{for(i=l.length;i>t;t++)l[t]&&"Object/CHelpdeskThread"===Si.pExport(l[t],"@Object","")&&(r=new ft,r.parse(l[t]),r.OwnerIsMe=Si.pString(r.IdOwner),o===Si.pString(r.Id)&&(s.postsCount(r.postsCount()),r.selected(!0),this.selector.itemSelected(r)),n.push(r));this.loadingList(!1),this.threads(n),Ci.helpdeskUnseenCount(_.filter(n,function(e){return e.unseen()},this).length),this.oPageSwitcher.setCount(Si.pInt(e.Result.ItemsCount)),Ti.HelpdeskThreadId&&(a=_.find(n,function(e){return e.Id===Ti.HelpdeskThreadId},this),a&&(a=a,this.onItemSelect(a)))}},ui.prototype.requestPosts=function(e,t){var i=this.selectedItem(),s=e?e.Id:i?i.Id:0,o=t?t:0,n={};s&&(n={Action:"HelpdeskThreadPosts",IsExt:this.bExtApp?1:0,ThreadId:s,StartFromId:o,Limit:5},o&&this.loadingMoreMessages(!0),Ci.Ajax[this.ajaxSendFunc](n,this.onHelpdeskThreadPostsResponse,this))},ui.prototype.onHelpdeskThreadPostsResponse=function(e){var t=this,i=!1,s=0,o=0,n=[],r=[],a=null,l="",h=e.Result&&_.isArray(e.Result.List)?e.Result.List:[];if(e.Result===!1)Ci.Api.showErrorByCode(e);else{if(this.selectedItem()&&e.Result.ThreadId===this.selectedItem().Id){for(this.selectedItem().postsCount(Si.pInt(e.Result.ItemsCount)),o=h.length;o>s;s++)h[s]&&"Object/CHelpdeskPost"===Si.pExport(h[s],"@Object","")&&(a=new bt,a.parse(h[s]),n.push(a));if(e.Result.StartFromId){for(r=this.posts(),l=e.Result.StartFromId,o=r.length,s=0;o>s&&r.Id!==l;s++);n=_.union(_.first(r,s).reverse(),n),this.loadingMoreMessages(!1)}else i=!0;this.selectedItem().unseen()&&this.executeThreadSeen(this.selectedItem().Id)}this.posts(n.reverse()),i?(t.scrollPostsToBottom(),_.delay(function(){t.scrollPostsToBottom()},10),_.delay(function(){t.scrollPostsToBottom()},100)):t.scrollPostsToTop()}},ui.prototype.onItemClick=function(e){this.selectedItem()&&this.selectedItem().ThreadHash===e.ThreadHash||(Ci.Routing.setHash([vi.Screens.Helpdesk,e.ThreadHash]),e.postsCount(0),this.posts([]))},ui.prototype.onRoute=function(e){var t=e[0],i=_.find(this.threads(),function(e){return e.ThreadHash===t});i?(i=i,this.onItemSelect(i)):0===this.threads().length&&this.loadingList()&&void 0===this.threadSubscription&&!Ti.SingleMode?this.threadSubscription=this.threads.subscribe(function(){this.onRoute(e),this.threadSubscription.dispose(),this.threadSubscription=void 0},this):t&&Ci.Ajax[this.ajaxSendFunc]({Action:"HelpdeskGetThreadByHash",IsExt:this.bExtApp?1:0,ThreadHash:t},this.onHelpdeskGetThreadByHashResponse,this)},ui.prototype.onHelpdeskGetThreadByHashResponse=function(e){var t=new ft;e.Result&&(t.parse(e.Result),t.OwnerIsMe=Si.pString(t.IdOwner),this.onItemSelect(t)) },ui.prototype.onItemSelect=function(e){if(this.visibleNewThread(!1),this.selector.listCheckedAndSelected(!1),this.selector.itemSelected(this.selectedItem()),null===this.selectedItem()||this.selectedItem().Id!==e.Id)if(this.uploadedFiles().length>0||this.replyText().length>0){var t=this.selectedItem(),i=Si.i18n("HELPDESK/CONFIRM_CANCEL_REPLY"),s=_.bind(function(i){i?(this.clearQuickReply(),this.selector.itemSelected(e),this.selectedItem(e),this.visibleNewThread(!1),this.isQuickReplyHidden(e.ItsMe||!this.bAgent),this.requestPosts(e),this.cleanAll()):(this.replyTextFocus(!0),this.isQuickReplyHidden(!1),this.selector.itemSelected(t),this.selectedItem(t),this.cleanAll())},this);Ci.Screens.showPopup(C,[i,s])}else this.clearQuickReply(),this.selector.itemSelected(e),this.selectedItem(e),this.isQuickReplyHidden(e.ItsMe||!this.bAgent),this.requestPosts(e)},ui.prototype.onItemDelete=function(){this.executeDelete()},ui.prototype.openNewThread=function(){if(this.uploadedFiles().length>0||this.replyText().length>0){var e=Si.i18n("HELPDESK/CONFIRM_CANCEL_REPLY"),t=_.bind(function(e){e?(this.clearQuickReply(),this.visibleNewThread(!0)):(this.visibleNewThread(!1),this.cleanAll())},this);Ci.Screens.showPopup(C,[e,t])}else this.selector.itemSelected(null),this.selectedItem(null),this.visibleNewThread(!0)},ui.prototype.cancelNewThread=function(){if(this.uploadedFiles().length>0||this.newThreadText().length>0){var e=Si.i18n("HELPDESK/CONFIRM_CANCEL_REPLY"),t=_.bind(function(e){e&&(this.newThreadText(""),this.uploadedFiles([]),this.visibleNewThread(!1))},this);Ci.Screens.showPopup(C,[e,t])}else this.newThreadText(""),this.uploadedFiles([]),this.visibleNewThread(!1),this.selector.itemSelected(null),this.selectedItem(null)},ui.prototype.onSearch=function(){this.requestThreadsList()},ui.prototype.clearSearch=function(){this.requestThreadsList()},ui.prototype.isEnableListActions=function(){return!!this.selectedItem()},ui.prototype.executeDelete=function(){var e=this,t=this.selectedItem();t&&(_.each(this.threads(),function(e){e===t&&e.deleted(!0)}),_.delay(function(){e.threads.remove(function(e){return e.deleted()})},500),this.selectedItem(null),Ci.Ajax[this.ajaxSendFunc]({Action:"HelpdeskThreadDelete",IsExt:this.bExtApp?1:0,ThreadId:t.Id},this.onHelpdeskThreadDeleteResponse,this),Ci.Routing.setHash([vi.Screens.Helpdesk,""]))},ui.prototype.executeOpenNewWindow=function(){var e=Ci.Routing.buildHashFromArray([vi.Screens.SingleHelpdesk,this.selectedItem().ThreadHash]);Si.WindowOpener.openTab(e)},ui.prototype.onHelpdeskThreadDeleteResponse=function(){this.requestThreadsList(),this.updateOpenerWindow()},ui.prototype.executeChangeState=function(e){var t=this.selectedItem();void 0!==e&&t&&(t.state(e),Ci.Ajax[this.ajaxSendFunc]({Action:"HelpdeskThreadChangeState",IsExt:this.bExtApp?1:0,ThreadId:t.Id,Type:t.state()},this.onHelpdeskThreadChangeStateResponse,this))},ui.prototype.onHelpdeskThreadChangeStateResponse=function(){this.requestThreadsList(),this.updateOpenerWindow()},ui.prototype.executeThreadPing=function(e){void 0!==e&&Ci.Ajax[this.ajaxSendFunc]({Action:"HelpdeskThreadPing",IsExt:this.bExtApp?1:0,ThreadId:e},this.onThreadPingResponse,this)},ui.prototype.onThreadPingResponse=function(e){this.watchers(_.map(e.Result,function(e){var t=e.length>0?e[0]:"",i=e.length>0?e[1]:"",s={name:t,email:i,text:"",initial:"",icon:""};return i.length>0&&t.length>0?(s.text='"'+t+'" <'+i+">",s.initial=/\s/g.test(t)?_.reduce(t.split(" ",2),function(e,t){return e+t.substr(0,1)},""):t.substr(0,2)):i.length>0&&(s.text=i,s.initial=i.substr(0,2)),s},this))},ui.prototype.executeThreadSeen=function(e){void 0!==e&&Ci.Ajax[this.ajaxSendFunc]({Action:"HelpdeskThreadSeen",IsExt:this.bExtApp?1:0,ThreadId:e},this.onHelpdeskThreadSeenResponse,this)},ui.prototype.onHelpdeskThreadSeenResponse=function(e,t){var i=0,s=0,o=[],n=0;if(t.ThreadId&&(o=this.threads(),n=this.selectedItem()?this.selectedItem().Id:0,n>0))for(s=o.length;s>i;i++)if(n===t.ThreadId){Ci.helpdeskUnseenCount(Ci.helpdeskUnseenCount()-1),this.selectedItem().unseen(!1);break}this.updateOpenerWindow()},ui.prototype.executeThreadCreate=function(){var e="",t=-1;e=Si.trim(this.newThreadText().replace(/[\n\r]/," ")),t=e.indexOf(" ",40),t>=0&&(e=e.substring(0,t)),this.newThreadCreating(!0),this.sendHelpdeskPostCreate(0,e,this.newThreadText(),this.onThreadCreateResponse)},ui.prototype.onThreadCreateResponse=function(e,t){this.newThreadCreating(!1),e.Result&&t&&(Ci.Api.showReport(Si.i18n("HELPDESK/REPORT_THREAD_SUCCESSFULLY_CREATED")),this.cleanAll(),this.posts([]),this.visibleNewThread(!1)),this.requestThreadsList(),this.updateOpenerWindow()},ui.prototype.executePostCreate=function(){this.selectedItem()&&(this.replySendingStarted(!0),this.sendHelpdeskPostCreate(this.selectedItem().Id,"",this.replyText(),this.onPostCreateResponse))},ui.prototype.onPostCreateResponse=function(e,t){this.replySendingStarted(!1),e.Result&&t&&(Ci.Api.showReport(Si.i18n("HELPDESK/REPORT_POST_SUCCESSFULLY_ADDED")),this.clearQuickReply(),this.requestPosts()),this.requestThreadsList(),this.updateOpenerWindow()},ui.prototype.sendHelpdeskPostCreate=function(e,t,i,s){var o={},n={};_.each(this.uploadedFiles(),function(e){o[e.tempName()]=e.hash()}),n={Action:"HelpdeskPostCreate",IsExt:this.bExtApp?1:0,ThreadId:e,IsInternal:this.internalNote()?1:0,Subject:t,Text:i,Attachments:o},Ci.Ajax[this.ajaxSendFunc](n,s,this)},ui.prototype.executeShowThreadsByOwner=function(){this.search("owner:"+this.selectedItem().aOwner[0]),this.prevListFilter(this.listFilter()),this.listFilter(vi.HelpdeskFilters.All)},ui.prototype.onClearSearchClick=function(){this.search(""),""!==this.prevListFilter()&&(this.listFilter(this.prevListFilter()),this.prevListFilter("")),this.searchSubmitCommand()},ui.prototype.initUploader=function(){this.oJua=this.createJuaObject(this.uploaderButton()),this.oJuaCompose=this.createJuaObject(this.uploaderButtonCompose())},ui.prototype.createJuaObject=function(e){if(e){var t=new Jua({action:"?/Upload/HelpdeskFile/",name:"jua-uploader",queueSize:2,clickElement:e,dragAndDropElement:e,disableAjaxUpload:!1,disableFolderDragAndDrop:!1,disableDragAndDrop:!1,hidden:{IsExt:this.bExtApp?"1":"0",Token:Ti.Token,TenantHash:this.bExtApp&&Ti?Ti.TenantHash:"",AccountID:this.bExtApp?0:Ti.Accounts.currentId()}});return t.on("onProgress",_.bind(this.onFileUploadProgress,this)).on("onSelect",_.bind(this.onFileUploadSelect,this)).on("onStart",_.bind(this.onFileUploadStart,this)).on("onComplete",_.bind(this.onFileUploadComplete,this)).on("onBodyDragEnter",_.bind(this.bDragActive,this,!0)).on("onBodyDragLeave",_.bind(this.bDragActive,this,!1)),t}return null},ui.prototype.onFileRemove=function(e){var t=this.getUploadedFileByUID(e);this.oJua&&this.oJua.cancel(e),this.uploadedFiles.remove(t)},ui.prototype.getUploadedFileByUID=function(e){return _.find(this.uploadedFiles(),function(t){return t.uploadUid()===e})},ui.prototype.onFileUploadSelect=function(e,t){var i,s=Si.i18n("COMPOSE/UPLOAD_ERROR_FILENAME_SIZE",{FILENAME:t.FileName,MAXSIZE:Si.friendlySize(Ti.App.AttachmentSizeLimit)}),o=Si.i18n("HELPDESK/ERROR_UPLOAD_FILES_COUNT"),n=Si.i18n("MAIN/BUTTON_CLOSE"),r=this.uploadedFiles().length;return r>=5?(Ci.Screens.showPopup(A,[o,null,"",n]),!1):Ti.App&&Ti.App.AttachmentSizeLimit>0&&t.Size>Ti.App.AttachmentSizeLimit?(Ci.Screens.showPopup(A,[s]),!1):(i=new yt,i.onUploadSelect(e,t),this.uploadedFiles.push(i),!0)},ui.prototype.onFileUploadProgress=function(e,t,i){var s=this.getUploadedFileByUID(e);s&&s.onUploadProgress(t,i)},ui.prototype.onFileUploadStart=function(e){var t=this.getUploadedFileByUID(e);t&&t.onUploadStart()},ui.prototype.onFileUploadComplete=function(e,t,i){var s=this.getUploadedFileByUID(e);s&&s.onUploadComplete(e,t,i)},ui.prototype.cleanAll=function(){this.uploadedFiles([]),this.replyText(""),this.newThreadText("")},ui.prototype.hotKeysBind=function(){},ui.prototype.quoteText=function(e){var t=this.replyText(),i=_.bind(function(){this.replyText(""===t?">"+e:t+"\n>"+e),this.replyTextFocus(!0)},this);this.isQuickReplyHidden()?_.delay(function(){i()},300):i(),this.isQuickReplyHidden(!1)},di.prototype.initScreens=function(){},di.prototype.initLayout=function(){},di.prototype.init=function(){this.initScreens(),this.initLayout(),e("#pSevenContent").addClass("single_mode"),_.defer(function(){Ti.SingleMode||e("#pSevenContent").removeClass("single_mode")}),this.informationScreen(this.showNormalScreen(vi.Screens.Information))},di.prototype.getCurrentScreenModel=function(){var e=this.oScreens[this.currentScreen()],t="undefined"!=typeof e?e.Model:null;return t},di.prototype.showCurrentScreen=function(e,t){var i=this.oScreens[this.currentScreen()],s="undefined"!=typeof i?i.Model:null;this.currentScreen()!==e&&(s&&i.bInitialized&&s.hideViewModel(),this.currentScreen(e)),this.showNormalScreen(e,t),this.resizeAll()},di.prototype.showNormalScreen=function(e,t){var i=e,s=this.oScreens[i];return s&&(s.bInitialized="boolean"!=typeof s.bInitialized?!1:s.bInitialized,s.bInitialized||(s.Model=this.initViewModel(s.Model,s.TemplateName),s.bInitialized=!0),s.Model.showViewModel(t)),s?s.Model:null},di.prototype.initViewModel=function(t,s){var o=null,n=null;return o=new t,n=e('div[data-view-model="'+s+'"]').attr("data-bind","template: {name: '"+s+"'}").hide(),o.$viewModel=n,o.bShown=!1,o.showViewModel=function(e){this.$viewModel.show(),"function"==typeof this.onRoute&&this.onRoute(e),this.bShown||("function"==typeof this.onShow&&this.onShow(e),Ei.runPluginHook&&this.__name&&Ei.runPluginHook("view-model-on-show",[this.__name,this]),this.bShown=!0)},o.hideViewModel=function(){this.$viewModel.hide(),"function"==typeof this.onHide&&this.onHide(),this.bShown=!1},i.applyBindings(o,n[0]),"function"==typeof o.onApplyBindings&&o.onApplyBindings(n),o},di.prototype.showPopup=function(t,s){if(t){if(!t.__builded){var o=null,n=new t,r=n.popupTemplate?n.popupTemplate():"";""!==r&&(o=e('div[data-view-model="'+r+'"]').attr("data-bind","template: {name: '"+r+"'}").removeClass("visible").hide(),o&&1===o.length&&(n.visibility=i.observable(!1),t.__builded=!0,t.__vm=n,n.$viewModel=o,t.__dom=o,n.showViewModel=Si.createCommand(n,function(){Ci&&Ci.Screens&&Ci.Screens.showPopup(t)}),n.closeCommand=Si.createCommand(n,function(){Ci&&Ci.Screens&&Ci.Screens.hidePopup(t)}),i.applyBindings(n,o[0]),Si.delegateRun(n,"onApplyBindings",[o])))}t.__vm&&t.__dom&&(t.__dom.show(),_.delay(function(){t.__dom.addClass("visible")},50),t.__vm.visibility(!0),Si.delegateRun(t.__vm,"onShow",s),this.popupVisibility(!0),this.popups.push(t),this.keyupPopupBinded=_.bind(this.keyupPopup,this,t.__vm),e(document).on("keyup",this.keyupPopupBinded))}},di.prototype.keyupPopup=function(e,i){if(i){var s=t.parseInt(i.keyCode,10);vi.Key.Esc===s&&(e.onEscHandler?e.onEscHandler():e.closeCommand()),vi.Key.Enter!==s&&vi.Key.Space!==s||!e.onEnterHandler||e.onEnterHandler()}},di.prototype.hidePopup=function(t){t&&t.__vm&&t.__dom&&(this.keyupPopupBinded&&(e(document).off("keyup",this.keyupPopupBinded),this.keyupPopupBinded=void 0),t.__dom.removeClass("visible").hide(),t.__vm.visibility(!1),Si.delegateRun(t.__vm,"onHide"),this.popupVisibility(!1),this.popups=_.without(this.popups,t))},di.prototype.hideAllPopup=function(){_.each(this.popups,function(e){this.hidePopup(e)},this)},di.prototype.showLoading=function(e){this.informationScreen()&&this.informationScreen().showLoading(e)},di.prototype.hideLoading=function(){this.informationScreen()&&this.informationScreen().hideLoading()},di.prototype.showReport=function(e,t){this.informationScreen()&&this.informationScreen().showReport(e,t)},di.prototype.showError=function(e,t,i,s){this.informationScreen()&&this.informationScreen().showError(e,t,i,s)},di.prototype.hideError=function(e){this.informationScreen()&&this.informationScreen().hideError(e)},di.prototype.initHelpdesk=function(){var e=this.oScreens[vi.Screens.Helpdesk];Ti.User.IsHelpdeskSupported&&e&&!e.bInitialized&&(e.Model=this.initViewModel(e.Model,e.TemplateName),e.bInitialized=!0)},di.prototype.initScreens=function(){this.oScreens[vi.Screens.Information]={Model:It,TemplateName:"Common_InformationViewModel"},this.oScreens[vi.Screens.Login]={Model:Nt,TemplateName:"Login_WrapLoginViewModel"},this.oScreens[vi.Screens.Header]={Model:Pt,TemplateName:"Common_HeaderViewModel"},this.oScreens[vi.Screens.Mailbox]={Model:Gt,TemplateName:"Mail_LayoutSidePane_MailViewModel"},this.oScreens[vi.Screens.SingleMessageView]={Model:Ht,TemplateName:"Mail_LayoutSidePane_MessagePaneViewModel"},this.oScreens[vi.Screens.Compose]={Model:Bt,TemplateName:"Mail_ComposeViewModel"},this.oScreens[vi.Screens.SingleCompose]={Model:Bt,TemplateName:"Mail_ComposeViewModel"},this.oScreens[vi.Screens.Settings]={Model:Kt,TemplateName:"Settings_SettingsViewModel"},this.oScreens[vi.Screens.SingleHelpdesk]={Model:ui,TemplateName:"Helpdesk_ViewThreadInNewWindow"}},di.prototype.initLayout=function(){e("#pSevenContent").append(e("#Layout").html())},pi.prototype.init=function(){var e=null;Ci.Ajax.openedRequestsCount.subscribe(function(){0===Ci.Ajax.openedRequestsCount()&&_.delay(_.bind(function(){0===Ci.Ajax.openedRequestsCount()&&(this.checkMailStarted(!1),this.folderListLoading(!1),this.messagesLoading(!1))},this),10)},this),Ti.SingleMode&&t.opener&&(e=t.opener.App.MailCache,this.oFolderListItems=e.oFolderListItems,this.uidList(e.uidList()),e.uidList.subscribe(_.bind(function(){this.uidList(e.uidList())},this)),t.name&&this.currentAccountId(Si.pInt(t.name))),this.currentAccountId.valueHasMutated()},pi.prototype.getCurrentFolder=function(){return this.folderList().currentFolder()},pi.prototype.getFolderByFullName=function(e,t){var i=this.oFolderListItems[e];return i?i.getFolderByFullName(t):null},pi.prototype.checkCurrentFolderList=function(){var e=Ti.Accounts.currentId(),t=this.oFolderListItems[e];t||this.messagesLoading()||(this.messagesLoading(!0),this.messagesLoadingError(!1),this.getFolderList(e))},pi.prototype.getFolderList=function(e){var t={Action:"FolderList"};Si.isUnd(e)||(t.AccountID=e),this.folderListLoading(!0),Ci.Ajax.send(t,this.onFolderListResponse,this)},pi.prototype.markMessageReplied=function(e,t,i,s){var o=this.oFolderListItems[e],n=null;o&&(n=o.getFolderByFullName(t),n&&n.markMessageReplied(i,s))},pi.prototype.hideThreads=function(e){Ti.User.useThreads()&&e.folder()===this.folderList().currentFolderFullName()&&!e.threadOpened()&&this.folderList().currentFolder().hideThreadMessages(e)},pi.prototype.showOpenedThreads=function(e){this.messages(this.getMessagesWithThreads(e,this.uidList(),this.messages()))},pi.prototype.useThreadsInCurrentList=function(e){e=e||this.uidList();var t=this.folderList().currentFolder(),i=t&&t.withoutThreads(),s=""===e.search()&&""===e.filters();return Ti.User.useThreads()&&!i&&s},pi.prototype.getMessagesWithThreads=function(e,t,i){var s=[],o=[],n=this.folderList().currentFolder();return n&&e===n.fullName()&&this.useThreadsInCurrentList(t)?(o=_.filter(i,function(e){return!e.threadPart()}),_.each(o,function(e){var t=[];s.push(e),e.threadCount()>0&&(e.threadOpened()&&(t=this.folderList().currentFolder().getThreadMessages(e),s=_.union(s,t)),n.computeThreadData(e))},this),s):i},pi.prototype.setMessagesFromUidList=function(e,t,i,s){var o=e.getUidsForOffset(t,i),n=_.map(o,function(e){return i[e]},this),r=n.length;return s&&(this.messages(this.getMessagesWithThreads(this.folderList().currentFolderFullName(),e,n)),t+r<e.resultCount()&&r<Ti.User.MailsPerPage&&(e.filters()!==vi.FolderFilter.Unseen||this.waitForUnseenMessages())&&this.messagesLoading(!0),this.currentMessage()&&(this.currentMessage().deleted()||this.currentMessage().folder()!==this.folderList().currentFolderFullName())&&this.currentMessage(null)),o},pi.prototype.executeCheckMail=function(){var e=this.oFolderListItems[this.currentAccountId()],t=e?e.inboxFolder():null,i=t?t.uidNext():"",s=Ti.Accounts.getCurrentFetchersAndFiltersFolderNames(),o=e?[e.inboxFolderFullName(),e.spamFolderFullName(),e.currentFolderFullName()]:[],n=e?e.iAccountId:0,r=this.checkMailStarted()&&this.checkMailStartedAccountId()===n,a=null;Ci.Ajax.hasOpenedRequests("FolderCounts")&&r||!(o.length>0)||(o=_.uniq(_.compact(_.union(o,s))),a={Action:"FolderCounts",Folders:o,AccountID:n,InboxUidnext:i},this.checkMailStarted(!0),this.checkMailStartedAccountId(n),Ci.Ajax.send(a,this.onFolderCountsResponse,this))},pi.prototype.setAutocheckmailTimer=function(){clearTimeout(this.iAutoCheckMailTimer),!Ti.SingleMode&&Ti.User.AutoCheckMailInterval>0&&(this.iAutoCheckMailTimer=setTimeout(function(){Ci.Ajax.isSearchMessages()||Ci.MailCache.executeCheckMail()},60*Ti.User.AutoCheckMailInterval*1e3))},pi.prototype.checkMessageFlags=function(){var e=this.folderList().inboxFolder(),t=e?e.getFlaggedMessageUids():[],i={Action:"MessageFlags",Folder:this.folderList().inboxFolderFullName(),Uids:t};t>0&&Ci.Ajax.send(i,this.onMessageFlagsResponse,this)},pi.prototype.onMessageFlagsResponse=function(e){var t=this.folderList().inboxFolder();e.Result&&_.each(e.Result,function(e,i){-1===_.indexOf(e,"\\flagged")&&t.setMessageUnflaggedByUid(i)}),t.removeFlaggedMessageListsFromCache(),Ci.Prefetcher.prefetchStarredMessageList()},pi.prototype.changeCurrentMessageList=function(e,t,i,s){this.requestCurrentMessageList(e,t,i,s,!0)},pi.prototype.requestCurrentMessageList=function(e,t,i,s,o){var n=this.requestMessageList(e,t,i,s||"",!0,o||!1),r=60*Ti.User.AutoCheckMailInterval*1e3,a=n.Folder.relevantInformationLastMoment?moment().diff(n.Folder.relevantInformationLastMoment):r+1;this.uidList(n.UidList),this.page(t),this.messagesLoading(n.DataExpected),this.messagesLoadingError(!1),!n.DataExpected&&r>0&&a>r&&this.executeCheckMail()},pi.prototype.requestMessageList=function(e,t,i,s,o,n){var r=this.oFolderListItems[this.currentAccountId()],a=r?r.getFolderByFullName(e):null,l=a&&a.withoutThreads(),h=Ti.User.useThreads()&&!l&&""===i&&""===s,c=a?a.getUidList(i,s):null,u=c&&-1===c.resultCount(),d=(t-1)*Ti.User.MailsPerPage,p={Action:"MessageList",Folder:e,Offset:d,Limit:Ti.User.MailsPerPage,Search:i,Filters:s,UseThreads:h?"1":"0"},g=!1,m=!1,b=o?this.onCurrentMessageListResponse:this.onMessageListResponse,f=[];return a.type()===vi.FolderTypes.Inbox&&(p.InboxUidnext=a.uidNext()),u&&c.search()===this.uidList().search()&&c.filters()===this.uidList().filters()&&(c=this.uidList()),c&&(f=this.setMessagesFromUidList(c,d,a.oMessages,n)),c&&(m=u||d+f.length<c.resultCount()&&f.length<Ti.User.MailsPerPage,g=a.hasChanges()||m),g?Ci.Ajax.send(p,b,this):this.waitForUnseenMessages(!1),{UidList:c,RequestStarted:g,DataExpected:m,Folder:a}},pi.prototype.executeEmptyTrash=function(){var e=this.folderList().trashFolder();e&&e.emptyFolder()},pi.prototype.executeEmptySpam=function(){var e=this.folderList().spamFolder();e&&e.emptyFolder()},pi.prototype.onClearFolder=function(e){if(e&&e.selected()){this.messages.removeAll(),this.currentMessage(null);var t=e?e.getUidList(this.uidList().search(),this.uidList().filters()):null;this.uidList(t?t:new at),this.checkMailStarted(!1),this.setAutocheckmailTimer()}},pi.prototype.moveMessagesToFolder=function(e,t,i){if(t.length>0){var s=this.folderList().currentFolder(),o=this.folderList().getFolderByFullName(e),n={Action:"MessageMove",Folder:s?s.fullName():"",ToFolder:e,Uids:t.join(",")},r=null;s&&o&&(r=s.markDeletedByUids(t),o.addMessagesCountsDiff(r.MinusDiff,r.UnseenMinusDiff),(Si.isUnd(i)?0:!i)||o.recivedAnim(!0),this.excludeDeletedMessages(),o.markHasChanges(),Ci.Ajax.send(n,this.onMoveMessagesResponse,this),o&&o.type()===vi.FolderTypes.Trash&&Ei.runPluginHook("move-messages-to-trash",[Ti.Accounts.currentId(),n.Folder,t]),o&&o.type()===vi.FolderTypes.Spam&&Ei.runPluginHook("move-messages-to-spam",[Ti.Accounts.currentId(),n.Folder,t]))}},pi.prototype.copyMessagesToFolder=function(e,t,i){if(t.length>0){var s=this.folderList().currentFolder(),o=this.folderList().getFolderByFullName(e),n={Action:"MessageCopy",Folder:s?s.fullName():"",ToFolder:e,Uids:t.join(",")};s&&o&&((Si.isUnd(i)?0:!i)||o.recivedAnim(!0),o.markHasChanges(),Ci.Ajax.send(n,this.onCopyMessagesResponse,this),o&&o.type()===vi.FolderTypes.Trash&&Ei.runPluginHook("copy-messages-to-trash",[Ti.Accounts.currentId(),n.Folder,t]),o&&o.type()===vi.FolderTypes.Spam&&Ei.runPluginHook("copy-messages-to-spam",[Ti.Accounts.currentId(),n.Folder,t]))}},pi.prototype.excludeDeletedMessages=function(){_.delay(_.bind(function(){var e=this.folderList().currentFolder(),t=(this.page()-1)*Ti.User.MailsPerPage;this.setMessagesFromUidList(this.uidList(),t,e.oMessages,!0)},this),500)},pi.prototype.removeMessagesFromCacheForFolder=function(e,t){var i=this.folderList().getFolderByFullName(e),s=this.folderList().currentFolderFullName();i&&(i.type()===vi.FolderTypes.Drafts&&(i.markDeletedByUids([t]),i.commitDeleted([t])),i.markHasChanges(),e===s&&this.requestCurrentMessageList(s,this.page(),this.uidList().search(),"",!0))},pi.prototype.deleteMessages=function(e){var t=this.folderList().currentFolder();t&&this.deleteMessagesFromFolder(t,e)},pi.prototype.deleteMessagesFromFolder=function(e,t){var i={Action:"MessageDelete",Folder:e.fullName(),Uids:t.join(",")};e.markDeletedByUids(t),this.excludeDeletedMessages(),Ci.Ajax.send(i,this.onMoveMessagesResponse,this),Ei.runPluginHook("delete-messages",[Ti.Accounts.currentId(),i.Folder,t])},pi.prototype.showExternalPictures=function(e){var t=[],i=null;this.currentMessage()&&(t=this.currentMessage().oFrom.aCollection,i=this.folderList().getFolderByFullName(this.currentMessage().folder()),e&&t.length>0?i.alwaysShowExternalPicturesForSender(t[0].sEmail):i.showExternalPictures(this.currentMessage().uid()))},pi.prototype.setCurrentMessage=function(e,t){var i=Ti.SingleMode?this.folderList().getFolderByFullName(t):this.folderList().currentFolder(),s=i&&e?i.oMessages[e]:null;s&&!s.deleted()?(this.currentMessage(s),this.currentMessage().seen()||this.executeGroupOperation("MessageSetSeen",[this.currentMessage().uid()],"seen",!0),i.getCompletelyFilledMessage(e,this.onCurrentMessageResponse,this)):this.currentMessage(null)},pi.prototype.onCurrentMessageResponse=function(e,t){var i=this.currentMessage()?this.currentMessage().uid():"";null===e&&i===t?this.currentMessage(null):e&&i===t&&this.currentMessage.valueHasMutated()},pi.prototype.getMessage=function(e,t,i,s){var o=this.folderList().getFolderByFullName(e);o&&o.getCompletelyFilledMessage(t,i,s)},pi.prototype.executeGroupOperation=function(e,t,i,s){var o=this.folderList().currentFolder(),n={Action:e,Folder:o?o.fullName():"",Uids:t.join(","),SetAction:s?1:0},r=(this.page()-1)*Ti.User.MailsPerPage,a=t.length,l=this.folderList().oStarredFolder?this.folderList().oStarredFolder.messageCount():0,h=o.getUidList("",vi.FolderFilter.Flagged);o&&("MessageSetSeen"===n.Action&&this.iMessageSetSeenCount++,Ci.Ajax.send(n,this.onExecuteGroupOperationResponse,this),o.executeGroupOperation(i,t,s),o.type()===vi.FolderTypes.Inbox&&"flagged"===i&&(this.uidList().filters()===vi.FolderFilter.Flagged?s||(this.uidList().deleteUids(t),this.folderList().oStarredFolder&&this.folderList().oStarredFolder.messageCount(h.resultCount())):(o.removeFlaggedMessageListsFromCache(),""===this.uidList().search()&&this.folderList().oStarredFolder&&this.folderList().oStarredFolder.messageCount(s?l+a:l-a>0?l-a:0))),"seen"===i&&o.removeUnseenMessageListsFromCache(),(this.uidList().filters()!==vi.FolderFilter.Unseen||this.waitForUnseenMessages())&&this.setMessagesFromUidList(this.uidList(),r,o.oMessages,!0))},pi.prototype.onExecuteGroupOperationResponse=function(e,t){"MessageSetSeen"===t.Action&&(this.iMessageSetSeenCount--,this.iMessageSetSeenCount<0&&(this.iMessageSetSeenCount=0),this.folderList().currentFolder()&&0===this.iMessageSetSeenCount&&(this.uidList().filters()!==vi.FolderFilter.Unseen||this.waitForUnseenMessages())&&this.requestCurrentMessageList(this.folderList().currentFolder().fullName(),this.page(),this.uidList().search(),this.uidList().filters(),!1))},pi.prototype.onFolderListResponse=function(e,t){var i=new nt,s=parseInt(e.AccountID,10),o=this.oFolderListItems[s],n=o?o.oNamedCollection:{};e.Result===!1?(Ci.Api.showErrorByCode(e),t.AccountID===this.currentAccountId()&&0===this.messages().length&&(this.messagesLoading(!1),this.messagesLoadingError(!0))):(i.parse(s,e.Result,n),this.oFolderListItems[s]=i,setTimeout(_.bind(this.getAllFolderCounts,this,s),2e3),this.currentAccountId()===s&&this.folderList(i),this.editedAccountId()===s&&this.editedFolderList(i),Ti.Accounts.defaultId()===s&&this.defaultFolderList(i)),this.folderListLoading(!1)},pi.prototype.setCurrentFolderList=function(e){var t=e.iAccountId;t===this.currentAccountId()&&t!==this.folderList().iAccountId&&this.folderList(e)},pi.prototype.getAllFolderCounts=function(e){var t=this.oFolderListItems[e],i=t.inboxFolder(),s=i?i.uidNext():"",o=t?t.getFoldersWithoutCountInfo():[],n={Action:"FolderCounts",Folders:o,AccountID:e,InboxUidnext:s};o.length>0&&Ci.Ajax.send(n,this.onFolderCountsResponse,this)},pi.prototype.onFolderCountsResponse=function(e){var t=!1,i=e.AccountID,s=this.oFolderListItems[i],o=this.folderList().currentFolderFullName(),n=this.currentAccountId()===i;e.Result===!1?Ci.Api.showErrorByCode(e):(_.each(e.Result&&e.Result.Counts,function(e,i){if(_.isArray(e)&&e.length>3){var r=e[0],a=e[1],l=e[2],h=e[3],c=!1,u=!1,d=null;s&&(d=s.getFolderByFullName(i),d&&(u=n&&d.fullName()===o,c=d.setRelevantInformation(l,h,r,a,u),u&&c&&this.uidList().filters()!==vi.FolderFilter.Unseen&&(this.requestCurrentMessageList(d.fullName(),this.page(),this.uidList().search(),this.uidList().filters(),!1),t=!0)))}},this),this.showNotificationsForNewMessages(e)),this.checkMailStarted(t),this.checkMailStarted()||this.setAutocheckmailTimer()},pi.prototype.showNotificationsForNewMessages=function(e){var t=0,i={};e.Result.New&&e.Result.New.length&&(t=e.Result.New.length,i={action:"show",icon:"skins/wm_logo_140x140.png",title:Si.i18n("NOTIFICATION/NEW_MESSAGE_PLURAL",{COUNT:t},null,t),timeout:5e3},1===t&&(i.body=Si.i18n("MESSAGE/HEADER_SUBJECT")+": "+e.Result.New[0].Subject+"\r\n"+Si.i18n("MESSAGE/HEADER_FROM")+": "+_.map(e.Result.New[0].From,function(e){return""!==e.DisplayName?e.DisplayName:e.Email}).join(", ")),Ci.desktopNotify(i))},pi.prototype.onCurrentMessageListResponse=function(e,t){if(this.checkMailStarted(!1),e.Result){if(this.messagesLoadingError(!1),this.parseMessageList(e,t),""!==this.deletedDraftMessageUid()){var i=this.deletedDraftMessageUid(),s=_.find(e.Result["@Collection"],function(e){return e.Uid===i});s||(this.setCurrentMessage("",""),this.deletedDraftMessageUid(""))}}else Ci.Api.showErrorByCode(e),this.messagesLoading()!==!0||0!==this.messages().length&&e.ErrorCode===vi.Errors.NotDisplayedError||this.messagesLoadingError(!0),this.messagesLoading(!1),this.setAutocheckmailTimer()},pi.prototype.onMessageListResponse=function(e,t){e&&e.Result&&this.parseMessageList(e,t)},pi.prototype.parseMessageList=function(e,t){var i=e.Result,s=this.oFolderListItems[e.AccountID],o=null,n=null,r="1"===t.UseThreads,a=!1,l=this.currentAccountId()===e.AccountID&&this.folderList().currentFolderFullName()===i.FolderName,h=l&&this.uidList().search()===i.Search&&this.uidList().filters()===i.Filters,c=this.page()===i.Offset/Ti.User.MailsPerPage+1,u=[];this.showNotificationsForNewMessages(e),i!==!1&&"Collection/MessageCollection"===i["@Object"]&&(o=s.getFolderByFullName(i.FolderName),o.setRelevantInformation(i.UidNext.toString(),i.FolderHash,i.MessageCount,i.MessageUnseenCount,l&&!h),a=o.hasChanges(),o.removeAllMessageListsFromCacheIfHasChanges(),n=o.getUidList(i.Search,i.Filters),n.setUidsAndCount(i),_.each(i["@Collection"],function(e){var t=o.parseAndCacheMessage(e,!1,r);u.push(t)},this),Ei.runPluginHook("response-custom-messages",[e.AccountID,o.fullName(),u]),h&&(this.uidList(n),c&&(n.filters()!==vi.FolderFilter.Unseen||this.waitForUnseenMessages())&&(this.setMessagesFromUidList(n,i.Offset,o.oMessages,!0),this.messagesLoading(!1),this.waitForUnseenMessages(!1),this.setAutocheckmailTimer())),!a||!l||h&&c||this.uidList().filters()===vi.FolderFilter.Unseen||this.requestCurrentMessageList(this.folderList().currentFolderFullName(),this.page(),this.uidList().search(),this.uidList().filters(),!1),o.type()===vi.FolderTypes.Inbox&&n.filters()===vi.FolderFilter.Flagged&&""===n.search()&&this.folderList().oStarredFolder&&this.folderList().oStarredFolder.messageCount(n.resultCount()))},pi.prototype.onMoveMessagesResponse=function(e,t){var i=e.Result,s=this.folderList().getFolderByFullName(t.Folder),o=this.folderList().getFolderByFullName(t.ToFolder),n=o&&o.type()===vi.FolderTypes.Trash,r=o&&o.type()===vi.FolderTypes.Spam,a=null,l=Si.i18n(n?"MAILBOX/CONFIRM_MESSAGES_DELETE_WITHOUT_TRASH":"MAILBOX/CONFIRM_MESSAGES_MARK_SPAM_WITHOUT_SPAM"),h=_.bind(function(e){e&&s&&this.deleteMessagesFromFolder(s,t.Uids.split(","))},this),c=this.folderList().currentFolder(),u=c.fullName();i===!1?(a=s.revertDeleted(t.Uids.split(",")),o?(o.addMessagesCountsDiff(-a.PlusDiff,-a.UnseenPlusDiff),e.ErrorCode===vi.Errors.ImapQuota&&(n||r)?Ci.Screens.showPopup(C,[l,h]):Ci.Api.showErrorByCode(e,Si.i18n("MAILBOX/ERROR_MOVING_MESSAGES"))):Ci.Api.showErrorByCode(e,Si.i18n("MAILBOX/ERROR_DELETING_MESSAGES"))):s.commitDeleted(t.Uids.split(",")),u===s.fullName()||o&&u===o.fullName()?(c.markHasChanges(),this.uidList().filters()!==vi.FolderFilter.Unseen&&this.uidList().filters()!==vi.FolderFilter.Flagged&&this.requestCurrentMessageList(u,this.page(),this.uidList().search(),"",!1)):u!==s.fullName()?Ci.Prefetcher.startFolderPrefetch(s):o&&u!==o.fullName()&&Ci.Prefetcher.startFolderPrefetch(o)},pi.prototype.onCopyMessagesResponse=function(e,t){var i=e.Result,s=this.folderList().getFolderByFullName(t.Folder),o=this.folderList().getFolderByFullName(t.ToFolder),n=this.folderList().currentFolder(),r=n.fullName();i===!1&&Ci.Api.showErrorByCode(e,Si.i18n("MAILBOX/ERROR_COPYING_MESSAGES")),r===s.fullName()||o&&r===o.fullName()?(n.markHasChanges(),this.requestCurrentMessageList(r,this.page(),this.uidList().search(),"",!1)):r!==s.fullName()?Ci.Prefetcher.startFolderPrefetch(s):o&&r!==o.fullName()&&Ci.Prefetcher.startFolderPrefetch(o)},pi.prototype.searchMessagesInCurrentFolder=function(e){var t=this.folderList().currentFolderFullName()||"INBOX",i=this.currentMessage()?this.currentMessage().uid():"",s=this.uidList().filters();Ci.Routing.setHash(Ci.Links.mailbox(t,1,i,e,s))},pi.prototype.searchMessagesInInbox=function(e){Ci.Routing.setHash(Ci.Links.mailbox(this.folderList().inboxFolderFullName()||"INBOX",1,"",e,""))},pi.prototype.countMessages=function(e){var t=[],i=function(e){_.each(e.subfolders(),function(e){e.subscribed()&&(t.push(e.unseenMessageCount()),e.subfolders().length&&e.subscribed()&&i(e))},this)};e.expanded()||e.isNamespace()?e.subfoldersMessagesCount(0):(i(e),e.subfoldersMessagesCount(_.reduce(t,function(e,t){return e+t},0)))},gi.prototype.clearInfoAboutEmail=function(e){this.contacts[e]=void 0},gi.prototype.getContactByEmail=function(e,t,i){if(Ti.User.ShowContacts){var s=this.contacts[e],o={Action:"ContactByEmail",Email:e};void 0!==s?t.apply(i,[s,e]):(this.responseHandlers[e]={Handler:t,Context:i},Ci.Ajax.send(o,this.onContactByEmailResponse,this))}},gi.prototype.onContactByEmailResponse=function(e,t){var i=null,s=this.responseHandlers[t.Email];e.Result&&(i=new ct,i.parse(e.Result)),this.contacts[t.Email]=i,s&&(s.Handler.apply(s.Context,[i,t.Email]),this.responseHandlers[t.Email]=void 0)},gi.prototype.addVcard=function(e){this.vcardAttachments.push(e)},gi.prototype.markVcardsNonexistentByUid=function(e){_.each(this.vcardAttachments,function(t){-1!==_.indexOf(e,t.uid())&&t.isExists(!1)})},gi.prototype.markVcardExistentByFile=function(e){_.each(this.vcardAttachments,function(t){t.file()===e&&t.isExists(!0)})},gi.prototype.addToContacts=function(e,t,i,s){var o={Action:"ContactCreate",PrimaryEmail:"Home",UseFriendlyName:"1",FullName:e,HomeEmail:t};Ci.Ajax.send(o,i,s),Ci.ContactsCache.recivedAnim(!0)},mi.prototype.addIcal=function(e){this.icalAttachments.push(e),0===this.calendars().length&&this.canRequestCalendarList()&&this.requestCalendarList()},mi.prototype.firstRequestCalendarList=function(){return this.canRequestCalendarList(!0),this.icalAttachments.length>0&&0===this.calendars().length&&this.requestCalendarList(),this.calendarsLoadingStarted() },mi.prototype.onCalendarListResponse=function(e){if(e&&e.Result){var t=Ti.Accounts,i=t.currentId(),s=t.getAccount(i).email(),o=_.filter(e.Result,function(e){return e.Owner===s||e.Access===vi.CalendarAccess.Full||e.Access===vi.CalendarAccess.Write});this.calendars(_.map(o,function(e){return{name:e.Name+" <"+e.Owner+">",id:e.Id}}))}this.calendarsLoadingStarted(!1)},mi.prototype.requestCalendarList=function(){this.calendarsLoadingStarted()||(Ci.Ajax.send({Action:"CalendarList"},this.onCalendarListResponse,this),this.calendarsLoadingStarted(!0))},mi.prototype.markIcalNonexistent=function(e){_.each(this.icalAttachments,function(t){e===t.uid()&&t.onEventDelete()})},mi.prototype.markIcalTypeByFile=function(e,t,i,s,o,n){_.each(this.icalAttachments,function(r){e===r.file()&&(r.type(t),r.cancelDecision(i),r.replyDecision(s),r.calendarId(o),r.selectedCalendarId(n))})},mi.prototype.markIcalTentative=function(e){_.each(this.icalAttachments,function(t){e===t.uid()&&t.onEventTentative()})},mi.prototype.markIcalAccepted=function(e){_.each(this.icalAttachments,function(t){e===t.uid()&&t.onEventAccept()})},bi.prototype.init=function(){},bi.prototype.collectScreensData=function(){},bi.prototype.run=function(){},bi.prototype.momentDateTriggerCallback=function(){var e=i.dataFor(this);e&&e.updateMomentDate&&e.updateMomentDate()},bi.prototype.fastMomentDateTrigger=function(){e(".moment-date-trigger-fast").each(this.momentDateTriggerCallback)},bi.prototype.setTitle=function(e){document.title=".",document.title=e||""},_.extend(fi.prototype,bi.prototype),fi.prototype.initPhone=function(){return null},fi.prototype.init=function(){var s=this,o=Ti.User,n=new Q,r=Ti.Accounts,a=new J,l=Ti.App,h=new z(!!l.AllowOpenPGP&&this.Api.isPgpSupported());h.parse(l),Ti.App=h,n.parse(o),Ti.User=n,a.parse(Si.pInt(Ti.Default),r),Ti.Accounts=a,this.MailCache=new pi,this.Phone=this.initPhone(n.AllowVoice&&!this.browser.ie&&!Ii),this.useGoogleAnalytics(),this.collectScreensData(),e(t).unload(function(){Si.WindowOpener.closeAll()}),this.nowMoment=i.observable(moment()),t.setInterval(function(){s.fastMomentDateTrigger(),moment().diff(s.nowMoment(),"days")>0&&s.nowMoment(moment())},6e4)},fi.prototype.collectScreensData=function(){},fi.prototype.registerHelpdeskUpdateFunction=function(e){this.fHelpdeskUpdate=e},fi.prototype.updateHelpdesk=function(){this.fHelpdeskUpdate&&this.fHelpdeskUpdate()},fi.prototype.useGoogleAnalytics=function(){var e=null,i=null;Ti.App.GoogleAnalyticsAccount&&0<Ti.App.GoogleAnalyticsAccount.length&&(t._gaq=t._gaq||[],t._gaq.push(["_setAccount",Ti.App.GoogleAnalyticsAccount]),t._gaq.push(["_trackPageview"]),e=document.createElement("script"),e.type="text/javascript",e.async=!0,e.src=("https:"===document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js",i=document.getElementsByTagName("script")[0],i.parentNode.insertBefore(e,i))},fi.prototype.tokenProblem=function(){var e="window.location.reload(); return false;",t=Si.i18n("WARNING/TOKEN_PROBLEM_HTML",{RELOAD_FUNC:e});Ti.Auth=!1,Ci.Api.showError(t,!0,!0)},fi.prototype.logout=function(e){var t={Action:"Logout"};e&&(t.LastErrorCode=e),Ci.Ajax.send(t,this.onLogout,this),Ti.Auth=!1},fi.prototype.authProblem=function(){this.logout(vi.Errors.AuthError)},fi.prototype.onLogout=function(){Si.WindowOpener.closeAll(),Ci.Routing.finalize(),""!==Ti.App.CustomLogoutUrl?t.location.href=Ti.App.CustomLogoutUrl:t.location.reload()},fi.prototype.getAccounts=function(){return Ti.Accounts},fi.prototype.run=function(){if(this.Screens.init(),Pi&&Ti&&Ti.Auth&&Ti.App.IosDetectOnLogin&&Ci.browser.safari&&Ti.App.AllowIosProfile?t.location.href="?ios":Ti&&Ti.Auth?(Ti.SingleMode=this.Routing.isSingleMode(),Ti.SingleMode&&t.opener&&Ti.Accounts.populateIdentitiesFromSourceAccount(t.opener.App.getAccounts()),Ti.App.AllowWebMail&&this.MailCache.init(),Ti.HelpdeskRedirect&&this.Routing.currentScreen!==vi.Screens.Helpdesk&&this.Routing.setHash([vi.Screens.Helpdesk]),""!==Ti.App.DefaultTab?this.Routing.init(Ti.App.DefaultTab):Ti.App.AllowWebMail?this.Routing.init(vi.Screens.Mailbox):this.headerTabs()[0]&&this.Routing.init(this.headerTabs()[0].name)):Ti&&""!==Ti.App.CustomLoginUrl?t.location.href=Ti.App.CustomLoginUrl:(this.Screens.showCurrentScreen(vi.Screens.Login),Ti&&Ti.LastErrorCode===vi.Errors.AuthError&&this.Api.showError(Si.i18n("WARNING/AUTH_PROBLEM"),!1,!0)),this.Phone&&t.localStorage){var i=this;e(t).on("storage",function(){"false"!==t.localStorage.getItem("phoneLoad")&&t.localStorage.setItem("phoneLoad","false")}),t.localStorage.setItem("phoneLoad",Math.floor(900*Math.random()+100).toString()),t.setTimeout(function(){Ti.SingleMode||!i.Phone||"false"===t.localStorage.getItem("phoneLoad")&&!t.sessionStorage.getItem("phoneTab")||(i.Phone.init(),t.sessionStorage.setItem("phoneTab","true"))},1e3)}Si.registerMailto(this.browser.firefox)},fi.prototype.getHelpLink=function(e){return Ti&&Ti.Links&&Ti.Links[e]?Ti.Links[e]:""},fi.prototype.addScreenToHeader=function(e,t,s,o,n,r,a){var l=this.Routing.buildHashFromArray([e]),h=this;e===vi.Screens.Helpdesk&&(l=i.computed(function(){return"#"+h.Routing.lastHelpdeskHash()})),vi.Screens[e]=e,this.Screens.oScreens[e]={Model:n,TemplateName:o},this.headerTabs.push({name:e,title:t,hash:l,koVisibleTab:r,koRecivedAnim:a}),this.screensTitle[e]=s},fi.prototype.registerSessionTimeoutFunction=function(e){this.sessionTimeoutFunctions.push(e)},fi.prototype.initSessionTimeout=function(){this.setSessionTimeout(),e("body").on("click",_.bind(this.setSessionTimeout,this)).on("keydown",_.bind(this.setSessionTimeout,this))},fi.prototype.setSessionTimeout=function(){clearTimeout(this.iSessionTimeout),Ti&&Ti.Auth&&Ti.App.IdleSessionTimeout&&(this.iSessionTimeout=setTimeout(_.bind(this.logoutBySessionTimeout,this),Ti.App.IdleSessionTimeout))},fi.prototype.logoutBySessionTimeout=function(){Ti.Auth&&(_.each(this.sessionTimeoutFunctions,function(e){e()}),_.delay(_.bind(this.logout,this),500))},fi.prototype.initHeaderInfo=function(){this.browser.ie?e(document).bind("focusin",_.bind(this.onFocus,this)).bind("focusout",_.bind(this.onBlur,this)):e(t).bind("focus",_.bind(this.onFocus,this)).bind("blur",_.bind(this.onBlur,this))},fi.prototype.onFocus=function(){this.focused(!0)},fi.prototype.onBlur=function(){this.focused(!1)},fi.prototype.setTitle=function(e){var t=this.newMessagesCount(),i="";e=e||"",e=this.focused()||0===t||!Ti.App.AllowWebMail?this.getTitleByScreen():Si.i18n("TITLE/HAS_UNSEEN_MESSAGES_PLURAL",{COUNT:t},null,t)+" - "+Ti.Accounts.getEmail(),this.favico&&(i=t>99?"99+":t,this.favico._cachevalue!==i&&(this.favico._cachevalue=i,this.favico.badge(i))),document.title=".",document.title=e},fi.prototype.getTitleByScreen=function(){var e="",t="";try{this.MailCache.currentMessage()&&(t=this.MailCache.currentMessage().subject())}catch(i){}switch(this.currentScreen()){case vi.Screens.Login:e=Si.i18n("TITLE/LOGIN",null,"");break;case vi.Screens.Mailbox:e=Ti.Accounts.getEmail()+" - "+Si.i18n("TITLE/MAILBOX");break;case vi.Screens.Compose:case vi.Screens.SingleCompose:e=Ti.Accounts.getEmail()+" - "+Si.i18n("TITLE/COMPOSE");break;case vi.Screens.SingleMessageView:e=Ti.Accounts.getEmail()+" - "+Si.i18n("TITLE/VIEW_MESSAGE"),t&&(e=t+" - "+e);break;default:this.screensTitle[this.currentScreen()]&&(e=this.screensTitle[this.currentScreen()])}return""===e?e=Ti.App.SiteName:e+=Ti.App.SiteName&&""!==Ti.App.SiteName?" - "+Ti.App.SiteName:"",e},fi.prototype.desktopNotify=function(e,t,i,s,o,n){Si.desktopNotify(e,t,i,s,o,n)},_.extend(yi.prototype,fi.prototype),yi.prototype.initPhone=function(e){return e?new g:null},yi.prototype.collectScreensData=function(){Ti.User.ShowContacts&&this.addScreenToHeader("contacts",Si.i18n("HEADER/CONTACTS"),Si.i18n("TITLE/CONTACTS"),"Contacts_ContactsViewModel",jt,!0,this.ContactsCache.recivedAnim),Ti.User.AllowCalendar&&this.addScreenToHeader("calendar",Si.i18n("HEADER/CALENDAR"),Si.i18n("TITLE/CALENDAR"),"Calendar_CalendarViewModel",hi,!0,this.CalendarCache.recivedAnim,!0),Ti.User.IsFilesSupported&&this.addScreenToHeader("files",Si.i18n("HEADER/FILESTORAGE"),Si.i18n("TITLE/FILESTORAGE"),"FileStorage_FileStorageViewModel",ci,Ti.User.filesEnable,this.filesRecievedAnim),Ti.User.IsHelpdeskSupported&&this.addScreenToHeader("helpdesk",Si.i18n("HEADER/HELPDESK"),Si.i18n("TITLE/HELPDESK"),"Helpdesk_HelpdeskViewModel",ui,!0)},Ci=new yi,t.App=Ci,-1===Ti.IsMobile){var _i=t.matchMedia("all and (min-width: 768px)").matches?0:1;t.App.Ajax.send({Action:"SetMobile",Mobile:_i},function(){_i?t.location.reload():e(function(){_.defer(function(){Ci.run()})})},this)}else e(function(){_.defer(function(){Ci.run()})});t.Modernizr&&navigator&&t.Modernizr.addTest("mobile",function(){return Ii}),t.AfterLogicApi=Ei,t.Enums=vi,wi.removeClass("no-js").addClass("js"),wi.hasClass("pdf")&&(Di.push("application/pdf"),Di.push("application/x-pdf"))}(jQuery,window,ko,crossroads,hasher);