diff --git a/UI/WebServerResources/js/Mailer.services.js b/UI/WebServerResources/js/Mailer.services.js index 75fb9e143..fccd2f7d6 100644 --- a/UI/WebServerResources/js/Mailer.services.js +++ b/UI/WebServerResources/js/Mailer.services.js @@ -1,3 +1,3 @@ -!function(){"use strict";function a(b,c){"function"!=typeof b.then&&(angular.extend(this,b),_.forEach(this.identities,function(a){a.fullName?a.full=a.fullName+" <"+a.email+">":a.full="<"+a.email+">"}),a.$log.debug("Account: "+JSON.stringify(b,void 0,2))),this.fetchAll=!1,angular.isDefined(c)&&c&&(this.fetchAll=!0,this.$getMailboxes())}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Preferences","Mailbox","Message",function(b,c,d,e,f,g,h,i){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Preferences:g,$Mailbox:h,$Message:i}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").factory("Account",a.$factory),a.$findAll=function(b){return b?a.$unwrapCollection(b):a.$$resource.fetch("","mailAccounts").then(function(b){return a.$unwrapCollection(b)})},a.$unwrapCollection=function(b){var c=[];return angular.forEach(b,function(b,d){b.id=d,c[d]=new a(b)}),a.$accounts=c,c},a.prototype.getLength=function(){return this.$flattenMailboxes().length},a.prototype.getItemAtIndex=function(a){var b;return b=this.$flattenMailboxes(),a>=0&&a=0,a.children&&a.children.length>0&&d(a.children)})};a.$Preferences.settings.Mail.ExpandedFolders&&(b=angular.isString(a.$Preferences.settings.Mail.ExpandedFolders)?angular.fromJson(a.$Preferences.settings.Mail.ExpandedFolders):a.$Preferences.settings.Mail.ExpandedFolders,c.$expanded=b.indexOf("/"+c.id)>=0,b.length>0&&d(c.$mailboxes)),a.$accounts&&(c.$expanded|=1==a.$accounts.length),c.$flattenMailboxes({reload:!0})}),c.$mailboxes}):a.$q.when(this.$mailboxes)},a.prototype.$flattenMailboxes=function(b){var c=this,d=[],e=[],f=function(a){_.forEach(a,function(a){d.push(a),(b&&b.all||a.$expanded)&&a.children&&a.children.length>0&&f(a.children)})};return!this.$$flattenMailboxes||b&&(b.reload||b.all)?(f(this.$mailboxes),b&&b.all||(c.$$flattenMailboxes=d,b&&b.saveState&&(_.forEach(a.$accounts,function(a){a.$expanded&&e.push("/"+a.id),_.reduce(a.$$flattenMailboxes,function(a,b){return b.$expanded&&a.push("/"+b.id),a},e)}),a.$$resource.post(null,"saveFoldersState",e)))):d=this.$$flattenMailboxes,d},a.prototype.$getMailboxByType=function(a){var b,c=function(b){var d=_.find(b,function(b){return b.type==a});return d||angular.forEach(b,function(a){!d&&a.children&&a.children.length>0&&(d=c(a.children))}),d};return b=c(this.$mailboxes)},a.prototype.$getMailboxByPath=function(a){var b=null,c=function(b){var d=_.find(b,function(b){return b.path==a});return d||angular.forEach(b,function(a){!d&&a.children&&a.children.length>0&&(d=c(a.children))}),d};return b=c(this.$mailboxes)},a.prototype.$newMailbox=function(b,c){var d=this;return a.$$resource.post(b.toString(),"createFolder",{name:c}).then(function(){d.$getMailboxes({reload:!0})})},a.prototype.updateQuota=function(a){var b,c,d;b=Math.round(1e4*a.usedSpace/a.maxQuota)/100,c=l("quotasFormat"),d=c.formatted(b,Math.round(a.maxQuota/10.24)/100),this.$quota={percent:b,description:d}},a.prototype.$newMessage=function(){var b=this;return a.$$resource.fetch(this.id.toString(),"compose").then(function(c){a.$log.debug("New message (compose): "+JSON.stringify(c,void 0,2));var d=new a.$Message(c.accountId,b.$getMailboxByPath(c.mailboxPath),c);return d}).then(function(b){return a.$$resource.fetch(b.$absolutePath({asDraft:!0}),"edit").then(function(c){return a.$log.debug("New message (edit): "+JSON.stringify(c,void 0,2)),angular.extend(b.editable,c),b.isNew=!0,b})})},a.prototype.$addDelegate=function(b){var c=this,d=a.$q.defer(),e={uid:b.uid};return!b.uid||_.indexOf(_.map(this.delegates,"uid"),b.uid)>-1?d.resolve():a.$$resource.fetch(this.id.toString(),"addDelegate",e).then(function(){c.delegates.push(b),d.resolve(c.users)},function(a,b){d.reject(l("An error occured please try again."))}),d.promise},a.prototype.$removeDelegate=function(b){var c=this,d={uid:b};return a.$$resource.fetch(this.id.toString(),"removeDelegate",d).then(function(){var a=_.indexOf(_.map(c.delegates,"uid"),b);a>=0&&c.delegates.splice(a,1)})}}(),function(){"use strict";function a(b,c){if(this.$account=b,"function"!=typeof c.then){if(this.init(c),this.name&&!this.path){var d=a.$$resource.create("createFolder",this.name);this.$unwrap(d)}}else this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Message","Acl","Preferences","sgMailbox_PRELOAD",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Message:g,$$Acl:h,$Preferences:i,$query:{sort:"date",asc:0},selectedFolder:null,$refreshTimeout:null,$virtualMode:!1,PRELOAD:j}),i.ready().then(function(){i.settings.Mail.SortingState&&(a.$query.sort=i.settings.Mail.SortingState[0],a.$query.asc=parseInt(i.settings.Mail.SortingState[1]))}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMailbox_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("Mailbox",a.$factory),a.$find=function(b){var c;return c=b.fetchAll?this.$$resource.fetch(b.id.toString(),"viewAll"):this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,c)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&a=0},a.prototype.isNoSelect=function(){return this.flags.indexOf("noselect")>=0},a.prototype.$rename=function(){var b,c,d,e,f=this;return this.name==this.$shadowData.name?a.$q.when():(b=function(a,c){var d=null,e=_.find(c,function(a){return a.path==f.path});return e?d=a:angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a,a.children))}),d},c=b(null,this.$account.$mailboxes),d=null===c?this.$account.$mailboxes:c.children,e=_.indexOf(_.map(d,"id"),this.id),this.$save().then(function(b){var c;angular.extend(f,b),f.id=f.$id(),d.splice(e,1),c=_.find(d,function(b){return a.$log.debug(b.name+" ? "+f.name),"folder"==b.type&&b.name.localeCompare(f.name)>0}),e=c?_.indexOf(_.map(d,"id"),c.id):d.length,d.splice(e,0,f)}))},a.prototype.$compact=function(){var b=this;return a.$$resource.post(this.id,"expunge").then(function(a){a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$setFolderAs=function(b){return a.$$resource.post(this.id,"setAs"+b+"Folder")},a.prototype.$emptyTrash=function(){var b=this;return a.$$resource.post(this.id,"emptyTrash").then(function(a){b.$messages=[],b.uidsMap={},b.unseenCount=0,angular.isDefined(b.children)&&b.children.length&&b.$account.$getMailboxes({reload:!0}),a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$markAsRead=function(){return a.$$resource.post(this.id,"markRead")},a.prototype.$flagMessages=function(b,c,d){var e={msgUIDs:_.map(b,"uid"),flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e).then(function(){return b})},a.prototype.saveSelectedMessages=function(){var b,c;return b=_.filter(this.$messages,function(a){return a.selected}),c=_.map(b,"uid"),a.$$resource.download(this.id,"saveMessages",{uids:c})},a.prototype.exportFolder=function(){return a.$$resource.download(this.id,"exportFolder")},a.prototype.$delete=function(){var b=this;return a.$$resource.remove(this.id).then(function(){return b.$account.$getMailboxes({reload:!0}),!0})},a.prototype.$_deleteMessages=function(a,b){var c,d=this,e=this.$messages.length;return c=_.filter(b,function(a,b){return!a.isread}),this.unseenCount-=c.length,_.forEachRight(this.$messages,function(b,c){var f=_.findIndex(a,function(a){return b.uid==a});f>-1?(a.splice(f,1),delete d.uidsMap[b.uid],b.uid==d.selectedMessage&&delete d.selectedMessage,d.$messages.splice(c,1),cb.uids.length-1)&&(c.$topIndex=0),c.init(b),c.uids&&(a.$log.debug("unwrapping "+b.uids.length+" messages"),f=_.invokeMap(c.headers[0],"toLowerCase"),c.headers.splice(0,1),c.threaded&&(e=c.uids[0],c.uids.splice(0,1)),_.reduce(c.uids,function(b,d,f){var g;return g=c.threaded?_.zipObject(e,d):{uid:d.toString()},c.uidsMap[g.uid]=f,b.push(new a.$Message(c.$account.id,c,g,(!0))),b},c.$messages),_.forEach(c.headers,function(a){var b=_.zipObject(f,a),d=c.uidsMap[b.uid.toString()];_.extend(c.$messages[d],b)})),a.$log.debug("mailbox "+c.id+" ready"),c.$isLoading=!1,d.resolve(c.$messages)})},function(a){angular.extend(c,a),c.isError=!0,d.reject()}),d.promise},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.uidsMap[b.uid.toString()],angular.isDefined(d)&&_.extend(c.$messages[d],b)}))})})},a.prototype.$toggleSubscribe=function(){return this.subscribed?a.$$resource.post(this.id,"subscribe"):a.$$resource.post(this.id,"unsubscribe")}}(),function(){"use strict";function a(a,b,c,d){this.accountId=a,this.$mailbox=b,this.$hasUnsafeContent=!1,this.$loadUnsafeContent=!1,this.editable={to:[],cc:[],bcc:[]},this.selected=!1,"function"!=typeof c.then?(!angular.isUndefined(d)&&d||(angular.extend(this,c),this.$formatFullAddresses()),this.uid=parseInt(c.uid)):this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","sgMessage_STATUS","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{STATUS:f,$q:b,$timeout:c,$log:d,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser()),$avatar:angular.bind(h,h.avatar)}),h.ready().then(function(){h.defaults.SOGoMailLabelsColors&&(a.$tags=h.defaults.SOGoMailLabelsColors),h.defaults.SOGoMailDisplayRemoteInlineImages&&"always"==h.defaults.SOGoMailDisplayRemoteInlineImages&&(a.$displayRemoteInlineImages=!0)}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMessage_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Message",a.$factory),a.filterTags=function(b,c){var d=new RegExp(b,"i"),e=[];return _.forEach(_.keys(a.$tags),function(b){var f=a.$tags[b];f[0].search(d)!=-1&&(_.includes(c,b)||e.push({name:b,description:f[0],color:f[1]}))}),e},a.prototype.$absolutePath=function(a){function b(){var a;return a=_.map(c.$mailbox.path.split("/"),function(a){return"folder"+a.asCSSIdentifier()}),a.splice(0,0,c.accountId),a.join("/")}var c=this,d=this.id;return(angular.isUndefined(this.id)||a&&a.nocache)&&(this.id=b()+"/"+this.uid,d=this.id),a&&a.asDraft&&this.draftId&&(d=b()+"/"+this.draftId),d},a.prototype.$setUID=function(a){var b,c=this.uid||-1,d=this;c!=parseInt(a)&&(this.uid=parseInt(a),this.$absolutePath({nocache:!0}),c>-1?(c=c.toString(),angular.isDefined(this.$mailbox.uidsMap[c])&&(b=this.$mailbox.uidsMap[c],this.$mailbox.uidsMap[a]=b,delete this.$mailbox.uidsMap[c],_.forEach(["from","to","subject"],function(a){d.$mailbox.$messages[b][a]=d[a]}))):this.$mailbox.constructor.selectedFolder&&"draft"==this.$mailbox.constructor.selectedFolder.type&&this.$mailbox.constructor.selectedFolder.$filter())},a.prototype.$formatFullAddresses=function(){var b=this,c=_.map(b.$mailbox.$account.identities,"email");_.forEach(["from","to","cc","bcc","reply-to"],function(d){_.forEach(b[d],function(b){b.name&&b.name!=b.email?(b.full=b.name+" <"+b.email+">",b.name.length<10?b.shortname=b.name:b.name.split(" ").length&&(b.shortname=_.first(_.last(b.name.split(/, */)).split(/ +/)).replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$avatar(b.email,32),_.indexOf(c,b.email)>=0&&(b.shortname=l("me"))})})},a.prototype.$shortRecipients=function(a){var b=this,c=[],d=0,e=0;return _.forEach(["to","cc","bcc"],function(f){e+=b[f]?b[f].length:0,_.forEach(b[f],function(b,e){da&&c.push(l("and %{0} more...",e-a)),c.join(", ")},a.prototype.$shortAddress=function(a){var b="";return this[a]&&this[a].length>0&&(b=this[a][0].name||this[a][0].email||""),b},a.prototype.allowReplyAll=function(){var a=0;return a=_.reduce(["to","cc"],_.bind(function(a,b){return this[b]?a+this[b].length:a},this),a),!this.isDraft&&a>1},a.prototype.loadUnsafeContent=function(){this.$loadUnsafeContent=!0},a.prototype.$content=function(){var b=this,c=[],d=function(e){if(e.msgclass="msg-attachment-other","UIxMailPartAlternativeViewer"==e.type)d(_.find(e.content,function(a){return e.preferredPart==a.contentType}));else if(angular.isArray(e.content)){if("UIxMailPartSignedViewer"==e.type&&1===e["supports-smime"]){var f="

"+e.error.replace(/\n/,'

');f=f.replace(/\n/g,'

')+"

",b.$smime={validSignature:e.valid,message:f}}_.forEach(e.content,function(a){d(a)})}else angular.isUndefined(e.safeContent)&&(e.safeContent=e.content,b.$hasUnsafeContent|=e.safeContent.indexOf(" unsafe-")>-1),"UIxMailPartHTMLViewer"==e.type?(e.html=!0,b.$loadUnsafeContent||a.$displayRemoteInlineImages?(angular.isUndefined(e.unsafeContent)&&(e.unsafeContent=document.createElement("div"),e.unsafeContent.innerHTML=e.safeContent,angular.forEach(["src","data","classid","background","style"],function(a){var b,c,d,f=e.unsafeContent.querySelectorAll("[unsafe-"+a+"]");for(d=0;d=0)for(b=0,c=0;c0){var d=_.map(b,"uid");f.push(b);var h=a.$$resource.post(c,"addOrRemoveLabel",_.assign(e,{msgUIDs:d}));g.push(h)}}),a.$q.all(g).then(function(){return _.flatten(f)})},a.prototype.$deleteMessages=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$deleteMessages(a);c.push(e)}}),a.$q.all(c)},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$markOrUnMarkMessagesAsJunk(a);c.push(e)}}),a.$q.all(c)},a.prototype.$copyMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$copyMessages(a,c);d.push(f)}}),a.$q.all(d)},a.prototype.$moveMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$moveMessages(a,c);d.push(f)}}),a.$q.all(d)}}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q){function r(a){a.push(k.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:v})),a.push(k.createHotkey({key:l("hotkey_compose"),description:l("Write a new message"),callback:x})),a.push(k.createHotkey({key:"space",description:l("Toggle item"),callback:D})),a.push(k.createHotkey({key:"up",description:l("View next item"),callback:y,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"down",description:l("View previous item"),callback:z,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:A,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:B,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:G})),_.forEach(a,function(a){k.registerHotkey(a)})}function s(a){return O.selectedFolder.$compact()}function t(a){O.selectedFolder.$filter({sort:a})}function u(a){return q.$query.sort==a}function v(){O.mode.search=!0,n("search")}function w(){O.mode.search=!1,O.selectedFolder.$filter().then(function(){O.selectedFolder.selectedMessage&&c(function(){O.selectedFolder.$topIndex=O.selectedFolder.uidsMap[O.selectedFolder.selectedMessage]})})}function x(a){var b;null===P&&(b=O.account.$newMessage(),P=f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:O.account,stateMessage:b,stateRecipients:[]}}).finally(function(){P=null}))}function y(a){var b=O.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?b--:b=O.selectedFolder.getLength()-1,b>-1&&C(O.selectedFolder.$messages[b]),O.selectedFolder.$topIndex>0&&O.selectedFolder.$topIndex--,a.preventDefault(),b}function z(a){var b=O.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?b++:b=0,b=0&&D(a,O.selectedFolder.$messages[b]))}function B(a){var b;O.selectedFolder.hasSelectedMessage()&&(b=z(a),b>=0&&D(a,O.selectedFolder.$messages[b]))}function C(a){q.$virtualMode?e.go("mail.account.virtualMailbox.message",{mailboxId:m(a.$mailbox.path),messageId:a.uid}):e.go("mail.account.mailbox.message",{messageId:a.uid})}function D(a,b){b||(b=O.selectedFolder.$selectedMessage()),b.selected=!b.selected,O.mode.multiple+=b.selected?1:-1,a.preventDefault(),a.stopPropagation()}function E(){return q.$virtualMode?O.selectedFolder.$mailboxes:[O.selectedFolder]}function F(a,b){var d,f,g=b;O.mode.multiple=O.selectedFolder.$selectedCount(),a?(b>0&&(g-=1,d=O.selectedFolder.$messages[g]),b0&&(P=o.confirm(l("Warning"),l("Are you sure you want to delete the selected messages?"),{ok:l("Delete")}).then(function(){var a=O.selectedFolder.hasSelectedMessage();O.selectedFolder.$deleteMessages(b).then(function(b){q.$virtualMode?a&&e.go("mail.account.virtualMailbox"):F(a,b)})}).finally(function(){P=null})),a.preventDefault()}function H(){var a=O.selectedFolder.hasSelectedMessage(),b=O.selectedFolder.$selectedMessages();_.size(b)>0&&O.selectedFolder.$markOrUnMarkMessagesAsJunk(b).then(function(){var c="/"+O.account.id+"/folderINBOX";"junk"!=O.selectedFolder.type&&(c="/"+O.account.$getMailboxByType("junk").id),O.selectedFolder.$moveMessages(b,c).then(function(b){q.$virtualMode?a&&e.go("mail.account.virtualMailbox"):F(a,b)})})}function I(a){var b=O.selectedFolder.$selectedMessages();_.size(b)>0&&O.selectedFolder.$copyMessages(b,"/"+a).then(function(){g.show(g.simple().content(l("%{0} message(s) copied",O.selectedFolder.$selectedCount())).position("top right").hideDelay(2e3))})}function J(a){var b=O.selectedFolder.hasSelectedMessage(),c=O.selectedFolder.$selectedMessages(),d=O.selectedFolder.$selectedCount();_.size(c)>0&&O.selectedFolder.$moveMessages(c,"/"+a).then(function(a){g.show(g.simple().content(l("%{0} message(s) moved",d)).position("top right").hideDelay(2e3)),q.$virtualMode?b&&e.go("mail.account.virtualMailbox"):F(b,a)})}function K(){var a=0;_.forEach(E(),function(b){for(var c=0,d=b.$messages.length;c0&&O.selectedFolder.$flagMessages(a,"\\Flagged","add").then(function(a){_.forEach(a,function(a){ -a.isflagged=!0})})}function N(){var a=O.selectedFolder.$selectedMessages();_.size(a)>0&&O.selectedFolder.$flagMessages(a,"seen","remove").then(function(a){_.forEach(a,function(a){a.isread=!1,a.$mailbox.unseenCount++})})}var O=this,P=null,Q=angular.element(a.document).find("title").attr("sg-default")||"SOGo",R=[];a.$mailboxController=O,O.service=q,O.accounts=h,O.account=i,O.selectedFolder=j,O.selectMessage=C,O.toggleMessageSelection=D,O.sort=t,O.sortedBy=u,O.searchMode=v,O.cancelSearch=w,O.newMessage=x,O.mode={search:!1,multiple:0},O.confirmDeleteSelectedMessages=G,O.markOrUnMarkMessagesAsJunk=H,O.copySelectedMessages=I,O.moveSelectedMessages=J,O.markSelectedMessagesAsFlagged=M,O.markSelectedMessagesAsUnread=N,O.selectAll=K,O.unselectMessages=L,j.selectFolder(),r(R),angular.element(a).on("beforeunload",s),b.$on("$destroy",function(){angular.element(a).off("beforeunload",s),_.forEach(R,function(a){k.deregisterHotkey(a)})}),b.$watch(function(){return O.selectedFolder.unseenCount},function(b){var c=Q+" - ";b&&(c+="("+b+") "),c+=O.selectedFolder.name,a.document.title=c})}function b(a){return a[0].controller.prototype.resetScroll=function(){"messagesList"==this.$element.parent().attr("id")?this.updateSize():this.scrollTo(0)},a}a.$inject=["$window","$scope","$timeout","$q","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgFocus","Dialog","Account","Mailbox"],angular.module("material.components.virtualRepeat").decorator("mdVirtualRepeatContainerDirective",b),b.$inject=["$delegate"],angular.module("SOGo.MailerUI").controller("MailboxController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:function(){q.selectedFolder&&!q.selectedFolder.hasSelectedMessage()&&L(q.selectedFolder)}})),_.forEach(a,function(a){o.registerHotkey(a)})}function w(a){V.showingAdvancedSearch=!0,V.search.mailbox=a,g(i["gt-md"])||h("left").close()}function x(){V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,T=V.accounts[0],U=V.searchPreviousMailbox,b.go("mail.account.mailbox",{accountId:T.id,mailboxId:k(U.path)})}function y(){if(q.selectedFolder.$isLoading)V.virtualMailbox.stopSearch();else{var a,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};V.virtualMailbox=new r(V.accounts[0]),q.$virtualMode||(V.searchPreviousMailbox=q.selectedFolder),q.selectedFolder=V.virtualMailbox,q.$virtualMode=!0,angular.isDefined(V.search.mailbox)?(a=V.accounts[0].$getMailboxByPath(V.search.mailbox),c.push(a),V.search.subfolders&&a.children.length&&d(a.children)):c=V.accounts[0].$flattenMailboxes(),V.virtualMailbox.setMailboxes(c),V.virtualMailbox.startSearch(V.search.match,V.search.params),b.go("mail.account.virtualMailbox",{accountId:V.accounts[0].id})}}function z(a){return V.currentSearchParam=a,j("advancedSearch"),!1}function A(a){if(a.length&&V.currentSearchParam.length){var b=0,c=V.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),V.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function B(a){a.$expanded=!a.$expanded,a.$flattenMailboxes({reload:!0,saveState:!0}),c(function(){angular.element(d).triggerHandler("resize")},150)}function C(a){function b(a,b,c,d){function e(){b.cancel()}var f=this;f.app=c,f.account=new p({id:d.id,name:d.name},(!0)),f.close=e}e.show({templateUrl:a.id+"/subscribe",controller:b,controllerAs:"subscriptions",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcApp:V,srcAccount:a}}).finally(function(){a.$getMailboxes({reload:!0})}),b.$inject=["$scope","$mdDialog","srcApp","srcAccount"]}function D(a){m.prompt(l("New folder"),l("Enter the new name of your folder :")).then(function(b){a.$newMailbox(a.id,b).then(function(){},function(a,c){m.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function E(a){function b(a,b,c,d){function e(a){return c.$filter(a,d.delegates)}function f(){b.hide()}function g(a){d.$removeDelegate(a.uid).catch(function(a,b){m.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){i.userToAdd="",i.searchText=""},function(a){m.alert(l("Warning"),a)})}var i=this;i.users=d.delegates,i.account=d,i.userToAdd="",i.searchText="",i.userFilter=e,i.closeModal=f,i.removeUser=g,i.addUser=h}e.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:s,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function F(a){V.editMode=a.path,j("mailboxName_"+a.path)}function G(a){a.$reset(),V.editMode=!1}function H(a,c,d){V.editMode!=d.path&&(V.editMode=!1,V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,g(i["gt-md"])||h("left").close(),b.go("mail.account.mailbox",{accountId:c.id,mailboxId:k(d.path)}),a.stopPropagation(),a.preventDefault())}function I(a){a.$rename().then(function(a){V.editMode=!1})}function J(a){a.$compact().then(function(){f.show(f.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function K(a){a.$emptyTrash().then(function(){f.show(f.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function L(a){m.confirm(l("Confirmation"),l("Do you really want to move this folder into the trash ?")).then(function(){a.$delete().then(function(){b.go("mail.account.inbox")},function(b,c){m.alert(l('An error occured while deleting the mailbox "%{0}".',a.name),l(b.error))})})}function M(a){a.$markAsRead()}function N(a){a.$acl.$users().then(function(){e.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:s,folder:a}})})}function O(a){return"inbox"==a.type?{name:a.name,icon:"inbox",special:!0}:"draft"==a.type?{name:l("DraftsFolderName"),icon:"drafts",special:!0}:"sent"==a.type?{name:l("SentFolderName"),icon:"send",special:!0}:"trash"==a.type?{name:l("TrashFolderName"),icon:"delete",special:!0}:"junk"==a.type?{name:l("JunkFolderName"),icon:"thumb_down",special:!0}:"additional"==a.type?{name:a.name,icon:"folder_shared",special:!0}:{name:a.name,icon:"folder_open",special:!1}}function P(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function Q(){var a=d.unseenCountFolders;_.forEach(V.accounts,function(b){_.includes(a,b.id+"/folderINBOX")||a.push(b.id+"/folderINBOX"),_.forEach(b.$$flattenMailboxes,function(b){angular.isDefined(b.unseenCount)&&!_.includes(a,b.id)&&a.push(b.id)})}),p.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(V.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),t.ready().then(function(){var a=t.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&c(V.refreshUnseenCount,1e3*a.timeInterval())})}function R(a,b){return b.id!=a.id&&!b.isNoSelect()}function S(a,c,d){var e,g,h,i,j,k;e="/"+c.id,g=a.$selectedMessages(),0===g.length&&(g=[a.$selectedMessage()]),h=_.map(g,"uid"),i=a.selectedMessage&&h.indexOf(a.selectedMessage)>=0,"copy"==d?(j=a.$copyMessages(g,e),k=l("%{0} message(s) copied",g.length)):(j=a.$moveMessages(g,e),k=l("%{0} message(s) moved",g.length)),j.then(function(){i&&b.go("mail.account.mailbox"),f.show(f.simple().content(k).position("top right").hideDelay(2e3))})}var T,U,V=this,W=[];V.service=q,V.accounts=u,V.toggleAccountState=B,V.subscribe=C,V.newFolder=D,V.delegate=E,V.editFolder=F,V.revertEditing=G,V.selectFolder=H,V.saveFolder=I,V.compactFolder=J,V.emptyTrashFolder=K,V.confirmDelete=L,V.markFolderRead=M,V.share=N,V.metadataForFolder=O,V.setFolderAs=P,V.refreshUnseenCount=Q,V.isDroppableFolder=R,V.dragSelectedMessages=S,V.showingAdvancedSearch=!1,V.currentSearchParam="",V.addSearchParam=z,V.newSearchParam=A,V.showAdvancedSearch=w,V.hideAdvancedSearch=x,V.toggleAdvancedSearch=y,V.search={options:{"":l("Select a criteria"),subject:l("Enter Subject"),from:l("Enter From"),to:l("Enter To"),cc:l("Enter Cc"),body:l("Enter Body")},mailbox:"INBOX",subfolders:1,match:"AND",params:[]},t.ready().then(function(){V.showSubscribedOnly=t.defaults.SOGoMailShowSubscribedFoldersOnly}),V.refreshUnseenCount(),v(W),a.$on("$destroy",function(){_.forEach(W,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$state","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgConstant","sgFocus","encodeUriFilter","Dialog","sgSettings","sgHotkeys","Account","Mailbox","VirtualMailbox","User","Preferences","stateAccounts"],angular.module("SOGo.MailerUI").controller("MailboxesController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){function u(a){a.push(k.createHotkey({key:"backspace",callback:function(a){0===N.mailbox.$selectedCount()&&y(),a.preventDefault()}})),_.forEach(a,function(a){k.registerHotkey(a)})}function v(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==i.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==j.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function w(a){N.$showDetailedRecipients=!N.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function x(a){var b,c,d,e;"A"==a.target.tagName&&"href"in a.target.attributes&&(b=a.target.attributes.href.value,c=/^mailto:([^\?]+)/.exec(b),c&&(d=_.map(decodeURIComponent(c[1]).split(","),function(a){return"<"+a+">"}),e={to:d},_.forEach(["subject","body"],function(a){var d=new RegExp(a+"=([^&]+)");a="body"==a?"text":a,c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),_.forEach(["cc","bcc"],function(a){var d=new RegExp(a+"=([^&]+)");c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),H(a,e)))}function y(){var a,b,e,g,h,k=v();k.messageCtrl?(a=k.mailboxCtrl.selectedFolder,b=k.messageCtrl.message,e=k.messageCtrl.$state):(a=i,b=j,e=c),a.$deleteMessages([b]).then(function(c){var i=c;if(b=null,angular.isDefined(e)){c>0&&(i-=1,g=a.$messages[i]),ca.$lastVisibleIndex&&(a.$topIndex=i-(a.$lastVisibleIndex-a.$topIndex))):e.go("mail.account.mailbox").then(function(){b=null,delete a.selectedMessage})}catch(a){}}G()})}function z(a,b){null===O&&(O=e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:N.account,stateMessage:b}}).finally(function(){O=null,G()}))}function A(){c.go("mail.account.mailbox").then(function(){N.message=null,delete i.selectedMessage})}function B(a){var b=N.message.$reply();z(a,b)}function C(a){var b=N.message.$replyAll();z(a,b)}function D(a){var b=N.message.$forward();z(a,b)}function E(a){N.message.$editableContent().then(function(){z(a,N.message)})}function F(){var b=[m.baseURL(),"UIxMailPopupView#/Mail",N.message.accountId,l(l(N.message.$mailbox.path)),N.message.uid].join("/"),c=N.message.$absolutePath();P=a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function G(){a.opener&&a.close()}function H(a,b){N.account.$newMessage().then(function(c){angular.extend(c.editable,b),z(a,c)}),a.stopPropagation(),a.preventDefault()}function I(a){N.showRawSource||N.message.$rawSource?N.showRawSource=!N.showRawSource:t.$$resource.post(N.message.id,"viewsource").then(function(a){N.message.$rawSource=a,N.showRawSource=!0})}function J(b){a.print()}function K(a){return M(a,"appointment")}function L(a){return M(a,"task")}function M(a,b){N.message.$plainContent().then(function(c){var d={pid:p.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new q(d),g=[m.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var N=this,O=null,P=null,Q=[];a.$messageController=N,N.$state=c,N.accounts=g,N.account=h,N.mailbox=i,N.message=j,N.service=t,N.tags={searchText:"",selected:""},N.showFlags=j.flags&&j.flags.length>0,N.$showDetailedRecipients=!1,N.toggleDetailedRecipients=w,N.filterMailtoLinks=x,N.deleteMessage=y,N.close=A,N.reply=B,N.replyAll=C,N.forward=D,N.edit=E,N.openPopup=F,N.closePopup=G,N.newMessage=H,N.toggleRawSource=I,N.showRawSource=!1,N.print=J,N.convertToEvent=K,N.convertToTask=L,u(Q),a.opener?(b.$watchCollection(function(){return N.message.flags},function(a,b){var c;(a||b)&&(c=v(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.showFlags=!0,c.messageCtrl.message.flags=a}))}),b.$watch(function(){return N.message.isflagged},function(a,b){var c=v();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){var b=_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:N.message.uid});b.isflagged=a})})):b.$watchCollection(function(){return N.message.flags},function(a,b){var c,d,e;(a||b)&&(c=a||[],d=b||[],_.forEach(c,function(a,b){angular.isObject(a)&&(c[b]=a.name)}),c.length>d.length?(e=_.difference(c,d),_.forEach(e,function(a){N.message.addTag(a)})):c.length":a.full="<"+a.email+">"}),a.$log.debug("Account: "+JSON.stringify(b,void 0,2)))}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Preferences","Mailbox","Message",function(b,c,d,e,f,g,h,i){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Preferences:g,$Mailbox:h,$Message:i}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").factory("Account",a.$factory),a.$findAll=function(b){return b?a.$unwrapCollection(b):a.$$resource.fetch("","mailAccounts").then(function(b){return a.$unwrapCollection(b)})},a.$unwrapCollection=function(b){var c=[];return angular.forEach(b,function(b,d){b.id=d,c[d]=new a(b)}),a.$accounts=c,c},a.prototype.getLength=function(){return this.$flattenMailboxes().length},a.prototype.getItemAtIndex=function(a){var b;return b=this.$flattenMailboxes(),a>=0&&a=0,a.children&&a.children.length>0&&d(a.children)})};a.$Preferences.settings.Mail.ExpandedFolders&&(b=angular.isString(a.$Preferences.settings.Mail.ExpandedFolders)?angular.fromJson(a.$Preferences.settings.Mail.ExpandedFolders):a.$Preferences.settings.Mail.ExpandedFolders,c.$expanded=b.indexOf("/"+c.id)>=0,b.length>0&&d(c.$mailboxes)),a.$accounts&&(c.$expanded|=1==a.$accounts.length),c.$flattenMailboxes({reload:!0})}),c.$mailboxes}):a.$q.when(this.$mailboxes)},a.prototype.$flattenMailboxes=function(b){var c=this,d=[],e=[],f=function(a){_.forEach(a,function(a){d.push(a),(b&&b.all||a.$expanded)&&a.children&&a.children.length>0&&f(a.children)})};return!this.$$flattenMailboxes||b&&(b.reload||b.all)?(f(this.$mailboxes),b&&b.all||(c.$$flattenMailboxes=d,b&&b.saveState&&(_.forEach(a.$accounts,function(a){a.$expanded&&e.push("/"+a.id),_.reduce(a.$$flattenMailboxes,function(a,b){return b.$expanded&&a.push("/"+b.id),a},e)}),a.$$resource.post(null,"saveFoldersState",e)))):d=this.$$flattenMailboxes,d},a.prototype.$getMailboxByType=function(a){var b,c=function(b){var d=_.find(b,function(b){return b.type==a});return d||angular.forEach(b,function(a){!d&&a.children&&a.children.length>0&&(d=c(a.children))}),d};return b=c(this.$mailboxes)},a.prototype.$getMailboxByPath=function(a){var b=null,c=function(b){var d=_.find(b,function(b){return b.path==a});return d||angular.forEach(b,function(a){!d&&a.children&&a.children.length>0&&(d=c(a.children))}),d};return b=c(this.$mailboxes)},a.prototype.$newMailbox=function(b,c){var d=this;return a.$$resource.post(b.toString(),"createFolder",{name:c}).then(function(){d.$getMailboxes({reload:!0})})},a.prototype.updateQuota=function(a){var b,c,d;b=Math.round(1e4*a.usedSpace/a.maxQuota)/100,c=l("quotasFormat"),d=c.formatted(b,Math.round(a.maxQuota/10.24)/100),this.$quota={percent:b,description:d}},a.prototype.$newMessage=function(){var b=this;return a.$$resource.fetch(this.id.toString(),"compose").then(function(c){a.$log.debug("New message (compose): "+JSON.stringify(c,void 0,2));var d=new a.$Message(c.accountId,b.$getMailboxByPath(c.mailboxPath),c);return d}).then(function(b){return a.$$resource.fetch(b.$absolutePath({asDraft:!0}),"edit").then(function(c){return a.$log.debug("New message (edit): "+JSON.stringify(c,void 0,2)),angular.extend(b.editable,c),b.isNew=!0,b})})},a.prototype.$addDelegate=function(b){var c=this,d=a.$q.defer(),e={uid:b.uid};return!b.uid||_.indexOf(_.map(this.delegates,"uid"),b.uid)>-1?d.resolve():a.$$resource.fetch(this.id.toString(),"addDelegate",e).then(function(){c.delegates.push(b),d.resolve(c.users)},function(a,b){d.reject(l("An error occured please try again."))}),d.promise},a.prototype.$removeDelegate=function(b){var c=this,d={uid:b};return a.$$resource.fetch(this.id.toString(),"removeDelegate",d).then(function(){var a=_.indexOf(_.map(c.delegates,"uid"),b);a>=0&&c.delegates.splice(a,1)})}}(),function(){"use strict";function a(b,c){if(this.$account=b,"function"!=typeof c.then){if(this.init(c),this.name&&!this.path){var d=a.$$resource.create("createFolder",this.name);this.$unwrap(d)}}else this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Message","Acl","Preferences","sgMailbox_PRELOAD",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Message:g,$$Acl:h,$Preferences:i,$query:{sort:"date",asc:0},selectedFolder:null,$refreshTimeout:null,$virtualMode:!1,PRELOAD:j}),i.ready().then(function(){i.settings.Mail.SortingState&&(a.$query.sort=i.settings.Mail.SortingState[0],a.$query.asc=parseInt(i.settings.Mail.SortingState[1]))}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMailbox_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("Mailbox",a.$factory),a.$find=function(b){var c;return c=b.fetchAll?this.$$resource.fetch(b.id.toString(),"viewAll"):this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,c)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&a=0},a.prototype.isNoSelect=function(){return this.flags.indexOf("noselect")>=0},a.prototype.$rename=function(){var b,c,d,e,f=this;return this.name==this.$shadowData.name?a.$q.when():(b=function(a,c){var d=null,e=_.find(c,function(a){return a.path==f.path});return e?d=a:angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a,a.children))}),d},c=b(null,this.$account.$mailboxes),d=null===c?this.$account.$mailboxes:c.children,e=_.indexOf(_.map(d,"id"),this.id),this.$save().then(function(b){var c;angular.extend(f,b),f.id=f.$id(),d.splice(e,1),c=_.find(d,function(b){return a.$log.debug(b.name+" ? "+f.name),"folder"==b.type&&b.name.localeCompare(f.name)>0}),e=c?_.indexOf(_.map(d,"id"),c.id):d.length,d.splice(e,0,f)}))},a.prototype.$compact=function(){var b=this;return a.$$resource.post(this.id,"expunge").then(function(a){a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$setFolderAs=function(b){return a.$$resource.post(this.id,"setAs"+b+"Folder")},a.prototype.$emptyTrash=function(){var b=this;return a.$$resource.post(this.id,"emptyTrash").then(function(a){b.$messages=[],b.uidsMap={},b.unseenCount=0,angular.isDefined(b.children)&&b.children.length&&b.$account.$getMailboxes({reload:!0}),a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$markAsRead=function(){return a.$$resource.post(this.id,"markRead")},a.prototype.$flagMessages=function(b,c,d){var e={msgUIDs:_.map(b,"uid"),flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e).then(function(){return b})},a.prototype.saveSelectedMessages=function(){var b,c;return b=_.filter(this.$messages,function(a){return a.selected}),c=_.map(b,"uid"),a.$$resource.download(this.id,"saveMessages",{uids:c})},a.prototype.exportFolder=function(){return a.$$resource.download(this.id,"exportFolder")},a.prototype.$delete=function(){var b=this;return a.$$resource.remove(this.id).then(function(){return b.$account.$getMailboxes({reload:!0}),!0})},a.prototype.$_deleteMessages=function(a,b){var c,d=this,e=this.$messages.length;return c=_.filter(b,function(a,b){return!a.isread}),this.unseenCount-=c.length,_.forEachRight(this.$messages,function(b,c){var f=_.findIndex(a,function(a){return b.uid==a});f>-1?(a.splice(f,1),delete d.uidsMap[b.uid],b.uid==d.selectedMessage&&delete d.selectedMessage,d.$messages.splice(c,1),cb.uids.length-1)&&(c.$topIndex=0),c.init(b),c.uids&&(a.$log.debug("unwrapping "+b.uids.length+" messages"),f=_.invokeMap(c.headers[0],"toLowerCase"),c.headers.splice(0,1),c.threaded&&(e=c.uids[0],c.uids.splice(0,1)),_.reduce(c.uids,function(b,d,f){var g;return g=c.threaded?_.zipObject(e,d):{uid:d.toString()},c.uidsMap[g.uid]=f,b.push(new a.$Message(c.$account.id,c,g,(!0))),b},c.$messages),_.forEach(c.headers,function(a){var b=_.zipObject(f,a),d=c.uidsMap[b.uid.toString()];_.extend(c.$messages[d],b)})),a.$log.debug("mailbox "+c.id+" ready"),c.$isLoading=!1,d.resolve(c.$messages)})},function(a){angular.extend(c,a),c.isError=!0,d.reject()}),d.promise},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.uidsMap[b.uid.toString()],angular.isDefined(d)&&_.extend(c.$messages[d],b)}))})})},a.prototype.$toggleSubscribe=function(){return this.subscribed?a.$$resource.post(this.id,"subscribe"):a.$$resource.post(this.id,"unsubscribe")}}(),function(){"use strict";function a(a,b,c,d){this.accountId=a,this.$mailbox=b,this.$hasUnsafeContent=!1,this.$loadUnsafeContent=!1,this.editable={to:[],cc:[],bcc:[]},this.selected=!1,"function"!=typeof c.then?(!angular.isUndefined(d)&&d||(angular.extend(this,c),this.$formatFullAddresses()),this.uid=parseInt(c.uid)):this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","sgMessage_STATUS","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{STATUS:f,$q:b,$timeout:c,$log:d,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser()),$avatar:angular.bind(h,h.avatar)}),h.ready().then(function(){h.defaults.SOGoMailLabelsColors&&(a.$tags=h.defaults.SOGoMailLabelsColors),h.defaults.SOGoMailDisplayRemoteInlineImages&&"always"==h.defaults.SOGoMailDisplayRemoteInlineImages&&(a.$displayRemoteInlineImages=!0)}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMessage_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Message",a.$factory),a.filterTags=function(b,c){var d=new RegExp(b,"i"),e=[];return _.forEach(_.keys(a.$tags),function(b){var f=a.$tags[b];f[0].search(d)!=-1&&(_.includes(c,b)||e.push({name:b,description:f[0],color:f[1]}))}),e},a.prototype.$absolutePath=function(a){function b(){var a;return a=_.map(c.$mailbox.path.split("/"),function(a){return"folder"+a.asCSSIdentifier()}),a.splice(0,0,c.accountId),a.join("/")}var c=this,d=this.id;return(angular.isUndefined(this.id)||a&&a.nocache)&&(this.id=b()+"/"+this.uid,d=this.id),a&&a.asDraft&&this.draftId&&(d=b()+"/"+this.draftId),d},a.prototype.$setUID=function(a){var b,c=this.uid||-1,d=this;c!=parseInt(a)&&(this.uid=parseInt(a),this.$absolutePath({nocache:!0}),c>-1?(c=c.toString(),angular.isDefined(this.$mailbox.uidsMap[c])&&(b=this.$mailbox.uidsMap[c],this.$mailbox.uidsMap[a]=b,delete this.$mailbox.uidsMap[c],_.forEach(["from","to","subject"],function(a){d.$mailbox.$messages[b][a]=d[a]}))):this.$mailbox.constructor.selectedFolder&&"draft"==this.$mailbox.constructor.selectedFolder.type&&this.$mailbox.constructor.selectedFolder.$filter())},a.prototype.$formatFullAddresses=function(){var b=this,c=_.map(b.$mailbox.$account.identities,"email");_.forEach(["from","to","cc","bcc","reply-to"],function(d){_.forEach(b[d],function(b){b.name&&b.name!=b.email?(b.full=b.name+" <"+b.email+">",b.name.length<10?b.shortname=b.name:b.name.split(" ").length&&(b.shortname=_.first(_.last(b.name.split(/, */)).split(/ +/)).replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$avatar(b.email,32),_.indexOf(c,b.email)>=0&&(b.shortname=l("me"))})})},a.prototype.$shortRecipients=function(a){var b=this,c=[],d=0,e=0;return _.forEach(["to","cc","bcc"],function(f){e+=b[f]?b[f].length:0,_.forEach(b[f],function(b,e){da&&c.push(l("and %{0} more...",e-a)),c.join(", ")},a.prototype.$shortAddress=function(a){var b="";return this[a]&&this[a].length>0&&(b=this[a][0].name||this[a][0].email||""),b},a.prototype.allowReplyAll=function(){var a=0;return a=_.reduce(["to","cc"],_.bind(function(a,b){return this[b]?a+this[b].length:a},this),a),!this.isDraft&&a>1},a.prototype.loadUnsafeContent=function(){this.$loadUnsafeContent=!0},a.prototype.$content=function(){var b=this,c=[],d=function(e){if(e.msgclass="msg-attachment-other","UIxMailPartAlternativeViewer"==e.type)d(_.find(e.content,function(a){return e.preferredPart==a.contentType}));else if(angular.isArray(e.content)){if("UIxMailPartSignedViewer"==e.type&&1===e["supports-smime"]){var f="

"+e.error.replace(/\n/,'

');f=f.replace(/\n/g,'

')+"

",b.$smime={validSignature:e.valid,message:f}}_.forEach(e.content,function(a){d(a)})}else angular.isUndefined(e.safeContent)&&(e.safeContent=e.content,b.$hasUnsafeContent|=e.safeContent.indexOf(" unsafe-")>-1),"UIxMailPartHTMLViewer"==e.type?(e.html=!0,b.$loadUnsafeContent||a.$displayRemoteInlineImages?(angular.isUndefined(e.unsafeContent)&&(e.unsafeContent=document.createElement("div"),e.unsafeContent.innerHTML=e.safeContent,angular.forEach(["src","data","classid","background","style"],function(a){var b,c,d,f=e.unsafeContent.querySelectorAll("[unsafe-"+a+"]");for(d=0;d=0)for(b=0,c=0;c0){var d=_.map(b,"uid");f.push(b);var h=a.$$resource.post(c,"addOrRemoveLabel",_.assign(e,{msgUIDs:d}));g.push(h)}}),a.$q.all(g).then(function(){return _.flatten(f)})},a.prototype.$deleteMessages=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$deleteMessages(a);c.push(e)}}),a.$q.all(c)},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$markOrUnMarkMessagesAsJunk(a);c.push(e)}}),a.$q.all(c)},a.prototype.$copyMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$copyMessages(a,c);d.push(f)}}),a.$q.all(d)},a.prototype.$moveMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$moveMessages(a,c);d.push(f)}}),a.$q.all(d)}}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q){function r(a){a.push(k.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:v})),a.push(k.createHotkey({key:l("hotkey_compose"),description:l("Write a new message"),callback:x})),a.push(k.createHotkey({key:"space",description:l("Toggle item"),callback:D})),a.push(k.createHotkey({key:"up",description:l("View next item"),callback:y,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"down",description:l("View previous item"),callback:z,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:A,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:B,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:G})),_.forEach(a,function(a){k.registerHotkey(a)})}function s(a){return O.selectedFolder.$compact()}function t(a){O.selectedFolder.$filter({sort:a})}function u(a){return q.$query.sort==a}function v(){O.mode.search=!0,n("search")}function w(){O.mode.search=!1,O.selectedFolder.$filter().then(function(){O.selectedFolder.selectedMessage&&c(function(){O.selectedFolder.$topIndex=O.selectedFolder.uidsMap[O.selectedFolder.selectedMessage]})})}function x(a){var b;null===P&&(b=O.account.$newMessage(),P=f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:O.account,stateMessage:b,stateRecipients:[]}}).finally(function(){P=null}))}function y(a){var b=O.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?b--:b=O.selectedFolder.getLength()-1,b>-1&&C(O.selectedFolder.$messages[b]),O.selectedFolder.$topIndex>0&&O.selectedFolder.$topIndex--,a.preventDefault(),b}function z(a){var b=O.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?b++:b=0,b=0&&D(a,O.selectedFolder.$messages[b]))}function B(a){var b;O.selectedFolder.hasSelectedMessage()&&(b=z(a),b>=0&&D(a,O.selectedFolder.$messages[b]))}function C(a){q.$virtualMode?e.go("mail.account.virtualMailbox.message",{mailboxId:m(a.$mailbox.path),messageId:a.uid}):e.go("mail.account.mailbox.message",{messageId:a.uid})}function D(a,b){b||(b=O.selectedFolder.$selectedMessage()),b.selected=!b.selected,O.mode.multiple+=b.selected?1:-1,a.preventDefault(),a.stopPropagation()}function E(){return q.$virtualMode?O.selectedFolder.$mailboxes:[O.selectedFolder]}function F(a,b){var d,f,g=b;O.mode.multiple=O.selectedFolder.$selectedCount(),a?(b>0&&(g-=1,d=O.selectedFolder.$messages[g]),b0&&(P=o.confirm(l("Warning"),l("Are you sure you want to delete the selected messages?"),{ok:l("Delete")}).then(function(){var a=O.selectedFolder.hasSelectedMessage();O.selectedFolder.$deleteMessages(b).then(function(b){q.$virtualMode?a&&e.go("mail.account.virtualMailbox"):F(a,b)})}).finally(function(){P=null})),a.preventDefault()}function H(){var a=O.selectedFolder.hasSelectedMessage(),b=O.selectedFolder.$selectedMessages();_.size(b)>0&&O.selectedFolder.$markOrUnMarkMessagesAsJunk(b).then(function(){var c="/"+O.account.id+"/folderINBOX";"junk"!=O.selectedFolder.type&&(c="/"+O.account.$getMailboxByType("junk").id),O.selectedFolder.$moveMessages(b,c).then(function(b){q.$virtualMode?a&&e.go("mail.account.virtualMailbox"):F(a,b)})})}function I(a){var b=O.selectedFolder.$selectedMessages();_.size(b)>0&&O.selectedFolder.$copyMessages(b,"/"+a).then(function(){g.show(g.simple().content(l("%{0} message(s) copied",O.selectedFolder.$selectedCount())).position("top right").hideDelay(2e3))})}function J(a){var b=O.selectedFolder.hasSelectedMessage(),c=O.selectedFolder.$selectedMessages(),d=O.selectedFolder.$selectedCount();_.size(c)>0&&O.selectedFolder.$moveMessages(c,"/"+a).then(function(a){g.show(g.simple().content(l("%{0} message(s) moved",d)).position("top right").hideDelay(2e3)),q.$virtualMode?b&&e.go("mail.account.virtualMailbox"):F(b,a)})}function K(){var a=0;_.forEach(E(),function(b){for(var c=0,d=b.$messages.length;c0&&O.selectedFolder.$flagMessages(a,"\\Flagged","add").then(function(a){_.forEach(a,function(a){a.isflagged=!0})})}function N(){var a=O.selectedFolder.$selectedMessages();_.size(a)>0&&O.selectedFolder.$flagMessages(a,"seen","remove").then(function(a){ +_.forEach(a,function(a){a.isread=!1,a.$mailbox.unseenCount++})})}var O=this,P=null,Q=angular.element(a.document).find("title").attr("sg-default")||"SOGo",R=[];a.$mailboxController=O,O.service=q,O.accounts=h,O.account=i,O.selectedFolder=j,O.selectMessage=C,O.toggleMessageSelection=D,O.sort=t,O.sortedBy=u,O.searchMode=v,O.cancelSearch=w,O.newMessage=x,O.mode={search:!1,multiple:0},O.confirmDeleteSelectedMessages=G,O.markOrUnMarkMessagesAsJunk=H,O.copySelectedMessages=I,O.moveSelectedMessages=J,O.markSelectedMessagesAsFlagged=M,O.markSelectedMessagesAsUnread=N,O.selectAll=K,O.unselectMessages=L,j.selectFolder(),r(R),angular.element(a).on("beforeunload",s),b.$on("$destroy",function(){angular.element(a).off("beforeunload",s),_.forEach(R,function(a){k.deregisterHotkey(a)})}),b.$watch(function(){return O.selectedFolder.unseenCount},function(b){var c=Q+" - ";b&&(c+="("+b+") "),c+=O.selectedFolder.name,a.document.title=c})}function b(a){return a[0].controller.prototype.resetScroll=function(){"messagesList"==this.$element.parent().attr("id")?this.updateSize():this.scrollTo(0)},a}a.$inject=["$window","$scope","$timeout","$q","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgFocus","Dialog","Account","Mailbox"],angular.module("material.components.virtualRepeat").decorator("mdVirtualRepeatContainerDirective",b),b.$inject=["$delegate"],angular.module("SOGo.MailerUI").controller("MailboxController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:function(){q.selectedFolder&&!q.selectedFolder.hasSelectedMessage()&&L(q.selectedFolder)}})),_.forEach(a,function(a){o.registerHotkey(a)})}function w(a){V.showingAdvancedSearch=!0,V.search.mailbox=a,g(i["gt-md"])||h("left").close()}function x(){V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,T=V.accounts[0],U=V.searchPreviousMailbox,b.go("mail.account.mailbox",{accountId:T.id,mailboxId:k(U.path)})}function y(){if(q.selectedFolder.$isLoading)V.virtualMailbox.stopSearch();else{var a,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};V.virtualMailbox=new r(V.accounts[0]),q.$virtualMode||(V.searchPreviousMailbox=q.selectedFolder),q.selectedFolder=V.virtualMailbox,q.$virtualMode=!0,angular.isDefined(V.search.mailbox)?(a=V.accounts[0].$getMailboxByPath(V.search.mailbox),c.push(a),V.search.subfolders&&a.children.length&&d(a.children)):c=V.accounts[0].$flattenMailboxes(),V.virtualMailbox.setMailboxes(c),V.virtualMailbox.startSearch(V.search.match,V.search.params),b.go("mail.account.virtualMailbox",{accountId:V.accounts[0].id})}}function z(a){return V.currentSearchParam=a,j("advancedSearch"),!1}function A(a){if(a.length&&V.currentSearchParam.length){var b=0,c=V.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),V.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function B(a){a.$expanded=!a.$expanded,a.$flattenMailboxes({reload:!0,saveState:!0}),c(function(){angular.element(d).triggerHandler("resize")},150)}function C(a){function b(a,b,c,d){function e(){b.cancel()}var f=this;f.loading=!0,f.filter={name:""},f.metadataForFolder=c,f.account=new p({id:d.id,name:d.name}),f.close=e,f.account.$getMailboxes().then(function(){f.loading=!1})}e.show({templateUrl:a.id+"/subscribe",controller:b,controllerAs:"subscriptions",clickOutsideToClose:!0,escapeToClose:!0,locals:{metadataForFolder:O,srcAccount:a}}).finally(function(){a.$getMailboxes({reload:!0})}),b.$inject=["$scope","$mdDialog","metadataForFolder","srcAccount"]}function D(a){m.prompt(l("New folder"),l("Enter the new name of your folder :")).then(function(b){a.$newMailbox(a.id,b).then(function(){},function(a,c){m.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function E(a){function b(a,b,c,d){function e(a){return c.$filter(a,d.delegates)}function f(){b.hide()}function g(a){d.$removeDelegate(a.uid).catch(function(a,b){m.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){i.userToAdd="",i.searchText=""},function(a){m.alert(l("Warning"),a)})}var i=this;i.users=d.delegates,i.account=d,i.userToAdd="",i.searchText="",i.userFilter=e,i.closeModal=f,i.removeUser=g,i.addUser=h}e.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:s,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function F(a){V.editMode=a.path,j("mailboxName_"+a.path)}function G(a){a.$reset(),V.editMode=!1}function H(a,c,d){V.editMode!=d.path&&(V.editMode=!1,V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,g(i["gt-md"])||h("left").close(),b.go("mail.account.mailbox",{accountId:c.id,mailboxId:k(d.path)}),a.stopPropagation(),a.preventDefault())}function I(a){a.$rename().then(function(a){V.editMode=!1})}function J(a){a.$compact().then(function(){f.show(f.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function K(a){a.$emptyTrash().then(function(){f.show(f.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function L(a){m.confirm(l("Confirmation"),l("Do you really want to move this folder into the trash ?")).then(function(){a.$delete().then(function(){b.go("mail.account.inbox")},function(b,c){m.alert(l('An error occured while deleting the mailbox "%{0}".',a.name),l(b.error))})})}function M(a){a.$markAsRead()}function N(a){a.$acl.$users().then(function(){e.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:s,folder:a}})})}function O(a){return"inbox"==a.type?{name:a.name,icon:"inbox",special:!0}:"draft"==a.type?{name:l("DraftsFolderName"),icon:"drafts",special:!0}:"sent"==a.type?{name:l("SentFolderName"),icon:"send",special:!0}:"trash"==a.type?{name:l("TrashFolderName"),icon:"delete",special:!0}:"junk"==a.type?{name:l("JunkFolderName"),icon:"thumb_down",special:!0}:"additional"==a.type?{name:a.name,icon:"folder_shared",special:!0}:{name:a.name,icon:"folder_open",special:!1}}function P(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function Q(){var a=d.unseenCountFolders;_.forEach(V.accounts,function(b){_.includes(a,b.id+"/folderINBOX")||a.push(b.id+"/folderINBOX"),_.forEach(b.$$flattenMailboxes,function(b){angular.isDefined(b.unseenCount)&&!_.includes(a,b.id)&&a.push(b.id)})}),p.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(V.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),t.ready().then(function(){var a=t.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&c(V.refreshUnseenCount,1e3*a.timeInterval())})}function R(a,b){return b.id!=a.id&&!b.isNoSelect()}function S(a,c,d){var e,g,h,i,j,k;e="/"+c.id,g=a.$selectedMessages(),0===g.length&&(g=[a.$selectedMessage()]),h=_.map(g,"uid"),i=a.selectedMessage&&h.indexOf(a.selectedMessage)>=0,"copy"==d?(j=a.$copyMessages(g,e),k=l("%{0} message(s) copied",g.length)):(j=a.$moveMessages(g,e),k=l("%{0} message(s) moved",g.length)),j.then(function(){i&&b.go("mail.account.mailbox"),f.show(f.simple().content(k).position("top right").hideDelay(2e3))})}var T,U,V=this,W=[];V.service=q,V.accounts=u,V.toggleAccountState=B,V.subscribe=C,V.newFolder=D,V.delegate=E,V.editFolder=F,V.revertEditing=G,V.selectFolder=H,V.saveFolder=I,V.compactFolder=J,V.emptyTrashFolder=K,V.confirmDelete=L,V.markFolderRead=M,V.share=N,V.metadataForFolder=O,V.setFolderAs=P,V.refreshUnseenCount=Q,V.isDroppableFolder=R,V.dragSelectedMessages=S,V.showingAdvancedSearch=!1,V.currentSearchParam="",V.addSearchParam=z,V.newSearchParam=A,V.showAdvancedSearch=w,V.hideAdvancedSearch=x,V.toggleAdvancedSearch=y,V.search={options:{"":l("Select a criteria"),subject:l("Enter Subject"),from:l("Enter From"),to:l("Enter To"),cc:l("Enter Cc"),body:l("Enter Body")},mailbox:"INBOX",subfolders:1,match:"AND",params:[]},t.ready().then(function(){V.showSubscribedOnly=t.defaults.SOGoMailShowSubscribedFoldersOnly}),V.refreshUnseenCount(),v(W),a.$on("$destroy",function(){_.forEach(W,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$state","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgConstant","sgFocus","encodeUriFilter","Dialog","sgSettings","sgHotkeys","Account","Mailbox","VirtualMailbox","User","Preferences","stateAccounts"],angular.module("SOGo.MailerUI").controller("MailboxesController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(k.createHotkey({key:l("hotkey_flag"),callback:angular.bind(j,j.toggleFlag)})),a.push(k.createHotkey({key:"backspace",callback:function(a){0===O.mailbox.$selectedCount()&&z(),a.preventDefault()}})),_.forEach(a,function(a){k.registerHotkey(a)})}function w(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==i.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==j.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function x(a){O.$showDetailedRecipients=!O.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function y(a){var b,c,d,e;"A"==a.target.tagName&&"href"in a.target.attributes&&(b=a.target.attributes.href.value,c=/^mailto:([^\?]+)/.exec(b),c&&(d=_.map(decodeURIComponent(c[1]).split(","),function(a){return"<"+a+">"}),e={to:d},_.forEach(["subject","body"],function(a){var d=new RegExp(a+"=([^&]+)");a="body"==a?"text":a,c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),_.forEach(["cc","bcc"],function(a){var d=new RegExp(a+"=([^&]+)");c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),I(a,e)))}function z(){var a,b,e,g,h,k=w();k.messageCtrl?(a=k.mailboxCtrl.selectedFolder,b=k.messageCtrl.message,e=k.messageCtrl.$state):(a=i,b=j,e=c),a.$deleteMessages([b]).then(function(c){var i=c;if(b=null,angular.isDefined(e)){c>0&&(i-=1,g=a.$messages[i]),ca.$lastVisibleIndex&&(a.$topIndex=i-(a.$lastVisibleIndex-a.$topIndex))):e.go("mail.account.mailbox").then(function(){b=null,delete a.selectedMessage})}catch(a){}}H()})}function A(a,b){null===P&&(P=e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:O.account,stateMessage:b}}).finally(function(){P=null,H()}))}function B(){c.go("mail.account.mailbox").then(function(){O.message=null,delete i.selectedMessage})}function C(a){var b=O.message.$reply();A(a,b)}function D(a){var b=O.message.$replyAll();A(a,b)}function E(a){var b=O.message.$forward();A(a,b)}function F(a){O.message.$editableContent().then(function(){A(a,O.message)})}function G(){var b=[n.baseURL(),"UIxMailPopupView#/Mail",O.message.accountId,m(m(O.message.$mailbox.path)),O.message.uid].join("/"),c=O.message.$absolutePath();Q=a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function H(){a.opener&&a.close()}function I(a,b){O.account.$newMessage().then(function(c){angular.extend(c.editable,b),A(a,c)}),a.stopPropagation(),a.preventDefault()}function J(a){O.showRawSource||O.message.$rawSource?O.showRawSource=!O.showRawSource:u.$$resource.post(O.message.id,"viewsource").then(function(a){O.message.$rawSource=a,O.showRawSource=!0})}function K(b){a.print()}function L(a){return N(a,"appointment")}function M(a){return N(a,"task")}function N(a,b){O.message.$plainContent().then(function(c){var d={pid:q.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new r(d),g=[n.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var O=this,P=null,Q=null,R=[];a.$messageController=O,O.$state=c,O.accounts=g,O.account=h,O.mailbox=i,O.message=j,O.service=u,O.tags={searchText:"",selected:""},O.showFlags=j.flags&&j.flags.length>0,O.$showDetailedRecipients=!1,O.toggleDetailedRecipients=x,O.filterMailtoLinks=y,O.deleteMessage=z,O.close=B,O.reply=C,O.replyAll=D,O.forward=E,O.edit=F,O.openPopup=G,O.closePopup=H,O.newMessage=I,O.toggleRawSource=J,O.showRawSource=!1,O.print=K,O.convertToEvent=L,O.convertToTask=M,v(R),a.opener?(b.$watchCollection(function(){return O.message.flags},function(a,b){var c;(a||b)&&(c=w(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.showFlags=!0,c.messageCtrl.message.flags=a}))}),b.$watch(function(){return O.message.isflagged},function(a,b){var c=w();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){var b=_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:O.message.uid});b.isflagged=a})})):b.$watchCollection(function(){return O.message.flags},function(a,b){var c,d,e;(a||b)&&(c=a||[],d=b||[],_.forEach(c,function(a,b){angular.isObject(a)&&(c[b]=a.name)}),c.length>d.length?(e=_.difference(c,d),_.forEach(e,function(a){O.message.addTag(a)})):c.length';\n else\n identity.full = '<' + identity.email + '>';\n });\n Account.$log.debug('Account: ' + JSON.stringify(futureAccountData, undefined, 2));\n }\n else {\n // The promise will be unwrapped first\n //this.$unwrap(futureAccountData);\n }\n\n this.fetchAll = false;\n\n // Check if we're displaying the IMAP subscription management dialog\n if (angular.isDefined(fetchAll) && fetchAll) {\n this.fetchAll = true;\n this.$getMailboxes();\n }\n }\n\n /**\n * @memberof Account\n * @desc The factory we'll use to register with Angular\n * @returns the Account constructor\n */\n Account.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Mailbox', 'Message', function($q, $timeout, $log, Settings, Resource, Preferences, Mailbox, Message) {\n angular.extend(Account, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Preferences: Preferences,\n $Mailbox: Mailbox,\n $Message: Message\n });\n\n return Account; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Account in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .factory('Account', Account.$factory);\n\n /**\n * @memberof Account\n * @desc Set the list of accounts and instanciate a new Account object for each item.\n * @param {array} [data] - the metadata of the accounts\n * @returns the list of accounts\n */\n Account.$findAll = function(data) {\n if (!data) {\n return Account.$$resource.fetch('', 'mailAccounts').then(function(o) {\n return Account.$unwrapCollection(o);\n });\n }\n return Account.$unwrapCollection(data);\n };\n\n /**\n * @memberof Account\n * @desc Unwrap to a collection of Account instances.\n * @param {object} data - the accounts information\n * @returns a collection of Account objects\n */\n Account.$unwrapCollection = function(data) {\n var collection = [];\n\n angular.forEach(data, function(o, i) {\n o.id = i;\n collection[i] = new Account(o);\n });\n Account.$accounts = collection;\n\n return collection;\n };\n\n /**\n * @function getLength\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of mailboxes in the account\n */\n Account.prototype.getLength = function() {\n return this.$flattenMailboxes().length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the mailbox at the specified index\n */\n Account.prototype.getItemAtIndex = function(index) {\n var expandedMailboxes;\n\n expandedMailboxes = this.$flattenMailboxes();\n if (index >= 0 && index < expandedMailboxes.length)\n return expandedMailboxes[index];\n\n return null;\n };\n\n /**\n * @function $getMailboxes\n * @memberof Account.prototype\n * @desc Fetch the list of mailboxes for the current account.\n * @param {object} [options] - force a reload by setting 'reload' to true\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxes = function(options) {\n var _this = this;\n\n if (this.$mailboxes && !(options && options.reload)) {\n return Account.$q.when(this.$mailboxes);\n }\n else {\n return Account.$Mailbox.$find(this).then(function(data) {\n _this.$mailboxes = data;\n _this.$expanded = false;\n\n // Set expanded folders from user's settings\n Account.$Preferences.ready().then(function() {\n var expandedFolders,\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n o.$expanded = (expandedFolders.indexOf('/' + o.id) >= 0);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n if (Account.$Preferences.settings.Mail.ExpandedFolders) {\n if (angular.isString(Account.$Preferences.settings.Mail.ExpandedFolders))\n // Backward compatibility support\n expandedFolders = angular.fromJson(Account.$Preferences.settings.Mail.ExpandedFolders);\n else\n expandedFolders = Account.$Preferences.settings.Mail.ExpandedFolders;\n _this.$expanded = (expandedFolders.indexOf('/' + _this.id) >= 0);\n if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\n if (Account.$accounts)\n _this.$expanded |= (Account.$accounts.length == 1); // Always expand single account\n _this.$flattenMailboxes({reload: true});\n });\n\n return _this.$mailboxes;\n });\n }\n };\n\n /**\n * @function $flattenMailboxes\n * @memberof Account.prototype\n * @desc Get a flatten array of the mailboxes.\n * @param {object} [options] - the following boolean attributes are available:\n * - reload: rebuild the flatten array of mailboxes from the original tree representation (this.$mailboxes)\n * - all: return all mailboxes, ignoring their expanstion state\n * - saveState: save expansion state of mailboxes to the server\n * @returns an array of Mailbox instances\n */\n Account.prototype.$flattenMailboxes = function(options) {\n var _this = this,\n allMailboxes = [],\n expandedMailboxes = [],\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n allMailboxes.push(o);\n if ((options && options.all || o.$expanded) && o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n if (this.$$flattenMailboxes && !(options && (options.reload || options.all))) {\n allMailboxes = this.$$flattenMailboxes;\n }\n else {\n _visit(this.$mailboxes);\n if (!options || !options.all) {\n _this.$$flattenMailboxes = allMailboxes;\n if (options && options.saveState) {\n // Save expansion state of mailboxes to the server\n _.forEach(Account.$accounts, function(account) {\n if (account.$expanded) {\n expandedMailboxes.push('/' + account.id);\n }\n _.reduce(account.$$flattenMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\n });\n Account.$$resource.post(null, 'saveFoldersState', expandedMailboxes);\n }\n }\n }\n\n return allMailboxes;\n };\n\n Account.prototype.$getMailboxByType = function(type) {\n var mailbox,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.type == type;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $getMailboxByPath\n * @memberof Account.prototype\n * @desc Recursively find a mailbox using its path\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxByPath = function(path) {\n var mailbox = null,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.path == path;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $newMailbox\n * @memberof Account.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMailbox = function(path, name) {\n var _this = this;\n\n return Account.$$resource.post(path.toString(), 'createFolder', {name: name}).then(function() {\n _this.$getMailboxes({reload: true});\n });\n };\n\n /**\n * @function updateQuota\n * @memberof Account.prototype\n * @param {Object} data - the inbox quota information returned by the server\n * @desc Update the quota definition associated to the account\n */\n Account.prototype.updateQuota = function(data) {\n var percent, format, description;\n\n percent = (Math.round(data.usedSpace * 10000 / data.maxQuota) / 100);\n format = l(\"quotasFormat\");\n description = format.formatted(percent, Math.round(data.maxQuota/10.24)/100);\n\n this.$quota = { percent: percent, description: description };\n };\n\n /**\n * @function $newMessage\n * @memberof Account.prototype\n * @desc Prepare a new Message object associated to the appropriate mailbox.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMessage = function() {\n var _this = this;\n\n // Query account for draft folder and draft UID\n return Account.$$resource.fetch(this.id.toString(), 'compose').then(function(data) {\n Account.$log.debug('New message (compose): ' + JSON.stringify(data, undefined, 2));\n var message = new Account.$Message(data.accountId, _this.$getMailboxByPath(data.mailboxPath), data);\n return message;\n }).then(function(message) {\n // Fetch draft initial data\n return Account.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Account.$log.debug('New message (edit): ' + JSON.stringify(data, undefined, 2));\n angular.extend(message.editable, data);\n message.isNew = true;\n return message;\n });\n });\n };\n\n /**\n * @function $addDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @see {@link User.$filter}\n */\n Account.prototype.$addDelegate = function(user) {\n var _this = this,\n deferred = Account.$q.defer(),\n param = {uid: user.uid};\n if (!user.uid || _.indexOf(_.map(this.delegates, 'uid'), user.uid) > -1) {\n // No UID specified or user already in delegates\n deferred.resolve();\n }\n else {\n Account.$$resource.fetch(this.id.toString(), 'addDelegate', param).then(function() {\n _this.delegates.push(user);\n deferred.resolve(_this.users);\n }, function(data, status) {\n deferred.reject(l('An error occured please try again.'));\n });\n }\n return deferred.promise;\n };\n\n /**\n * @function $removeDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @return a promise of the server call to remove the user from the account's delegates\n */\n Account.prototype.$removeDelegate = function(uid) {\n var _this = this,\n param = {uid: uid};\n return Account.$$resource.fetch(this.id.toString(), 'removeDelegate', param).then(function() {\n var i = _.indexOf(_.map(_this.delegates, 'uid'), uid);\n if (i >= 0) {\n _this.delegates.splice(i, 1);\n }\n });\n };\n \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Mailbox\n * @constructor\n * @param {object} futureMailboxData - either an object literal or a promise\n */\n function Mailbox(account, futureMailboxData) {\n this.$account = account;\n // Data is immediately available\n if (typeof futureMailboxData.then !== 'function') {\n this.init(futureMailboxData);\n if (this.name && !this.path) {\n // Create a new mailbox on the server\n var newMailboxData = Mailbox.$$resource.create('createFolder', this.name);\n this.$unwrap(newMailboxData);\n }\n }\n else {\n // The promise will be unwrapped first\n // NOTE: this condition never happen for the moment\n this.$unwrap(futureMailboxData);\n }\n }\n\n /**\n * @memberof Mailbox\n * @desc The factory we'll use to register with Angular\n * @returns the Mailbox constructor\n */\n Mailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Acl', 'Preferences', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Message, Acl, Preferences, PRELOAD) {\n angular.extend(Mailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: { sort: 'date', asc: 0 },\n selectedFolder: null,\n $refreshTimeout: null,\n $virtualMode: false,\n PRELOAD: PRELOAD\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Mail.SortingState) {\n Mailbox.$query.sort = Preferences.settings.Mail.SortingState[0];\n Mailbox.$query.asc = parseInt(Preferences.settings.Mail.SortingState[1]);\n }\n });\n\n return Mailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Mailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('Mailbox', Mailbox.$factory);\n\n /**\n * @memberof Mailbox\n * @desc Fetch list of mailboxes of a specific account\n * @param {string} accountId - the account\n * @return a promise of the HTTP operation\n * @see {@link Account.$getMailboxes}\n */\n Mailbox.$find = function(account) {\n var path, futureMailboxData;\n\n if (account.fetchAll)\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'viewAll');\n else\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'view');\n\n return Mailbox.$unwrapCollection(account, futureMailboxData); // a collection of mailboxes\n };\n\n /**\n * @memberof Mailbox\n * @desc Unwrap to a collection of Mailbox instances.\n * @param {string} account - the account\n * @param {promise} futureMailboxData - a promise of the mailboxes metadata\n * @returns a promise of a collection of Mailbox objects\n */\n Mailbox.$unwrapCollection = function(account, futureMailboxData) {\n var collection = [],\n // Local recursive function\n createMailboxes = function(level, mailbox) {\n for (var i = 0; i < mailbox.children.length; i++) {\n mailbox.children[i].level = level;\n mailbox.children[i] = new Mailbox(account, mailbox.children[i]);\n createMailboxes(level+1, mailbox.children[i]);\n }\n };\n //collection.$futureMailboxData = futureMailboxData;\n\n return futureMailboxData.then(function(data) {\n return Mailbox.$timeout(function() {\n // Each entry is spun up as a Mailbox instance\n angular.forEach(data.mailboxes, function(data, index) {\n data.level = 0;\n var mailbox = new Mailbox(account, data);\n createMailboxes(1, mailbox); // recursively create all sub-mailboxes\n collection.push(mailbox);\n });\n // Update inbox quota\n if (data.quotas)\n account.updateQuota(data.quotas);\n return collection;\n });\n });\n };\n\n /**\n * @memberof Mailbox\n * @desc Build the path of the mailbox (or account only).\n * @param {string} accountId - the account ID\n * @param {string} [mailboxPath] - the mailbox path\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.$absolutePath = function(accountId, mailboxPath) {\n var path = [];\n\n if (mailboxPath) {\n path = _.map(mailboxPath.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n }\n\n path.splice(0, 0, accountId); // insert account ID\n\n return path.join('/');\n };\n\n /**\n * @function init\n * @memberof Mailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n Mailbox.prototype.init = function(data) {\n var _this = this;\n this.$isLoading = true;\n this.$messages = [];\n this.uidsMap = {};\n angular.extend(this, data);\n if (this.path) {\n this.id = this.$id();\n this.$acl = new Mailbox.$$Acl('Mail/' + this.id);\n }\n if (this.type) {\n this.$isEditable = this.isEditable();\n }\n this.$isNoInferiors = this.isNoInferiors();\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function selectFolder\n * @memberof Mailbox.prototype\n * @desc Mark the folder as selected in the constructor unless virtual mode is active\n */\n Mailbox.prototype.selectFolder = function() {\n if (!Mailbox.$virtualMode)\n Mailbox.selectedFolder = this;\n };\n\n /**\n * @function getLength\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of messages in the mailbox\n */\n Mailbox.prototype.getLength = function() {\n return this.$messages.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message at the specified index\n */\n Mailbox.prototype.getItemAtIndex = function(index) {\n var message;\n\n if (index >= 0 && index < this.$messages.length) {\n message = this.$messages[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadMessage(message.uid))\n return message;\n }\n return null;\n };\n\n /**\n * @function $id\n * @memberof Mailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.prototype.$id = function() {\n return Mailbox.$absolutePath(this.$account.id, this.path);\n };\n\n /**\n * @function $selectedMessages\n * @memberof Mailbox.prototype\n * @desc Return the messages selected by the user.\n * @returns Message instances\n */\n Mailbox.prototype.$selectedMessages = function() {\n return _.filter(this.$messages, function(message) { return message.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof Mailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n Mailbox.prototype.$selectedCount = function() {\n return this.$selectedMessages().length;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is displayed in the detailed view.\n * @param {string} messageId\n * @returns true if the specified message is displayed\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\n };\n\n /**\n * @function $selectedMessage\n * @memberof Mailbox.prototype\n * @desc Return the currently visible message.\n * @returns a Message instance or undefined if no message is displayed\n */\n Mailbox.prototype.$selectedMessage = function() {\n var _this = this;\n\n return _.find(this.$messages, function(message) { return message.uid == _this.selectedMessage; });\n };\n\n /**\n * @function $selectedMessageIndex\n * @memberof Mailbox.prototype\n * @desc Return the index of the currently visible message.\n * @returns a number or undefined if no message is selected\n */\n Mailbox.prototype.$selectedMessageIndex = function() {\n return this.uidsMap[this.selectedMessage];\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if a message is selected.\n * @returns true if the a message is selected\n */\n Mailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(this.selectedMessage);\n };\n\n /**\n * @function $filter\n * @memberof Mailbox.prototype\n * @desc Fetch the messages metadata of the mailbox\n * @param {object} [sort] - sort preferences. Defaults to descendent by date.\n * @param {string} sort.match - either AND or OR\n * @param {string} sort.sort - either arrival, subject, from, to, date, or size\n * @param {boolean} sort.asc - sort is ascendant if true\n * @param {object[]} [filters] - list of filters for the query\n * @param {string} filters.searchBy - either subject, from, to, cc, or body\n * @param {string} filters.searchInput - the search string to match\n * @param {boolean} filters.negative - negate the condition\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$filter = function(sortingAttributes, filters) {\n var _this = this, options = {};\n\n if (!angular.isDefined(this.unseenCount))\n this.unseenCount = 0;\n\n Mailbox.$timeout(function() {\n _this.$isLoading = true;\n });\n\n return Mailbox.$Preferences.ready().then(function() {\n\n if (Mailbox.$refreshTimeout)\n Mailbox.$timeout.cancel(Mailbox.$refreshTimeout);\n\n if (sortingAttributes)\n // Sorting preferences are common to all mailboxes\n angular.extend(Mailbox.$query, sortingAttributes);\n\n angular.extend(options, { sortingAttributes: Mailbox.$query });\n if (angular.isDefined(filters)) {\n options.filters = _.reject(filters, function(filter) {\n return !filter.searchInput || filter.searchInput.length === 0;\n });\n // Decompose filters that match two fields\n _.forEach(options.filters, function(filter) {\n var secondFilter,\n match = filter.searchBy.match(/(\\w+)_or_(\\w+)/);\n if (match) {\n options.sortingAttributes.match = 'OR';\n filter.searchBy = match[1];\n secondFilter = angular.copy(filter);\n secondFilter.searchBy = match[2];\n options.filters.push(secondFilter);\n }\n });\n }\n\n // Restart the refresh timer, if needed\n if (!Mailbox.$virtualMode) {\n var refreshViewCheck = Mailbox.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Mailbox.prototype.$filter, null, filters);\n Mailbox.$refreshTimeout = Mailbox.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n }\n\n var futureMailboxData = Mailbox.$$resource.post(_this.id, 'view', options);\n return _this.$unwrap(futureMailboxData);\n });\n };\n\n /**\n * @function $loadMessage\n * @memberof Mailbox.prototype\n * @desc Check if the message is loaded and in any case, fetch more messages headers from the server.\n * @returns true if the message metadata are already fetched\n */\n Mailbox.prototype.$loadMessage = function(messageId) {\n var startIndex = this.uidsMap[messageId],\n endIndex,\n index,\n max = this.$messages.length,\n loaded = false,\n uids,\n futureHeadersData;\n if (angular.isDefined(this.uidsMap[messageId]) && startIndex < this.$messages.length) {\n // Index is valid\n if (angular.isDefined(this.$messages[startIndex].subject)) {// || this.$messages[startIndex].loading) {\n // Message headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.LOOKAHEAD, max - 1);\n if (angular.isDefined(this.$messages[endIndex].subject) ||\n angular.isDefined(this.$messages[endIndex].loading)) {\n index = Math.max(startIndex - Mailbox.PRELOAD.LOOKAHEAD, 0);\n if (!angular.isDefined(this.$messages[index].subject) &&\n !angular.isDefined(this.$messages[index].loading)) {\n // Previous messages not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - Mailbox.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next messages not load; preload more headers further down\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.SIZE, max - 1);\n\n if (!angular.isDefined(this.$messages[startIndex].subject) &&\n !angular.isDefined(this.$messages[startIndex].loading) ||\n !angular.isDefined(this.$messages[endIndex].subject) &&\n !angular.isDefined(this.$messages[endIndex].loading)) {\n\n for (uids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (angular.isDefined(this.$messages[startIndex].subject) || this.$messages[startIndex].loading) {\n // Message at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Message at this index will be loaded\n uids.push(this.$messages[startIndex].uid);\n this.$messages[startIndex].loading = true;\n }\n }\n\n Mailbox.$log.debug('Loading UIDs ' + uids.join(' '));\n futureHeadersData = Mailbox.$$resource.post(this.id, 'headers', {uids: uids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n return loaded;\n };\n\n /**\n * @function isEditable\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox is editable based on its type.\n * @returns true if the mailbox is not a special folder.\n */\n Mailbox.prototype.isEditable = function() {\n return this.type == 'folder';\n };\n\n /**\n * @function isNoInferiors\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can contain submailboxes\n * @returns true if the mailbox can not contain submailboxes\n */\n Mailbox.prototype.isNoInferiors = function() {\n return this.flags.indexOf('noinferiors') >= 0;\n };\n\n /**\n * @function isNoSelect\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can be selected\n * @returns true if the mailbox can not be selected\n */\n Mailbox.prototype.isNoSelect = function() {\n return this.flags.indexOf('noselect') >= 0;\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$rename = function() {\n var _this = this,\n findParent,\n parent,\n children,\n i;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Mailbox.$q.when();\n }\n\n // Local recursive function\n findParent = function(parent, children) {\n var parentMailbox = null,\n mailbox = _.find(children, function(o) {\n return o.path == _this.path;\n });\n if (mailbox) {\n parentMailbox = parent;\n }\n else {\n angular.forEach(children, function(o) {\n if (!parentMailbox && o.children && o.children.length > 0) {\n parentMailbox = findParent(o, o.children);\n }\n });\n }\n return parentMailbox;\n };\n\n // Find mailbox parent\n parent = findParent(null, this.$account.$mailboxes);\n if (parent === null)\n children = this.$account.$mailboxes;\n else\n children = parent.children;\n\n // Find index of mailbox among siblings\n i = _.indexOf(_.map(children, 'id'), this.id);\n\n return this.$save().then(function(data) {\n var sibling;\n angular.extend(_this, data); // update the path attribute\n _this.id = _this.$id();\n\n // Move mailbox among its siblings according to its new name\n children.splice(i, 1);\n sibling = _.find(children, function(o) {\n Mailbox.$log.debug(o.name + ' ? ' + _this.name);\n return (o.type == 'folder' && o.name.localeCompare(_this.name) > 0);\n });\n if (sibling) {\n i = _.indexOf(_.map(children, 'id'), sibling.id);\n }\n else {\n i = children.length;\n }\n children.splice(i, 0, _this);\n });\n };\n\n /**\n * @function $compact\n * @memberof Mailbox.prototype\n * @desc Compact the mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$compact = function() {\n var _this = this;\n return Mailbox.$$resource.post(this.id, 'expunge')\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $setFolderAs\n * @memberof Mailbox.prototype\n * @desc Set a folder as Drafts/Sent/Trash\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$setFolderAs = function(type) {\n return Mailbox.$$resource.post(this.id, 'setAs' + type + 'Folder');\n };\n\n /**\n * @function $emptyTrash\n * @memberof Mailbox.prototype\n * @desc Empty the Trash folder.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$emptyTrash = function() {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'emptyTrash').then(function(data) {\n // Remove all messages from the mailbox\n _this.$messages = [];\n _this.uidsMap = {};\n _this.unseenCount = 0;\n\n // If we had any submailboxes, lets do a refresh of the mailboxes list\n if (angular.isDefined(_this.children) && _this.children.length)\n _this.$account.$getMailboxes({reload: true});\n\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $markAsRead\n * @memberof Mailbox.prototype\n * @desc Mark all messages from folder as read\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$markAsRead = function() {\n return Mailbox.$$resource.post(this.id, 'markRead');\n };\n\n /**\n * @function $flagMessages\n * @memberof Mailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$flagMessages = function(messages, flags, operation) {\n var data = {msgUIDs: _.map(messages, 'uid'),\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data).then(function() {\n return messages;\n });\n };\n\n /**\n * @function saveSelectedMessages\n * @memberof Mailbox.prototype\n * @desc Download the selected messages\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.saveSelectedMessages = function() {\n var selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function exportFolder\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.exportFolder = function() {\n return Mailbox.$$resource.download(this.id, 'exportFolder');\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function() {\n var _this = this;\n\n return Mailbox.$$resource.remove(this.id)\n .then(function() {\n _this.$account.$getMailboxes({reload: true});\n return true;\n });\n };\n\n /**\n * @function $_deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from Mailbox object.\n * @param {string[]} uids - the messages uids\n * @param {object[]} messages - the Message instances\n * @return the index of the first deleted message\n */\n Mailbox.prototype.$_deleteMessages = function(uids, messages) {\n var _this = this, selectedUIDs, _$messages, unseen, firstIndex = this.$messages.length;\n\n // Decrement the unseen count\n unseen = _.filter(messages, function(message, i) { return !message.isread; });\n this.unseenCount -= unseen.length;\n\n // Remove messages from $messages and uidsMap\n _.forEachRight(this.$messages, function(message, index) {\n var selectedIndex = _.findIndex(uids, function(uid) {\n return message.uid == uid;\n });\n if (selectedIndex > -1) {\n uids.splice(selectedIndex, 1);\n delete _this.uidsMap[message.uid];\n if (message.uid == _this.selectedMessage)\n delete _this.selectedMessage;\n _this.$messages.splice(index, 1);\n if (index < firstIndex)\n firstIndex = index;\n }\n else {\n _this.uidsMap[message.uid] -= uids.length;\n }\n });\n\n // Return the index of the first deleted message\n return firstIndex;\n };\n\n /**\n * @function $deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'batchDelete', {uids: uids})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof Mailbox.prototype\n * @desc Mark messages as junk/not junk\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messages) {\n var _this = this,\n uids = _.map(messages, 'uid'),\n method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n\n return Mailbox.$$resource.post(this.id, method, {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof Mailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$copyMessages = function(messages, folder) {\n var _this = this,\n uids = _.map(messages, 'uid');\n\n return Mailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $moveMessages\n * @memberof Mailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$moveMessages = function(messages, folder) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteMessages(uids, messages);\n });\n };\n \n /**\n * @function $reset\n * @memberof Mailbox.prototype\n * @desc Reset the original state the mailbox's data.\n */\n Mailbox.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this.$shadowData, function(value, key) {\n delete _this[key];\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Mailbox.prototype\n * @desc Save the mailbox to the server. This currently can only affect the name of the mailbox.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$save = function() {\n var _this = this;\n\n return Mailbox.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n Mailbox.$log.debug(JSON.stringify(data, undefined, 2));\n return data;\n }, function(response) {\n Mailbox.$log.error(JSON.stringify(response.data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return response.data;\n });\n };\n\n /**\n * @function $newMailbox\n * @memberof Mailbox.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Mailbox.prototype.$newMailbox = function(path, name) {\n return this.$account.$newMailbox(path, name);\n };\n\n /**\n * @function $omit\n * @memberof Mailbox.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Mailbox instance\n */\n Mailbox.prototype.$omit = function() {\n var mailbox = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'children' &&\n key != 'headers' &&\n key != 'uids' &&\n key != 'uidsMap' &&\n key[0] != '$') {\n mailbox[key] = value;\n }\n });\n return mailbox;\n };\n\n /**\n * @function $unwrap\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and instanciate new Message objects using received data.\n * @param {promise} futureMailboxData - a promise of the Mailbox's metadata\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$unwrap = function(futureMailboxData) {\n var _this = this,\n deferred = Mailbox.$q.defer();\n\n this.$futureMailboxData = futureMailboxData;\n this.$futureMailboxData.then(function(data) {\n Mailbox.$timeout(function() {\n var uids, headers;\n\n if (!data.uids || _this.$topIndex > data.uids.length - 1)\n _this.$topIndex = 0;\n\n _this.init(data);\n\n if (_this.uids) {\n Mailbox.$log.debug('unwrapping ' + data.uids.length + ' messages');\n\n // First entry of 'headers' are keys\n headers = _.invokeMap(_this.headers[0], 'toLowerCase');\n _this.headers.splice(0, 1);\n\n // First entry of 'uids' are keys when threaded view is enabled\n if (_this.threaded) {\n uids = _this.uids[0];\n _this.uids.splice(0, 1);\n }\n\n // Instanciate Message objects\n _.reduce(_this.uids, function(msgs, msg, i) {\n var data;\n if (_this.threaded)\n data = _.zipObject(uids, msg);\n else\n data = {uid: msg.toString()};\n\n // Build map of UID <=> index\n _this.uidsMap[data.uid] = i;\n\n msgs.push(new Mailbox.$Message(_this.$account.id, _this, data, true));\n\n return msgs;\n }, _this.$messages);\n\n // Extend Message objects with received headers\n _.forEach(_this.headers, function(data) {\n var msg = _.zipObject(headers, data),\n i = _this.uidsMap[msg.uid.toString()];\n _.extend(_this.$messages[i], msg);\n });\n }\n Mailbox.$log.debug('mailbox ' + _this.id + ' ready');\n _this.$isLoading = false;\n deferred.resolve(_this.$messages);\n });\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n deferred.reject();\n });\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and extend matching Message objects using received data.\n * @param {promise} futureHeadersData - a promise of some messages metadata\n */\n Mailbox.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n Mailbox.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(messageHeaders) {\n messageHeaders = _.zipObject(headers, messageHeaders);\n j = _this.uidsMap[messageHeaders.uid.toString()];\n if (angular.isDefined(j)) {\n _.extend(_this.$messages[j], messageHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $toggleSubscribe\n * @memberof Mailbox.prototype\n * @desc Subscribe or unsubscribe to a mailbox\n */\n Mailbox.prototype.$toggleSubscribe = function() {\n if (this.subscribed)\n return Mailbox.$$resource.post(this.id, 'subscribe');\n\n return Mailbox.$$resource.post(this.id, 'unsubscribe');\n };\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Message\n * @constructor\n * @param {string} accountId - the account ID\n * @param {string} mailboxPath - an array of the mailbox path components\n * @param {object} futureAddressBookData - either an object literal or a promise\n * @param {bool} lazy - do \"lazy loading\" so we are very quick at initializing message instances\n */\n function Message(accountId, mailbox, futureMessageData, lazy) {\n this.accountId = accountId;\n this.$mailbox = mailbox;\n this.$hasUnsafeContent = false;\n this.$loadUnsafeContent = false;\n this.editable = {to: [], cc: [], bcc: []};\n this.selected = false;\n\n // Data is immediately available\n if (typeof futureMessageData.then !== 'function') {\n //console.debug(JSON.stringify(futureMessageData, undefined, 2));\n if (angular.isUndefined(lazy) || !lazy) {\n angular.extend(this, futureMessageData);\n this.$formatFullAddresses();\n }\n this.uid = parseInt(futureMessageData.uid);\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureMessageData);\n }\n }\n\n /**\n * @memberof Message\n * @desc The factory we'll use to register with Angular\n * @returns the Message constructor\n */\n Message.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgMessage_STATUS', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Message_STATUS, Resource, Preferences) {\n angular.extend(Message, {\n STATUS: Message_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $avatar: angular.bind(Preferences, Preferences.avatar)\n });\n // Initialize tags form user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailLabelsColors) {\n Message.$tags = Preferences.defaults.SOGoMailLabelsColors;\n }\n if (Preferences.defaults.SOGoMailDisplayRemoteInlineImages &&\n Preferences.defaults.SOGoMailDisplayRemoteInlineImages == 'always') {\n Message.$displayRemoteInlineImages = true;\n }\n });\n\n return Message; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Message in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMessage_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Message', Message.$factory);\n\n /**\n * @function filterTags\n * @memberof Message.prototype\n * @desc Search for tags (ie., mail labels) matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Message.filterTags = function(query, excludedTags) {\n var re = new RegExp(query, 'i'),\n results = [];\n\n _.forEach(_.keys(Message.$tags), function(tag) {\n var pair = Message.$tags[tag];\n if (pair[0].search(re) != -1) {\n if (!_.includes(excludedTags, tag))\n results.push({ name: tag, description: pair[0], color: pair[1] });\n }\n });\n\n return results;\n };\n\n /**\n * @function $absolutePath\n * @memberof Message.prototype\n * @desc Build the path of the message\n * @returns a string representing the path relative to the mail module\n */\n Message.prototype.$absolutePath = function(options) {\n var _this = this, id = this.id;\n\n function buildPath() {\n var path;\n path = _.map(_this.$mailbox.path.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n path.splice(0, 0, _this.accountId); // insert account ID\n return path.join('/');\n }\n\n if (angular.isUndefined(this.id) || options && options.nocache) {\n this.id = buildPath() + '/' + this.uid; // add message UID\n id = this.id;\n }\n if (options && options.asDraft && this.draftId) {\n id = buildPath() + '/' + this.draftId; // add draft ID\n }\n\n return id;\n };\n\n /**\n * @function $setUID\n * @memberof Message.prototype\n * @desc Change the UID of the message. This happens when saving a draft.\n * @param {number} uid - the new message UID\n */\n Message.prototype.$setUID = function(uid) {\n var oldUID = (this.uid || -1), _this = this, index;\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n this.$absolutePath({nocache: true});\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n index = this.$mailbox.uidsMap[oldUID];\n this.$mailbox.uidsMap[uid] = index;\n delete this.$mailbox.uidsMap[oldUID];\n\n // Update messages list of mailbox\n _.forEach(['from', 'to', 'subject'], function(attr) {\n _this.$mailbox.$messages[index][attr] = _this[attr];\n });\n }\n }\n else {\n // Refresh selected folder if it's the drafts mailbox\n if (this.$mailbox.constructor.selectedFolder &&\n this.$mailbox.constructor.selectedFolder.type == 'draft') {\n this.$mailbox.constructor.selectedFolder.$filter();\n }\n }\n }\n };\n\n /**\n * @function $formatFullAddresses\n * @memberof Message.prototype\n * @desc Format all sender and recipients addresses with a complete description (name ).\n * This function also generates the avatar URL for each email address and a short name\n */\n Message.prototype.$formatFullAddresses = function() {\n var _this = this;\n var identities = _.map(_this.$mailbox.$account.identities, 'email');\n\n // Build long representation of email addresses\n _.forEach(['from', 'to', 'cc', 'bcc', 'reply-to'], function(type) {\n _.forEach(_this[type], function(data) {\n if (data.name && data.name != data.email) {\n data.full = data.name + ' <' + data.email + '>';\n\n if (data.name.length < 10)\n // Name is already short\n data.shortname = data.name;\n else if (data.name.split(' ').length)\n // If we have \"Alice Foo\" or \"Foo, Alice\" as name, we grab \"Alice\"\n data.shortname = _.first(_.last(data.name.split(/, */)).split(/ +/)).replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n data.image = Message.$avatar(data.email, 32);\n\n // If the current user is the recepient, overwrite\n // the short name with 'me'\n if (_.indexOf(identities, data.email) >= 0)\n data.shortname = l('me');\n });\n });\n };\n\n /**\n * @function $shortRecipients\n * @memberof Message.prototype\n * @desc Format all recipients into a very compact string\n * @returns a compacted string of all recipients\n */\n Message.prototype.$shortRecipients = function(max) {\n var _this = this, result = [], count = 0, total = 0;\n\n // Build short representation of email addresses\n _.forEach(['to', 'cc', 'bcc'], function(type) {\n total += _this[type]? _this[type].length : 0;\n _.forEach(_this[type], function(data, i) {\n if (count < max)\n result.push(data.shortname);\n count++;\n });\n });\n\n if (total > max)\n result.push(l('and %{0} more...', (total - max)));\n\n return result.join(', ');\n };\n\n /**\n * @function $shortAddress\n * @memberof Message.prototype\n * @desc Format the first address of a specific type with a short description.\n * @returns a string of the name or the email of the envelope address type\n */\n Message.prototype.$shortAddress = function(type) {\n var address = '';\n if (this[type] && this[type].length > 0) {\n address = this[type][0].name || this[type][0].email || '';\n }\n\n return address;\n };\n\n /**\n * @function allowReplyAll\n * @memberof Message.prototype\n * @desc Check if 'Reply to All' is an appropriate action on the message.\n * @returns true if the message is not a draft and has more than one recipient\n */\n Message.prototype.allowReplyAll = function() {\n var recipientsCount = 0;\n recipientsCount = _.reduce(['to', 'cc'], _.bind(function(count, type) {\n if (this[type])\n return count + this[type].length;\n else\n return count;\n }, this), recipientsCount);\n\n return !this.isDraft && recipientsCount > 1;\n };\n\n /**\n * @function loadUnsafeContent\n * @memberof Message.prototype\n * @desc Mark the message to load unsafe resources when calling $content().\n */\n Message.prototype.loadUnsafeContent = function() {\n this.$loadUnsafeContent = true;\n };\n\n /**\n * @function $content\n * @memberof Message.prototype\n * @desc Get the message body as accepted by SCE (Angular Strict Contextual Escaping).\n * @returns the HTML representation of the body\n */\n Message.prototype.$content = function() {\n var _this = this,\n parts = [],\n _visit = function(part) {\n part.msgclass = 'msg-attachment-other';\n if (part.type == 'UIxMailPartAlternativeViewer') {\n _visit(_.find(part.content, function(alternatePart) {\n return part.preferredPart == alternatePart.contentType;\n }));\n }\n // Can be used for UIxMailPartMixedViewer, UIxMailPartMessageViewer, and UIxMailPartSignedViewer\n else if (angular.isArray(part.content)) {\n if (part.type == 'UIxMailPartSignedViewer' && part['supports-smime'] === 1) {\n // First line in a h1, others each in a p\n var formattedMessage = \"

\" + part.error.replace(/\\n/, \"

\");\n formattedMessage = formattedMessage.replace(/\\n/g, \"

\") + \"

\";\n _this.$smime = {\n validSignature: part.valid,\n message: formattedMessage\n };\n }\n _.forEach(part.content, function(mixedPart) {\n _visit(mixedPart);\n });\n }\n else {\n if (angular.isUndefined(part.safeContent)) {\n // Keep a copy of the original content\n part.safeContent = part.content;\n _this.$hasUnsafeContent |= (part.safeContent.indexOf(' unsafe-') > -1);\n }\n if (part.type == 'UIxMailPartHTMLViewer') {\n part.html = true;\n if (_this.$loadUnsafeContent || Message.$displayRemoteInlineImages) {\n if (angular.isUndefined(part.unsafeContent)) {\n part.unsafeContent = document.createElement('div');\n part.unsafeContent.innerHTML = part.safeContent;\n angular.forEach(['src', 'data', 'classid', 'background', 'style'], function(suffix) {\n var elements = part.unsafeContent.querySelectorAll('[unsafe-' + suffix + ']'),\n element,\n value,\n i;\n for (i = 0; i < elements.length; i++) {\n element = angular.element(elements[i]);\n value = element.attr('unsafe-' + suffix);\n element.attr(suffix, value);\n element.removeAttr('unsafe-' + suffix);\n }\n });\n _this.$hasUnsafeContent = false;\n }\n part.content = part.unsafeContent.innerHTML;\n }\n else {\n part.content = part.safeContent;\n }\n parts.push(part);\n }\n else if (part.type == 'UIxMailPartICalViewer' ||\n part.type == 'UIxMailPartImageViewer' ||\n part.type == 'UIxMailPartLinkViewer') {\n\n if (part.type == 'UIxMailPartImageViewer')\n part.msgclass = 'msg-attachment-image';\n else if (part.type == 'UIxMailPartLinkViewer')\n part.msgclass = 'msg-attachment-link';\n\n // Trusted content that can be compiled (Angularly-speaking)\n part.compile = true;\n parts.push(part);\n }\n else {\n part.html = true;\n part.content = part.safeContent;\n parts.push(part);\n }\n }\n };\n\n if (this.parts)\n _visit(this.parts);\n\n return parts;\n };\n\n /**\n * @function $editableContent\n * @memberof Message.prototype\n * @desc First, fetch the draft ID that corresponds to the temporary draft object on the SOGo server.\n * Secondly, fetch the editable message body along with other metadata such as the recipients.\n * @returns the HTML representation of the body\n */\n Message.prototype.$editableContent = function() {\n var _this = this;\n\n return Message.$$resource.fetch(this.$absolutePath(), 'edit').then(function(data) {\n angular.extend(_this, data);\n return Message.$$resource.fetch(_this.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n // Try to match a known account identity from the specified \"from\" address\n var identity = _.find(_this.$mailbox.$account.identities, function(identity) {\n return data.from.toLowerCase().indexOf(identity.email) !== -1;\n });\n if (identity)\n data.from = identity.full;\n Message.$log.debug('editable = ' + JSON.stringify(data, undefined, 2));\n angular.extend(_this.editable, data);\n return data.text;\n });\n });\n };\n\n /**\n * @function $plainContent\n * @memberof Message.prototype\n * @returns the a plain text representation of the subject and body\n */\n Message.prototype.$plainContent = function() {\n return Message.$$resource.fetch(this.$absolutePath(), 'viewplain');\n };\n\n /**\n * @function addTag\n * @memberof Message.prototype\n * @desc Add a mail tag on the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.addTag = function(tag) {\n return this.$addOrRemoveTag('add', tag);\n };\n\n /**\n * @function removeTag\n * @memberof Message.prototype\n * @desc Remove a mail tag from the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.removeTag = function(tag) {\n return this.$addOrRemoveTag('remove', tag);\n };\n\n /**\n * @function $addOrRemoveTag\n * @memberof Message.prototype\n * @desc Add or remove a mail tag on the current message.\n * @param {string} operation - the operation name to perform\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$addOrRemoveTag = function(operation, tag) {\n var data = {\n operation: operation,\n msgUIDs: [this.uid],\n flags: tag\n };\n\n if (tag)\n return Message.$$resource.post(this.$mailbox.$id(), 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $imipAction\n * @memberof Message.prototype\n * @desc Perform IMIP actions on the current message.\n * @param {string} path - the path of the IMIP calendar part \n * @param {string} action - the the IMIP action to perform\n * @param {object} data - the delegation info \n */\n Message.prototype.$imipAction = function(path, action, data) {\n var _this = this;\n Message.$$resource.post([this.$absolutePath(), path].join('/'), action, data).then(function(data) {\n Message.$timeout(function() {\n _this.$reload();\n });\n });\n };\n\n /**\n * @function $sendMDN\n * @memberof Message.prototype\n * @desc Send MDN response for current email message\n */\n Message.prototype.$sendMDN = function() {\n this.shouldAskReceipt = 0;\n return Message.$$resource.post(this.$absolutePath(), 'sendMDN');\n };\n\n /**\n * @function $deleteAttachment\n * @memberof Message.prototype\n * @desc Delete an attachment from a message being composed\n * @param {string} filename - the filename of the attachment to delete\n */\n Message.prototype.$deleteAttachment = function(filename) {\n var action = 'deleteAttachment?filename=' + filename;\n var _this = this;\n Message.$$resource.post(this.$absolutePath({asDraft: true}), action).then(function(data) {\n Message.$timeout(function() {\n _this.editable.attachmentAttrs = _.filter(_this.editable.attachmentAttrs, function(attachment) {\n return attachment.filename != filename;\n });\n });\n });\n };\n\n /**\n * @function $markAsFlaggedOrUnflagged\n * @memberof Message.prototype\n * @desc Add or remove a the \\\\Flagged flag on the current message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.toggleFlag = function() {\n var _this = this,\n action = 'markMessageFlagged';\n\n if (this.isflagged)\n action = 'markMessageUnflagged';\n\n return Message.$$resource.post(this.$absolutePath(), action).then(function(data) {\n Message.$timeout(function() {\n _this.isflagged = !_this.isflagged;\n });\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Message.prototype\n * @returns true if the Message content is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Message.prototype.$isLoading = function() {\n return this.$loaded == Message.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @param {object} [options] - set {useCache: true} to use already fetched data\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var _this = this, futureMessageData;\n\n if (options && options.useCache && this.$futureMessageData) {\n if (!this.isread) {\n Message.$$resource.fetch(this.$absolutePath(), 'markMessageRead').then(function() {\n Message.$timeout(function() {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n });\n });\n }\n return this;\n }\n\n futureMessageData = Message.$$resource.fetch(this.$absolutePath(options), 'view');\n\n return this.$unwrap(futureMessageData);\n };\n\n /**\n * @function $reply\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$reply = function() {\n return this.$newDraft('reply');\n };\n\n /**\n * @function $replyAll\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender and all recipients.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$replyAll = function() {\n return this.$newDraft('replyall');\n };\n\n /**\n * @function $forward\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a forward.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$forward = function() {\n return this.$newDraft('forward');\n };\n\n /**\n * @function $newDraft\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply or a forward of the current message and associated\n * to the draft mailbox.\n * @see {@link Account.$newMessage}\n * @see {@link Message.$editableContent}\n * @see {@link Message.$reply}\n * @see {@link Message.$replyAll}\n * @see {@link Message.$forwad}\n * @param {string} action - the HTTP action to perform on the message\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$newDraft = function(action) {\n var _this = this;\n\n // Query server for draft folder and draft UID\n return Message.$$resource.fetch(this.$absolutePath(), action).then(function(data) {\n var mailbox, message;\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2));\n mailbox = _this.$mailbox.$account.$getMailboxByPath(data.mailboxPath);\n message = new Message(data.accountId, mailbox, data);\n // Fetch draft initial data\n return Message.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2) + ' original UID: ' + _this.uid);\n angular.extend(message.editable, data);\n\n // We keep a reference to our original message in order to update the flags\n message.origin = {message: _this, action: action};\n return message;\n });\n });\n };\n\n /**\n * @function $save\n * @memberof Message.prototype\n * @desc Save the message to the server.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$save = function() {\n var _this = this,\n data = this.editable;\n\n Message.$log.debug('save = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.save(this.$absolutePath({asDraft: true}), data).then(function(response) {\n Message.$log.debug('save = ' + JSON.stringify(response, undefined, 2));\n _this.$setUID(response.uid);\n _this.$reload(); // fetch a new viewable version of the message\n _this.isNew = false;\n });\n };\n\n /**\n * @function $send\n * @memberof Message.prototype\n * @desc Send the message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$send = function() {\n var _this = this,\n data = angular.copy(this.editable);\n\n Message.$log.debug('send = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.post(this.$absolutePath({asDraft: true}), 'send', data).then(function(response) {\n if (response.status == 'success') {\n if (angular.isDefined(_this.origin)) {\n if (_this.origin.action.startsWith('reply'))\n _this.origin.message.isanswered = true;\n else if (_this.origin.action == 'forward')\n _this.origin.message.isforwarded = true;\n }\n return response;\n }\n else {\n return Message.$q.reject(response.data);\n }\n });\n };\n\n /**\n * @function $unwrap\n * @memberof Message.prototype\n * @desc Unwrap a promise. \n * @param {promise} futureMessageData - a promise of some of the Message's data\n */\n Message.prototype.$unwrap = function(futureMessageData) {\n var _this = this;\n\n // Message is not loaded yet\n this.$loaded = Message.STATUS.DELAYED_LOADING;\n Message.$timeout(function() {\n if (_this.$loaded != Message.STATUS.LOADED)\n _this.$loaded = Message.STATUS.LOADING;\n }, Message.STATUS.DELAYED_MS);\n\n // Resolve and expose the promise\n this.$futureMessageData = futureMessageData.then(function(data) {\n // Calling $timeout will force Angular to refresh the view\n if (_this.isread === 0) {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n }\n return Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\n _this.$loaded = Message.STATUS.LOADED;\n return _this;\n });\n });\n\n return this.$futureMessageData;\n };\n\n /**\n * @function $omit\n * @memberof Message.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Message instance\n */\n Message.prototype.$omit = function(options) {\n var message = {},\n privateAttributes = options && options.privateAttributes;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$' || privateAttributes) {\n message[key] = value;\n }\n });\n\n return message;\n };\n\n /**\n * @function saveMessage\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.saveMessage = function() {\n var selectedUIDs;\n\n selectedUIDs = [ this.uid ];\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name VirtualMailbox\n * @constructor\n * @param {object} account - the mail account associated with the virtual search\n */\n function VirtualMailbox(account) {\n this.$account = account;\n }\n\n /**\n * @memberof VirtualMailbox\n * @desc The factory we'll use to register with Angular\n * @returns the VirtualMailbox constructor\n */\n VirtualMailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n selectedFolder: null,\n PRELOAD: PRELOAD\n });\n\n return VirtualMailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of VirtualMailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('VirtualMailbox', VirtualMailbox.$factory);\n\n /**\n * @memberof VirtualMailbox\n * @desc Build the path of the virtual mailbox (or account only).\n * @param {string} accountId - the account ID\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.$absolutePath = function(accountId) {\n return [accountId, \"virtual\"].join('/');\n };\n\n /**\n * @function init\n * @memberof VirtualMailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n VirtualMailbox.prototype.init = function(data) {\n this.$isLoading = false;\n this.$mailboxes = [];\n this.uidsMap = {};\n angular.extend(this, data);\n this.id = this.$id();\n };\n\n VirtualMailbox.prototype.setMailboxes = function(data) {\n this.$mailboxes = data;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n mailbox.$messages = [];\n mailbox.uidsMap = {};\n });\n };\n\n VirtualMailbox.prototype.startSearch = function(match, params) {\n var _this = this,\n search = VirtualMailbox.$q.when();\n\n this.$isLoading = true;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n search = search.then(function() {\n if (_this.$isLoading) {\n VirtualMailbox.$log.debug(\"searching mailbox \" + mailbox.path);\n return mailbox.$filter( {sort: \"date\", asc: false, match: match}, params);\n }\n });\n });\n\n search.finally(function() {\n _this.$isLoading = false;\n });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\n };\n\n /**\n * @function selectFolder\n * @memberof VirtualMailbox.prototype\n * @desc A no-op for virtual mailbox\n */\n VirtualMailbox.prototype.selectFolder = function() {\n return;\n };\n\n /**\n * @function resetSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Delete 'selectedMessage' attribute of all submailboxes.\n */\n VirtualMailbox.prototype.resetSelectedMessage = function() {\n _.forEach(this.$mailboxes, function(mailbox) {\n delete mailbox.selectedMessage;\n });\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if a message is selected among the resulting mailboxes\n * @returns true if one message is selected\n */\n VirtualMailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return angular.isDefined(mailbox.selectedMessage);\n }));\n };\n\n /**\n * @function isSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if the message of the specified mailbox is selected.\n * @param {string} messageId\n * @param {string} mailboxPath\n * @returns true if the specified message is selected\n */\n VirtualMailbox.prototype.isSelectedMessage = function(messageId, mailboxPath) {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return mailbox.path == mailboxPath && mailbox.selectedMessage == messageId;\n }));\n };\n\n /**\n * @function getLength\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of items in the mailbox\n */\n VirtualMailbox.prototype.getLength = function() {\n var len = 0;\n\n if (!angular.isDefined(this.$mailboxes))\n return len;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n len += mailbox.$messages.length;\n });\n\n return len;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message as the specified index\n */\n VirtualMailbox.prototype.getItemAtIndex = function(index) {\n var i, j, k, mailbox, message;\n\n if (angular.isDefined(this.$mailboxes) && index >= 0) {\n i = 0;\n for (j = 0; j < this.$mailboxes.length; j++) {\n mailbox = this.$mailboxes[j];\n for (k = 0; k < mailbox.$messages.length; i++, k++) {\n message = mailbox.$messages[k];\n if (i == index) {\n if (mailbox.$loadMessage(message.uid))\n return message;\n }\n }\n }\n }\n\n return null;\n };\n\n /**\n * @function $id\n * @memberof VirtualMailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.prototype.$id = function() {\n return VirtualMailbox.$absolutePath(this.$account.id);\n };\n\n /**\n * @function $selectedMessages\n * @memberof VirtualMailbox.prototype\n * @desc Return an associative array of the selected messages for each mailbox. Keys are the mailboxes ids.\n * @returns an associative array\n */\n VirtualMailbox.prototype.$selectedMessages = function() {\n var messagesMap = {};\n return _.transform(this.$mailboxes, function(messagesMap, mailbox) {\n messagesMap[mailbox.id] = mailbox.$selectedMessages();\n }, {});\n };\n\n /**\n * @function $selectedCount\n * @memberof VirtualMailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n VirtualMailbox.prototype.$selectedCount = function() {\n return _.sum(_.invokeMap(this.$mailboxes, '$selectedCount'));\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @param {object} messagesMap\n * @param {array} flags\n * @param {string} operation\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(messagesMap, flags, operation) {\n var data = {\n flags: flags,\n operation: operation\n };\n var allMessages = [];\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var uids = _.map(messages, 'uid');\n allMessages.push(messages);\n var promise = VirtualMailbox.$$resource.post(id, 'addOrRemoveLabel', _.assign(data, {msgUIDs: uids}));\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises).then(function() {\n return _.flatten(allMessages);\n });\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$deleteMessages(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof VirtualMailbox.prototype\n * @desc Mark messages as junk/not junk\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$markOrUnMarkMessagesAsJunk(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$copyMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$moveMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxController.$inject = ['$window', '$scope', '$timeout', '$q', '$state', '$mdDialog', '$mdToast', 'stateAccounts', 'stateAccount', 'stateMailbox', 'sgHotkeys', 'encodeUriFilter', 'sgFocus', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $scope, $timeout, $q, $state, $mdDialog, $mdToast, stateAccounts, stateAccount, stateMailbox, sgHotkeys, encodeUriFilter, focus, Dialog, Account, Mailbox) {\n var vm = this, messageDialog = null,\n defaultWindowTitle = angular.element($window.document).find('title').attr('sg-default') || \"SOGo\",\n hotkeys = [];\n\n // Expose controller for eventual popup windows\n $window.$mailboxController = vm;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n vm.confirmDeleteSelectedMessages = confirmDeleteSelectedMessages;\n vm.markOrUnMarkMessagesAsJunk = markOrUnMarkMessagesAsJunk;\n vm.copySelectedMessages = copySelectedMessages;\n vm.moveSelectedMessages = moveSelectedMessages;\n vm.markSelectedMessagesAsFlagged = markSelectedMessagesAsFlagged;\n vm.markSelectedMessagesAsUnread = markSelectedMessagesAsUnread;\n vm.selectAll = selectAll;\n vm.unselectMessages = unselectMessages;\n\n\n stateMailbox.selectFolder();\n\n _registerHotkeys(hotkeys);\n\n // Expunge mailbox when leaving the Mail module\n angular.element($window).on('beforeunload', _compactBeforeUnload);\n $scope.$on('$destroy', function() {\n angular.element($window).off('beforeunload', _compactBeforeUnload);\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n // Update window's title with unseen messages count of selected mailbox\n $scope.$watch(function() { return vm.selectedFolder.unseenCount; }, function(unseenCount) {\n var title = defaultWindowTitle + ' - ';\n if (unseenCount)\n title += '(' + unseenCount + ') ';\n title += vm.selectedFolder.name;\n $window.document.title = title;\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_compose'),\n description: l('Write a new message'),\n callback: newMessage\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: confirmDeleteSelectedMessages\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function _compactBeforeUnload(event) {\n return vm.selectedFolder.$compact();\n }\n\n function sort(field) {\n vm.selectedFolder.$filter({ sort: field });\n }\n\n function sortedBy(field) {\n return Mailbox.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter().then(function() {\n if (vm.selectedFolder.selectedMessage) {\n $timeout(function() {\n vm.selectedFolder.$topIndex = vm.selectedFolder.uidsMap[vm.selectedFolder.selectedMessage];\n });\n }\n });\n }\n\n function newMessage($event) {\n var message;\n\n if (messageDialog === null) {\n message = vm.account.$newMessage();\n messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message,\n stateRecipients: []\n }\n })\n .finally(function() {\n messageDialog = null;\n });\n }\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index))\n index--;\n else\n // No message is selected, show oldest message\n index = vm.selectedFolder.getLength() - 1;\n\n if (index > -1)\n selectMessage(vm.selectedFolder.$messages[index]);\n\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index))\n index++;\n else\n // No message is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.getLength())\n selectMessage(vm.selectedFolder.$messages[index]);\n else\n index = -1;\n\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.getLength())\n vm.selectedFolder.$topIndex++;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _nextMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function _addPreviousMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _previousMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {mailboxId: encodeUriFilter(message.$mailbox.path), messageId: message.uid});\n else\n $state.go('mail.account.mailbox.message', {messageId: message.uid});\n }\n\n function toggleMessageSelection($event, message) {\n if (!message) message = vm.selectedFolder.$selectedMessage();\n message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n /**\n * Batch operations\n */\n\n function _currentMailboxes() {\n if (Mailbox.$virtualMode)\n return vm.selectedFolder.$mailboxes;\n else\n return [vm.selectedFolder];\n }\n\n function _unselectMessage(message, index) {\n // Unselect current message and cleverly load the next message.\n // This function must not be called in virtual mode.\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = vm.selectedFolder.$messages[nextIndex];\n }\n if (index < vm.selectedFolder.$messages.length)\n previousMessage = vm.selectedFolder.$messages[index];\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n if (nextMessage) {\n vm.selectedFolder.$topIndex = nextIndex;\n $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n else {\n $timeout(function() {\n console.warn('go to mailbox');\n $state.go('mail.account.mailbox');\n });\n }\n }\n\n function confirmDeleteSelectedMessages($event) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n\n if (messageDialog === null && _.size(selectedMessages) > 0)\n messageDialog = Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n });\n })\n .finally(function() {\n messageDialog = null;\n });\n\n $event.preventDefault();\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var dstFolder = '/' + vm.account.id + '/folderINBOX';\n if (vm.selectedFolder.type != 'junk') {\n dstFolder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n vm.selectedFolder.$moveMessages(selectedMessages, dstFolder).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n });\n }\n\n function copySelectedMessages(dstFolder) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$copyMessages(selectedMessages, '/' + dstFolder).then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) copied', vm.selectedFolder.$selectedCount()))\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n function moveSelectedMessages(dstFolder) {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n var count = vm.selectedFolder.$selectedCount();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + dstFolder).then(function(index) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) moved', count))\n .position('top right')\n .hideDelay(2000));\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was moved, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n }\n\n function selectAll() {\n var count = 0;\n _.forEach(_currentMailboxes(), function(folder) {\n var i = 0, length = folder.$messages.length;\n for (; i < length; i++)\n folder.$messages[i].selected = true;\n count += length;\n });\n vm.mode.multiple = count;\n }\n\n function unselectMessages() {\n _.forEach(_currentMailboxes(), function(folder) {\n _.forEach(folder.$messages, function(message) {\n message.selected = false;\n });\n });\n vm.mode.multiple = 0;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, '\\\\Flagged', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'remove').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isread = false;\n message.$mailbox.unseenCount++;\n });\n });\n }\n\n }\n\n angular\n .module('material.components.virtualRepeat')\n .decorator('mdVirtualRepeatContainerDirective', mdVirtualRepeatContainerDirectiveDecorator);\n\n /**\n * @ngInject\n */\n mdVirtualRepeatContainerDirectiveDecorator.$inject = ['$delegate'];\n function mdVirtualRepeatContainerDirectiveDecorator($delegate) {\n $delegate[0].controller.prototype.resetScroll = function() {\n // Don't scroll to top if current virtual repeater is the messages list\n // but do update the container size\n if (this.$element.parent().attr('id') == 'messagesList')\n this.updateSize();\n else\n this.scrollTo(0);\n };\n return $delegate;\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxController', MailboxController);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2; -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$scope', '$state', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgConstant', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'sgHotkeys', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($scope, $state, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, sgConstant, focus, encodeUriFilter, Dialog, Settings, sgHotkeys, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox,\n hotkeys = [];\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.toggleAccountState = toggleAccountState;\n vm.subscribe = subscribe;\n vm.newFolder = newFolder;\n vm.delegate = delegate;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.selectFolder = selectFolder;\n vm.saveFolder = saveFolder;\n vm.compactFolder = compactFolder;\n vm.emptyTrashFolder = emptyTrashFolder;\n vm.confirmDelete = confirmDelete;\n vm.markFolderRead = markFolderRead;\n vm.share = share;\n vm.metadataForFolder = metadataForFolder;\n vm.setFolderAs = setFolderAs;\n vm.refreshUnseenCount = refreshUnseenCount;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedMessages = dragSelectedMessages;\n\n // Advanced search options\n vm.showingAdvancedSearch = false;\n vm.currentSearchParam = '';\n vm.addSearchParam = addSearchParam;\n vm.newSearchParam = newSearchParam;\n vm.showAdvancedSearch = showAdvancedSearch;\n vm.hideAdvancedSearch = hideAdvancedSearch;\n vm.toggleAdvancedSearch = toggleAdvancedSearch;\n vm.search = {\n options: {'': l('Select a criteria'),\n subject: l('Enter Subject'),\n from: l('Enter From'),\n to: l('Enter To'),\n cc: l('Enter Cc'),\n body: l('Enter Body')\n },\n mailbox: 'INBOX',\n subfolders: 1,\n match: 'AND',\n params: []\n };\n\n\n Preferences.ready().then(function() {\n vm.showSubscribedOnly = Preferences.defaults.SOGoMailShowSubscribedFoldersOnly;\n });\n\n vm.refreshUnseenCount();\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: function() {\n if (Mailbox.selectedFolder && !Mailbox.selectedFolder.hasSelectedMessage())\n confirmDelete(Mailbox.selectedFolder);\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n }\n\n function hideAdvancedSearch() {\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n\n account = vm.accounts[0];\n mailbox = vm.searchPreviousMailbox;\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(mailbox.path) });\n }\n\n function toggleAdvancedSearch() {\n if (Mailbox.selectedFolder.$isLoading) {\n // Stop search\n vm.virtualMailbox.stopSearch();\n }\n else {\n // Start search\n var root, mailboxes = [],\n _visit = function(folders) {\n _.forEach(folders, function(o) {\n mailboxes.push(o);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n vm.virtualMailbox = new VirtualMailbox(vm.accounts[0]);\n\n // Don't set the previous selected mailbox if we're in virtual mode\n // That allows users to do multiple advanced search but return\n // correctly to the previously selected mailbox once done.\n if (!Mailbox.$virtualMode)\n vm.searchPreviousMailbox = Mailbox.selectedFolder;\n\n Mailbox.selectedFolder = vm.virtualMailbox;\n Mailbox.$virtualMode = true;\n\n if (angular.isDefined(vm.search.mailbox)) {\n root = vm.accounts[0].$getMailboxByPath(vm.search.mailbox);\n mailboxes.push(root);\n if (vm.search.subfolders && root.children.length)\n _visit(root.children);\n }\n else {\n mailboxes = vm.accounts[0].$flattenMailboxes();\n }\n\n vm.virtualMailbox.setMailboxes(mailboxes);\n vm.virtualMailbox.startSearch(vm.search.match, vm.search.params);\n $state.go('mail.account.virtualMailbox', { accountId: vm.accounts[0].id });\n }\n }\n\n function addSearchParam(v) {\n vm.currentSearchParam = v;\n focus('advancedSearch');\n return false;\n }\n\n function newSearchParam(pattern) {\n if (pattern.length && vm.currentSearchParam.length) {\n var n = 0, searchParam = vm.currentSearchParam;\n if (pattern.startsWith(\"!\")) {\n n = 1;\n pattern = pattern.substring(1).trim();\n }\n vm.currentSearchParam = '';\n return { searchBy: searchParam, searchInput: pattern, negative: n };\n }\n }\n\n function toggleAccountState(account) {\n account.$expanded = !account.$expanded;\n account.$flattenMailboxes({ reload: true, saveState: true });\n // Fire a window resize to recompute the virtual-repeater.\n // This is a fix until the following issue is officially resolved:\n // https://github.com/angular/material/issues/7309\n $timeout(function() {\n angular.element($window).triggerHandler('resize');\n }, 150);\n }\n\n function subscribe(account) {\n $mdDialog.show({\n templateUrl: account.id + '/subscribe',\n controller: SubscriptionsDialogController,\n controllerAs: 'subscriptions',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcApp: vm,\n srcAccount: account\n }\n }).finally(function() {\n account.$getMailboxes({reload: true});\n });\n\n /**\n * @ngInject\n */\n SubscriptionsDialogController.$inject = ['$scope', '$mdDialog', 'srcApp', 'srcAccount'];\n function SubscriptionsDialogController($scope, $mdDialog, srcApp, srcAccount) {\n var vm = this;\n\n vm.app = srcApp;\n vm.account = new Account({id: srcAccount.id,\n name: srcAccount.name},\n true);\n vm.close = close;\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function newFolder(parentFolder) {\n Dialog.prompt(l('New folder'),\n l('Enter the new name of your folder :'))\n .then(function(name) {\n parentFolder.$newMailbox(parentFolder.id, name)\n .then(function() {\n // success\n }, function(data, status) {\n Dialog.alert(l('An error occured while creating the mailbox \"%{0}\".', name),\n l(data.error));\n });\n });\n }\n\n function delegate(account) {\n $mdDialog.show({\n templateUrl: account.id + '/delegation', // UI/Templates/MailerUI/UIxMailUserDelegation.wox\n controller: MailboxDelegationController,\n controllerAs: 'delegate',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n User: User,\n account: account\n }\n });\n\n /**\n * @ngInject\n */\n MailboxDelegationController.$inject = ['$scope', '$mdDialog', 'User', 'account'];\n function MailboxDelegationController($scope, $mdDialog, User, account) {\n var vm = this;\n\n vm.users = account.delegates;\n vm.account = account;\n vm.userToAdd = '';\n vm.searchText = '';\n vm.userFilter = userFilter;\n vm.closeModal = closeModal;\n vm.removeUser = removeUser;\n vm.addUser = addUser;\n\n function userFilter($query) {\n return User.$filter($query, account.delegates);\n }\n\n function closeModal() {\n $mdDialog.hide();\n }\n\n function removeUser(user) {\n account.$removeDelegate(user.uid).catch(function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured please try again.'));\n });\n }\n\n function addUser(data) {\n if (data) {\n account.$addDelegate(data).then(function() {\n vm.userToAdd = '';\n vm.searchText = '';\n }, function(error) {\n Dialog.alert(l('Warning'), error);\n });\n }\n }\n }\n } // delegate\n\n function editFolder(folder) {\n vm.editMode = folder.path;\n focus('mailboxName_' + folder.path);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function selectFolder($event, account, folder) {\n if (vm.editMode == folder.path)\n return;\n vm.editMode = false;\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(folder.path) });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function saveFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function compactFolder(folder) {\n folder.$compact().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Folder compacted'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function emptyTrashFolder(folder) {\n folder.$emptyTrash().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Trash emptied'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function confirmDelete(folder) {\n Dialog.confirm(l('Confirmation'), l('Do you really want to move this folder into the trash ?'))\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(data, status) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(data.error));\n });\n });\n }\n\n function markFolderRead(folder) {\n folder.$markAsRead();\n }\n\n function share(folder) {\n // Fetch list of ACL users\n folder.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: folder.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: folder.$acl.users,\n User: User,\n folder: folder\n }\n });\n });\n } // share\n\n function metadataForFolder(folder) {\n if (folder.type == 'inbox')\n return {name: folder.name, icon:'inbox', special: true};\n else if (folder.type == 'draft')\n return {name: l('DraftsFolderName'), icon: 'drafts', special: true};\n else if (folder.type == 'sent')\n return {name: l('SentFolderName'), icon: 'send', special: true};\n else if (folder.type == 'trash')\n return {name: l('TrashFolderName'), icon: 'delete', special: true};\n else if (folder.type == 'junk')\n return {name: l('JunkFolderName'), icon: 'thumb_down', special: true};\n else if (folder.type == 'additional')\n return {name: folder.name, icon: 'folder_shared', special: true};\n\n return {name: folder.name, icon: 'folder_open', special: false};\n }\n\n function setFolderAs(folder, type) {\n folder.$setFolderAs(type).then(function() {\n folder.$account.$getMailboxes({reload: true});\n });\n }\n\n function refreshUnseenCount() {\n var unseenCountFolders = $window.unseenCountFolders;\n\n _.forEach(vm.accounts, function(account) {\n\n // Always include the INBOX\n if (!_.includes(unseenCountFolders, account.id + '/folderINBOX'))\n unseenCountFolders.push(account.id + '/folderINBOX');\n\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (angular.isDefined(mailbox.unseenCount) &&\n !_.includes(unseenCountFolders, mailbox.id))\n unseenCountFolders.push(mailbox.id);\n });\n });\n\n Account.$$resource.post('', 'unseenCount', {mailboxes: unseenCountFolders}).then(function(data) {\n _.forEach(vm.accounts, function(account) {\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (data[mailbox.id])\n mailbox.unseenCount = data[mailbox.id];\n });\n });\n });\n\n Preferences.ready().then(function() {\n var refreshViewCheck = Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually')\n $timeout(vm.refreshUnseenCount, refreshViewCheck.timeInterval()*1000);\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && !dstFolder.isNoSelect();\n }\n\n function dragSelectedMessages(srcFolder, dstFolder, mode) {\n var dstId, messages, uids, clearMessageView, promise, success;\n\n dstId = '/' + dstFolder.id;\n messages = srcFolder.$selectedMessages();\n if (messages.length === 0)\n messages = [srcFolder.$selectedMessage()];\n uids = _.map(messages, 'uid');\n clearMessageView = (srcFolder.selectedMessage && uids.indexOf(srcFolder.selectedMessage) >= 0);\n\n if (mode == 'copy') {\n promise = srcFolder.$copyMessages(messages, dstId);\n success = l('%{0} message(s) copied', messages.length);\n }\n else {\n promise = srcFolder.$moveMessages(messages, dstId);\n success = l('%{0} message(s) moved', messages.length);\n }\n\n promise.then(function() {\n if (clearMessageView)\n $state.go('mail.account.mailbox');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxesController', MailboxesController);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageController.$inject = ['$window', '$scope', '$state', '$mdMedia', '$mdDialog', 'sgConstant', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdMedia, $mdDialog, sgConstant, stateAccounts, stateAccount, stateMailbox, stateMessage, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, messageDialog = null, popupWindow = null, hotkeys = [];\n\n // Expose controller\n $window.$messageController = vm;\n\n vm.$state = $state;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.mailbox = stateMailbox;\n vm.message = stateMessage;\n vm.service = Message;\n vm.tags = { searchText: '', selected: '' };\n vm.showFlags = stateMessage.flags && stateMessage.flags.length > 0;\n vm.$showDetailedRecipients = false;\n vm.toggleDetailedRecipients = toggleDetailedRecipients;\n vm.filterMailtoLinks = filterMailtoLinks;\n vm.deleteMessage = deleteMessage;\n vm.close = close;\n vm.reply = reply;\n vm.replyAll = replyAll;\n vm.forward = forward;\n vm.edit = edit;\n vm.openPopup = openPopup;\n vm.closePopup = closePopup;\n vm.newMessage = newMessage;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n vm.print = print;\n vm.convertToEvent = convertToEvent;\n vm.convertToTask = convertToTask;\n\n _registerHotkeys(hotkeys);\n\n // One-way refresh of the parent window when modifying the message from a popup window.\n if ($window.opener) {\n // Update the message flags. The message must be displayed in the parent window.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(newTags, oldTags) {\n var ctrls;\n if (newTags || oldTags) {\n ctrls = $parentControllers();\n if (ctrls.messageCtrl) {\n ctrls.messageCtrl.service.$timeout(function() {\n ctrls.messageCtrl.showFlags = true;\n ctrls.messageCtrl.message.flags = newTags;\n });\n }\n }\n });\n // Update the \"isflagged\" (star icon) of the message. The mailbox must be displayed in the parent window.\n $scope.$watch(function() { return vm.message.isflagged; }, function(isflagged, wasflagged) {\n var ctrls = $parentControllers();\n if (ctrls.mailboxCtrl) {\n ctrls.mailboxCtrl.service.$timeout(function() {\n var message = _.find(ctrls.mailboxCtrl.selectedFolder.$messages, { uid: vm.message.uid });\n message.isflagged = isflagged;\n });\n }\n });\n }\n else {\n // Flatten new tags when coming from the predefined list of tags (Message.$tags) and\n // sync tags with server when adding or removing a tag.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(_newTags, _oldTags) {\n var newTags, oldTags, tags;\n if (_newTags || _oldTags) {\n newTags = _newTags || [];\n oldTags = _oldTags || [];\n _.forEach(newTags, function(tag, i) {\n if (angular.isObject(tag))\n newTags[i] = tag.name;\n });\n if (newTags.length > oldTags.length) {\n tags = _.difference(newTags, oldTags);\n _.forEach(tags, function(tag) {\n vm.message.addTag(tag);\n });\n }\n else if (newTags.length < oldTags.length) {\n tags = _.difference(oldTags, newTags);\n _.forEach(tags, function(tag) {\n vm.message.removeTag(tag);\n });\n }\n }\n });\n }\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n callback: function($event) {\n if (vm.mailbox.$selectedCount() === 0)\n deleteMessage();\n $event.preventDefault();\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n /**\n * If this is a popup window, retrieve the matching controllers (mailbox and message) of the parent window.\n */\n function $parentControllers() {\n var message, mailbox, ctrls = {};\n if ($window.opener) {\n // Deleting the message from a popup window\n if ($window.opener.$mailboxController &&\n $window.opener.$mailboxController.selectedFolder.$id() == stateMailbox.$id()) {\n // The message mailbox is opened in the parent window\n mailbox = $window.opener.$mailboxController;\n ctrls.mailboxCtrl = mailbox;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The message is opened in the parent window\n message = $window.opener.$messageController;\n ctrls.messageCtrl = message;\n }\n }\n }\n return ctrls;\n }\n\n function toggleDetailedRecipients($event) {\n vm.$showDetailedRecipients = !vm.$showDetailedRecipients;\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function filterMailtoLinks($event) {\n var href, match, to, cc, bcc, subject, body, data;\n if ($event.target.tagName == 'A' && 'href' in $event.target.attributes) {\n href = $event.target.attributes.href.value;\n match = /^mailto:([^\\?]+)/.exec(href);\n if (match) {\n // Recipients\n to = _.map(decodeURIComponent(match[1]).split(','), function(email) {\n return '<' + email + '>';\n });\n data = { to: to };\n // Subject & body\n _.forEach(['subject', 'body'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n param = (param == 'body')? 'text' : param;\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n // Recipients\n _.forEach(['cc', 'bcc'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n newMessage($event, data); // will stop event propagation\n }\n }\n }\n\n function deleteMessage() {\n var mailbox, message, state, nextMessage, previousMessage,\n parentCtrls = $parentControllers();\n\n if (parentCtrls.messageCtrl) {\n mailbox = parentCtrls.mailboxCtrl.selectedFolder;\n message = parentCtrls.messageCtrl.message;\n state = parentCtrls.messageCtrl.$state;\n }\n else {\n mailbox = stateMailbox;\n message = stateMessage;\n state = $state;\n }\n\n mailbox.$deleteMessages([message]).then(function(index) {\n var nextIndex = index;\n // Remove message object from scope\n message = null;\n if (angular.isDefined(state)) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = mailbox.$messages[nextIndex];\n }\n if (index < mailbox.$messages.length)\n previousMessage = mailbox.$messages[index];\n\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n\n try {\n if (nextMessage && $mdMedia(sgConstant['gt-md'])) {\n state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n if (nextIndex < mailbox.$topIndex)\n mailbox.$topIndex = nextIndex;\n else if (nextIndex > mailbox.$lastVisibleIndex)\n mailbox.$topIndex = nextIndex - (mailbox.$lastVisibleIndex - mailbox.$topIndex);\n }\n else {\n state.go('mail.account.mailbox').then(function() {\n message = null;\n delete mailbox.selectedMessage;\n });\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (messageDialog === null) {\n messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n messageDialog = null;\n closePopup();\n });\n }\n }\n\n function close() {\n $state.go('mail.account.mailbox').then(function() {\n vm.message = null;\n delete stateMailbox.selectedMessage;\n });\n }\n\n function reply($event) {\n var message = vm.message.$reply();\n showMailEditor($event, message);\n }\n\n function replyAll($event) {\n var message = vm.message.$replyAll();\n showMailEditor($event, message);\n }\n\n function forward($event) {\n var message = vm.message.$forward();\n showMailEditor($event, message);\n }\n\n function edit($event) {\n vm.message.$editableContent().then(function() {\n showMailEditor($event, vm.message);\n });\n }\n\n function openPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#/Mail',\n vm.message.accountId,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.message.$mailbox.path)),\n vm.message.uid]\n .join('/'),\n wId = vm.message.$absolutePath();\n popupWindow = $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n function closePopup() {\n if ($window.opener)\n $window.close();\n }\n\n function newMessage($event, editableContent) {\n vm.account.$newMessage().then(function(message) {\n angular.extend(message.editable, editableContent);\n showMailEditor($event, message);\n });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.message.$rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.message.$rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n\n function print($event) {\n $window.print();\n }\n\n function convertToEvent($event) {\n return convertToComponent($event, 'appointment');\n }\n\n function convertToTask($event) {\n return convertToComponent($event, 'task');\n }\n\n function convertToComponent($event, type) {\n vm.message.$plainContent().then(function(data) {\n var componentData = {\n pid: Calendar.$defaultCalendar(),\n type: type,\n summary: data.subject,\n comment: data.content\n };\n var component = new Component(componentData);\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = [\n sgSettings.activeUser('folderURL'),\n 'Calendar',\n 'UIx' + type.capitalize() + 'EditorTemplate'\n ].join('/');\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n });\n }\n }\n \n angular\n .module('SOGo.MailerUI') \n .controller('MessageController', MessageController); \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageEditorController.$inject = ['$scope', '$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($scope, $window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this;\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.cancel = cancel;\n vm.save = save;\n vm.send = send;\n vm.sendState = false;\n vm.removeAttachment = removeAttachment;\n vm.contactFilter = contactFilter;\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.recipientSeparatorKeys = [\n $mdConstant.KEY_CODE.ENTER,\n $mdConstant.KEY_CODE.TAB,\n $mdConstant.KEY_CODE.COMMA,\n $mdConstant.KEY_CODE.SEMICOLON\n ];\n vm.uploader = new FileUploader({\n url: stateMessage.$absolutePath({asDraft: true}) + '/save',\n autoUpload: true,\n alias: 'attachments',\n removeAfterUpload: false,\n // onProgressItem: function(item, progress) {\n // console.debug(item); console.debug(progress);\n // },\n onSuccessItem: function(item, response, status, headers) {\n stateMessage.$setUID(response.uid);\n stateMessage.$reload({asDraft: false});\n item.inlineUrl = response.lastAttachmentAttrs[0].url;\n //console.debug(item); console.debug('success = ' + JSON.stringify(response, undefined, 2));\n },\n onCancelItem: function(item, response, status, headers) {\n //console.debug(item); console.debug('cancel = ' + JSON.stringify(response, undefined, 2));\n // We remove the attachment\n stateMessage.$deleteAttachment(item.file.name);\n this.removeFromQueue(item);\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Error while uploading the file \\\"%{0}\\\":', item.file.name))\n .position('top right')\n .hideDelay(3000));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\n\n // Destroy file uploader when the controller is being deactivated\n $scope.$on('$destroy', function() { vm.uploader.destroy(); });\n\n if ($stateParams.actionName == 'reply') {\n stateMessage.$reply().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'replyall') {\n stateMessage.$replyAll().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'forward') {\n stateMessage.$forward().then(function(msgObject) {\n vm.message = msgObject;\n addAttachments();\n });\n }\n else if (angular.isDefined(stateMessage)) {\n vm.message = stateMessage;\n addAttachments();\n }\n\n /**\n * If this is a popup window, retrieve the mailbox controller of the parent window.\n */\n function $parentControllers() {\n var originMessage, ctrls = {};\n if ($window.opener) {\n if ($window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The draft is opened in the parent window\n ctrls.draftMessageCtrl = $window.opener.$messageController;\n }\n }\n else if (stateMessage.origin) {\n originMessage = stateMessage.origin.message;\n if ($window.opener.$mailboxController.selectedFolder.$id() == originMessage.$mailbox.$id()) {\n // The message mailbox is opened in the parent window\n ctrls.originMailboxCtrl = $window.opener.$mailboxController;\n }\n }\n }\n }\n return ctrls;\n }\n\n function addAttachments() {\n // Add existing attached files to uploader\n var i, data, fileItem, attrs = vm.message.editable.attachmentAttrs;\n if (attrs)\n for (i = 0; i < attrs.length; i++) {\n data = {\n name: attrs[i].filename,\n type: attrs[i].mimetype,\n size: parseInt(attrs[i].size)\n };\n fileItem = new FileUploader.FileItem(vm.uploader, data);\n fileItem.progress = 100;\n fileItem.isUploaded = true;\n fileItem.isSuccess = true;\n fileItem.inlineUrl = attrs[i].url;\n vm.uploader.queue.push(fileItem);\n }\n }\n\n function removeAttachment(item) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\n }\n\n function cancel() {\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n if (vm.message.isNew && vm.message.attachmentAttrs)\n vm.message.$mailbox.$deleteMessages([vm.message]);\n\n $mdDialog.cancel();\n }\n\n function save() {\n var ctrls = $parentControllers();\n vm.message.$save().then(function(data) {\n vm.message.$rawSource = null;\n if (ctrls.draftMailboxCtrl) {\n // We're saving a draft from a popup window.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Reload selected message\n ctrls.draftMessageCtrl.$state.go('mail.account.mailbox.message', { messageId: vm.message.uid });\n }\n });\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been saved'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function send() {\n var ctrls = $parentControllers();\n\n vm.sendState = 'sending';\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\n vm.sendState = 'sent';\n if (ctrls.draftMailboxCtrl) {\n // We're sending a draft from a popup window and the draft mailbox is opened.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Close draft\n ctrls.draftMessageCtrl.close();\n }\n });\n }\n if (ctrls.originMailboxCtrl) {\n // We're sending a draft from a popup window and the original mailbox is opened.\n // Reload mailbox\n ctrls.originMailboxCtrl.selectedFolder.$filter();\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been sent'))\n .position('top right')\n .hideDelay(3000));\n\n // Let the user see the succesfull message before closing the dialog\n $timeout($mdDialog.hide, 1000);\n }, function(response) {\n vm.sendState = 'error';\n vm.errorMessage = response.data? response.data.message : response.statusText;\n });\n }\n\n function contactFilter($query) {\n return AddressBook.$filterAll($query).then(function(cards) {\n // Divide the matching cards by email addresses so the user can select\n // the recipient address of her choice\n var explodedCards = [];\n _.forEach(_.invokeMap(cards, 'explode'), function(manyCards) {\n _.forEach(manyCards, function(card) {\n explodedCards.push(card);\n });\n });\n // Remove duplicates\n return _.uniqBy(explodedCards, function(card) {\n return card.$$fullname + ' ' + card.$$email;\n });\n });\n }\n\n function addRecipient(contact, field) {\n var recipients, recipient, list;\n\n if (angular.isString(contact))\n return contact;\n\n recipients = vm.message.editable[field];\n\n if (contact.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(contact.refs) && contact.refs.length) {\n _.forEach(contact.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n list = Card.$find(contact.container, contact.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n });\n }\n }\n else {\n recipient = contact.$shortFormat();\n }\n\n if (recipient)\n return recipient;\n else\n return null;\n }\n\n // Drafts autosaving\n function autosaveDrafts() {\n vm.message.$save();\n if (Preferences.defaults.SOGoMailAutoSave)\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n }\n\n // Read user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailAutoSave)\n // Enable auto-save of draft\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n // Set the locale of CKEditor\n vm.localeCode = Preferences.defaults.LocaleCode;\n });\n }\n\n SendMessageToastController.$inject = ['$scope', '$mdToast'];\n function SendMessageToastController($scope, $mdToast) {\n $scope.closeToast = function() {\n $mdToast.hide();\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('SendMessageToastController', SendMessageToastController)\n .controller('MessageEditorController', MessageEditorController);\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /**\n * sgIMIP - A directive to handle IMIP actions on emails\n * @memberof SOGo.MailerUI\n * @example:\n\n */\n function sgImip() {\n return {\n restrict: 'A',\n link: link,\n controller: 'sgImipController'\n };\n\n function link(scope, iElement, attrs, ctrl) {\n ctrl.pathToAttachment = attrs.sgImipPath;\n }\n }\n\n /**\n * @ngInject\n */\n sgImipController.$inject = ['$scope', 'User'];\n function sgImipController($scope, User) {\n var vm = this;\n\n $scope.delegateInvitation = false;\n $scope.delegatedTo = '';\n $scope.searchText = '';\n\n $scope.userFilter = function($query) {\n return User.$filter($query);\n };\n\n $scope.iCalendarAction = function(action) {\n var data;\n\n if (action == 'delegate') {\n data = {\n receiveUpdates: false,\n delegatedTo: $scope.delegatedTo.c_email\n };\n }\n\n $scope.viewer.message.$imipAction(vm.pathToAttachment, action, data);\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('sgImipController', sgImipController)\n .directive('sgImip', sgImip);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgZoomableImage - Toggle the 'sg-zoom' class when clicking on the image inside the container.\n * @memberof SOGo.MailerUI\n * @restrict attribute\n * @ngInject\n * @example:\n\n
\n \n \n \n
\n */\n function sgZoomableImage() {\n return {\n restrict: 'A',\n link: link\n };\n\n function link(scope, iElement, attrs, ctrl) {\n var parentNode = iElement.parent(),\n toggleClass;\n\n toggleClass = function(event) {\n if (event.target.tagName == 'IMG')\n parentNode.toggleClass('sg-zoom');\n };\n\n iElement.on('click', toggleClass);\n }\n }\n\n angular\n .module('SOGo.MailerUI')\n .directive('sgZoomableImage', sgZoomableImage);\n})();\n"]} \ No newline at end of file +{"version":3,"sources":["Mailer/Account.service.js","Mailer/Mailbox.service.js","Mailer/Message.service.js","Mailer/VirtualMailbox.service.js","Mailer/MailboxController.js","Mailer/MailboxesController.js","Mailer/MessageController.js","Mailer/MessageEditorController.js","Mailer/sgIMIP.directive.js","Mailer/sgZoomableImage.directive.js"],"names":["Account","futureAccountData","then","angular","extend","this","_","forEach","identities","identity","fullName","full","email","$log","debug","JSON","stringify","undefined","$factory","$q","$timeout","Settings","Resource","Preferences","Mailbox","Message","$$resource","activeUser","$Preferences","$Mailbox","$Message","module","e","factory","$findAll","data","$unwrapCollection","fetch","o","collection","i","id","$accounts","prototype","getLength","$flattenMailboxes","length","getItemAtIndex","index","expandedMailboxes","$getMailboxes","options","_this","$mailboxes","reload","$find","$expanded","ready","expandedFolders","_visit","mailboxes","indexOf","children","settings","Mail","ExpandedFolders","isString","fromJson","when","allMailboxes","push","all","$$flattenMailboxes","saveState","account","reduce","mailbox","post","$getMailboxByType","type","_find","find","$getMailboxByPath","path","$newMailbox","name","toString","updateQuota","percent","format","description","Math","round","usedSpace","maxQuota","l","formatted","$quota","$newMessage","message","accountId","mailboxPath","$absolutePath","asDraft","editable","isNew","$addDelegate","user","deferred","defer","param","uid","map","delegates","resolve","users","status","reject","promise","$removeDelegate","splice","futureMailboxData","$account","init","newMailboxData","create","$unwrap","Acl","PRELOAD","$$Acl","$query","sort","asc","selectedFolder","$refreshTimeout","$virtualMode","SortingState","parseInt","constant","LOOKAHEAD","SIZE","fetchAll","createMailboxes","level","quotas","split","component","asCSSIdentifier","join","$isLoading","$messages","uidsMap","$id","$acl","$isEditable","isEditable","$isNoInferiors","isNoInferiors","isUndefined","$shadowData","$omit","selectFolder","$lastVisibleIndex","max","$loadMessage","$selectedMessages","filter","selected","$selectedCount","isSelectedMessage","messageId","selectedMessage","$selectedMessage","$selectedMessageIndex","hasSelectedMessage","isDefined","$filter","sortingAttributes","filters","unseenCount","cancel","searchInput","secondFilter","match","searchBy","copy","refreshViewCheck","defaults","SOGoRefreshViewCheck","f","bind","timeInterval","endIndex","uids","futureHeadersData","startIndex","loaded","subject","min","loading","$unwrapHeaders","flags","isNoSelect","$rename","findParent","parent","parentMailbox","$save","sibling","localeCompare","$compact","$setFolderAs","$emptyTrash","$markAsRead","$flagMessages","messages","operation","msgUIDs","saveSelectedMessages","selectedMessages","selectedUIDs","download","exportFolder","$delete","remove","$_deleteMessages","unseen","firstIndex","isread","forEachRight","selectedIndex","findIndex","$deleteMessages","$markOrUnMarkMessagesAsJunk","method","$copyMessages","folder","$moveMessages","$reset","value","key","save","response","error","$futureMailboxData","headers","$topIndex","invokeMap","threaded","msgs","msg","zipObject","isError","j","messageHeaders","$toggleSubscribe","subscribed","futureMessageData","lazy","$mailbox","$hasUnsafeContent","$loadUnsafeContent","to","cc","bcc","$formatFullAddresses","Message_STATUS","STATUS","$avatar","avatar","SOGoMailLabelsColors","$tags","SOGoMailDisplayRemoteInlineImages","$displayRemoteInlineImages","NOT_LOADED","DELAYED_LOADING","LOADING","LOADED","DELAYED_MS","filterTags","query","excludedTags","re","RegExp","results","keys","tag","pair","search","includes","color","buildPath","nocache","draftId","$setUID","oldUID","attr","constructor","shortname","first","last","replace","image","$shortRecipients","result","count","total","$shortAddress","address","allowReplyAll","recipientsCount","isDraft","loadUnsafeContent","$content","parts","part","msgclass","content","alternatePart","preferredPart","contentType","isArray","formattedMessage","$smime","validSignature","valid","mixedPart","safeContent","html","unsafeContent","document","createElement","innerHTML","suffix","element","elements","querySelectorAll","removeAttr","compile","$editableContent","from","toLowerCase","text","$plainContent","addTag","$addOrRemoveTag","removeTag","$imipAction","action","$reload","$sendMDN","shouldAskReceipt","$deleteAttachment","filename","attachmentAttrs","attachment","toggleFlag","isflagged","$loaded","useCache","$futureMessageData","$reply","$newDraft","$replyAll","$forward","origin","$send","startsWith","isanswered","isforwarded","privateAttributes","saveMessage","VirtualMailbox","setMailboxes","startSearch","params","finally","stopSearch","resetSelectedMessage","len","k","transform","messagesMap","sum","allMessages","promises","assign","flatten","MailboxController","$window","$scope","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","focus","Dialog","_registerHotkeys","createHotkey","callback","searchMode","newMessage","toggleMessageSelection","_nextMessage","preventInClass","_previousMessage","_addNextMessageToSelection","_addPreviousMessageToSelection","confirmDeleteSelectedMessages","registerHotkey","_compactBeforeUnload","event","vm","field","sortedBy","mode","cancelSearch","$event","messageDialog","show","body","targetEvent","clickOutsideToClose","escapeToClose","templateUrl","controller","controllerAs","locals","stateMessage","stateRecipients","selectMessage","preventDefault","go","mailboxId","multiple","stopPropagation","_currentMailboxes","_unselectMessage","nextMessage","previousMessage","nextIndex","console","warn","size","confirm","ok","deleteSelectedMessage","markOrUnMarkMessagesAsJunk","moveSelectedMessage","dstFolder","copySelectedMessages","simple","position","hideDelay","moveSelectedMessages","selectAll","unselectMessages","markSelectedMessagesAsFlagged","markSelectedMessagesAsUnread","defaultWindowTitle","hotkeys","$mailboxController","service","accounts","on","$on","off","deregisterHotkey","$watch","title","mdVirtualRepeatContainerDirectiveDecorator","$delegate","resetScroll","$element","updateSize","scrollTo","$inject","decorator","MailboxesController","$mdMedia","$mdSidenav","sgConstant","User","confirmDelete","showAdvancedSearch","showingAdvancedSearch","close","hideAdvancedSearch","searchPreviousMailbox","toggleAdvancedSearch","virtualMailbox","root","folders","subfolders","addSearchParam","v","currentSearchParam","newSearchParam","pattern","n","searchParam","substring","trim","negative","toggleAccountState","triggerHandler","subscribe","SubscriptionsDialogController","metadataForFolder","srcAccount","newFolder","parentFolder","prompt","alert","delegate","MailboxDelegationController","userFilter","closeModal","hide","removeUser","catch","addUser","userToAdd","searchText","editFolder","editMode","revertEditing","saveFolder","compactFolder","emptyTrashFolder","markFolderRead","share","$users","usersWithACL","icon","special","setFolderAs","refreshUnseenCount","unseenCountFolders","isDroppableFolder","srcFolder","dragSelectedMessages","dstId","clearMessageView","success","","showSubscribedOnly","SOGoMailShowSubscribedFoldersOnly","MessageController","sgSettings","Calendar","Component","deleteMessage","$parentControllers","ctrls","opener","mailboxCtrl","$messageController","messageCtrl","toggleDetailedRecipients","$showDetailedRecipients","filterMailtoLinks","href","target","tagName","attributes","exec","decodeURIComponent","state","parentCtrls","closePopup","showMailEditor","reply","replyAll","forward","edit","openPopup","url","baseURL","wId","popupWindow","open","editableContent","toggleRawSource","showRawSource","$rawSource","print","convertToEvent","convertToComponent","convertToTask","componentData","pid","$defaultCalendar","summary","comment","capitalize","stateComponent","tags","showFlags","$watchCollection","newTags","oldTags","wasflagged","_newTags","_oldTags","isObject","difference","MessageEditorController","$stateParams","$mdConstant","FileUploader","AddressBook","Card","originMessage","draftMailboxCtrl","draftMessageCtrl","originMailboxCtrl","addAttachments","fileItem","attrs","mimetype","FileItem","uploader","progress","isUploaded","isSuccess","inlineUrl","queue","removeAttachment","item","isUploading","cancelItem","file","autosave","send","sendState","errorMessage","statusText","contactFilter","$filterAll","cards","explodedCards","manyCards","card","uniqBy","$$fullname","$$email","addRecipient","contact","recipients","recipient","list","$isList","expandable","refs","ref","$shortFormat","container","c_name","listId","autosaveDrafts","SOGoMailAutoSave","autocomplete","hideCc","hideBcc","recipientSeparatorKeys","KEY_CODE","ENTER","TAB","COMMA","SEMICOLON","autoUpload","alias","removeAfterUpload","onSuccessItem","lastAttachmentAttrs","onCancelItem","removeFromQueue","onErrorItem","destroy","actionName","msgObject","localeCode","LocaleCode","SendMessageToastController","closeToast","sgImip","link","scope","iElement","ctrl","pathToAttachment","sgImipPath","restrict","sgImipController","delegateInvitation","delegatedTo","iCalendarAction","receiveUpdates","c_email","viewer","directive","sgZoomableImage","toggleClass","parentNode"],"mappings":"CAEA,WACE,YAOE,SAASA,GAAQC,GAEqB,kBAA3BA,GAAkBC,OAC3BC,QAAQC,OAAOC,KAAMJ,GACrBK,EAAEC,QAAQF,KAAKG,WAAY,SAASC,GAC9BA,EAASC,SACX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3Bd,EAASjO,GAAG,QAAS+O,GAdvB,OACEV,SAAU,IACVN,KAAMA,GAgBVhrB,QACG4B,OAAO,iBACPkqB,UAAU,kBAAmBC","file":"Mailer.services.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Account\n * @constructor\n * @param {object} futureAccountData\n */\n function Account(futureAccountData) {\n // Data is immediately available\n if (typeof futureAccountData.then !== 'function') {\n angular.extend(this, futureAccountData);\n _.forEach(this.identities, function(identity) {\n if (identity.fullName)\n identity.full = identity.fullName + ' <' + identity.email + '>';\n else\n identity.full = '<' + identity.email + '>';\n });\n Account.$log.debug('Account: ' + JSON.stringify(futureAccountData, undefined, 2));\n }\n else {\n // The promise will be unwrapped first\n //this.$unwrap(futureAccountData);\n }\n }\n\n /**\n * @memberof Account\n * @desc The factory we'll use to register with Angular\n * @returns the Account constructor\n */\n Account.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Mailbox', 'Message', function($q, $timeout, $log, Settings, Resource, Preferences, Mailbox, Message) {\n angular.extend(Account, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Preferences: Preferences,\n $Mailbox: Mailbox,\n $Message: Message\n });\n\n return Account; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Account in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .factory('Account', Account.$factory);\n\n /**\n * @memberof Account\n * @desc Set the list of accounts and instanciate a new Account object for each item.\n * @param {array} [data] - the metadata of the accounts\n * @returns the list of accounts\n */\n Account.$findAll = function(data) {\n if (!data) {\n return Account.$$resource.fetch('', 'mailAccounts').then(function(o) {\n return Account.$unwrapCollection(o);\n });\n }\n return Account.$unwrapCollection(data);\n };\n\n /**\n * @memberof Account\n * @desc Unwrap to a collection of Account instances.\n * @param {object} data - the accounts information\n * @returns a collection of Account objects\n */\n Account.$unwrapCollection = function(data) {\n var collection = [];\n\n angular.forEach(data, function(o, i) {\n o.id = i;\n collection[i] = new Account(o);\n });\n Account.$accounts = collection;\n\n return collection;\n };\n\n /**\n * @function getLength\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of mailboxes in the account\n */\n Account.prototype.getLength = function() {\n return this.$flattenMailboxes().length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the mailbox at the specified index\n */\n Account.prototype.getItemAtIndex = function(index) {\n var expandedMailboxes;\n\n expandedMailboxes = this.$flattenMailboxes();\n if (index >= 0 && index < expandedMailboxes.length)\n return expandedMailboxes[index];\n\n return null;\n };\n\n /**\n * @function $getMailboxes\n * @memberof Account.prototype\n * @desc Fetch the list of mailboxes for the current account.\n * @param {object} [options] - force a reload by setting 'reload' to true\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxes = function(options) {\n var _this = this;\n\n if (this.$mailboxes && !(options && options.reload)) {\n return Account.$q.when(this.$mailboxes);\n }\n else {\n return Account.$Mailbox.$find(this).then(function(data) {\n _this.$mailboxes = data;\n _this.$expanded = false;\n\n // Set expanded folders from user's settings\n Account.$Preferences.ready().then(function() {\n var expandedFolders,\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n o.$expanded = (expandedFolders.indexOf('/' + o.id) >= 0);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n if (Account.$Preferences.settings.Mail.ExpandedFolders) {\n if (angular.isString(Account.$Preferences.settings.Mail.ExpandedFolders))\n // Backward compatibility support\n expandedFolders = angular.fromJson(Account.$Preferences.settings.Mail.ExpandedFolders);\n else\n expandedFolders = Account.$Preferences.settings.Mail.ExpandedFolders;\n _this.$expanded = (expandedFolders.indexOf('/' + _this.id) >= 0);\n if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\n if (Account.$accounts)\n _this.$expanded |= (Account.$accounts.length == 1); // Always expand single account\n _this.$flattenMailboxes({reload: true});\n });\n\n return _this.$mailboxes;\n });\n }\n };\n\n /**\n * @function $flattenMailboxes\n * @memberof Account.prototype\n * @desc Get a flatten array of the mailboxes.\n * @param {object} [options] - the following boolean attributes are available:\n * - reload: rebuild the flatten array of mailboxes from the original tree representation (this.$mailboxes)\n * - all: return all mailboxes, ignoring their expanstion state\n * - saveState: save expansion state of mailboxes to the server\n * @returns an array of Mailbox instances\n */\n Account.prototype.$flattenMailboxes = function(options) {\n var _this = this,\n allMailboxes = [],\n expandedMailboxes = [],\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n allMailboxes.push(o);\n if ((options && options.all || o.$expanded) && o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n if (this.$$flattenMailboxes && !(options && (options.reload || options.all))) {\n allMailboxes = this.$$flattenMailboxes;\n }\n else {\n _visit(this.$mailboxes);\n if (!options || !options.all) {\n _this.$$flattenMailboxes = allMailboxes;\n if (options && options.saveState) {\n // Save expansion state of mailboxes to the server\n _.forEach(Account.$accounts, function(account) {\n if (account.$expanded) {\n expandedMailboxes.push('/' + account.id);\n }\n _.reduce(account.$$flattenMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\n });\n Account.$$resource.post(null, 'saveFoldersState', expandedMailboxes);\n }\n }\n }\n\n return allMailboxes;\n };\n\n Account.prototype.$getMailboxByType = function(type) {\n var mailbox,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.type == type;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $getMailboxByPath\n * @memberof Account.prototype\n * @desc Recursively find a mailbox using its path\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxByPath = function(path) {\n var mailbox = null,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.path == path;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $newMailbox\n * @memberof Account.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMailbox = function(path, name) {\n var _this = this;\n\n return Account.$$resource.post(path.toString(), 'createFolder', {name: name}).then(function() {\n _this.$getMailboxes({reload: true});\n });\n };\n\n /**\n * @function updateQuota\n * @memberof Account.prototype\n * @param {Object} data - the inbox quota information returned by the server\n * @desc Update the quota definition associated to the account\n */\n Account.prototype.updateQuota = function(data) {\n var percent, format, description;\n\n percent = (Math.round(data.usedSpace * 10000 / data.maxQuota) / 100);\n format = l(\"quotasFormat\");\n description = format.formatted(percent, Math.round(data.maxQuota/10.24)/100);\n\n this.$quota = { percent: percent, description: description };\n };\n\n /**\n * @function $newMessage\n * @memberof Account.prototype\n * @desc Prepare a new Message object associated to the appropriate mailbox.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMessage = function() {\n var _this = this;\n\n // Query account for draft folder and draft UID\n return Account.$$resource.fetch(this.id.toString(), 'compose').then(function(data) {\n Account.$log.debug('New message (compose): ' + JSON.stringify(data, undefined, 2));\n var message = new Account.$Message(data.accountId, _this.$getMailboxByPath(data.mailboxPath), data);\n return message;\n }).then(function(message) {\n // Fetch draft initial data\n return Account.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Account.$log.debug('New message (edit): ' + JSON.stringify(data, undefined, 2));\n angular.extend(message.editable, data);\n message.isNew = true;\n return message;\n });\n });\n };\n\n /**\n * @function $addDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @see {@link User.$filter}\n */\n Account.prototype.$addDelegate = function(user) {\n var _this = this,\n deferred = Account.$q.defer(),\n param = {uid: user.uid};\n if (!user.uid || _.indexOf(_.map(this.delegates, 'uid'), user.uid) > -1) {\n // No UID specified or user already in delegates\n deferred.resolve();\n }\n else {\n Account.$$resource.fetch(this.id.toString(), 'addDelegate', param).then(function() {\n _this.delegates.push(user);\n deferred.resolve(_this.users);\n }, function(data, status) {\n deferred.reject(l('An error occured please try again.'));\n });\n }\n return deferred.promise;\n };\n\n /**\n * @function $removeDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @return a promise of the server call to remove the user from the account's delegates\n */\n Account.prototype.$removeDelegate = function(uid) {\n var _this = this,\n param = {uid: uid};\n return Account.$$resource.fetch(this.id.toString(), 'removeDelegate', param).then(function() {\n var i = _.indexOf(_.map(_this.delegates, 'uid'), uid);\n if (i >= 0) {\n _this.delegates.splice(i, 1);\n }\n });\n };\n \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Mailbox\n * @constructor\n * @param {object} futureMailboxData - either an object literal or a promise\n */\n function Mailbox(account, futureMailboxData) {\n this.$account = account;\n // Data is immediately available\n if (typeof futureMailboxData.then !== 'function') {\n this.init(futureMailboxData);\n if (this.name && !this.path) {\n // Create a new mailbox on the server\n var newMailboxData = Mailbox.$$resource.create('createFolder', this.name);\n this.$unwrap(newMailboxData);\n }\n }\n else {\n // The promise will be unwrapped first\n // NOTE: this condition never happen for the moment\n this.$unwrap(futureMailboxData);\n }\n }\n\n /**\n * @memberof Mailbox\n * @desc The factory we'll use to register with Angular\n * @returns the Mailbox constructor\n */\n Mailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Acl', 'Preferences', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Message, Acl, Preferences, PRELOAD) {\n angular.extend(Mailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: { sort: 'date', asc: 0 },\n selectedFolder: null,\n $refreshTimeout: null,\n $virtualMode: false,\n PRELOAD: PRELOAD\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Mail.SortingState) {\n Mailbox.$query.sort = Preferences.settings.Mail.SortingState[0];\n Mailbox.$query.asc = parseInt(Preferences.settings.Mail.SortingState[1]);\n }\n });\n\n return Mailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Mailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('Mailbox', Mailbox.$factory);\n\n /**\n * @memberof Mailbox\n * @desc Fetch list of mailboxes of a specific account\n * @param {string} accountId - the account\n * @return a promise of the HTTP operation\n * @see {@link Account.$getMailboxes}\n */\n Mailbox.$find = function(account) {\n var path, futureMailboxData;\n\n if (account.fetchAll)\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'viewAll');\n else\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'view');\n\n return Mailbox.$unwrapCollection(account, futureMailboxData); // a collection of mailboxes\n };\n\n /**\n * @memberof Mailbox\n * @desc Unwrap to a collection of Mailbox instances.\n * @param {string} account - the account\n * @param {promise} futureMailboxData - a promise of the mailboxes metadata\n * @returns a promise of a collection of Mailbox objects\n */\n Mailbox.$unwrapCollection = function(account, futureMailboxData) {\n var collection = [],\n // Local recursive function\n createMailboxes = function(level, mailbox) {\n for (var i = 0; i < mailbox.children.length; i++) {\n mailbox.children[i].level = level;\n mailbox.children[i] = new Mailbox(account, mailbox.children[i]);\n createMailboxes(level+1, mailbox.children[i]);\n }\n };\n //collection.$futureMailboxData = futureMailboxData;\n\n return futureMailboxData.then(function(data) {\n return Mailbox.$timeout(function() {\n // Each entry is spun up as a Mailbox instance\n angular.forEach(data.mailboxes, function(data, index) {\n data.level = 0;\n var mailbox = new Mailbox(account, data);\n createMailboxes(1, mailbox); // recursively create all sub-mailboxes\n collection.push(mailbox);\n });\n // Update inbox quota\n if (data.quotas)\n account.updateQuota(data.quotas);\n return collection;\n });\n });\n };\n\n /**\n * @memberof Mailbox\n * @desc Build the path of the mailbox (or account only).\n * @param {string} accountId - the account ID\n * @param {string} [mailboxPath] - the mailbox path\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.$absolutePath = function(accountId, mailboxPath) {\n var path = [];\n\n if (mailboxPath) {\n path = _.map(mailboxPath.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n }\n\n path.splice(0, 0, accountId); // insert account ID\n\n return path.join('/');\n };\n\n /**\n * @function init\n * @memberof Mailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n Mailbox.prototype.init = function(data) {\n var _this = this;\n this.$isLoading = true;\n this.$messages = [];\n this.uidsMap = {};\n angular.extend(this, data);\n if (this.path) {\n this.id = this.$id();\n this.$acl = new Mailbox.$$Acl('Mail/' + this.id);\n }\n if (this.type) {\n this.$isEditable = this.isEditable();\n }\n this.$isNoInferiors = this.isNoInferiors();\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function selectFolder\n * @memberof Mailbox.prototype\n * @desc Mark the folder as selected in the constructor unless virtual mode is active\n */\n Mailbox.prototype.selectFolder = function() {\n if (!Mailbox.$virtualMode)\n Mailbox.selectedFolder = this;\n };\n\n /**\n * @function getLength\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of messages in the mailbox\n */\n Mailbox.prototype.getLength = function() {\n return this.$messages.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message at the specified index\n */\n Mailbox.prototype.getItemAtIndex = function(index) {\n var message;\n\n if (index >= 0 && index < this.$messages.length) {\n message = this.$messages[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadMessage(message.uid))\n return message;\n }\n return null;\n };\n\n /**\n * @function $id\n * @memberof Mailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.prototype.$id = function() {\n return Mailbox.$absolutePath(this.$account.id, this.path);\n };\n\n /**\n * @function $selectedMessages\n * @memberof Mailbox.prototype\n * @desc Return the messages selected by the user.\n * @returns Message instances\n */\n Mailbox.prototype.$selectedMessages = function() {\n return _.filter(this.$messages, function(message) { return message.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof Mailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n Mailbox.prototype.$selectedCount = function() {\n return this.$selectedMessages().length;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is displayed in the detailed view.\n * @param {string} messageId\n * @returns true if the specified message is displayed\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\n };\n\n /**\n * @function $selectedMessage\n * @memberof Mailbox.prototype\n * @desc Return the currently visible message.\n * @returns a Message instance or undefined if no message is displayed\n */\n Mailbox.prototype.$selectedMessage = function() {\n var _this = this;\n\n return _.find(this.$messages, function(message) { return message.uid == _this.selectedMessage; });\n };\n\n /**\n * @function $selectedMessageIndex\n * @memberof Mailbox.prototype\n * @desc Return the index of the currently visible message.\n * @returns a number or undefined if no message is selected\n */\n Mailbox.prototype.$selectedMessageIndex = function() {\n return this.uidsMap[this.selectedMessage];\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if a message is selected.\n * @returns true if the a message is selected\n */\n Mailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(this.selectedMessage);\n };\n\n /**\n * @function $filter\n * @memberof Mailbox.prototype\n * @desc Fetch the messages metadata of the mailbox\n * @param {object} [sort] - sort preferences. Defaults to descendent by date.\n * @param {string} sort.match - either AND or OR\n * @param {string} sort.sort - either arrival, subject, from, to, date, or size\n * @param {boolean} sort.asc - sort is ascendant if true\n * @param {object[]} [filters] - list of filters for the query\n * @param {string} filters.searchBy - either subject, from, to, cc, or body\n * @param {string} filters.searchInput - the search string to match\n * @param {boolean} filters.negative - negate the condition\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$filter = function(sortingAttributes, filters) {\n var _this = this, options = {};\n\n if (!angular.isDefined(this.unseenCount))\n this.unseenCount = 0;\n\n Mailbox.$timeout(function() {\n _this.$isLoading = true;\n });\n\n return Mailbox.$Preferences.ready().then(function() {\n\n if (Mailbox.$refreshTimeout)\n Mailbox.$timeout.cancel(Mailbox.$refreshTimeout);\n\n if (sortingAttributes)\n // Sorting preferences are common to all mailboxes\n angular.extend(Mailbox.$query, sortingAttributes);\n\n angular.extend(options, { sortingAttributes: Mailbox.$query });\n if (angular.isDefined(filters)) {\n options.filters = _.reject(filters, function(filter) {\n return !filter.searchInput || filter.searchInput.length === 0;\n });\n // Decompose filters that match two fields\n _.forEach(options.filters, function(filter) {\n var secondFilter,\n match = filter.searchBy.match(/(\\w+)_or_(\\w+)/);\n if (match) {\n options.sortingAttributes.match = 'OR';\n filter.searchBy = match[1];\n secondFilter = angular.copy(filter);\n secondFilter.searchBy = match[2];\n options.filters.push(secondFilter);\n }\n });\n }\n\n // Restart the refresh timer, if needed\n if (!Mailbox.$virtualMode) {\n var refreshViewCheck = Mailbox.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Mailbox.prototype.$filter, null, filters);\n Mailbox.$refreshTimeout = Mailbox.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n }\n\n var futureMailboxData = Mailbox.$$resource.post(_this.id, 'view', options);\n return _this.$unwrap(futureMailboxData);\n });\n };\n\n /**\n * @function $loadMessage\n * @memberof Mailbox.prototype\n * @desc Check if the message is loaded and in any case, fetch more messages headers from the server.\n * @returns true if the message metadata are already fetched\n */\n Mailbox.prototype.$loadMessage = function(messageId) {\n var startIndex = this.uidsMap[messageId],\n endIndex,\n index,\n max = this.$messages.length,\n loaded = false,\n uids,\n futureHeadersData;\n if (angular.isDefined(this.uidsMap[messageId]) && startIndex < this.$messages.length) {\n // Index is valid\n if (angular.isDefined(this.$messages[startIndex].subject)) {// || this.$messages[startIndex].loading) {\n // Message headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.LOOKAHEAD, max - 1);\n if (angular.isDefined(this.$messages[endIndex].subject) ||\n angular.isDefined(this.$messages[endIndex].loading)) {\n index = Math.max(startIndex - Mailbox.PRELOAD.LOOKAHEAD, 0);\n if (!angular.isDefined(this.$messages[index].subject) &&\n !angular.isDefined(this.$messages[index].loading)) {\n // Previous messages not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - Mailbox.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next messages not load; preload more headers further down\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.SIZE, max - 1);\n\n if (!angular.isDefined(this.$messages[startIndex].subject) &&\n !angular.isDefined(this.$messages[startIndex].loading) ||\n !angular.isDefined(this.$messages[endIndex].subject) &&\n !angular.isDefined(this.$messages[endIndex].loading)) {\n\n for (uids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (angular.isDefined(this.$messages[startIndex].subject) || this.$messages[startIndex].loading) {\n // Message at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Message at this index will be loaded\n uids.push(this.$messages[startIndex].uid);\n this.$messages[startIndex].loading = true;\n }\n }\n\n Mailbox.$log.debug('Loading UIDs ' + uids.join(' '));\n futureHeadersData = Mailbox.$$resource.post(this.id, 'headers', {uids: uids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n return loaded;\n };\n\n /**\n * @function isEditable\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox is editable based on its type.\n * @returns true if the mailbox is not a special folder.\n */\n Mailbox.prototype.isEditable = function() {\n return this.type == 'folder';\n };\n\n /**\n * @function isNoInferiors\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can contain submailboxes\n * @returns true if the mailbox can not contain submailboxes\n */\n Mailbox.prototype.isNoInferiors = function() {\n return this.flags.indexOf('noinferiors') >= 0;\n };\n\n /**\n * @function isNoSelect\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can be selected\n * @returns true if the mailbox can not be selected\n */\n Mailbox.prototype.isNoSelect = function() {\n return this.flags.indexOf('noselect') >= 0;\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$rename = function() {\n var _this = this,\n findParent,\n parent,\n children,\n i;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Mailbox.$q.when();\n }\n\n // Local recursive function\n findParent = function(parent, children) {\n var parentMailbox = null,\n mailbox = _.find(children, function(o) {\n return o.path == _this.path;\n });\n if (mailbox) {\n parentMailbox = parent;\n }\n else {\n angular.forEach(children, function(o) {\n if (!parentMailbox && o.children && o.children.length > 0) {\n parentMailbox = findParent(o, o.children);\n }\n });\n }\n return parentMailbox;\n };\n\n // Find mailbox parent\n parent = findParent(null, this.$account.$mailboxes);\n if (parent === null)\n children = this.$account.$mailboxes;\n else\n children = parent.children;\n\n // Find index of mailbox among siblings\n i = _.indexOf(_.map(children, 'id'), this.id);\n\n return this.$save().then(function(data) {\n var sibling;\n angular.extend(_this, data); // update the path attribute\n _this.id = _this.$id();\n\n // Move mailbox among its siblings according to its new name\n children.splice(i, 1);\n sibling = _.find(children, function(o) {\n Mailbox.$log.debug(o.name + ' ? ' + _this.name);\n return (o.type == 'folder' && o.name.localeCompare(_this.name) > 0);\n });\n if (sibling) {\n i = _.indexOf(_.map(children, 'id'), sibling.id);\n }\n else {\n i = children.length;\n }\n children.splice(i, 0, _this);\n });\n };\n\n /**\n * @function $compact\n * @memberof Mailbox.prototype\n * @desc Compact the mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$compact = function() {\n var _this = this;\n return Mailbox.$$resource.post(this.id, 'expunge')\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $setFolderAs\n * @memberof Mailbox.prototype\n * @desc Set a folder as Drafts/Sent/Trash\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$setFolderAs = function(type) {\n return Mailbox.$$resource.post(this.id, 'setAs' + type + 'Folder');\n };\n\n /**\n * @function $emptyTrash\n * @memberof Mailbox.prototype\n * @desc Empty the Trash folder.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$emptyTrash = function() {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'emptyTrash').then(function(data) {\n // Remove all messages from the mailbox\n _this.$messages = [];\n _this.uidsMap = {};\n _this.unseenCount = 0;\n\n // If we had any submailboxes, lets do a refresh of the mailboxes list\n if (angular.isDefined(_this.children) && _this.children.length)\n _this.$account.$getMailboxes({reload: true});\n\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $markAsRead\n * @memberof Mailbox.prototype\n * @desc Mark all messages from folder as read\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$markAsRead = function() {\n return Mailbox.$$resource.post(this.id, 'markRead');\n };\n\n /**\n * @function $flagMessages\n * @memberof Mailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$flagMessages = function(messages, flags, operation) {\n var data = {msgUIDs: _.map(messages, 'uid'),\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data).then(function() {\n return messages;\n });\n };\n\n /**\n * @function saveSelectedMessages\n * @memberof Mailbox.prototype\n * @desc Download the selected messages\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.saveSelectedMessages = function() {\n var selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function exportFolder\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.exportFolder = function() {\n return Mailbox.$$resource.download(this.id, 'exportFolder');\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function() {\n var _this = this;\n\n return Mailbox.$$resource.remove(this.id)\n .then(function() {\n _this.$account.$getMailboxes({reload: true});\n return true;\n });\n };\n\n /**\n * @function $_deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from Mailbox object.\n * @param {string[]} uids - the messages uids\n * @param {object[]} messages - the Message instances\n * @return the index of the first deleted message\n */\n Mailbox.prototype.$_deleteMessages = function(uids, messages) {\n var _this = this, selectedUIDs, _$messages, unseen, firstIndex = this.$messages.length;\n\n // Decrement the unseen count\n unseen = _.filter(messages, function(message, i) { return !message.isread; });\n this.unseenCount -= unseen.length;\n\n // Remove messages from $messages and uidsMap\n _.forEachRight(this.$messages, function(message, index) {\n var selectedIndex = _.findIndex(uids, function(uid) {\n return message.uid == uid;\n });\n if (selectedIndex > -1) {\n uids.splice(selectedIndex, 1);\n delete _this.uidsMap[message.uid];\n if (message.uid == _this.selectedMessage)\n delete _this.selectedMessage;\n _this.$messages.splice(index, 1);\n if (index < firstIndex)\n firstIndex = index;\n }\n else {\n _this.uidsMap[message.uid] -= uids.length;\n }\n });\n\n // Return the index of the first deleted message\n return firstIndex;\n };\n\n /**\n * @function $deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'batchDelete', {uids: uids})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof Mailbox.prototype\n * @desc Mark messages as junk/not junk\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messages) {\n var _this = this,\n uids = _.map(messages, 'uid'),\n method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n\n return Mailbox.$$resource.post(this.id, method, {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof Mailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$copyMessages = function(messages, folder) {\n var _this = this,\n uids = _.map(messages, 'uid');\n\n return Mailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $moveMessages\n * @memberof Mailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$moveMessages = function(messages, folder) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteMessages(uids, messages);\n });\n };\n \n /**\n * @function $reset\n * @memberof Mailbox.prototype\n * @desc Reset the original state the mailbox's data.\n */\n Mailbox.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this.$shadowData, function(value, key) {\n delete _this[key];\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Mailbox.prototype\n * @desc Save the mailbox to the server. This currently can only affect the name of the mailbox.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$save = function() {\n var _this = this;\n\n return Mailbox.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n Mailbox.$log.debug(JSON.stringify(data, undefined, 2));\n return data;\n }, function(response) {\n Mailbox.$log.error(JSON.stringify(response.data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return response.data;\n });\n };\n\n /**\n * @function $newMailbox\n * @memberof Mailbox.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Mailbox.prototype.$newMailbox = function(path, name) {\n return this.$account.$newMailbox(path, name);\n };\n\n /**\n * @function $omit\n * @memberof Mailbox.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Mailbox instance\n */\n Mailbox.prototype.$omit = function() {\n var mailbox = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'children' &&\n key != 'headers' &&\n key != 'uids' &&\n key != 'uidsMap' &&\n key[0] != '$') {\n mailbox[key] = value;\n }\n });\n return mailbox;\n };\n\n /**\n * @function $unwrap\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and instanciate new Message objects using received data.\n * @param {promise} futureMailboxData - a promise of the Mailbox's metadata\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$unwrap = function(futureMailboxData) {\n var _this = this,\n deferred = Mailbox.$q.defer();\n\n this.$futureMailboxData = futureMailboxData;\n this.$futureMailboxData.then(function(data) {\n Mailbox.$timeout(function() {\n var uids, headers;\n\n if (!data.uids || _this.$topIndex > data.uids.length - 1)\n _this.$topIndex = 0;\n\n _this.init(data);\n\n if (_this.uids) {\n Mailbox.$log.debug('unwrapping ' + data.uids.length + ' messages');\n\n // First entry of 'headers' are keys\n headers = _.invokeMap(_this.headers[0], 'toLowerCase');\n _this.headers.splice(0, 1);\n\n // First entry of 'uids' are keys when threaded view is enabled\n if (_this.threaded) {\n uids = _this.uids[0];\n _this.uids.splice(0, 1);\n }\n\n // Instanciate Message objects\n _.reduce(_this.uids, function(msgs, msg, i) {\n var data;\n if (_this.threaded)\n data = _.zipObject(uids, msg);\n else\n data = {uid: msg.toString()};\n\n // Build map of UID <=> index\n _this.uidsMap[data.uid] = i;\n\n msgs.push(new Mailbox.$Message(_this.$account.id, _this, data, true));\n\n return msgs;\n }, _this.$messages);\n\n // Extend Message objects with received headers\n _.forEach(_this.headers, function(data) {\n var msg = _.zipObject(headers, data),\n i = _this.uidsMap[msg.uid.toString()];\n _.extend(_this.$messages[i], msg);\n });\n }\n Mailbox.$log.debug('mailbox ' + _this.id + ' ready');\n _this.$isLoading = false;\n deferred.resolve(_this.$messages);\n });\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n deferred.reject();\n });\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and extend matching Message objects using received data.\n * @param {promise} futureHeadersData - a promise of some messages metadata\n */\n Mailbox.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n Mailbox.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(messageHeaders) {\n messageHeaders = _.zipObject(headers, messageHeaders);\n j = _this.uidsMap[messageHeaders.uid.toString()];\n if (angular.isDefined(j)) {\n _.extend(_this.$messages[j], messageHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $toggleSubscribe\n * @memberof Mailbox.prototype\n * @desc Subscribe or unsubscribe to a mailbox\n */\n Mailbox.prototype.$toggleSubscribe = function() {\n if (this.subscribed)\n return Mailbox.$$resource.post(this.id, 'subscribe');\n\n return Mailbox.$$resource.post(this.id, 'unsubscribe');\n };\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Message\n * @constructor\n * @param {string} accountId - the account ID\n * @param {string} mailboxPath - an array of the mailbox path components\n * @param {object} futureAddressBookData - either an object literal or a promise\n * @param {bool} lazy - do \"lazy loading\" so we are very quick at initializing message instances\n */\n function Message(accountId, mailbox, futureMessageData, lazy) {\n this.accountId = accountId;\n this.$mailbox = mailbox;\n this.$hasUnsafeContent = false;\n this.$loadUnsafeContent = false;\n this.editable = {to: [], cc: [], bcc: []};\n this.selected = false;\n\n // Data is immediately available\n if (typeof futureMessageData.then !== 'function') {\n //console.debug(JSON.stringify(futureMessageData, undefined, 2));\n if (angular.isUndefined(lazy) || !lazy) {\n angular.extend(this, futureMessageData);\n this.$formatFullAddresses();\n }\n this.uid = parseInt(futureMessageData.uid);\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureMessageData);\n }\n }\n\n /**\n * @memberof Message\n * @desc The factory we'll use to register with Angular\n * @returns the Message constructor\n */\n Message.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgMessage_STATUS', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Message_STATUS, Resource, Preferences) {\n angular.extend(Message, {\n STATUS: Message_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $avatar: angular.bind(Preferences, Preferences.avatar)\n });\n // Initialize tags form user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailLabelsColors) {\n Message.$tags = Preferences.defaults.SOGoMailLabelsColors;\n }\n if (Preferences.defaults.SOGoMailDisplayRemoteInlineImages &&\n Preferences.defaults.SOGoMailDisplayRemoteInlineImages == 'always') {\n Message.$displayRemoteInlineImages = true;\n }\n });\n\n return Message; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Message in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMessage_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Message', Message.$factory);\n\n /**\n * @function filterTags\n * @memberof Message.prototype\n * @desc Search for tags (ie., mail labels) matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Message.filterTags = function(query, excludedTags) {\n var re = new RegExp(query, 'i'),\n results = [];\n\n _.forEach(_.keys(Message.$tags), function(tag) {\n var pair = Message.$tags[tag];\n if (pair[0].search(re) != -1) {\n if (!_.includes(excludedTags, tag))\n results.push({ name: tag, description: pair[0], color: pair[1] });\n }\n });\n\n return results;\n };\n\n /**\n * @function $absolutePath\n * @memberof Message.prototype\n * @desc Build the path of the message\n * @returns a string representing the path relative to the mail module\n */\n Message.prototype.$absolutePath = function(options) {\n var _this = this, id = this.id;\n\n function buildPath() {\n var path;\n path = _.map(_this.$mailbox.path.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n path.splice(0, 0, _this.accountId); // insert account ID\n return path.join('/');\n }\n\n if (angular.isUndefined(this.id) || options && options.nocache) {\n this.id = buildPath() + '/' + this.uid; // add message UID\n id = this.id;\n }\n if (options && options.asDraft && this.draftId) {\n id = buildPath() + '/' + this.draftId; // add draft ID\n }\n\n return id;\n };\n\n /**\n * @function $setUID\n * @memberof Message.prototype\n * @desc Change the UID of the message. This happens when saving a draft.\n * @param {number} uid - the new message UID\n */\n Message.prototype.$setUID = function(uid) {\n var oldUID = (this.uid || -1), _this = this, index;\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n this.$absolutePath({nocache: true});\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n index = this.$mailbox.uidsMap[oldUID];\n this.$mailbox.uidsMap[uid] = index;\n delete this.$mailbox.uidsMap[oldUID];\n\n // Update messages list of mailbox\n _.forEach(['from', 'to', 'subject'], function(attr) {\n _this.$mailbox.$messages[index][attr] = _this[attr];\n });\n }\n }\n else {\n // Refresh selected folder if it's the drafts mailbox\n if (this.$mailbox.constructor.selectedFolder &&\n this.$mailbox.constructor.selectedFolder.type == 'draft') {\n this.$mailbox.constructor.selectedFolder.$filter();\n }\n }\n }\n };\n\n /**\n * @function $formatFullAddresses\n * @memberof Message.prototype\n * @desc Format all sender and recipients addresses with a complete description (name ).\n * This function also generates the avatar URL for each email address and a short name\n */\n Message.prototype.$formatFullAddresses = function() {\n var _this = this;\n var identities = _.map(_this.$mailbox.$account.identities, 'email');\n\n // Build long representation of email addresses\n _.forEach(['from', 'to', 'cc', 'bcc', 'reply-to'], function(type) {\n _.forEach(_this[type], function(data) {\n if (data.name && data.name != data.email) {\n data.full = data.name + ' <' + data.email + '>';\n\n if (data.name.length < 10)\n // Name is already short\n data.shortname = data.name;\n else if (data.name.split(' ').length)\n // If we have \"Alice Foo\" or \"Foo, Alice\" as name, we grab \"Alice\"\n data.shortname = _.first(_.last(data.name.split(/, */)).split(/ +/)).replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n data.image = Message.$avatar(data.email, 32);\n\n // If the current user is the recepient, overwrite\n // the short name with 'me'\n if (_.indexOf(identities, data.email) >= 0)\n data.shortname = l('me');\n });\n });\n };\n\n /**\n * @function $shortRecipients\n * @memberof Message.prototype\n * @desc Format all recipients into a very compact string\n * @returns a compacted string of all recipients\n */\n Message.prototype.$shortRecipients = function(max) {\n var _this = this, result = [], count = 0, total = 0;\n\n // Build short representation of email addresses\n _.forEach(['to', 'cc', 'bcc'], function(type) {\n total += _this[type]? _this[type].length : 0;\n _.forEach(_this[type], function(data, i) {\n if (count < max)\n result.push(data.shortname);\n count++;\n });\n });\n\n if (total > max)\n result.push(l('and %{0} more...', (total - max)));\n\n return result.join(', ');\n };\n\n /**\n * @function $shortAddress\n * @memberof Message.prototype\n * @desc Format the first address of a specific type with a short description.\n * @returns a string of the name or the email of the envelope address type\n */\n Message.prototype.$shortAddress = function(type) {\n var address = '';\n if (this[type] && this[type].length > 0) {\n address = this[type][0].name || this[type][0].email || '';\n }\n\n return address;\n };\n\n /**\n * @function allowReplyAll\n * @memberof Message.prototype\n * @desc Check if 'Reply to All' is an appropriate action on the message.\n * @returns true if the message is not a draft and has more than one recipient\n */\n Message.prototype.allowReplyAll = function() {\n var recipientsCount = 0;\n recipientsCount = _.reduce(['to', 'cc'], _.bind(function(count, type) {\n if (this[type])\n return count + this[type].length;\n else\n return count;\n }, this), recipientsCount);\n\n return !this.isDraft && recipientsCount > 1;\n };\n\n /**\n * @function loadUnsafeContent\n * @memberof Message.prototype\n * @desc Mark the message to load unsafe resources when calling $content().\n */\n Message.prototype.loadUnsafeContent = function() {\n this.$loadUnsafeContent = true;\n };\n\n /**\n * @function $content\n * @memberof Message.prototype\n * @desc Get the message body as accepted by SCE (Angular Strict Contextual Escaping).\n * @returns the HTML representation of the body\n */\n Message.prototype.$content = function() {\n var _this = this,\n parts = [],\n _visit = function(part) {\n part.msgclass = 'msg-attachment-other';\n if (part.type == 'UIxMailPartAlternativeViewer') {\n _visit(_.find(part.content, function(alternatePart) {\n return part.preferredPart == alternatePart.contentType;\n }));\n }\n // Can be used for UIxMailPartMixedViewer, UIxMailPartMessageViewer, and UIxMailPartSignedViewer\n else if (angular.isArray(part.content)) {\n if (part.type == 'UIxMailPartSignedViewer' && part['supports-smime'] === 1) {\n // First line in a h1, others each in a p\n var formattedMessage = \"

\" + part.error.replace(/\\n/, \"

\");\n formattedMessage = formattedMessage.replace(/\\n/g, \"

\") + \"

\";\n _this.$smime = {\n validSignature: part.valid,\n message: formattedMessage\n };\n }\n _.forEach(part.content, function(mixedPart) {\n _visit(mixedPart);\n });\n }\n else {\n if (angular.isUndefined(part.safeContent)) {\n // Keep a copy of the original content\n part.safeContent = part.content;\n _this.$hasUnsafeContent |= (part.safeContent.indexOf(' unsafe-') > -1);\n }\n if (part.type == 'UIxMailPartHTMLViewer') {\n part.html = true;\n if (_this.$loadUnsafeContent || Message.$displayRemoteInlineImages) {\n if (angular.isUndefined(part.unsafeContent)) {\n part.unsafeContent = document.createElement('div');\n part.unsafeContent.innerHTML = part.safeContent;\n angular.forEach(['src', 'data', 'classid', 'background', 'style'], function(suffix) {\n var elements = part.unsafeContent.querySelectorAll('[unsafe-' + suffix + ']'),\n element,\n value,\n i;\n for (i = 0; i < elements.length; i++) {\n element = angular.element(elements[i]);\n value = element.attr('unsafe-' + suffix);\n element.attr(suffix, value);\n element.removeAttr('unsafe-' + suffix);\n }\n });\n _this.$hasUnsafeContent = false;\n }\n part.content = part.unsafeContent.innerHTML;\n }\n else {\n part.content = part.safeContent;\n }\n parts.push(part);\n }\n else if (part.type == 'UIxMailPartICalViewer' ||\n part.type == 'UIxMailPartImageViewer' ||\n part.type == 'UIxMailPartLinkViewer') {\n\n if (part.type == 'UIxMailPartImageViewer')\n part.msgclass = 'msg-attachment-image';\n else if (part.type == 'UIxMailPartLinkViewer')\n part.msgclass = 'msg-attachment-link';\n\n // Trusted content that can be compiled (Angularly-speaking)\n part.compile = true;\n parts.push(part);\n }\n else {\n part.html = true;\n part.content = part.safeContent;\n parts.push(part);\n }\n }\n };\n\n if (this.parts)\n _visit(this.parts);\n\n return parts;\n };\n\n /**\n * @function $editableContent\n * @memberof Message.prototype\n * @desc First, fetch the draft ID that corresponds to the temporary draft object on the SOGo server.\n * Secondly, fetch the editable message body along with other metadata such as the recipients.\n * @returns the HTML representation of the body\n */\n Message.prototype.$editableContent = function() {\n var _this = this;\n\n return Message.$$resource.fetch(this.$absolutePath(), 'edit').then(function(data) {\n angular.extend(_this, data);\n return Message.$$resource.fetch(_this.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n // Try to match a known account identity from the specified \"from\" address\n var identity = _.find(_this.$mailbox.$account.identities, function(identity) {\n return data.from.toLowerCase().indexOf(identity.email) !== -1;\n });\n if (identity)\n data.from = identity.full;\n Message.$log.debug('editable = ' + JSON.stringify(data, undefined, 2));\n angular.extend(_this.editable, data);\n return data.text;\n });\n });\n };\n\n /**\n * @function $plainContent\n * @memberof Message.prototype\n * @returns the a plain text representation of the subject and body\n */\n Message.prototype.$plainContent = function() {\n return Message.$$resource.fetch(this.$absolutePath(), 'viewplain');\n };\n\n /**\n * @function addTag\n * @memberof Message.prototype\n * @desc Add a mail tag on the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.addTag = function(tag) {\n return this.$addOrRemoveTag('add', tag);\n };\n\n /**\n * @function removeTag\n * @memberof Message.prototype\n * @desc Remove a mail tag from the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.removeTag = function(tag) {\n return this.$addOrRemoveTag('remove', tag);\n };\n\n /**\n * @function $addOrRemoveTag\n * @memberof Message.prototype\n * @desc Add or remove a mail tag on the current message.\n * @param {string} operation - the operation name to perform\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$addOrRemoveTag = function(operation, tag) {\n var data = {\n operation: operation,\n msgUIDs: [this.uid],\n flags: tag\n };\n\n if (tag)\n return Message.$$resource.post(this.$mailbox.$id(), 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $imipAction\n * @memberof Message.prototype\n * @desc Perform IMIP actions on the current message.\n * @param {string} path - the path of the IMIP calendar part \n * @param {string} action - the the IMIP action to perform\n * @param {object} data - the delegation info \n */\n Message.prototype.$imipAction = function(path, action, data) {\n var _this = this;\n Message.$$resource.post([this.$absolutePath(), path].join('/'), action, data).then(function(data) {\n Message.$timeout(function() {\n _this.$reload();\n });\n });\n };\n\n /**\n * @function $sendMDN\n * @memberof Message.prototype\n * @desc Send MDN response for current email message\n */\n Message.prototype.$sendMDN = function() {\n this.shouldAskReceipt = 0;\n return Message.$$resource.post(this.$absolutePath(), 'sendMDN');\n };\n\n /**\n * @function $deleteAttachment\n * @memberof Message.prototype\n * @desc Delete an attachment from a message being composed\n * @param {string} filename - the filename of the attachment to delete\n */\n Message.prototype.$deleteAttachment = function(filename) {\n var action = 'deleteAttachment?filename=' + filename;\n var _this = this;\n Message.$$resource.post(this.$absolutePath({asDraft: true}), action).then(function(data) {\n Message.$timeout(function() {\n _this.editable.attachmentAttrs = _.filter(_this.editable.attachmentAttrs, function(attachment) {\n return attachment.filename != filename;\n });\n });\n });\n };\n\n /**\n * @function $markAsFlaggedOrUnflagged\n * @memberof Message.prototype\n * @desc Add or remove a the \\\\Flagged flag on the current message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.toggleFlag = function() {\n var _this = this,\n action = 'markMessageFlagged';\n\n if (this.isflagged)\n action = 'markMessageUnflagged';\n\n return Message.$$resource.post(this.$absolutePath(), action).then(function(data) {\n Message.$timeout(function() {\n _this.isflagged = !_this.isflagged;\n });\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Message.prototype\n * @returns true if the Message content is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Message.prototype.$isLoading = function() {\n return this.$loaded == Message.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @param {object} [options] - set {useCache: true} to use already fetched data\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var _this = this, futureMessageData;\n\n if (options && options.useCache && this.$futureMessageData) {\n if (!this.isread) {\n Message.$$resource.fetch(this.$absolutePath(), 'markMessageRead').then(function() {\n Message.$timeout(function() {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n });\n });\n }\n return this;\n }\n\n futureMessageData = Message.$$resource.fetch(this.$absolutePath(options), 'view');\n\n return this.$unwrap(futureMessageData);\n };\n\n /**\n * @function $reply\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$reply = function() {\n return this.$newDraft('reply');\n };\n\n /**\n * @function $replyAll\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender and all recipients.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$replyAll = function() {\n return this.$newDraft('replyall');\n };\n\n /**\n * @function $forward\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a forward.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$forward = function() {\n return this.$newDraft('forward');\n };\n\n /**\n * @function $newDraft\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply or a forward of the current message and associated\n * to the draft mailbox.\n * @see {@link Account.$newMessage}\n * @see {@link Message.$editableContent}\n * @see {@link Message.$reply}\n * @see {@link Message.$replyAll}\n * @see {@link Message.$forwad}\n * @param {string} action - the HTTP action to perform on the message\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$newDraft = function(action) {\n var _this = this;\n\n // Query server for draft folder and draft UID\n return Message.$$resource.fetch(this.$absolutePath(), action).then(function(data) {\n var mailbox, message;\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2));\n mailbox = _this.$mailbox.$account.$getMailboxByPath(data.mailboxPath);\n message = new Message(data.accountId, mailbox, data);\n // Fetch draft initial data\n return Message.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2) + ' original UID: ' + _this.uid);\n angular.extend(message.editable, data);\n\n // We keep a reference to our original message in order to update the flags\n message.origin = {message: _this, action: action};\n return message;\n });\n });\n };\n\n /**\n * @function $save\n * @memberof Message.prototype\n * @desc Save the message to the server.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$save = function() {\n var _this = this,\n data = this.editable;\n\n Message.$log.debug('save = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.save(this.$absolutePath({asDraft: true}), data).then(function(response) {\n Message.$log.debug('save = ' + JSON.stringify(response, undefined, 2));\n _this.$setUID(response.uid);\n _this.$reload(); // fetch a new viewable version of the message\n _this.isNew = false;\n });\n };\n\n /**\n * @function $send\n * @memberof Message.prototype\n * @desc Send the message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$send = function() {\n var _this = this,\n data = angular.copy(this.editable);\n\n Message.$log.debug('send = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.post(this.$absolutePath({asDraft: true}), 'send', data).then(function(response) {\n if (response.status == 'success') {\n if (angular.isDefined(_this.origin)) {\n if (_this.origin.action.startsWith('reply'))\n _this.origin.message.isanswered = true;\n else if (_this.origin.action == 'forward')\n _this.origin.message.isforwarded = true;\n }\n return response;\n }\n else {\n return Message.$q.reject(response.data);\n }\n });\n };\n\n /**\n * @function $unwrap\n * @memberof Message.prototype\n * @desc Unwrap a promise. \n * @param {promise} futureMessageData - a promise of some of the Message's data\n */\n Message.prototype.$unwrap = function(futureMessageData) {\n var _this = this;\n\n // Message is not loaded yet\n this.$loaded = Message.STATUS.DELAYED_LOADING;\n Message.$timeout(function() {\n if (_this.$loaded != Message.STATUS.LOADED)\n _this.$loaded = Message.STATUS.LOADING;\n }, Message.STATUS.DELAYED_MS);\n\n // Resolve and expose the promise\n this.$futureMessageData = futureMessageData.then(function(data) {\n // Calling $timeout will force Angular to refresh the view\n if (_this.isread === 0) {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n }\n return Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\n _this.$loaded = Message.STATUS.LOADED;\n return _this;\n });\n });\n\n return this.$futureMessageData;\n };\n\n /**\n * @function $omit\n * @memberof Message.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Message instance\n */\n Message.prototype.$omit = function(options) {\n var message = {},\n privateAttributes = options && options.privateAttributes;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$' || privateAttributes) {\n message[key] = value;\n }\n });\n\n return message;\n };\n\n /**\n * @function saveMessage\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.saveMessage = function() {\n var selectedUIDs;\n\n selectedUIDs = [ this.uid ];\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name VirtualMailbox\n * @constructor\n * @param {object} account - the mail account associated with the virtual search\n */\n function VirtualMailbox(account) {\n this.$account = account;\n }\n\n /**\n * @memberof VirtualMailbox\n * @desc The factory we'll use to register with Angular\n * @returns the VirtualMailbox constructor\n */\n VirtualMailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n selectedFolder: null,\n PRELOAD: PRELOAD\n });\n\n return VirtualMailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of VirtualMailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('VirtualMailbox', VirtualMailbox.$factory);\n\n /**\n * @memberof VirtualMailbox\n * @desc Build the path of the virtual mailbox (or account only).\n * @param {string} accountId - the account ID\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.$absolutePath = function(accountId) {\n return [accountId, \"virtual\"].join('/');\n };\n\n /**\n * @function init\n * @memberof VirtualMailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n VirtualMailbox.prototype.init = function(data) {\n this.$isLoading = false;\n this.$mailboxes = [];\n this.uidsMap = {};\n angular.extend(this, data);\n this.id = this.$id();\n };\n\n VirtualMailbox.prototype.setMailboxes = function(data) {\n this.$mailboxes = data;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n mailbox.$messages = [];\n mailbox.uidsMap = {};\n });\n };\n\n VirtualMailbox.prototype.startSearch = function(match, params) {\n var _this = this,\n search = VirtualMailbox.$q.when();\n\n this.$isLoading = true;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n search = search.then(function() {\n if (_this.$isLoading) {\n VirtualMailbox.$log.debug(\"searching mailbox \" + mailbox.path);\n return mailbox.$filter( {sort: \"date\", asc: false, match: match}, params);\n }\n });\n });\n\n search.finally(function() {\n _this.$isLoading = false;\n });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\n };\n\n /**\n * @function selectFolder\n * @memberof VirtualMailbox.prototype\n * @desc A no-op for virtual mailbox\n */\n VirtualMailbox.prototype.selectFolder = function() {\n return;\n };\n\n /**\n * @function resetSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Delete 'selectedMessage' attribute of all submailboxes.\n */\n VirtualMailbox.prototype.resetSelectedMessage = function() {\n _.forEach(this.$mailboxes, function(mailbox) {\n delete mailbox.selectedMessage;\n });\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if a message is selected among the resulting mailboxes\n * @returns true if one message is selected\n */\n VirtualMailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return angular.isDefined(mailbox.selectedMessage);\n }));\n };\n\n /**\n * @function isSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if the message of the specified mailbox is selected.\n * @param {string} messageId\n * @param {string} mailboxPath\n * @returns true if the specified message is selected\n */\n VirtualMailbox.prototype.isSelectedMessage = function(messageId, mailboxPath) {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return mailbox.path == mailboxPath && mailbox.selectedMessage == messageId;\n }));\n };\n\n /**\n * @function getLength\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of items in the mailbox\n */\n VirtualMailbox.prototype.getLength = function() {\n var len = 0;\n\n if (!angular.isDefined(this.$mailboxes))\n return len;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n len += mailbox.$messages.length;\n });\n\n return len;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message as the specified index\n */\n VirtualMailbox.prototype.getItemAtIndex = function(index) {\n var i, j, k, mailbox, message;\n\n if (angular.isDefined(this.$mailboxes) && index >= 0) {\n i = 0;\n for (j = 0; j < this.$mailboxes.length; j++) {\n mailbox = this.$mailboxes[j];\n for (k = 0; k < mailbox.$messages.length; i++, k++) {\n message = mailbox.$messages[k];\n if (i == index) {\n if (mailbox.$loadMessage(message.uid))\n return message;\n }\n }\n }\n }\n\n return null;\n };\n\n /**\n * @function $id\n * @memberof VirtualMailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.prototype.$id = function() {\n return VirtualMailbox.$absolutePath(this.$account.id);\n };\n\n /**\n * @function $selectedMessages\n * @memberof VirtualMailbox.prototype\n * @desc Return an associative array of the selected messages for each mailbox. Keys are the mailboxes ids.\n * @returns an associative array\n */\n VirtualMailbox.prototype.$selectedMessages = function() {\n var messagesMap = {};\n return _.transform(this.$mailboxes, function(messagesMap, mailbox) {\n messagesMap[mailbox.id] = mailbox.$selectedMessages();\n }, {});\n };\n\n /**\n * @function $selectedCount\n * @memberof VirtualMailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n VirtualMailbox.prototype.$selectedCount = function() {\n return _.sum(_.invokeMap(this.$mailboxes, '$selectedCount'));\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @param {object} messagesMap\n * @param {array} flags\n * @param {string} operation\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(messagesMap, flags, operation) {\n var data = {\n flags: flags,\n operation: operation\n };\n var allMessages = [];\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var uids = _.map(messages, 'uid');\n allMessages.push(messages);\n var promise = VirtualMailbox.$$resource.post(id, 'addOrRemoveLabel', _.assign(data, {msgUIDs: uids}));\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises).then(function() {\n return _.flatten(allMessages);\n });\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$deleteMessages(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof VirtualMailbox.prototype\n * @desc Mark messages as junk/not junk\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$markOrUnMarkMessagesAsJunk(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$copyMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$moveMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxController.$inject = ['$window', '$scope', '$timeout', '$q', '$state', '$mdDialog', '$mdToast', 'stateAccounts', 'stateAccount', 'stateMailbox', 'sgHotkeys', 'encodeUriFilter', 'sgFocus', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $scope, $timeout, $q, $state, $mdDialog, $mdToast, stateAccounts, stateAccount, stateMailbox, sgHotkeys, encodeUriFilter, focus, Dialog, Account, Mailbox) {\n var vm = this, messageDialog = null,\n defaultWindowTitle = angular.element($window.document).find('title').attr('sg-default') || \"SOGo\",\n hotkeys = [];\n\n // Expose controller for eventual popup windows\n $window.$mailboxController = vm;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n vm.confirmDeleteSelectedMessages = confirmDeleteSelectedMessages;\n vm.markOrUnMarkMessagesAsJunk = markOrUnMarkMessagesAsJunk;\n vm.copySelectedMessages = copySelectedMessages;\n vm.moveSelectedMessages = moveSelectedMessages;\n vm.markSelectedMessagesAsFlagged = markSelectedMessagesAsFlagged;\n vm.markSelectedMessagesAsUnread = markSelectedMessagesAsUnread;\n vm.selectAll = selectAll;\n vm.unselectMessages = unselectMessages;\n\n\n stateMailbox.selectFolder();\n\n _registerHotkeys(hotkeys);\n\n // Expunge mailbox when leaving the Mail module\n angular.element($window).on('beforeunload', _compactBeforeUnload);\n $scope.$on('$destroy', function() {\n angular.element($window).off('beforeunload', _compactBeforeUnload);\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n // Update window's title with unseen messages count of selected mailbox\n $scope.$watch(function() { return vm.selectedFolder.unseenCount; }, function(unseenCount) {\n var title = defaultWindowTitle + ' - ';\n if (unseenCount)\n title += '(' + unseenCount + ') ';\n title += vm.selectedFolder.name;\n $window.document.title = title;\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_compose'),\n description: l('Write a new message'),\n callback: newMessage\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: confirmDeleteSelectedMessages\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function _compactBeforeUnload(event) {\n return vm.selectedFolder.$compact();\n }\n\n function sort(field) {\n vm.selectedFolder.$filter({ sort: field });\n }\n\n function sortedBy(field) {\n return Mailbox.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter().then(function() {\n if (vm.selectedFolder.selectedMessage) {\n $timeout(function() {\n vm.selectedFolder.$topIndex = vm.selectedFolder.uidsMap[vm.selectedFolder.selectedMessage];\n });\n }\n });\n }\n\n function newMessage($event) {\n var message;\n\n if (messageDialog === null) {\n message = vm.account.$newMessage();\n messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message,\n stateRecipients: []\n }\n })\n .finally(function() {\n messageDialog = null;\n });\n }\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index))\n index--;\n else\n // No message is selected, show oldest message\n index = vm.selectedFolder.getLength() - 1;\n\n if (index > -1)\n selectMessage(vm.selectedFolder.$messages[index]);\n\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index))\n index++;\n else\n // No message is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.getLength())\n selectMessage(vm.selectedFolder.$messages[index]);\n else\n index = -1;\n\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.getLength())\n vm.selectedFolder.$topIndex++;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _nextMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function _addPreviousMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _previousMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {mailboxId: encodeUriFilter(message.$mailbox.path), messageId: message.uid});\n else\n $state.go('mail.account.mailbox.message', {messageId: message.uid});\n }\n\n function toggleMessageSelection($event, message) {\n if (!message) message = vm.selectedFolder.$selectedMessage();\n message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n /**\n * Batch operations\n */\n\n function _currentMailboxes() {\n if (Mailbox.$virtualMode)\n return vm.selectedFolder.$mailboxes;\n else\n return [vm.selectedFolder];\n }\n\n function _unselectMessage(message, index) {\n // Unselect current message and cleverly load the next message.\n // This function must not be called in virtual mode.\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = vm.selectedFolder.$messages[nextIndex];\n }\n if (index < vm.selectedFolder.$messages.length)\n previousMessage = vm.selectedFolder.$messages[index];\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n if (nextMessage) {\n vm.selectedFolder.$topIndex = nextIndex;\n $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n else {\n $timeout(function() {\n console.warn('go to mailbox');\n $state.go('mail.account.mailbox');\n });\n }\n }\n\n function confirmDeleteSelectedMessages($event) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n\n if (messageDialog === null && _.size(selectedMessages) > 0)\n messageDialog = Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n });\n })\n .finally(function() {\n messageDialog = null;\n });\n\n $event.preventDefault();\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var dstFolder = '/' + vm.account.id + '/folderINBOX';\n if (vm.selectedFolder.type != 'junk') {\n dstFolder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n vm.selectedFolder.$moveMessages(selectedMessages, dstFolder).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n });\n }\n\n function copySelectedMessages(dstFolder) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$copyMessages(selectedMessages, '/' + dstFolder).then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) copied', vm.selectedFolder.$selectedCount()))\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n function moveSelectedMessages(dstFolder) {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n var count = vm.selectedFolder.$selectedCount();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + dstFolder).then(function(index) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) moved', count))\n .position('top right')\n .hideDelay(2000));\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was moved, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n }\n\n function selectAll() {\n var count = 0;\n _.forEach(_currentMailboxes(), function(folder) {\n var i = 0, length = folder.$messages.length;\n for (; i < length; i++)\n folder.$messages[i].selected = true;\n count += length;\n });\n vm.mode.multiple = count;\n }\n\n function unselectMessages() {\n _.forEach(_currentMailboxes(), function(folder) {\n _.forEach(folder.$messages, function(message) {\n message.selected = false;\n });\n });\n vm.mode.multiple = 0;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, '\\\\Flagged', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'remove').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isread = false;\n message.$mailbox.unseenCount++;\n });\n });\n }\n\n }\n\n angular\n .module('material.components.virtualRepeat')\n .decorator('mdVirtualRepeatContainerDirective', mdVirtualRepeatContainerDirectiveDecorator);\n\n /**\n * @ngInject\n */\n mdVirtualRepeatContainerDirectiveDecorator.$inject = ['$delegate'];\n function mdVirtualRepeatContainerDirectiveDecorator($delegate) {\n $delegate[0].controller.prototype.resetScroll = function() {\n // Don't scroll to top if current virtual repeater is the messages list\n // but do update the container size\n if (this.$element.parent().attr('id') == 'messagesList')\n this.updateSize();\n else\n this.scrollTo(0);\n };\n return $delegate;\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxController', MailboxController);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2; -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$scope', '$state', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgConstant', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'sgHotkeys', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($scope, $state, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, sgConstant, focus, encodeUriFilter, Dialog, Settings, sgHotkeys, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox,\n hotkeys = [];\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.toggleAccountState = toggleAccountState;\n vm.subscribe = subscribe;\n vm.newFolder = newFolder;\n vm.delegate = delegate;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.selectFolder = selectFolder;\n vm.saveFolder = saveFolder;\n vm.compactFolder = compactFolder;\n vm.emptyTrashFolder = emptyTrashFolder;\n vm.confirmDelete = confirmDelete;\n vm.markFolderRead = markFolderRead;\n vm.share = share;\n vm.metadataForFolder = metadataForFolder;\n vm.setFolderAs = setFolderAs;\n vm.refreshUnseenCount = refreshUnseenCount;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedMessages = dragSelectedMessages;\n\n // Advanced search options\n vm.showingAdvancedSearch = false;\n vm.currentSearchParam = '';\n vm.addSearchParam = addSearchParam;\n vm.newSearchParam = newSearchParam;\n vm.showAdvancedSearch = showAdvancedSearch;\n vm.hideAdvancedSearch = hideAdvancedSearch;\n vm.toggleAdvancedSearch = toggleAdvancedSearch;\n vm.search = {\n options: {'': l('Select a criteria'),\n subject: l('Enter Subject'),\n from: l('Enter From'),\n to: l('Enter To'),\n cc: l('Enter Cc'),\n body: l('Enter Body')\n },\n mailbox: 'INBOX',\n subfolders: 1,\n match: 'AND',\n params: []\n };\n\n\n Preferences.ready().then(function() {\n vm.showSubscribedOnly = Preferences.defaults.SOGoMailShowSubscribedFoldersOnly;\n });\n\n vm.refreshUnseenCount();\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: function() {\n if (Mailbox.selectedFolder && !Mailbox.selectedFolder.hasSelectedMessage())\n confirmDelete(Mailbox.selectedFolder);\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n }\n\n function hideAdvancedSearch() {\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n\n account = vm.accounts[0];\n mailbox = vm.searchPreviousMailbox;\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(mailbox.path) });\n }\n\n function toggleAdvancedSearch() {\n if (Mailbox.selectedFolder.$isLoading) {\n // Stop search\n vm.virtualMailbox.stopSearch();\n }\n else {\n // Start search\n var root, mailboxes = [],\n _visit = function(folders) {\n _.forEach(folders, function(o) {\n mailboxes.push(o);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n vm.virtualMailbox = new VirtualMailbox(vm.accounts[0]);\n\n // Don't set the previous selected mailbox if we're in virtual mode\n // That allows users to do multiple advanced search but return\n // correctly to the previously selected mailbox once done.\n if (!Mailbox.$virtualMode)\n vm.searchPreviousMailbox = Mailbox.selectedFolder;\n\n Mailbox.selectedFolder = vm.virtualMailbox;\n Mailbox.$virtualMode = true;\n\n if (angular.isDefined(vm.search.mailbox)) {\n root = vm.accounts[0].$getMailboxByPath(vm.search.mailbox);\n mailboxes.push(root);\n if (vm.search.subfolders && root.children.length)\n _visit(root.children);\n }\n else {\n mailboxes = vm.accounts[0].$flattenMailboxes();\n }\n\n vm.virtualMailbox.setMailboxes(mailboxes);\n vm.virtualMailbox.startSearch(vm.search.match, vm.search.params);\n $state.go('mail.account.virtualMailbox', { accountId: vm.accounts[0].id });\n }\n }\n\n function addSearchParam(v) {\n vm.currentSearchParam = v;\n focus('advancedSearch');\n return false;\n }\n\n function newSearchParam(pattern) {\n if (pattern.length && vm.currentSearchParam.length) {\n var n = 0, searchParam = vm.currentSearchParam;\n if (pattern.startsWith(\"!\")) {\n n = 1;\n pattern = pattern.substring(1).trim();\n }\n vm.currentSearchParam = '';\n return { searchBy: searchParam, searchInput: pattern, negative: n };\n }\n }\n\n function toggleAccountState(account) {\n account.$expanded = !account.$expanded;\n account.$flattenMailboxes({ reload: true, saveState: true });\n // Fire a window resize to recompute the virtual-repeater.\n // This is a fix until the following issue is officially resolved:\n // https://github.com/angular/material/issues/7309\n $timeout(function() {\n angular.element($window).triggerHandler('resize');\n }, 150);\n }\n\n function subscribe(account) {\n $mdDialog.show({\n templateUrl: account.id + '/subscribe',\n controller: SubscriptionsDialogController,\n controllerAs: 'subscriptions',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n metadataForFolder: metadataForFolder,\n srcAccount: account\n }\n }).finally(function() {\n account.$getMailboxes({reload: true});\n });\n\n /**\n * @ngInject\n */\n SubscriptionsDialogController.$inject = ['$scope', '$mdDialog', 'metadataForFolder', 'srcAccount'];\n function SubscriptionsDialogController($scope, $mdDialog, metadataForFolder, srcAccount) {\n var vm = this;\n\n vm.loading = true;\n vm.filter = { name: '' };\n vm.metadataForFolder = metadataForFolder;\n vm.account = new Account({\n id: srcAccount.id,\n name: srcAccount.name\n });\n vm.close = close;\n\n\n vm.account.$getMailboxes().then(function() {\n vm.loading = false;\n });\n\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function newFolder(parentFolder) {\n Dialog.prompt(l('New folder'),\n l('Enter the new name of your folder :'))\n .then(function(name) {\n parentFolder.$newMailbox(parentFolder.id, name)\n .then(function() {\n // success\n }, function(data, status) {\n Dialog.alert(l('An error occured while creating the mailbox \"%{0}\".', name),\n l(data.error));\n });\n });\n }\n\n function delegate(account) {\n $mdDialog.show({\n templateUrl: account.id + '/delegation', // UI/Templates/MailerUI/UIxMailUserDelegation.wox\n controller: MailboxDelegationController,\n controllerAs: 'delegate',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n User: User,\n account: account\n }\n });\n\n /**\n * @ngInject\n */\n MailboxDelegationController.$inject = ['$scope', '$mdDialog', 'User', 'account'];\n function MailboxDelegationController($scope, $mdDialog, User, account) {\n var vm = this;\n\n vm.users = account.delegates;\n vm.account = account;\n vm.userToAdd = '';\n vm.searchText = '';\n vm.userFilter = userFilter;\n vm.closeModal = closeModal;\n vm.removeUser = removeUser;\n vm.addUser = addUser;\n\n function userFilter($query) {\n return User.$filter($query, account.delegates);\n }\n\n function closeModal() {\n $mdDialog.hide();\n }\n\n function removeUser(user) {\n account.$removeDelegate(user.uid).catch(function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured please try again.'));\n });\n }\n\n function addUser(data) {\n if (data) {\n account.$addDelegate(data).then(function() {\n vm.userToAdd = '';\n vm.searchText = '';\n }, function(error) {\n Dialog.alert(l('Warning'), error);\n });\n }\n }\n }\n } // delegate\n\n function editFolder(folder) {\n vm.editMode = folder.path;\n focus('mailboxName_' + folder.path);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function selectFolder($event, account, folder) {\n if (vm.editMode == folder.path)\n return;\n vm.editMode = false;\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(folder.path) });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function saveFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function compactFolder(folder) {\n folder.$compact().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Folder compacted'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function emptyTrashFolder(folder) {\n folder.$emptyTrash().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Trash emptied'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function confirmDelete(folder) {\n Dialog.confirm(l('Confirmation'), l('Do you really want to move this folder into the trash ?'))\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(data, status) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(data.error));\n });\n });\n }\n\n function markFolderRead(folder) {\n folder.$markAsRead();\n }\n\n function share(folder) {\n // Fetch list of ACL users\n folder.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: folder.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: folder.$acl.users,\n User: User,\n folder: folder\n }\n });\n });\n } // share\n\n function metadataForFolder(folder) {\n if (folder.type == 'inbox')\n return {name: folder.name, icon:'inbox', special: true};\n else if (folder.type == 'draft')\n return {name: l('DraftsFolderName'), icon: 'drafts', special: true};\n else if (folder.type == 'sent')\n return {name: l('SentFolderName'), icon: 'send', special: true};\n else if (folder.type == 'trash')\n return {name: l('TrashFolderName'), icon: 'delete', special: true};\n else if (folder.type == 'junk')\n return {name: l('JunkFolderName'), icon: 'thumb_down', special: true};\n else if (folder.type == 'additional')\n return {name: folder.name, icon: 'folder_shared', special: true};\n\n return {name: folder.name, icon: 'folder_open', special: false};\n }\n\n function setFolderAs(folder, type) {\n folder.$setFolderAs(type).then(function() {\n folder.$account.$getMailboxes({reload: true});\n });\n }\n\n function refreshUnseenCount() {\n var unseenCountFolders = $window.unseenCountFolders;\n\n _.forEach(vm.accounts, function(account) {\n\n // Always include the INBOX\n if (!_.includes(unseenCountFolders, account.id + '/folderINBOX'))\n unseenCountFolders.push(account.id + '/folderINBOX');\n\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (angular.isDefined(mailbox.unseenCount) &&\n !_.includes(unseenCountFolders, mailbox.id))\n unseenCountFolders.push(mailbox.id);\n });\n });\n\n Account.$$resource.post('', 'unseenCount', {mailboxes: unseenCountFolders}).then(function(data) {\n _.forEach(vm.accounts, function(account) {\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (data[mailbox.id])\n mailbox.unseenCount = data[mailbox.id];\n });\n });\n });\n\n Preferences.ready().then(function() {\n var refreshViewCheck = Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually')\n $timeout(vm.refreshUnseenCount, refreshViewCheck.timeInterval()*1000);\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && !dstFolder.isNoSelect();\n }\n\n function dragSelectedMessages(srcFolder, dstFolder, mode) {\n var dstId, messages, uids, clearMessageView, promise, success;\n\n dstId = '/' + dstFolder.id;\n messages = srcFolder.$selectedMessages();\n if (messages.length === 0)\n messages = [srcFolder.$selectedMessage()];\n uids = _.map(messages, 'uid');\n clearMessageView = (srcFolder.selectedMessage && uids.indexOf(srcFolder.selectedMessage) >= 0);\n\n if (mode == 'copy') {\n promise = srcFolder.$copyMessages(messages, dstId);\n success = l('%{0} message(s) copied', messages.length);\n }\n else {\n promise = srcFolder.$moveMessages(messages, dstId);\n success = l('%{0} message(s) moved', messages.length);\n }\n\n promise.then(function() {\n if (clearMessageView)\n $state.go('mail.account.mailbox');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxesController', MailboxesController);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageController.$inject = ['$window', '$scope', '$state', '$mdMedia', '$mdDialog', 'sgConstant', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdMedia, $mdDialog, sgConstant, stateAccounts, stateAccount, stateMailbox, stateMessage, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, messageDialog = null, popupWindow = null, hotkeys = [];\n\n // Expose controller\n $window.$messageController = vm;\n\n vm.$state = $state;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.mailbox = stateMailbox;\n vm.message = stateMessage;\n vm.service = Message;\n vm.tags = { searchText: '', selected: '' };\n vm.showFlags = stateMessage.flags && stateMessage.flags.length > 0;\n vm.$showDetailedRecipients = false;\n vm.toggleDetailedRecipients = toggleDetailedRecipients;\n vm.filterMailtoLinks = filterMailtoLinks;\n vm.deleteMessage = deleteMessage;\n vm.close = close;\n vm.reply = reply;\n vm.replyAll = replyAll;\n vm.forward = forward;\n vm.edit = edit;\n vm.openPopup = openPopup;\n vm.closePopup = closePopup;\n vm.newMessage = newMessage;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n vm.print = print;\n vm.convertToEvent = convertToEvent;\n vm.convertToTask = convertToTask;\n\n _registerHotkeys(hotkeys);\n\n // One-way refresh of the parent window when modifying the message from a popup window.\n if ($window.opener) {\n // Update the message flags. The message must be displayed in the parent window.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(newTags, oldTags) {\n var ctrls;\n if (newTags || oldTags) {\n ctrls = $parentControllers();\n if (ctrls.messageCtrl) {\n ctrls.messageCtrl.service.$timeout(function() {\n ctrls.messageCtrl.showFlags = true;\n ctrls.messageCtrl.message.flags = newTags;\n });\n }\n }\n });\n // Update the \"isflagged\" (star icon) of the message. The mailbox must be displayed in the parent window.\n $scope.$watch(function() { return vm.message.isflagged; }, function(isflagged, wasflagged) {\n var ctrls = $parentControllers();\n if (ctrls.mailboxCtrl) {\n ctrls.mailboxCtrl.service.$timeout(function() {\n var message = _.find(ctrls.mailboxCtrl.selectedFolder.$messages, { uid: vm.message.uid });\n message.isflagged = isflagged;\n });\n }\n });\n }\n else {\n // Flatten new tags when coming from the predefined list of tags (Message.$tags) and\n // sync tags with server when adding or removing a tag.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(_newTags, _oldTags) {\n var newTags, oldTags, tags;\n if (_newTags || _oldTags) {\n newTags = _newTags || [];\n oldTags = _oldTags || [];\n _.forEach(newTags, function(tag, i) {\n if (angular.isObject(tag))\n newTags[i] = tag.name;\n });\n if (newTags.length > oldTags.length) {\n tags = _.difference(newTags, oldTags);\n _.forEach(tags, function(tag) {\n vm.message.addTag(tag);\n });\n }\n else if (newTags.length < oldTags.length) {\n tags = _.difference(oldTags, newTags);\n _.forEach(tags, function(tag) {\n vm.message.removeTag(tag);\n });\n }\n }\n });\n }\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_flag'),\n callback: angular.bind(stateMessage, stateMessage.toggleFlag)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n callback: function($event) {\n if (vm.mailbox.$selectedCount() === 0)\n deleteMessage();\n $event.preventDefault();\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n /**\n * If this is a popup window, retrieve the matching controllers (mailbox and message) of the parent window.\n */\n function $parentControllers() {\n var message, mailbox, ctrls = {};\n if ($window.opener) {\n // Deleting the message from a popup window\n if ($window.opener.$mailboxController &&\n $window.opener.$mailboxController.selectedFolder.$id() == stateMailbox.$id()) {\n // The message mailbox is opened in the parent window\n mailbox = $window.opener.$mailboxController;\n ctrls.mailboxCtrl = mailbox;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The message is opened in the parent window\n message = $window.opener.$messageController;\n ctrls.messageCtrl = message;\n }\n }\n }\n return ctrls;\n }\n\n function toggleDetailedRecipients($event) {\n vm.$showDetailedRecipients = !vm.$showDetailedRecipients;\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function filterMailtoLinks($event) {\n var href, match, to, cc, bcc, subject, body, data;\n if ($event.target.tagName == 'A' && 'href' in $event.target.attributes) {\n href = $event.target.attributes.href.value;\n match = /^mailto:([^\\?]+)/.exec(href);\n if (match) {\n // Recipients\n to = _.map(decodeURIComponent(match[1]).split(','), function(email) {\n return '<' + email + '>';\n });\n data = { to: to };\n // Subject & body\n _.forEach(['subject', 'body'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n param = (param == 'body')? 'text' : param;\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n // Recipients\n _.forEach(['cc', 'bcc'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n newMessage($event, data); // will stop event propagation\n }\n }\n }\n\n function deleteMessage() {\n var mailbox, message, state, nextMessage, previousMessage,\n parentCtrls = $parentControllers();\n\n if (parentCtrls.messageCtrl) {\n mailbox = parentCtrls.mailboxCtrl.selectedFolder;\n message = parentCtrls.messageCtrl.message;\n state = parentCtrls.messageCtrl.$state;\n }\n else {\n mailbox = stateMailbox;\n message = stateMessage;\n state = $state;\n }\n\n mailbox.$deleteMessages([message]).then(function(index) {\n var nextIndex = index;\n // Remove message object from scope\n message = null;\n if (angular.isDefined(state)) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = mailbox.$messages[nextIndex];\n }\n if (index < mailbox.$messages.length)\n previousMessage = mailbox.$messages[index];\n\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n\n try {\n if (nextMessage && $mdMedia(sgConstant['gt-md'])) {\n state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n if (nextIndex < mailbox.$topIndex)\n mailbox.$topIndex = nextIndex;\n else if (nextIndex > mailbox.$lastVisibleIndex)\n mailbox.$topIndex = nextIndex - (mailbox.$lastVisibleIndex - mailbox.$topIndex);\n }\n else {\n state.go('mail.account.mailbox').then(function() {\n message = null;\n delete mailbox.selectedMessage;\n });\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (messageDialog === null) {\n messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n messageDialog = null;\n closePopup();\n });\n }\n }\n\n function close() {\n $state.go('mail.account.mailbox').then(function() {\n vm.message = null;\n delete stateMailbox.selectedMessage;\n });\n }\n\n function reply($event) {\n var message = vm.message.$reply();\n showMailEditor($event, message);\n }\n\n function replyAll($event) {\n var message = vm.message.$replyAll();\n showMailEditor($event, message);\n }\n\n function forward($event) {\n var message = vm.message.$forward();\n showMailEditor($event, message);\n }\n\n function edit($event) {\n vm.message.$editableContent().then(function() {\n showMailEditor($event, vm.message);\n });\n }\n\n function openPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#/Mail',\n vm.message.accountId,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.message.$mailbox.path)),\n vm.message.uid]\n .join('/'),\n wId = vm.message.$absolutePath();\n popupWindow = $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n function closePopup() {\n if ($window.opener)\n $window.close();\n }\n\n function newMessage($event, editableContent) {\n vm.account.$newMessage().then(function(message) {\n angular.extend(message.editable, editableContent);\n showMailEditor($event, message);\n });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.message.$rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.message.$rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n\n function print($event) {\n $window.print();\n }\n\n function convertToEvent($event) {\n return convertToComponent($event, 'appointment');\n }\n\n function convertToTask($event) {\n return convertToComponent($event, 'task');\n }\n\n function convertToComponent($event, type) {\n vm.message.$plainContent().then(function(data) {\n var componentData = {\n pid: Calendar.$defaultCalendar(),\n type: type,\n summary: data.subject,\n comment: data.content\n };\n var component = new Component(componentData);\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = [\n sgSettings.activeUser('folderURL'),\n 'Calendar',\n 'UIx' + type.capitalize() + 'EditorTemplate'\n ].join('/');\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n });\n }\n }\n \n angular\n .module('SOGo.MailerUI') \n .controller('MessageController', MessageController); \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageEditorController.$inject = ['$scope', '$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($scope, $window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this;\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.cancel = cancel;\n vm.save = save;\n vm.send = send;\n vm.sendState = false;\n vm.removeAttachment = removeAttachment;\n vm.contactFilter = contactFilter;\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.recipientSeparatorKeys = [\n $mdConstant.KEY_CODE.ENTER,\n $mdConstant.KEY_CODE.TAB,\n $mdConstant.KEY_CODE.COMMA,\n $mdConstant.KEY_CODE.SEMICOLON\n ];\n vm.uploader = new FileUploader({\n url: stateMessage.$absolutePath({asDraft: true}) + '/save',\n autoUpload: true,\n alias: 'attachments',\n removeAfterUpload: false,\n // onProgressItem: function(item, progress) {\n // console.debug(item); console.debug(progress);\n // },\n onSuccessItem: function(item, response, status, headers) {\n stateMessage.$setUID(response.uid);\n stateMessage.$reload({asDraft: false});\n item.inlineUrl = response.lastAttachmentAttrs[0].url;\n //console.debug(item); console.debug('success = ' + JSON.stringify(response, undefined, 2));\n },\n onCancelItem: function(item, response, status, headers) {\n //console.debug(item); console.debug('cancel = ' + JSON.stringify(response, undefined, 2));\n // We remove the attachment\n stateMessage.$deleteAttachment(item.file.name);\n this.removeFromQueue(item);\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Error while uploading the file \\\"%{0}\\\":', item.file.name))\n .position('top right')\n .hideDelay(3000));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\n\n // Destroy file uploader when the controller is being deactivated\n $scope.$on('$destroy', function() { vm.uploader.destroy(); });\n\n if ($stateParams.actionName == 'reply') {\n stateMessage.$reply().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'replyall') {\n stateMessage.$replyAll().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'forward') {\n stateMessage.$forward().then(function(msgObject) {\n vm.message = msgObject;\n addAttachments();\n });\n }\n else if (angular.isDefined(stateMessage)) {\n vm.message = stateMessage;\n addAttachments();\n }\n\n /**\n * If this is a popup window, retrieve the mailbox controller of the parent window.\n */\n function $parentControllers() {\n var originMessage, ctrls = {};\n if ($window.opener) {\n if ($window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The draft is opened in the parent window\n ctrls.draftMessageCtrl = $window.opener.$messageController;\n }\n }\n else if (stateMessage.origin) {\n originMessage = stateMessage.origin.message;\n if ($window.opener.$mailboxController.selectedFolder.$id() == originMessage.$mailbox.$id()) {\n // The message mailbox is opened in the parent window\n ctrls.originMailboxCtrl = $window.opener.$mailboxController;\n }\n }\n }\n }\n return ctrls;\n }\n\n function addAttachments() {\n // Add existing attached files to uploader\n var i, data, fileItem, attrs = vm.message.editable.attachmentAttrs;\n if (attrs)\n for (i = 0; i < attrs.length; i++) {\n data = {\n name: attrs[i].filename,\n type: attrs[i].mimetype,\n size: parseInt(attrs[i].size)\n };\n fileItem = new FileUploader.FileItem(vm.uploader, data);\n fileItem.progress = 100;\n fileItem.isUploaded = true;\n fileItem.isSuccess = true;\n fileItem.inlineUrl = attrs[i].url;\n vm.uploader.queue.push(fileItem);\n }\n }\n\n function removeAttachment(item) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\n }\n\n function cancel() {\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n if (vm.message.isNew && vm.message.attachmentAttrs)\n vm.message.$mailbox.$deleteMessages([vm.message]);\n\n $mdDialog.cancel();\n }\n\n function save() {\n var ctrls = $parentControllers();\n vm.message.$save().then(function(data) {\n vm.message.$rawSource = null;\n if (ctrls.draftMailboxCtrl) {\n // We're saving a draft from a popup window.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Reload selected message\n ctrls.draftMessageCtrl.$state.go('mail.account.mailbox.message', { messageId: vm.message.uid });\n }\n });\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been saved'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function send() {\n var ctrls = $parentControllers();\n\n vm.sendState = 'sending';\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\n vm.sendState = 'sent';\n if (ctrls.draftMailboxCtrl) {\n // We're sending a draft from a popup window and the draft mailbox is opened.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Close draft\n ctrls.draftMessageCtrl.close();\n }\n });\n }\n if (ctrls.originMailboxCtrl) {\n // We're sending a draft from a popup window and the original mailbox is opened.\n // Reload mailbox\n ctrls.originMailboxCtrl.selectedFolder.$filter();\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been sent'))\n .position('top right')\n .hideDelay(3000));\n\n // Let the user see the succesfull message before closing the dialog\n $timeout($mdDialog.hide, 1000);\n }, function(response) {\n vm.sendState = 'error';\n vm.errorMessage = response.data? response.data.message : response.statusText;\n });\n }\n\n function contactFilter($query) {\n return AddressBook.$filterAll($query).then(function(cards) {\n // Divide the matching cards by email addresses so the user can select\n // the recipient address of her choice\n var explodedCards = [];\n _.forEach(_.invokeMap(cards, 'explode'), function(manyCards) {\n _.forEach(manyCards, function(card) {\n explodedCards.push(card);\n });\n });\n // Remove duplicates\n return _.uniqBy(explodedCards, function(card) {\n return card.$$fullname + ' ' + card.$$email;\n });\n });\n }\n\n function addRecipient(contact, field) {\n var recipients, recipient, list;\n\n if (angular.isString(contact))\n return contact;\n\n recipients = vm.message.editable[field];\n\n if (contact.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(contact.refs) && contact.refs.length) {\n _.forEach(contact.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n list = Card.$find(contact.container, contact.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n });\n }\n }\n else {\n recipient = contact.$shortFormat();\n }\n\n if (recipient)\n return recipient;\n else\n return null;\n }\n\n // Drafts autosaving\n function autosaveDrafts() {\n vm.message.$save();\n if (Preferences.defaults.SOGoMailAutoSave)\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n }\n\n // Read user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailAutoSave)\n // Enable auto-save of draft\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n // Set the locale of CKEditor\n vm.localeCode = Preferences.defaults.LocaleCode;\n });\n }\n\n SendMessageToastController.$inject = ['$scope', '$mdToast'];\n function SendMessageToastController($scope, $mdToast) {\n $scope.closeToast = function() {\n $mdToast.hide();\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('SendMessageToastController', SendMessageToastController)\n .controller('MessageEditorController', MessageEditorController);\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /**\n * sgIMIP - A directive to handle IMIP actions on emails\n * @memberof SOGo.MailerUI\n * @example:\n\n */\n function sgImip() {\n return {\n restrict: 'A',\n link: link,\n controller: 'sgImipController'\n };\n\n function link(scope, iElement, attrs, ctrl) {\n ctrl.pathToAttachment = attrs.sgImipPath;\n }\n }\n\n /**\n * @ngInject\n */\n sgImipController.$inject = ['$scope', 'User'];\n function sgImipController($scope, User) {\n var vm = this;\n\n $scope.delegateInvitation = false;\n $scope.delegatedTo = '';\n $scope.searchText = '';\n\n $scope.userFilter = function($query) {\n return User.$filter($query);\n };\n\n $scope.iCalendarAction = function(action) {\n var data;\n\n if (action == 'delegate') {\n data = {\n receiveUpdates: false,\n delegatedTo: $scope.delegatedTo.c_email\n };\n }\n\n $scope.viewer.message.$imipAction(vm.pathToAttachment, action, data);\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('sgImipController', sgImipController)\n .directive('sgImip', sgImip);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgZoomableImage - Toggle the 'sg-zoom' class when clicking on the image inside the container.\n * @memberof SOGo.MailerUI\n * @restrict attribute\n * @ngInject\n * @example:\n\n
\n \n \n \n
\n */\n function sgZoomableImage() {\n return {\n restrict: 'A',\n link: link\n };\n\n function link(scope, iElement, attrs, ctrl) {\n var parentNode = iElement.parent(),\n toggleClass;\n\n toggleClass = function(event) {\n if (event.target.tagName == 'IMG')\n parentNode.toggleClass('sg-zoom');\n };\n\n iElement.on('click', toggleClass);\n }\n }\n\n angular\n .module('SOGo.MailerUI')\n .directive('sgZoomableImage', sgZoomableImage);\n})();\n"]} \ No newline at end of file diff --git a/UI/WebServerResources/js/Scheduler.services.js b/UI/WebServerResources/js/Scheduler.services.js index 25047a16b..d76cdf013 100644 --- a/UI/WebServerResources/js/Scheduler.services.js +++ b/UI/WebServerResources/js/Scheduler.services.js @@ -1,4 +1,4 @@ !function(){"use strict";function a(b){if(this.init(b),this.name&&!this.id){var c=a.$$resource.create("createFolder",this.name);this.$unwrap(c)}}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Preferences","Component","Acl",function(b,c,d,e,f,g,h,i){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Calendar",e.activeUser()),$Preferences:g,$Component:h,$$Acl:i,activeUser:e.activeUser(),$view:null}),a}];try{angular.module("SOGo.SchedulerUI")}catch(a){angular.module("SOGo.SchedulerUI",["SOGo.Common"])}angular.module("SOGo.SchedulerUI").value("CalendarSettings",{EventDragDayLength:96,EventDragHorizontalOffset:3}).factory("Calendar",a.$factory),a.$defaultCalendar=function(){var b,c=a.$Preferences.defaults.SOGoDefaultCalendar;return"first"==c&&(b=_.find(a.$findAll(null,!0),function(a){return a.active}))?b.id:"personal"},a.$add=function(b){var c,d,e;c=b.isWebCalendar?this.$webcalendars:b.isSubscription?this.$subscriptions:this.$calendars,d=_.find(c,function(a){return"personal"==b.id||"personal"!=a.id&&1===a.name.localeCompare(b.name)}),e=d?_.indexOf(_.map(c,"id"),d.id):1,c.splice(e,0,b),this.$Preferences.ready().then(function(){a.$Preferences.settings.Calendar.FoldersOrder&&a.saveFoldersOrder(_.flatMap(a.$findAll(),"id")).then(function(){a.$reloadAll()})})},a.$findAll=function(b,c){var d=this;if(b)this.$calendars=[],this.$subscriptions=[],this.$webcalendars=[],angular.forEach(b,function(b,c){var e=new a(b);e.isWebCalendar?d.$webcalendars.push(e):e.isSubscription?d.$subscriptions.push(e):d.$calendars.push(e)});else if(angular.isUndefined(this.$calendars))return this.$calendars=[],this.$subscriptions=[],this.$webcalendars=[],a.$$resource.fetch("calendarslist").then(function(b){return a.$findAll(b.calendars,c)});return c?_.union(this.$calendars,_.filter(this.$subscriptions,function(a){return a.isOwned||a.acls.objectCreator})):_.union(this.$calendars,this.$subscriptions,this.$webcalendars)},a.$reloadAll=function(){var b=this;a.$$resource.fetch("calendarslist").then(function(a){_.forEach(a.calendars,function(a){var c,d;c=a.isWebCalendar?b.$webcalendars:a.isSubscription?b.$subscriptions:b.$calendars,d=_.find(c,function(b){return b.id==a.id}),d&&d.init(a)})})},a.$get=function(b){var c;return c=_.find(a.$calendars,function(a){return a.id==b}),c||(c=_.find(a.$subscriptions,function(a){return a.id==b})),c||(c=_.find(a.$webcalendars,function(a){return a.id==b})),c},a.$getIndex=function(b){var c;return c=_.indexOf(_.map(a.$calendars,"id"),b),c<0&&(c=_.indexOf(_.map(a.$subscriptions,"id"),b)),c<0&&(c=_.indexOf(_.map(a.$webcalendars,"id"),b)),c},a.$subscribe=function(b,c){var d=this;return a.$$resource.userResource(b).fetch(c,"subscribe").then(function(b){var c=new a(angular.extend({active:1},b));return _.find(d.$subscriptions,function(a){return a.id==b.id})||a.$add(c),c})},a.$addWebCalendar=function(b){var c=this,d=a.$q.defer();return _.find(c.$webcalendars,function(a){return a.urls.webCalendarURL==b})?d.reject():a.$$resource.post(null,"addWebCalendar",{url:b}).then(function(c){angular.extend(c,{isWebCalendar:!0,isEditable:!0,isRemote:!1,owner:a.activeUser.login,urls:{webCalendarURL:b}});var e=new a(c);a.$$resource.fetch(e.id,"reload").then(function(b){a.$log.debug(JSON.stringify(b,void 0,2)),a.$add(e),d.resolve()},function(a){401==a.status?d.resolve(e):d.reject()})},d.reject),d.promise},a.reloadWebCalendars=function(){var b=[];return _.forEach(this.$webcalendars,function(c){var d=a.$$resource.fetch(c.id,"reload");d.then(function(a){c.$error=!1},function(a){c.$error=l(a.statusText)}),b.push(d)}),a.$q.all(b)},a.$deleteComponents=function(b){var c={},d=[];return _.forEach(b,function(a){angular.isDefined(c[a.pid])||(c[a.pid]=[]),c[a.pid].push(a.id)}),_.forEach(c,function(b,c){d.push(a.$$resource.post(c,"batchDelete",{uids:b}))}),a.$q.all(d)},a.saveFoldersOrder=function(b){return this.$$resource.post(null,"saveFoldersOrder",{folders:b}).then(function(){if(a.$Preferences.settings.Calendar.FoldersOrder=b,!b)return a.$$resource.fetch("calendarslist").then(function(b){return a.$findAll(b.calendars)})})},a.prototype.init=function(b){this.color=this.color||"#AAAAAA",this.active=1,angular.extend(this,b),this.id&&(this.$acl=new a.$$Acl("Calendar/"+this.id)),this.isOwned=a.activeUser.isSuperUser||this.owner==a.activeUser.login,this.isSubscription=!this.isRemote&&this.owner!=a.activeUser.login,angular.isUndefined(this.$shadowData)&&(this.$shadowData=this.$omit())},a.prototype.$id=function(){return this.id?a.$q.when(this.id):this.$futureCalendarData.then(function(a){return a.id})},a.prototype.getClassName=function(a){return angular.isUndefined(a)&&(a="fg"),a+"-folder"+this.id},a.prototype.$rename=function(){var b,c,d=this;return this.name==this.$shadowData.name?a.$q.when():(c=this.isWebCalendar?a.$webcalendars:this.isSubscription?a.$subscriptions:a.$calendars,b=_.indexOf(_.map(c,"id"),this.id),b>-1?this.$save().then(function(){c.splice(b,1),a.$add(d)}):a.$q.reject())},a.prototype.$delete=function(){var b,c,d=this;return this.isSubscription?(c=a.$$resource.fetch(this.id,"unsubscribe"),b=a.$subscriptions):(c=a.$$resource.remove(this.id),b=this.isWebCalendar?a.$webcalendars:a.$calendars),c.then(function(){var a=_.indexOf(_.map(b,"id"),d.id);b.splice(a,1)})},a.prototype.$reset=function(){var a=this;angular.forEach(this,function(b,c){"constructor"!=c&&"$"!=c[0]&&delete a[c]}),angular.extend(this,this.$shadowData),this.$shadowData=this.$omit()},a.prototype.$save=function(){var b=this;return a.$$resource.save(this.id,this.$omit()).then(function(a){return b.$shadowData=b.$omit(),a},function(c){return a.$log.error(JSON.stringify(c,void 0,2)),b.$reset(),c})},a.prototype.setCredentials=function(b,c){var d=this,e=a.$q.defer();return a.$$resource.post(this.id,"set-credentials",{username:b,password:c}).then(function(){a.$$resource.fetch(d.id,"reload").then(function(b){a.$add(d),e.resolve()},function(a){401==a.status?e.reject(l("Wrong username or password")):e.reject(a.statusText)})},e.reject),e.promise},a.prototype.export=function(){return a.$$resource.download(this.id+".ics","export",null,{type:"application/octet-stream"})},a.prototype.$setActivation=function(){return a.$$resource.fetch(this.id,(this.active?"":"de")+"activateFolder")},a.prototype.$getComponent=function(b,c){return a.$Component.$find(this.id,b,c)},a.prototype.$unwrap=function(b){var c=this;this.$futureCalendarData=b.then(function(b){return a.$timeout(function(){return c.init(b),c})},function(b){c.isError=!0,angular.isObject(b)&&a.$timeout(function(){angular.extend(c,b)})})},a.prototype.$omit=function(){var a={};return angular.forEach(this,function(b,c){"constructor"!=c&&"$"!=c[0]&&(a[c]=b)}),a}}(),function(){"use strict";function a(b){if("function"!=typeof b.then){if(this.init(b),this.pid&&!this.id){var c=a.$$resource.newguid(this.pid);this.$unwrap(c),this.isNew=!0}}else this.$unwrap(b)}a.$factory=["$q","$timeout","$log","sgSettings","sgComponent_STATUS","Preferences","Card","Gravatar","Resource",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{STATUS:f,$q:b,$timeout:c,$log:d,$Preferences:g,$Card:h,$gravatar:i,$$resource:new j(e.activeUser("folderURL")+"Calendar",e.activeUser()),timeFormat:"%H:%M",$query:{value:"",search:"title_Category_Location"},$queryEvents:{sort:"start",asc:1,filterpopup:"view_next7"},$queryTasks:{sort:"status",asc:1,filterpopup:"view_incomplete"},$refreshTimeout:null,$ghost:{}}),g.ready().then(function(){g.settings.Calendar.EventsFilterState&&(a.$queryEvents.filterpopup=g.settings.Calendar.EventsFilterState),g.settings.Calendar.TasksFilterState&&(a.$queryTasks.filterpopup=g.settings.Calendar.TasksFilterState),g.settings.Calendar.EventsSortingState&&(a.$queryEvents.sort=g.settings.Calendar.EventsSortingState[0],a.$queryEvents.asc=parseInt(g.settings.Calendar.EventsSortingState[1])),g.settings.Calendar.TasksSortingState&&(a.$queryTasks.sort=g.settings.Calendar.TasksSortingState[0],a.$queryTasks.asc=parseInt(g.settings.Calendar.TasksSortingState[1])),a.$queryTasks.show_completed=parseInt(g.settings.ShowCompletedTasks),a.$categories=g.defaults.SOGoCalendarCategoriesColors,g.defaults.SOGoTimeFormat&&(a.timeFormat=g.defaults.SOGoTimeFormat)}),a}];try{angular.module("SOGo.SchedulerUI")}catch(a){angular.module("SOGo.SchedulerUI",["SOGo.Common"])}angular.module("SOGo.SchedulerUI").constant("sgComponent_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Component",a.$factory),a.$selectedCount=function(){var b;return b=0,a.$events&&(b+=_.filter(a.$events,function(a){return a.selected}).length),a.$tasks&&(b+=_.filter(a.$tasks,function(a){return a.selected}).length),b},a.$startRefreshTimeout=function(b){var c=this;a.$refreshTimeout&&a.$timeout.cancel(a.$refreshTimeout),a.$Preferences.ready().then(function(){var d=a.$Preferences.defaults.SOGoRefreshViewCheck;if(d&&"manually"!=d){var e=angular.bind(c,a.$filter,b);a.$refreshTimeout=a.$timeout(e,1e3*d.timeInterval())}})},a.$isLoading=function(){return a.$loaded==a.STATUS.LOADING},a.$filter=function(b,c){var d=this,e=new Date,f=e.getDate(),g=e.getMonth()+1,h=e.getFullYear(),i="$query"+b.capitalize(),j={day:""+h+(g<10?"0":"")+g+(f<10?"0":"")+f};return a.$startRefreshTimeout(b),this.$Preferences.ready().then(function(){var e,f,g=!1;return angular.extend(d.$query,j),c&&_.forEach(_.keys(c),function(b){g|=d.$query[b]&&c[b]!=a.$query[b],"reload"==b&&c[b]?g=!0:angular.isDefined(d.$query[b])?d.$query[b]=c[b]:d[i][b]=c[b]}),e=d.$$resource.fetch(null,b+"list",angular.extend(d[i],d.$query)),f="tasks"==b?"$events":"$tasks",g&&(delete a[f],a.$log.debug("force reload of "+f)),d.$unwrapCollection(b,e)})},a.$find=function(b,c,d){var e,f=[b,c];return d&&f.push(d),e=this.$$resource.fetch(f.join("/"),"view"),new a(e)},a.filterCategories=function(b){var c=new RegExp(b,"i");return _.filter(_.keys(a.$categories),function(a){return a.search(c)!=-1})},a.saveSelectedList=function(a){return this.$$resource.post(null,"saveSelectedList",{list:a+"ListView"})},a.$eventsBlocksForView=function(b,c){var d=this;return a.$Preferences.ready().then(function(e){var f,g,h,i;return f=a.$Preferences.defaults.SOGoFirstDayOfWeek,"day"==b?(g="dayView",h=i=c):"multicolumnday"==b?(g="multicolumndayView",h=i=c):"week"==b?(g="weekView",h=c.beginOfWeek(f),i=new Date,i.setTime(h.getTime()),i.addDays(6)):"month"==b&&(g="monthView",h=c,h.setDate(1),h=h.beginOfWeek(f),i=new Date,i.setTime(c.getTime()),i.setMonth(i.getMonth()+1),i.addDays(-1),i=i.endOfWeek(f)),d.$eventsBlocks(g,h,i)})},a.$eventsBlocks=function(b,c,d){var e,f,g,h,i=[],j=[],k=a.$q.defer();return e={view:b.toLowerCase(),sd:c.getDayString(),ed:d.getDayString()},f=this.$$resource.fetch(null,"eventsblocks",e),f.then(function(b){var c,d;c=function(b,c,d){var e,f=_.zipObject(this.eventsFields,c),g=new Date(1e3*f.c_startdate);return f.hour=g.getHourString(),f.blocks=[],e=new a(f),e.categories=_.filter(e.categories,function(b){return a.$Preferences.defaults.SOGoCalendarCategoriesColors[b]}),b.push(e),b},d=function(a){this[a.nbr].blocks.push(a),a.component=this[a.nbr],a.isFirst=1==this[a.nbr].blocks.length},a.$views=[],a.$timeout(function(){_.forEach(b,function(b,e){var f,k=[],l={},m={};for(b.eventsFields.splice(_.indexOf(b.eventsFields,"c_folder"),1,"pid"),b.eventsFields.splice(_.indexOf(b.eventsFields,"c_name"),1,"id"),b.eventsFields.splice(_.indexOf(b.eventsFields,"c_recurrence_id"),1,"occurrenceId"),b.eventsFields.splice(_.indexOf(b.eventsFields,"c_title"),1,"summary"),_.reduce(b.events,_.bind(c,b),k),_.forEach(_.flatten(b.blocks),_.bind(d,k)),_.forEach(_.flatten(b.allDayBlocks),_.bind(d,k)),0===i.length&&(i=_.flatMap(b.days,"date"),j=_.flatMap(b.days,"number")),g=0;g1||this.repeat.days&&this.repeat.days.length>0||this.repeat.monthdays&&this.repeat.monthdays.length>0||this.repeat.months&&this.repeat.months.length>0);return a},a.prototype.isEditable=function(){return!this.occurrenceId&&!this.isReadOnly},a.prototype.isEditableOccurrence=function(){return this.occurrenceId&&!this.isReadOnly},a.prototype.isInvitation=function(){return!this.occurrenceId&&this.userHasRSVP},a.prototype.isInvitationOccurrence=function(){return this.occurrenceId&&this.userHasRSVP},a.prototype.isReadOnly=function(){return this.isReadOnly&&!this.userHasRSVP},a.prototype.enablePercentComplete=function(){return"task"==this.type&&"not-specified"!=this.status&&"cancelled"!=this.status},a.prototype.coversFreeBusy=function(a,b,c){var d=angular.isDefined(this.freebusy[a])&&angular.isDefined(this.freebusy[a][b])&&1==this.freebusy[a][b][c];return d},a.prototype.updateFreeBusyCoverage=function(){var a=this,b={};if(this.start&&this.end){var c=new Date(this.start.getTime()),d=new Date(this.end.getTime()),e=parseInt(c.getMinutes()/15+.5),f=parseInt(d.getMinutes()/15+.5);return c.setMinutes(15*e),d.setMinutes(15*f),_.forEach(c.daysUpTo(d),function(c,d){var f,g=c.getDate(),h=c.getDayString();if(h==a.start.getDayString())for(f=c.getHours().toString(),b[h]={},b[h][f]=[];e>0;)b[h][f].push(0),e--;else c=c.beginOfDay(),b[h]={};for(;c.getTime()0},a.prototype.addAttachUrl=function(a){if(angular.isUndefined(this.attachUrls))this.attachUrls=[{value:a}];else{for(var b=0;b-1&&this.attachUrls.length>a&&this.attachUrls.splice(a,1)},a.prototype.$addDueDate=function(){this.due=new Date,this.due.setMinutes(15*Math.round(this.due.getMinutes()/15)),this.dueDate=this.due.toISOString()},a.prototype.$deleteDueDate=function(){delete this.due,delete this.dueDate},a.prototype.$addStartDate=function(){this.start=new Date,this.start.setMinutes(15*Math.round(this.start.getMinutes()/15))},a.prototype.$deleteStartDate=function(){delete this.start,delete this.startDate},a.prototype.$reset=function(){var a=this;angular.forEach(this,function(b,c){"constructor"!=c&&"$"!=c[0]&&delete a[c]}),this.init(this.$shadowData),this.$shadowData=this.$omit()},a.prototype.$reply=function(){var b,c=this,d=[this.pid,this.id];return this.occurrenceId&&d.push(this.occurrenceId),b={reply:this.reply,delegatedTo:this.delegatedTo,alarm:this.$hasAlarm?this.alarm:{}},a.$$resource.save(d.join("/"),b,{action:"rsvpAppointment"}).then(function(a){return c.$shadowData=c.$omit(),a})},a.prototype.$adjust=function(b){var c=[this.pid,this.id];return _.every(_.values(b),function(a){return 0===a})?a.$q.when():(this.occurrenceId&&c.push(this.occurrenceId),a.$log.debug("adjust "+c.join("/")+" "+JSON.stringify(b)),a.$$resource.save(c.join("/"),b,{action:"adjust"}))},a.prototype.$save=function(b){var c,d,e,f,g=this;return e=this.$omit(),f=a.$Preferences.$mdDateLocaleProvider,e.startDate=e.start?e.start.format(f,"%Y-%m-%d"):"",e.startTime=e.start?e.start.format(f,"%H:%M"):"",e.endDate=e.end?e.end.format(f,"%Y-%m-%d"):"",e.endTime=e.end?e.end.format(f,"%H:%M"):"",e.dueDate=e.due?e.due.format(f,"%Y-%m-%d"):"",e.dueTime=e.due?e.due.format(f,"%H:%M"):"",e.completedDate=e.completed?e.completed.format(f,"%Y-%m-%d"):"",this.$hasCustomRepeat?"monthly"==this.repeat.frequency&&this.repeat.month.type&&"byday"==this.repeat.month.type||"yearly"==this.repeat.frequency&&this.repeat.year.byday?(delete e.repeat.monthdays,e.repeat.days=[{day:this.repeat.month.day,occurrence:this.repeat.month.occurrence.toString()}]):"monthly"!=this.repeat.frequency&&"yearly"!=this.repeat.frequency||!this.repeat.month.type||delete e.repeat.days:this.repeat.frequency&&"never"!=this.repeat.frequency&&(e.repeat={frequency:this.repeat.frequency}),this.repeat.frequency?"until"==this.repeat.end&&this.repeat.until?e.repeat.until=this.repeat.until.stringWithSeparator("-"):"count"==this.repeat.end&&this.repeat.count?e.repeat.count=this.repeat.count:(delete e.repeat.until,delete e.repeat.count):delete e.repeat,"not-specified"==this.status?delete e.status:"completed"!=this.status&&delete e.completedDate,this.$hasAlarm?!this.alarm.action||"email"!=this.alarm.action||this.attendees&&this.attendees.length>0||(e.alarm.attendees=0,e.alarm.organizer=1):e.alarm={},d=[this.pid,this.id],this.isNew&&(c={action:"saveAs"+this.type.capitalize()}),this.occurrenceId&&d.push(this.occurrenceId),angular.extend(e,b),a.$$resource.save(d.join("/"),e,c).then(function(a){return g.$shadowData=g.$omit(),a})},a.prototype.remove=function(b){var c=[this.pid,this.id];return b&&this.occurrenceId&&c.push(this.occurrenceId),a.$$resource.remove(c.join("/"))},a.prototype.$unwrap=function(b){var c=this;this.$futureComponentData=b,this.$futureComponentData.then(function(a){c.init(a),c.$shadowData=c.$omit()},function(b){angular.extend(c,b),c.isError=!0,a.$log.error(c.error)})},a.prototype.$omit=function(){var a={};return angular.forEach(this,function(b,c){"constructor"!=c&&"$"!=c[0]&&"blocks"!=c&&(a[c]=angular.copy(b))}),a},a.prototype.repeatDescription=function(){var a=null;return this.repeat&&(a=l("repeat_"+this.repeat.frequency.toUpperCase())),a},a.prototype.alarmDescription=function(){var a,b=null;return this.alarm&&(a=["reminder"+this.alarm.quantity,this.alarm.unit,this.alarm.reference].join("_"),b=l(a),a===b&&(b=[this.alarm.quantity,l("reminder_"+this.alarm.unit),l("reminder_"+this.alarm.reference)].join(" "))),b},a.prototype.copyTo=function(b){return a.$$resource.post(this.pid+"/"+this.id,"copy",{destination:b})},a.prototype.moveTo=function(b){return a.$$resource.post(this.pid+"/"+this.id,"move",{destination:b})},a.prototype.toString=function(){return"[Component "+this.id+"]"}}(),function(){"use strict";function a(b,c,d,e,f,g,h,i,j){function k(a){a.push(f.createHotkey({key:l("hotkey_today"),description:l("Today"),callback:q,args:new Date})),a.push(f.createHotkey({key:l("hotkey_dayview"),description:l("Day"),callback:r,args:"day"})),a.push(f.createHotkey({key:l("hotkey_weekview"),description:l("Week"),callback:r,args:"week"})),a.push(f.createHotkey({key:l("hotkey_monthview"),description:l("Month"),callback:r,args:"month"})),a.push(f.createHotkey({key:l("hotkey_multicolumndayview"),description:l("Multicolumn Day View"),callback:r,args:"multicolumnday"})),a.push(f.createHotkey({key:"left",description:l("Move backward"),callback:m,args:-1})),a.push(f.createHotkey({key:"right",description:l("Move forward"),callback:m,args:1})),_.forEach(a,function(a){f.registerHotkey(a)})}function m(a,b){var c;"week"==e.view?c=t.selectedDate.beginOfWeek(i.defaults.SOGoFirstDayOfWeek).addDays(7*b):"month"==e.view?(c=t.selectedDate,c.setDate(1),c.setMonth(c.getMonth()+b)):c=t.selectedDate.addDays(b),q(a,c)}function n(a){"month"==e.view?(a.setDate(1),a.setHours(12),a.$dateFormat="%B %Y"):"week"==e.view?(a.setTime(a.beginOfWeek(i.defaults.SOGoFirstDayOfWeek).getTime()),a.$dateFormat=l("Week %d").replace("%d","%U")):a.$dateFormat="%A"}function o(){a.expandedAllDays=!a.expandedAllDays,t.expandedAllDays=a.expandedAllDays}function p(){h.$eventsBlocksForView(e.view,e.day.asDate()).then(function(a){var b,c,d;for(b=0;b=b;c--)t.views.splice(c,1)})}function q(a,b){var c=b?b.getDayString():angular.element(a.currentTarget).attr("date");b&&n(b),d.go("calendars.view",{day:c})}function r(a,b){d.go("calendars.view",{view:b})}var s,t=this,u=[];angular.isUndefined(a.expandedAllDays)&&(a.expandedAllDays=!1),t.selectedDate=e.day.asDate(),t.expandedAllDays=a.expandedAllDays,t.toggleAllDays=o,t.views=j,t.changeDate=q,t.changeView=r,k(u),i.ready().then(function(){n(t.selectedDate)}),s=c.$on("calendars:list",p),b.$on("$destroy",function(){s(),_.forEach(u,function(a){f.deregisterHotkey(a)})})}a.$inject=["$scope","$rootScope","$state","$stateParams","sgHotkeys","Calendar","Component","Preferences","stateEventsBlocks"],angular.module("SOGo.SchedulerUI").controller("CalendarController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k){function m(a){a.push(f.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:r})),a.push(f.createHotkey({key:l("hotkey_create_event"),description:l("Create a new event"),callback:w,args:"appointment"})),a.push(f.createHotkey({key:l("hotkey_create_task"),description:l("Create a new task"),callback:w,args:"task"})),_.forEach(a,function(a){f.registerHotkey(a)})}function n(a,b){(b&&b.reload||F.componentType!=a)&&(angular.isUndefined(k["$"+a])&&k.$filter(a),F.unselectComponents(),F.componentType=a,k.saveSelectedList(a))}function o(){_.forEach(k["$"+F.componentType],function(a){a.selected=!1}),F.mode.multiple=0}function p(){_.forEach(k["$"+F.componentType],function(a){a.selected=!0}),F.mode.multiple=k["$"+F.componentType].length}function q(a,b){b.selected=!b.selected,F.mode.multiple+=b.selected?1:-1,a.preventDefault(),a.stopPropagation()}function r(){F.mode.search=!0,g("search")}function s(){h.confirm(l("Warning"),l("Are you sure you want to delete the selected components?"),{ok:l("Delete")}).then(function(){var b=_.filter(k["$"+F.componentType],function(a){return a.selected});j.$deleteComponents(b).then(function(){F.mode.multiple=0,a.$emit("calendars:list")})})}function t(a,b){v(a,b,"appointment")}function u(a,b){v(a,b,"task")}function v(a,b,c){if(b.viewable){var d="UIx"+c.capitalize()+"ViewTemplate";e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:d,controller:"ComponentController",controllerAs:"editor",locals:{stateComponent:b}})}}function w(a,b,c){var d;d=c?c:new k({pid:j.$defaultCalendar(),type:b});var f="UIx"+b.capitalize()+"EditorTemplate";return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:f,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:d}})}function x(b){function d(a,b,c,d){a.updateThisOccurrence=function(){c.$adjust(d).then(b.hide,function(a){b.cancel().then(function(){f(a,c,d)})})},a.updateAllOccurrences=function(){delete c.occurrenceId,c.$adjust(d).then(b.hide,function(a){b.cancel().then(function(){f(a,c,d)})})}}function f(b,c,d){403==b.status&&b.data&&b.data.message&&angular.isObject(b.data.message)&&e.show({parent:angular.element(document.body),clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxAttendeeConflictDialog",controller:g,controllerAs:"$AttendeeConflictDialogController",locals:{component:c,params:d,conflictError:b.data.message}}).then(function(){a.$emit("calendars:list")})}function g(a,b,c,d,e){function f(){c.$adjust(angular.extend({ignoreConflicts:!0},d)).then(b.hide)}var g=this;g.conflictError=e,g.cancel=b.cancel,g.save=f}var h,i,m,n,o,p,q;h=k.$ghost.component,i=k.$ghost.pointerHandler,h.isNew?(m=i.currentEventCoordinates,h.summary="",h.isAllDay&&(m.duration-=96),h.setDelta(15*m.duration),w(null,"appointment",h).finally(function(){c(function(){k.$resetGhost()})})):(n=i.currentEventCoordinates.getDelta(i.originalEventCoordinates),o={days:n.dayNumber,start:15*n.start,duration:15*n.duration},i.originalCalendar&&0!==n.dayNumber&&(p=i.currentEventCoordinates.dayNumber,q=_.filter(j.$findAll(),{active:1}),o.destination=q[p].id,o.days=0),h.isException||!h.occurrenceId?h.$adjust(o).then(function(){a.$emit("calendars:list")},function(a){f(a,h,o)}).finally(function(){c(function(){k.$resetGhost()})}):h.occurrenceId&&e.show({clickOutsideToClose:!0,escapeToClose:!0,locals:{component:h,params:o},template:['',' ',"

"+l("editRepeatingItem")+"

","
"," ",' '+l("button_thisOccurrenceOnly")+"",' '+l("button_allOccurrences")+""," ","
"].join(""),controller:d}).then(function(){a.$emit("calendars:list")}).finally(function(){c(function(){k.$resetGhost()})})),d.$inject=["$scope","$mdDialog","component","params"],g.$inject=["$scope","$mdDialog","component","params","conflictError"]}function y(){return k["$query"+F.componentType.capitalize()].filterpopup}function z(a){k.$filter(F.componentType,{filterpopup:a})}function A(a){return k["$query"+F.componentType.capitalize()].filterpopup==a}function B(a){k.$filter(F.componentType,{sort:a})}function C(a){return k["$query"+F.componentType.capitalize()].sort==a}function D(){j.reloadWebCalendars().finally(function(){a.$emit("calendars:list")})}function E(){F.mode.search=!1,k.$filter(F.componentType,{value:""})}var F=this,G=[];F.component=k,F.componentType="events",F.selectedList=0,F.selectComponentType=n,F.unselectComponents=o,F.selectAll=p,F.searchMode=r,F.toggleComponentSelection=q,F.confirmDeleteSelectedComponents=s,F.openEvent=t,F.openTask=u,F.newComponent=w,F.filterpopup=y,F.filter=z,F.filteredBy=A,F.sort=B,F.sortedBy=C,F.reload=D,F.cancelSearch=E,F.mode={search:!1,multiple:0},m(G),i.ready().then(function(){var a="events";"tasksListView"==i.settings.Calendar.SelectedList&&(F.selectedList=1,a="tasks"),n(a,{reload:!0}); -}),a.$on("calendars:list",function(){k.$filter(F.componentType,{reload:!0})}),a.$on("calendar:dragend",x),b.$on("$destroy",function(){_.forEach(G,function(a){f.deregisterHotkey(a)})})}a.$inject=["$rootScope","$scope","$timeout","$state","$mdDialog","sgHotkeys","sgFocus","Dialog","Preferences","Calendar","Component"],angular.module("SOGo.SchedulerUI").controller("CalendarListController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o){function p(a,b,c){return a.sortableScope.element[0]==b.element[0]}function q(){m.saveFoldersOrder(_.flatMap(m.$findAll(),"id"))}function r(){G.sortableMode=!G.sortableMode,G.filter.name=""}function s(){m.saveFoldersOrder()}function t(a){i.prompt(l("New calendar"),l("Name of the Calendar")).then(function(a){var b=new m({name:a,isEditable:!0,isRemote:!1,owner:UserLogin});b.$id().then(function(){m.$add(b)})})}function u(){function a(a,b,c,d){var e=this,f=c.split("/"),g=f[2];e.title=l("Please identify yourself to %{0}").formatted(g),e.authenticate=function(a){!a.$valid&&a.$error.required||d.setCredentials(e.username,e.password).then(function(a){b.hide()},function(b){a.password.$setValidity("credentials",!1)})},e.cancel=function(){b.cancel()}}i.prompt(l("Subscribe to a web calendar..."),l("URL of the Calendar"),{inputType:"url"}).then(function(b){m.$addWebCalendar(b).then(function(c){angular.isObject(c)&&d.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:"UIxWebCalendarAuthDialog",controller:a,controllerAs:"$WebCalendarAuthDialogController",locals:{url:b,calendar:c}})})}),a.$inject=["scope","$mdDialog","url","calendar"]}function v(a){a.isSubscription?a.$delete().catch(function(b,c){i.alert(l('An error occured while deleting the calendar "%{0}".',a.name),l(b.error))}):i.confirm(l("Warning"),l('Are you sure you want to delete the calendar "%{0}"?',a.name),{ok:l("Delete")}).then(function(){a.$delete().catch(function(b,c){i.alert(l('An error occured while deleting the calendar "%{0}".',a.name),l(b.error))})})}function w(b,c){function e(b,c,d){function e(a){var b=0===a.type.indexOf("text")||/\.(ics)$/.test(a.name);return b||f.show({template:["",'
',' error_outline'," "+l("Select an iCalendar file (.ics).")+"","
","
"].join(""),position:"top right",hideDelay:3e3}),b}var h=this;h.uploader=new g({url:ApplicationBaseURL+[d.id,"import"].join("/"),autoUpload:!0,queueLimit:1,filters:[{name:e,fn:e}],onSuccessItem:function(b,d,e,g){var h;c.hide(),0===d.imported?h=l("No event was imported."):(h=l("A total of %{0} events were imported in the calendar.",d.imported),a.$emit("calendars:list")),f.show(f.simple().content(h).position("top right").hideDelay(3e3))},onErrorItem:function(a,b,c,d){f.show({template:["",'
',' error_outline'," "+l("An error occurred while importing calendar.")+"","
","
"].join(""),position:"top right",hideDelay:3e3})}}),h.close=function(){c.hide()}}d.show({parent:angular.element(document.body),targetEvent:b,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:"UIxCalendarImportDialog",controller:e,controllerAs:"$CalendarImportDialogController",locals:{folder:c}}),e.$inject=["scope","$mdDialog","folder"]}function x(a){_.forEach(m.$findAll(),function(b){a.id==b.id?b.active=1:b.active=0})}function y(){_.forEach(m.$findAll(),function(a){a.active=1})}function z(a){function b(a,b){function c(){a.hide()}var d=this;d.calendar=b,d.close=c}d.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:a.id+"/links",controller:b,controllerAs:"links",locals:{calendar:a}}),b.$inject=["$mdDialog","calendar"]}function A(a){function b(a,b,c){function d(){f.calendar.$save(),c.init(f.calendar.$omit()),b.hide()}function e(){b.cancel()}var f=this;f.calendar=new m(c.$omit()),f.saveProperties=d,f.close=e,a.$watch(function(){return f.calendar.color},function(){c.color=f.calendar.color})}var c=a.color;d.show({templateUrl:a.id+"/properties",controller:b,controllerAs:"properties",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcCalendar:a}}).catch(function(){a.color=c}),b.$inject=["$scope","$mdDialog","srcCalendar"]}function B(a){G.calendarName=a.name,G.editMode=a.id,h("calendarName_"+a.id)}function C(a){a.$reset(),G.editMode=!1}function D(a){a.$rename().then(function(a){G.editMode=!1})}function E(a){a.$acl.$users().then(function(){d.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:n,folder:a}})})}function F(a){e.debug("subscribeToFolder "+a.owner+a.name),m.$subscribe(a.owner,a.name).then(function(a){f.show(f.simple().content(l("Successfully subscribed to calendar")).position("top right").hideDelay(3e3))})}var G=this;G.activeUser=j.activeUser,G.service=m,G.newCalendar=t,G.addWebCalendar=u,G.confirmDelete=v,G.editFolder=B,G.revertEditing=C,G.renameFolder=D,G.share=E,G.importCalendar=w,G.showOnly=x,G.showAll=y,G.showLinks=z,G.showProperties=A,G.subscribeToFolder=F,G.filter={name:""},G.sortableMode=!1,G.toggleSortableMode=r,G.resetSort=s,G.sortableCalendars={scrollableContainer:"#sidenav-content",containment:"md-list",orderChanged:q,accept:p},k.ready().then(function(){G.categories=_.map(k.defaults.SOGoCalendarCategories,function(a){return{id:a.asCSSIdentifier(),name:a,color:k.defaults.SOGoCalendarCategoriesColors[a]}})}),b.$watch(function(){return _.union(_.map(m.$calendars,function(a){return _.pick(a,["id","active","color"])}),_.map(m.$subscriptions,function(a){return _.pick(a,["id","active","color"])}),_.map(m.$webcalendars,function(a){return _.pick(a,["id","active","color"])}))},function(b,c){var d,f,g;d=_.intersectionBy(b,c,"id"),f=_.map(_.filter(d,function(a){var b=_.find(c,{id:a.id});return!_.isEqual(a,b)}),"id"),g=[],f.length>0&&(e.debug(f.join(", ")+" changed"),_.forEach(f,function(a){var b=m.$get(a);g.push(b.$setActivation())})),(g.length>0||d.length!=b.length||d.length!=c.length)&&m.$q.all(g).then(function(){a.$emit("calendars:list")})},!0)}a.$inject=["$rootScope","$scope","$window","$mdDialog","$log","$mdToast","FileUploader","sgFocus","Dialog","sgSettings","Preferences","Calendar","User","stateCalendars"],angular.module("SOGo.SchedulerUI").controller("CalendarsController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h){function i(){b.hide()}function j(a){return e.$filterAll(a),e.$cards}function k(a){var b=_.map(y.component.attendees,function(a){return a.name+" <"+a.email+">"});n(a,b)}function m(a,b,c){n(a,[b+" <"+c+">"])}function n(a,c){g.$findAll().then(function(d){var e=_.find(d,function(a){if(0===a.id)return a});e.$getMailboxes().then(function(d){e.$newMessage().then(function(d){angular.extend(d.editable,{to:c,subject:y.component.summary}),b.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"../Mail/UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:e,stateMessage:d}})})})}),a.preventDefault(),a.stopPropagation()}function o(){var a="vevent"==y.component.component?"Appointment":"Task";b.hide().then(function(){var c="UIx"+a+"EditorTemplate";b.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:c,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:y.component}})})}function p(){x=c.$get(y.component.pid).$getComponent(y.component.id),x.$futureComponentData.then(function(){y.component=x,o()})}function q(c){var d=c||y.component;d.$reply().then(function(){a.$emit("calendars:list"),b.hide(),f.getAlarms()})}function r(){x=c.$get(y.component.pid).$getComponent(y.component.id),x.$futureComponentData.then(function(){x.reply=y.component.reply,x.delegatedTo=y.component.delegatedTo,x.$hasAlarm=y.component.$hasAlarm,x.alarm=y.component.alarm,q(x)})}function s(){y.component.remove(!0).then(function(){a.$emit("calendars:list"),b.hide()})}function t(){y.component.remove().then(function(){a.$emit("calendars:list"),b.hide()})}function u(a){c.$$resource.post(y.component.pid+"/"+y.component.id,"raw").then(function(c){function d(a,b,c){a.data=c,a.close=function(){b.hide()}}b.hide(),b.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,template:['',' ','
',"  
"," ",' '+l("Close")+""," ","
"].join(""),controller:d,locals:{data:c}}),d.$inject=["scope","$mdDialog","data"]})}function v(c){y.component.copyTo(c).then(function(){b.hide(),a.$emit("calendars:list")})}function w(c){y.component.moveTo(c).then(function(){b.hide(),a.$emit("calendars:list")})}var x,y=this;y.calendarService=c,y.service=d,y.component=h,y.close=i,y.cardFilter=j,y.newMessageWithAllRecipients=k,y.newMessageWithRecipient=m,y.edit=o,y.editAllOccurrences=p,y.reply=q,y.replyAllOccurrences=r,y.deleteOccurrence=s,y.deleteAllOccurrences=t,y.toggleRawSource=u,y.copySelectedComponent=v,y.moveSelectedComponent=w,angular.isUndefined(y.component.$futureComponentData)&&(x=c.$get(y.component.pid).$getComponent(y.component.id,y.component.occurrenceId),x.$futureComponentData.then(function(){y.component=x,y.organizer=[y.component.organizer]}))}function b(a,b,c,d,e,f,g,h,i,j,k,m){function n(){var a=H.component.addAttachUrl("");focus("attachUrl_"+a)}function o(){H.showRecurrenceEditor=!H.showRecurrenceEditor,H.component.$hasCustomRepeat=H.showRecurrenceEditor}function p(){H.showAttendeesEditor=!H.showAttendeesEditor}function q(a){return i.$filterAll(a),i.$cards}function r(a){angular.isString(a)?a.isValidEmail()&&(H.component.addAttendee(new j({emails:[{value:a}]})),H.searchText=""):H.component.addAttendee(a)}function s(a){H.component.deleteAttendee(a),0===H.component.attendees.length&&(H.showAttendeesEditor=!1)}function t(){if(H.component&&H.component.priority)return H.component.priority>5?l("low"):H.component.priority>4?l("normal"):l("high")}function u(b,c){b.$valid&&H.component.$save(c).then(function(b){a.$emit("calendars:list"),e.hide(),k.getAlarms()},function(a){403==a.status&&a.data&&a.data.message&&angular.isObject(a.data.message)&&(H.attendeeConflictError=a.data.message)})}function v(){H.component.$reset(),H.component.isNew&&(H.component=null),e.cancel()}function w(){var a=[];return H.component.start&&H.component.end&&(a=H.component.start.daysUpTo(H.component.end)),_.map(a,function(a){return{stringWithSeparator:a.stringWithSeparator(),getDayString:a.getDayString()}})}function x(){for(var a=[],b=0;b<=23;b++)a.push(b.toString());return a}function y(){H.component.$addStartDate(),E=new Date(H.component.start.getTime())}function z(){H.component.$addDueDate(),G=new Date(H.component.due.getTime())}function A(){if(H.component.start){var a;a=E.valueOf()-H.component.start.valueOf(),0!==a&&(E=new Date(H.component.start.getTime()),"appointment"===H.component.type&&(H.component.end=new Date(H.component.start.getTime()),H.component.end.addMinutes(H.component.delta),F=new Date(H.component.end.getTime())),D())}}function B(){if(H.component.end){var a=F.valueOf()-H.component.end.valueOf();0!==a&&(a=H.component.start.minutesTo(H.component.end),a<0?H.component.end=new Date(F.getTime()):(H.component.delta=a,F=new Date(H.component.end.getTime())),D())}}function C(){G=new Date(H.component.due.getTime())}function D(){H.attendeesEditor.days=w(),H.component.updateFreeBusy()}var E,F,G,H=this;H.service=g,H.component=m,H.categories={},H.showRecurrenceEditor=H.component.$hasCustomRepeat,H.toggleRecurrenceEditor=o,H.showAttendeesEditor=!1,H.toggleAttendeesEditor=p,H.cardFilter=q,H.addAttendee=r,H.removeAttendee=s,H.addAttachUrl=n,H.priorityLevel=t,H.cancel=v,H.save=u,H.attendeeConflictError=!1,H.attendeesEditor={days:w(),hours:x()},H.addStartDate=y,H.addDueDate=z,H.adjustStartTime=A,H.adjustEndTime=B,H.adjustDueTime=C,H.component.start&&(E=new Date(H.component.start.getTime())),H.component.end&&(F=new Date(H.component.end.getTime())),H.component.due&&(G=new Date(H.component.due.getTime()))}a.$inject=["$rootScope","$mdDialog","Calendar","Component","AddressBook","Alarm","Account","stateComponent"],b.$inject=["$rootScope","$scope","$log","$timeout","$mdDialog","User","Calendar","Component","AddressBook","Card","Alarm","stateComponent"],angular.module("SOGo.SchedulerUI").controller("ComponentController",a).controller("ComponentEditorController",b)}(),function(){"use strict";function a(){return{restrict:"E",scope:{day:"@sgDay",dayNumber:"@sgDayNumber",dayString:"@sgDayString",calendar:"@sgCalendar"},controller:b}}function b(a,b){this.day=a.day,this.dayNumber=a.dayNumber,this.dayString=a.dayString,this.calendarData=function(){var c,d,e;return a.calendar?(c=a.calendar,e=_.filter(b.$findAll(),{active:1}),d=_.findIndex(e,function(a){return a.id==c}),{pid:c,index:d}):null}}b.$inject=["$scope","Calendar"],angular.module("SOGo.SchedulerUI").directive("sgCalendarDay",a)}(),function(){"use strict";function a(a){function b(a,b){var c=_.has(b,"sgCalendarGhost")?"":"::";return['
",'
','
",'
',' {{'+c+"block.component.c_priority}}"," {{ "+c+"block.component.summary }}",' ',' ',' ',' ',' '," ",'
'," place {{"+c+"block.component.c_location}}","
","
","
",'
{{ block.startHour }}
','
{{ block.endHour }}
',"
"].join("")}function c(a,b,c){var d,e,f;_.has(c,"sgCalendarGhost")||(d=100/a.block.siblings,e=a.block.position*d,f=100-(a.block.position+1)*d,d<100&&(e>0&&(e-=2),f>0&&(f-=2)),0===e&&(e=2),0===f&&(f=2),b.css("left",e+"%"),b.css("right",f+"%"),a.block.component&&a.block.component.c_isallday||(b.addClass("starts"+a.block.start),b.addClass("lasts"+a.block.length)),a.block.userState&&b.addClass("sg-event--"+a.block.userState),a.block.component&&(b.addClass("bg-folder"+a.block.component.pid),b.addClass("contrast-bdr-folder"+a.block.component.pid),0===a.block.component.c_isopaque&&b.addClass("sg-event--transparent"),0===a.block.component.c_status&&b.addClass("sg-event--cancelled")))}return{restrict:"E",scope:{block:"=sgBlock",clickBlock:"&sgClick"},replace:!0,template:b,link:c}}a.$inject=["CalendarSettings"],angular.module("SOGo.SchedulerUI").directive("sgCalendarDayBlock",a)}(),function(){"use strict";function a(){return{restrict:"E",scope:{blocks:"=sgBlocks",day:"@sgDay",clickBlock:"&sgClick"},template:["'].join("")}}angular.module("SOGo.SchedulerUI").directive("sgCalendarDayTable",a)}(),function(){"use strict";function a(a,b,c,d,e){function f(b,f,g,h){function i(){var a,c,d;b.block=e.$ghost,c=p.calendarData(),c&&(r=c.index,a=c.pid,s=b.block.pointerHandler.originalCalendar.index),a||(a=b.block.component.pid),d=b.block.component.blocks[0].userState,d&&f.addClass("sg-event--"+d),f.addClass("bg-folder"+a)}function j(){_.forEachRight(o.classList,function(a){/^bg-folder/.test(a)&&f.removeClass(a)}),f.addClass("ng-hide")}function k(){var a,e,g,h,i,j,k,l;if(a=!1,d.$view&&d.$view.type==q.type){if(e="multiday-allday"===q.type,g=b.block.component.c_isallday,h=b.block.pointerHandler.currentEventCoordinates.dayNumber,i=b.block.pointerHandler.currentEventCoordinates.start,k=b.block.pointerHandler.currentEventCoordinates.duration,l=c.EventDragDayLength-i,angular.isUndefined(k))return;for(j=k,j>l&&(j=l),h>-1&&(r<0&&h==p.dayNumber||h==r&&(s==r||!b.block.component.isException))&&(a=!0,e||(g||(b.block.startHour=m(i)),d.$view.quarterHeight?(f.css("top",i*d.$view.quarterHeight+"px"),f.css("height",j*d.$view.quarterHeight+"px")):f.css("top",d.$view.topOffset+"px")),f.removeClass("fg-folder"+b.block.component.pid),f.removeClass("sg-event--ghost--last"),f.addClass("sg-event--ghost--first"),b.block.isFirst=!0),k-=j,h++;!a&&k&&h<=p.dayNumber;)j=k,j>c.EventDragDayLength&&(j=c.EventDragDayLength),h>-1&&h==p.dayNumber&&(a=!0,e||(f.css("top",d.$view.topOffset+"px"),d.$view.quarterHeight&&f.css("height",j*d.$view.quarterHeight+"px")),f.removeClass("sg-event--ghost--first"),f.removeClass("sg-event--ghost--last"),f.addClass("fg-folder"+b.block.component.pid)),k-=j,h++,i=0;k||(e?f.addClass("sg-event--ghost--last"):g||(b.block.endHour=n(i,j)))}a?f.removeClass("ng-hide"):f.addClass("ng-hide")}function l(a){var b,c,d;return b=15*a,c=Math.floor(b/60),c<10&&(c="0"+c),d=b%60,d<10&&(d="0"+d),""+c+":"+d}function m(a){return l(a)}function n(a,b){var d=(a+b)%c.EventDragDayLength;return l(d)}var o,p,q,r,s;o=f[0],p=h[0],q=h[1],r=-1,f.addClass("sg-event--ghost md-whiteframe-3dp ng-hide");var t=a.$on("calendar:dragstart",i),u=a.$on("calendar:drag",k),v=a.$on("calendar:dragend",j);b.$on("$destroy",function(){t(),u(),v()})}return{restrict:"A",require:["^sgCalendarDay","^sgCalendarScrollView"],link:f}}a.$inject=["$rootScope","$timeout","CalendarSettings","Calendar","Component"],angular.module("SOGo.SchedulerUI").directive("sgCalendarGhost",a)}(),function(){"use strict";function a(){return{restrict:"E",scope:{blocks:"=sgBlocks",day:"@sgDay",clickBlock:"&sgClick"},template:["'].join("")}}angular.module("SOGo.SchedulerUI").directive("sgCalendarMonthDay",a)}(),function(){"use strict";function a(){function a(a,b){var c=_.has(b,"sgCalendarGhost")?"":"::";return['
','
",' {{ '+c+"block.component.startHour }}",' {{'+c+"block.component.c_priority}}"," {{ "+c+"block.component.summary }}",' ',' ',' ',' ',' '," ","
"].join("")}function b(a,b,c){_.has(c,"sgCalendarGhost")||(a.block.userState&&b.addClass("sg-event--"+a.block.userState),a.block.component&&(b.addClass("bg-folder"+a.block.component.pid),0===a.block.component.c_isopaque&&b.addClass("sg-event--transparent"),0===a.block.component.c_status&&b.addClass("sg-event--cancelled")))}return{restrict:"E",scope:{block:"=sgBlock",clickBlock:"&sgClick"},replace:!0,template:a,link:b}}angular.module("SOGo.SchedulerUI").directive("sgCalendarMonthEvent",a)}(),function(){"use strict";function a(a,c,d,e,f,g,h,i,j){return{restrict:"A",scope:{type:"@sgCalendarScrollView"},controller:b,link:function(b,d,e,g){function k(){m=new l(d,n),"monthly"!=n&&j.ready().then(function(){var a,b,c;j.defaults.SOGoDayStartTime&&(a=j.defaults.SOGoDayStartTime.split(":"),b=document.getElementById("hour"+parseInt(a[0])),c=parseInt(a[1])*m.quarterHeight,m.element.scrollTop=b.offsetTop+c)}),g.quarterHeight=m.quarterHeight}function l(b,d){this.$element=b,this.element=b[0],this.type=d,this.quarterHeight=this.getQuarterHeight(),this.scrollStep=6*this.quarterHeight,this.dayNumbers=this.getDayNumbers(),this.maxX=this.getMaxColumns(),this.deregisterDragStart=a.$on("calendar:dragstart",angular.bind(this,this.onDragStart)),this.deregisterDragStop=a.$on("calendar:dragend",angular.bind(this,this.onDragEnd)),this.bindedUpdateCoordinates=angular.bind(this,this.updateCoordinates),this.bindedUpdateFromPointerHandler=angular.bind(this,this.updateFromPointerHandler),this.updateCoordinates(),angular.element(c).on("resize",this.bindedUpdateCoordinates)}var m,n,o=!1;m=null,n=b.type,o="multicolumndayview"==d.attr("sg-view"),g.isMultiColumn=o,f(k),b.$on("$destroy",function(){m&&m.$destroy()}),l.prototype={$destroy:function(){this.deregisterDragStart(),this.deregisterDragStop(),this.$element.off("mousemove",this.bindedUpdateFromPointerHandler),angular.element(c).off("resize",this.bindedUpdateCoordinates)},onDragStart:function(){this.$element.on("mousemove",this.bindedUpdateFromPointerHandler),this.updateCoordinates(),this.updateFromPointerHandler()},onDragEnd:function(){this.$element.off("mousemove",this.bindedUpdateFromPointerHandler),h.$view=null},getQuarterHeight:function(){var a,b,c=null;return a=document.getElementById("hour0"),b=document.getElementById("hour23"),a&&b&&(c=(b.offsetTop-a.offsetTop)/92),c},getDayDimensions:function(a){var b,c,d,e,f,g,h;return c=b=d=e=0,f=this.element.getElementsByClassName("day"),f.length>0&&(g=f[0].getBoundingClientRect(),c=g.height,b=g.width,d=g.left-a,h=f[0].getElementsByClassName("sg-calendar-tile-header"),h.length>0&&(e=h[0].clientHeight)),{height:c,width:b,offset:{left:d,top:e}}},getDayNumbers:function(){var a;return a=this.element.getElementsByTagName("sg-calendar-day"),_.map(a,function(a,b){return o?b:parseInt(a.attributes["sg-day-number"].value)})},getMaxColumns:function(){var a,b=0;return"monthly"==this.type?(a=this.element.getElementsByTagName("md-grid-list")[0],b=parseInt(a.attributes["md-cols"].value)-1):b=this.element.getElementsByClassName("day").length-1,b},updateCoordinates:function(){var a,b;a=this.element.getBoundingClientRect(),b=this.getDayDimensions(a.left),angular.extend(this,{coordinates:{x:a.left,y:a.top},dayHeight:b.height,dayWidth:b.width,daysOffset:b.offset.left,topOffset:b.offset.top})},updateFromPointerHandler:function(){var a,b,c,d,e,f;a=i.$ghost.pointerHandler,this.coordinates&&a&&(b=a.getContainerBasedCoordinates(this),b&&(h.$view=this,c=(new Date).getTime(),(!this.lastScroll||c>this.lastScroll+100)&&(this.lastScroll=c,d=b.y-this.scrollStep,d<0?(e=-this.element.scrollTop,d0&&(this.element.scrollTop+=f)))))}}}}}function b(a){this.type=a.type}a.$inject=["$rootScope","$window","$document","$q","$timeout","$mdGesture","Calendar","Component","Preferences"],b.$inject=["$scope"],angular.module("SOGo.SchedulerUI").directive("sgCalendarScrollView",a)}(),function(){"use strict";function a(){return{restrict:"E",require:"ngModel",scope:{ngModel:"="},replace:!0,template:['"].join("")}}angular.module("SOGo.SchedulerUI").directive("sgCategoryStylesheet",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g){function h(h,i,j,k){function m(){var a,b,c,d,e,f,g,j,k,l;a=h.block.component,b=h.block.dayIndex,c=_.findIndex(a.blocks,["dayIndex",b]),d=0===c,e=c===a.blocks.length-1,f=angular.element('
'),f.addClass("bdr-folder"+a.pid),a.c_isallday||"SG-CALENDAR-MONTH-DAY"===i[0].parentNode.tagName?(d&&(g=angular.element('
').append(f),i.append(g)),e&&(j=angular.element('
').append(f.clone()),i.append(j))):(d&&(k=angular.element('
').append(f),i.append(k)),e&&(l=angular.element('
').append(f.clone()),i.append(l)))}function n(a){var b,c;a.stopPropagation(),b="move-event",h.block&&h.block.component?"dragGrip-top"==a.target.className||"dragGrip-left"==a.target.className?b="change-start":"dragGrip-bottom"!=a.target.className&&"dragGrip-right"!=a.target.className||(b="change-end"):b="change-end",c=new t(b),c.initFromEvent(a),g.$ghost.pointerHandler=c,angular.element(document).one("mouseup",q),angular.element(document).on("mousemove",p)}function o(b){var f,j,m,n,o,p,q,r,s;m=i.hasClass("clickableHourCell"),n="SG-CALENDAR-MONTH-DAY"==i[0].parentNode.tagName||i.hasClass("clickableDayCell"),s=k.calendarData(),h.block&&h.block.component?f=h.block:(o=k.dayString.parseDate(d.$mdDateLocaleProvider,"%Y-%m-%e"),p={type:"appointment",pid:s?s.pid:e.$defaultCalendar(),summary:l("New Event"),startDate:o,isAllDay:m?0:1},q=new g(p),f={component:q,dayNumber:k.dayNumber,length:0},f.component.blocks=[f]),j="multiday",n?j="monthly":f.component.c_isallday&&(j="multiday-allday"),_.forEach(f.component.blocks,function(a){a.dragging=!0}),r=g.$ghost.pointerHandler,r.prepareWithEventType(j),r.initFromBlock(f),s&&r.initFromCalendar(s),g.$ghost.component=f.component,c.debug("emit calendar:dragstart "+j),a.$emit("calendar:dragstart")}function p(a){var c=g.$ghost.pointerHandler;b(function(){c.updateFromEvent(a)})}function q(b){var c,d;c=h.block,d=g.$ghost.pointerHandler,angular.element(document).off("mousemove",p),d.dragHasStarted&&(a.$emit("calendar:dragend"),d.dragHasStarted=!1),c&&c.component&&_.forEach(c.component.blocks,function(a){a.dragging=!1})}function r(){}function s(a){this.setEventType(a)}function t(a){this.dragMode=a}if(h.block){if(!h.block.component.editable||h.block.userState)return void i.removeClass("sg-draggable-calendar-block");m()}i.on("mousedown",n),h.$on("$destroy",function(){i.off("mousedown",n),i.off("mousemove",p)}),r.prototype={x:-1,y:-1,getDelta:function(a){var b=new r;return b.x=this.x-a.x,b.y=this.y-a.y,e.$view&&(b.days=e.$view.dayNumbers[this.x]-e.$view.dayNumbers[a.x]),b},getDistance:function(a){var b=this.getDelta(a);return Math.sqrt(b.x*b.x+b.y*b.y)},clone:function(){var a=new r;return a.x=this.x,a.y=this.y,a}},s.prototype={dayNumber:-1,weekDay:-1,start:-1,duration:-1,eventType:null,setEventType:function(a){this.eventType=a},initFromBlock:function(a){var b=-1;"monthly"===this.eventType?(this.start=0,this.duration=a.component.blocks.length*f.EventDragDayLength):(this.start=a.component.blocks[0].start,this.duration=_.sumBy(a.component.blocks,function(a){var c,d;return d=a.dayNumber,c=b<0?0:d-b-1,b=d,a.length+c*f.EventDragDayLength}))},initFromCalendar:function(a){this.dayNumber=a},getDelta:function(a){var b=new s;return b.dayNumber=this.dayNumber-a.dayNumber,b.start=this.start-a.start,b.duration=this.duration-a.duration,b},_quartersToHM:function(a){var b=15*a,c=Math.floor(b/60);c<10&&(c="0"+c);var d=b%60;return d<10&&(d="0"+d),""+c+":"+d},getStartTime:function(){return this._quartersToHM(this.start)},getEndTime:function(){var a=(this.start+this.duration)%f.EventDragDayLength;return this._quartersToHM(a)},clone:function(){var a=new s;return a.dayNumber=this.dayNumber,a.start=this.start,a.duration=this.duration,a}},t.prototype={originalCoordinates:null,currentCoordinates:null,originalViewCoordinates:null,currentViewCoordinates:null,originalEventCoordinates:null,currentEventCoordinates:null,originalCalendar:null,dragHasStarted:!1,getEventViewCoordinates:null,initFromBlock:function(a){this.currentEventCoordinates=new s(this.eventType),this.originalEventCoordinates=new s(this.eventType),this.originalEventCoordinates.initFromBlock(a)},initFromEvent:function(a){this.currentCoordinates=new r,this.updateFromEvent(a),this.originalCoordinates=this.currentCoordinates.clone()},initFromCalendar:function(a){this.originalCalendar=a,this.currentEventCoordinates.initFromCalendar(a.index),this.originalEventCoordinates.initFromCalendar(a.index)},updateFromEvent:function(a){if(this.currentCoordinates.x=a.pageX,this.currentCoordinates.y=a.pageY,this.dragHasStarted&&e.$view){var b=this.getEventViewCoordinates(e.$view);this.originalViewCoordinates||(this.originalViewCoordinates=this.getEventViewCoordinates(e.$view,this.originalCoordinates),g.$ghost.component.isNew&&(this.setTimeFromQuarters(g.$ghost.component.start,this.originalViewCoordinates.y),c.debug("new event start date "+g.$ghost.component.start))),this.currentViewCoordinates&&b&&b.x==this.currentViewCoordinates.x&&b.y==this.currentViewCoordinates.y||(this.currentViewCoordinates=b,this.originalViewCoordinates&&(b||(this.currentViewCoordinates=this.originalViewCoordinates.clone()),this.updateEventCoordinates()))}else if(this.originalCoordinates&&this.currentCoordinates&&!this.dragHasStarted){var d=this.getDistance();d>3&&(this.dragHasStarted=!0,o(a))}},updateEventCoordinates:function(){var b,d=this.currentViewCoordinates.getDelta(this.originalViewCoordinates),g=d.days*f.EventDragDayLength+d.y;c.debug("quarters delta "+g),angular.isUndefined(this.originalEventCoordinates.start)?(this.originalEventCoordinates.dayNumber=e.$view.dayNumbers[this.originalViewCoordinates.x],this.originalEventCoordinates.start=this.originalViewCoordinates.y):this.originalEventCoordinates.dayNumber<0&&(this.originalEventCoordinates.dayNumber=e.$view.dayNumbers[h.block.component.blocks[0].dayIndex]),this.currentEventCoordinates.dayNumber=this.originalEventCoordinates.dayNumber,"move-event"==this.dragMode?(this.currentEventCoordinates.start=this.originalEventCoordinates.start+g,this.currentEventCoordinates.duration=this.originalEventCoordinates.duration):"change-start"==this.dragMode?(b=this.originalEventCoordinates.duration-g,b>0?(this.currentEventCoordinates.start=this.originalEventCoordinates.start+g,this.currentEventCoordinates.duration=b):b<0&&(this.currentEventCoordinates.start=this.originalEventCoordinates.start+this.originalEventCoordinates.duration,this.currentEventCoordinates.duration=-b)):"change-end"==this.dragMode&&(b=this.originalEventCoordinates.duration+g,b>0?(this.currentEventCoordinates.start=this.originalEventCoordinates.start,this.currentEventCoordinates.duration=b):b<0&&(this.currentEventCoordinates.start=this.originalEventCoordinates.start+b,this.currentEventCoordinates.duration=-b));var i;this.currentEventCoordinates.start<0?(i=Math.ceil(-this.currentEventCoordinates.start/f.EventDragDayLength),this.currentEventCoordinates.start+=i*f.EventDragDayLength,this.currentEventCoordinates.dayNumber-=i):this.currentEventCoordinates.start>=f.EventDragDayLength&&(i=Math.floor(this.currentEventCoordinates.start/f.EventDragDayLength),this.currentEventCoordinates.start-=i*f.EventDragDayLength,this.currentEventCoordinates.dayNumber+=i),c.debug("event coordinates "+JSON.stringify(this.currentEventCoordinates)),a.$emit("calendar:drag")},getContainerBasedCoordinates:function(a,b){ -var c=b||this.currentCoordinates,d=c.getDelta(a.coordinates),e=a.element;return(d.xe.clientWidth||d.y<0||d.y>e.clientHeight)&&(d=null),d},prepareWithEventType:function(a){var b={multiday:this.getEventMultiDayViewCoordinates,"multiday-allday":this.getEventMultiDayAllDayViewCoordinates,monthly:this.getEventMonthlyViewCoordinates,unknown:null},c=b[a];this.eventType=a,this.getEventViewCoordinates=c},getEventMultiDayViewCoordinates:function(a,b){var c=this.getEventMultiDayAllDayViewCoordinates(a,b);if(c){var d=a.quarterHeight,e=this.getContainerBasedCoordinates(a,b);e.y+=a.element.scrollTop,c.y=Math.floor((e.y-f.EventDragHorizontalOffset)/d);var g=f.EventDragDayLength-1;c.y<0?c.y=0:c.y>g&&(c.y=g)}return c},getEventMultiDayAllDayViewCoordinates:function(a,b){var c,d=this.getContainerBasedCoordinates(a,b);if(d){c=new r;var f=a.dayWidth,g=a.daysOffset;c.x=Math.floor((d.x-g)/f);var h=0,i=e.$view.maxX;if("move-event"!=this.dragMode){var j=k.calendarData();j&&(h=i=j.index)}c.xi&&(c.x=i),c.y=0}else c=null;return c},getEventMonthlyViewCoordinates:function(a,b){var c,d=this.getContainerBasedCoordinates(a,b);if(d){c=new r;var e=a.maxX,f=0,g=a.dayWidth,h=a.daysOffset,i=a.dayHeight,j=Math.floor((d.y-f)/i);j<0&&(j=0),c.x=Math.floor((d.x-h)/g),c.x<0?c.x=0:c.x>e&&(c.x=e),c.x+=(e+1)*j,c.y=0}else c=null;return c},getDistance:function(){return this.currentCoordinates.getDistance(this.originalCoordinates)},setTimeFromQuarters:function(a,b){var c,d;c=Math.floor(b/4),d=b%4*15,a.setHours(c,d)}}}return{restrict:"CA",require:"^sgCalendarDay",link:h}}a.$inject=["$rootScope","$timeout","$log","Preferences","Calendar","CalendarSettings","Component"],angular.module("SOGo.SchedulerUI").directive("sgDraggableCalendarBlock",a)}(),function(){"use strict";function a(){function a(a,b,c,d){function e(){return b.find("sg-calendar-day")}function f(){return d.quarterHeight}var g=a.$watch(f,function(b){if(b){g(),a.quarterHeight=b;var c=a.$watch(e,function(b){b.length&&(c(),a.days=b,a.updateLine())})}})}return{restrict:"C",require:"^^sgCalendarScrollView",link:a,controller:b}}function b(a,b,c){function d(b){var d=new Date,h=d.getDayString(),i=d.getHours(),j=4*a.quarterHeight,k=d.getMinutes(),l=a.quarterHeight/15,m=parseInt(i*j+k*l-1);(b||h!=a.nowDay)&&(a.lineElement&&a.lineElement.remove(),a.lineElement=e(h,a.days),a.nowDay=h),a.lineElement&&(a.lineElement.css("top",m+"px"),f=c(angular.bind(g,a.updateLine),6e4))}function e(a,c){var d=angular.element("");return h.isMultiColumn?c&&c[0].attributes["sg-day"].value==a&&b.append(d):_.forEach(c,function(b){b.attributes["sg-day"].value==a&&angular.element(b).find("div").eq(0).append(d)}),d}var f,g=this,h=b.controller("sgCalendarScrollView");a.nowDay=null,a.lineElement=null,a.updateLine=d,a.$on("$destroy",function(){f&&c.cancel(f)})}b.$inject=["$scope","$element","$timeout"],angular.module("SOGo.SchedulerUI").directive("sgNowLine",a)}(); +}),a.$on("calendars:list",function(){k.$filter(F.componentType,{reload:!0})}),a.$on("calendar:dragend",x),b.$on("$destroy",function(){_.forEach(G,function(a){f.deregisterHotkey(a)})})}a.$inject=["$rootScope","$scope","$timeout","$state","$mdDialog","sgHotkeys","sgFocus","Dialog","Preferences","Calendar","Component"],angular.module("SOGo.SchedulerUI").controller("CalendarListController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o){function p(a,b,c){return a.sortableScope.element[0]==b.element[0]}function q(){m.saveFoldersOrder(_.flatMap(m.$findAll(),"id"))}function r(){G.sortableMode=!G.sortableMode,G.filter.name=""}function s(){m.saveFoldersOrder()}function t(a){i.prompt(l("New calendar"),l("Name of the Calendar")).then(function(a){var b=new m({name:a,isEditable:!0,isRemote:!1,owner:UserLogin});b.$id().then(function(){m.$add(b)})})}function u(){function a(a,b,c,d){var e=this,f=c.split("/"),g=f[2];e.title=l("Please identify yourself to %{0}").formatted(g),e.authenticate=function(a){!a.$valid&&a.$error.required||d.setCredentials(e.username,e.password).then(function(a){b.hide()},function(b){a.password.$setValidity("credentials",!1)})},e.cancel=function(){b.cancel()}}i.prompt(l("Subscribe to a web calendar..."),l("URL of the Calendar"),{inputType:"url"}).then(function(b){m.$addWebCalendar(b).then(function(c){angular.isObject(c)&&d.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:"UIxWebCalendarAuthDialog",controller:a,controllerAs:"$WebCalendarAuthDialogController",locals:{url:b,calendar:c}})})}),a.$inject=["scope","$mdDialog","url","calendar"]}function v(a){a.isSubscription?a.$delete().catch(function(b,c){i.alert(l('An error occured while deleting the calendar "%{0}".',a.name),l(b.error))}):i.confirm(l("Warning"),l('Are you sure you want to delete the calendar "%{0}"?',a.name),{ok:l("Delete")}).then(function(){a.$delete().catch(function(b,c){i.alert(l('An error occured while deleting the calendar "%{0}".',a.name),l(b.error))})})}function w(b,c){function e(b,c,d){function e(a){var b=0===a.type.indexOf("text")||/\.(ics)$/.test(a.name);return b||f.show({template:["",'
',' error_outline'," "+l("Select an iCalendar file (.ics).")+"","
","
"].join(""),position:"top right",hideDelay:3e3}),b}var h=this;h.uploader=new g({url:ApplicationBaseURL+[d.id,"import"].join("/"),autoUpload:!0,queueLimit:1,filters:[{name:e,fn:e}],onSuccessItem:function(b,d,e,g){var h;c.hide(),0===d.imported?h=l("No event was imported."):(h=l("A total of %{0} events were imported in the calendar.",d.imported),a.$emit("calendars:list")),f.show(f.simple().content(h).position("top right").hideDelay(3e3))},onErrorItem:function(a,b,c,d){f.show({template:["",'
',' error_outline'," "+l("An error occurred while importing calendar.")+"","
","
"].join(""),position:"top right",hideDelay:3e3})}}),h.close=function(){c.hide()}}d.show({parent:angular.element(document.body),targetEvent:b,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:"UIxCalendarImportDialog",controller:e,controllerAs:"$CalendarImportDialogController",locals:{folder:c}}),e.$inject=["scope","$mdDialog","folder"]}function x(a){_.forEach(m.$findAll(),function(b){a.id==b.id?b.active=1:b.active=0})}function y(){_.forEach(m.$findAll(),function(a){a.active=1})}function z(a){function b(a,b){function c(){a.hide()}var d=this;d.calendar=b,d.close=c}d.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:a.id+"/links",controller:b,controllerAs:"links",locals:{calendar:a}}),b.$inject=["$mdDialog","calendar"]}function A(a){function b(a,b,c){function d(){f.calendar.$save(),c.init(f.calendar.$omit()),b.hide()}function e(){b.cancel()}var f=this;f.calendar=new m(c.$omit()),f.saveProperties=d,f.close=e,a.$watch(function(){return f.calendar.color},function(){c.color=f.calendar.color})}var c=a.color;d.show({templateUrl:a.id+"/properties",controller:b,controllerAs:"properties",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcCalendar:a}}).catch(function(){a.color=c}),b.$inject=["$scope","$mdDialog","srcCalendar"]}function B(a){G.calendarName=a.name,G.editMode=a.id,h("calendarName_"+a.id)}function C(a){a.$reset(),G.editMode=!1}function D(a){a.$rename().then(function(a){G.editMode=!1})}function E(a){a.$acl.$users().then(function(){d.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:n,folder:a}})})}function F(a){e.debug("subscribeToFolder "+a.owner+a.name),m.$subscribe(a.owner,a.name).then(function(a){f.show(f.simple().content(l("Successfully subscribed to calendar")).position("top right").hideDelay(3e3))})}var G=this;G.activeUser=j.activeUser,G.service=m,G.newCalendar=t,G.addWebCalendar=u,G.confirmDelete=v,G.editFolder=B,G.revertEditing=C,G.renameFolder=D,G.share=E,G.importCalendar=w,G.showOnly=x,G.showAll=y,G.showLinks=z,G.showProperties=A,G.subscribeToFolder=F,G.filter={name:""},G.sortableMode=!1,G.toggleSortableMode=r,G.resetSort=s,G.sortableCalendars={scrollableContainer:"#sidenav-content",containment:"md-list",orderChanged:q,accept:p},k.ready().then(function(){G.categories=_.map(k.defaults.SOGoCalendarCategories,function(a){return{id:a.asCSSIdentifier(),name:a,color:k.defaults.SOGoCalendarCategoriesColors[a]}})}),b.$watch(function(){return _.union(_.map(m.$calendars,function(a){return _.pick(a,["id","active","color"])}),_.map(m.$subscriptions,function(a){return _.pick(a,["id","active","color"])}),_.map(m.$webcalendars,function(a){return _.pick(a,["id","active","color"])}))},function(b,c){var d,f,g;d=_.intersectionBy(b,c,"id"),f=_.map(_.filter(d,function(a){var b=_.find(c,{id:a.id});return!_.isEqual(a,b)}),"id"),g=[],f.length>0&&(e.debug(f.join(", ")+" changed"),_.forEach(f,function(a){var b=m.$get(a);g.push(b.$setActivation())})),(g.length>0||d.length!=b.length||d.length!=c.length)&&m.$q.all(g).then(function(){a.$emit("calendars:list")})},!0)}a.$inject=["$rootScope","$scope","$window","$mdDialog","$log","$mdToast","FileUploader","sgFocus","Dialog","sgSettings","Preferences","Calendar","User","stateCalendars"],angular.module("SOGo.SchedulerUI").controller("CalendarsController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h){function i(){b.hide()}function j(a){return e.$filterAll(a),e.$cards}function k(a){var b=_.map(y.component.attendees,function(a){return a.name+" <"+a.email+">"});n(a,b)}function m(a,b,c){n(a,[b+" <"+c+">"])}function n(a,c){g.$findAll().then(function(d){var e=_.find(d,function(a){if(0===a.id)return a});e.$getMailboxes().then(function(d){e.$newMessage().then(function(d){angular.extend(d.editable,{to:c,subject:y.component.summary}),b.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"../Mail/UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:e,stateMessage:d}})})})}),a.preventDefault(),a.stopPropagation()}function o(){var a="vevent"==y.component.component?"Appointment":"Task";b.hide().then(function(){var c="UIx"+a+"EditorTemplate";b.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:c,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:y.component}})})}function p(){x=c.$get(y.component.pid).$getComponent(y.component.id),x.$futureComponentData.then(function(){y.component=x,o()})}function q(c){var d=c||y.component;d.$reply().then(function(){a.$emit("calendars:list"),b.hide(),f.getAlarms()})}function r(){x=c.$get(y.component.pid).$getComponent(y.component.id),x.$futureComponentData.then(function(){x.reply=y.component.reply,x.delegatedTo=y.component.delegatedTo,x.$hasAlarm=y.component.$hasAlarm,x.alarm=y.component.alarm,q(x)})}function s(){y.component.remove(!0).then(function(){a.$emit("calendars:list"),b.hide()})}function t(){y.component.remove().then(function(){a.$emit("calendars:list"),b.hide()})}function u(a){c.$$resource.post(y.component.pid+"/"+y.component.id,"raw").then(function(c){function d(a,b,c){a.data=c,a.close=function(){b.hide()}}b.hide(),b.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,template:['',' ','
',"  
"," ",' '+l("Close")+""," ","
"].join(""),controller:d,locals:{data:c}}),d.$inject=["scope","$mdDialog","data"]})}function v(c){y.component.copyTo(c).then(function(){b.hide(),a.$emit("calendars:list")})}function w(c){y.component.moveTo(c).then(function(){b.hide(),a.$emit("calendars:list")})}var x,y=this;y.calendarService=c,y.service=d,y.component=h,y.close=i,y.cardFilter=j,y.newMessageWithAllRecipients=k,y.newMessageWithRecipient=m,y.edit=o,y.editAllOccurrences=p,y.reply=q,y.replyAllOccurrences=r,y.deleteOccurrence=s,y.deleteAllOccurrences=t,y.toggleRawSource=u,y.copySelectedComponent=v,y.moveSelectedComponent=w,angular.isUndefined(y.component.$futureComponentData)&&(x=c.$get(y.component.pid).$getComponent(y.component.id,y.component.occurrenceId),x.$futureComponentData.then(function(){y.component=x,y.organizer=[y.component.organizer]}))}function b(a,b,c,d,e,f,g,h,i,j,k,m){function n(){var a=H.component.addAttachUrl("");focus("attachUrl_"+a)}function o(){H.showRecurrenceEditor=!H.showRecurrenceEditor,H.component.$hasCustomRepeat=H.showRecurrenceEditor}function p(){H.showAttendeesEditor=!H.showAttendeesEditor}function q(a){return i.$filterAll(a),i.$cards}function r(a){angular.isString(a)?a.isValidEmail()&&(H.component.addAttendee(new j({emails:[{value:a}]})),H.searchText=""):H.component.addAttendee(a)}function s(a){H.component.deleteAttendee(a),0===H.component.attendees.length&&(H.showAttendeesEditor=!1)}function t(){if(H.component&&H.component.priority)return H.component.priority>5?l("low"):H.component.priority>4?l("normal"):l("high")}function u(b,c){b.$valid&&H.component.$save(c).then(function(b){a.$emit("calendars:list"),e.hide(),k.getAlarms()},function(a){403==a.status&&a.data&&a.data.message&&angular.isObject(a.data.message)&&(H.attendeeConflictError=a.data.message)})}function v(){H.component.$reset(),H.component.isNew&&(H.component=null),e.cancel()}function w(){var a=[];return H.component.start&&H.component.end&&(a=H.component.start.daysUpTo(H.component.end)),_.map(a,function(a){return{stringWithSeparator:a.stringWithSeparator(),getDayString:a.getDayString()}})}function x(){for(var a=[],b=0;b<=23;b++)a.push(b.toString());return a}function y(){H.component.$addStartDate(),E=new Date(H.component.start.getTime())}function z(){H.component.$addDueDate(),G=new Date(H.component.due.getTime())}function A(){if(H.component.start){var a;a=E.valueOf()-H.component.start.valueOf(),0!==a&&(E=new Date(H.component.start.getTime()),"appointment"===H.component.type&&(H.component.end=new Date(H.component.start.getTime()),H.component.end.addMinutes(H.component.delta),F=new Date(H.component.end.getTime())),D())}}function B(){if(H.component.end){var a=F.valueOf()-H.component.end.valueOf();0!==a&&(a=H.component.start.minutesTo(H.component.end),a<0?H.component.end=new Date(F.getTime()):(H.component.delta=a,F=new Date(H.component.end.getTime())),D())}}function C(){G=new Date(H.component.due.getTime())}function D(){H.attendeesEditor.days=w(),H.component.updateFreeBusy()}var E,F,G,H=this;H.service=g,H.component=m,H.categories={},H.showRecurrenceEditor=H.component.$hasCustomRepeat,H.toggleRecurrenceEditor=o,H.showAttendeesEditor=!1,H.toggleAttendeesEditor=p,H.cardFilter=q,H.addAttendee=r,H.removeAttendee=s,H.addAttachUrl=n,H.priorityLevel=t,H.cancel=v,H.save=u,H.attendeeConflictError=!1,H.attendeesEditor={days:w(),hours:x()},H.addStartDate=y,H.addDueDate=z,H.adjustStartTime=A,H.adjustEndTime=B,H.adjustDueTime=C,H.component.start&&(E=new Date(H.component.start.getTime())),H.component.end&&(F=new Date(H.component.end.getTime())),H.component.due&&(G=new Date(H.component.due.getTime()))}a.$inject=["$rootScope","$mdDialog","Calendar","Component","AddressBook","Alarm","Account","stateComponent"],b.$inject=["$rootScope","$scope","$log","$timeout","$mdDialog","User","Calendar","Component","AddressBook","Card","Alarm","stateComponent"],angular.module("SOGo.SchedulerUI").controller("ComponentController",a).controller("ComponentEditorController",b)}(),function(){"use strict";function a(){return{restrict:"E",scope:{day:"@sgDay",dayNumber:"@sgDayNumber",dayString:"@sgDayString",calendar:"@sgCalendar"},controller:b}}function b(a,b){this.day=a.day,this.dayNumber=a.dayNumber,this.dayString=a.dayString,this.calendarData=function(){var c,d,e;return a.calendar?(c=a.calendar,e=_.filter(b.$findAll(),{active:1}),d=_.findIndex(e,function(a){return a.id==c}),{pid:c,index:d}):null}}b.$inject=["$scope","Calendar"],angular.module("SOGo.SchedulerUI").directive("sgCalendarDay",a)}(),function(){"use strict";function a(a){function b(a,b){var c=_.has(b,"sgCalendarGhost")?"":"::";return['
",'
','
",'
',' {{'+c+"block.component.c_priority}}"," {{ "+c+"block.component.summary }}",' ',' ',' ',' ',' '," ",'
'," place {{"+c+"block.component.c_location}}","
","
","
",'
{{ block.startHour }}
','
{{ block.endHour }}
',"
"].join("")}function c(a,b,c){var d,e,f;_.has(c,"sgCalendarGhost")||(d=100/a.block.siblings,e=a.block.position*d,f=100-(a.block.position+1)*d,d<100&&(e>0&&(e-=2),f>0&&(f-=2)),0===e&&(e=2),0===f&&(f=2),b.css("left",e+"%"),b.css("right",f+"%"),a.block.component&&a.block.component.c_isallday||(b.addClass("starts"+a.block.start),b.addClass("lasts"+a.block.length)),a.block.userState&&b.addClass("sg-event--"+a.block.userState),a.block.component&&(b.addClass("bg-folder"+a.block.component.pid),b.addClass("contrast-bdr-folder"+a.block.component.pid),0===a.block.component.c_isopaque&&b.addClass("sg-event--transparent"),0===a.block.component.c_status&&b.addClass("sg-event--cancelled")))}return{restrict:"E",scope:{block:"=sgBlock",clickBlock:"&sgClick"},replace:!0,template:b,link:c}}a.$inject=["CalendarSettings"],angular.module("SOGo.SchedulerUI").directive("sgCalendarDayBlock",a)}(),function(){"use strict";function a(){return{restrict:"E",scope:{blocks:"=sgBlocks",day:"@sgDay",clickBlock:"&sgClick"},template:["'].join("")}}angular.module("SOGo.SchedulerUI").directive("sgCalendarDayTable",a)}(),function(){"use strict";function a(a,b,c,d,e){function f(b,f,g,h){function i(){var a,c,d;b.block=e.$ghost,c=p.calendarData(),c&&(r=c.index,a=c.pid,s=b.block.pointerHandler.originalCalendar.index),a||(a=b.block.component.pid),d=b.block.component.blocks[0].userState,d&&f.addClass("sg-event--"+d),f.addClass("bg-folder"+a)}function j(){_.forEachRight(o.classList,function(a){/^bg-folder/.test(a)&&f.removeClass(a)}),f.addClass("ng-hide")}function k(){var a,e,g,h,i,j,k,l;if(a=!1,d.$view&&d.$view.type==q.type){if(e="multiday-allday"===q.type,g=b.block.component.c_isallday,h=b.block.pointerHandler.currentEventCoordinates.dayNumber,i=b.block.pointerHandler.currentEventCoordinates.start,k=b.block.pointerHandler.currentEventCoordinates.duration,l=c.EventDragDayLength-i,angular.isUndefined(k))return;for(j=k,j>l&&(j=l),h>-1&&(r<0&&h==p.dayNumber||h==r&&(s==r||!b.block.component.isException))&&(a=!0,e||(g||(b.block.startHour=m(i)),d.$view.quarterHeight?(f.css("top",i*d.$view.quarterHeight+"px"),f.css("height",j*d.$view.quarterHeight+"px")):f.css("top",d.$view.topOffset+"px")),f.removeClass("fg-folder"+b.block.component.pid),f.removeClass("sg-event--ghost--last"),f.addClass("sg-event--ghost--first"),b.block.isFirst=!0),k-=j,h++;!a&&k&&h<=p.dayNumber;)j=k,j>c.EventDragDayLength&&(j=c.EventDragDayLength),h>-1&&h==p.dayNumber&&(a=!0,e||(f.css("top",d.$view.topOffset+"px"),d.$view.quarterHeight&&f.css("height",j*d.$view.quarterHeight+"px")),f.removeClass("sg-event--ghost--first"),f.removeClass("sg-event--ghost--last"),f.addClass("fg-folder"+b.block.component.pid)),k-=j,h++,i=0;k||(e?f.addClass("sg-event--ghost--last"):g||(b.block.endHour=n(i,j)))}a?f.removeClass("ng-hide"):f.addClass("ng-hide")}function l(a){var b,c,d;return b=15*a,c=Math.floor(b/60),c<10&&(c="0"+c),d=b%60,d<10&&(d="0"+d),""+c+":"+d}function m(a){return l(a)}function n(a,b){var d=(a+b)%c.EventDragDayLength;return l(d)}var o,p,q,r,s;o=f[0],p=h[0],q=h[1],r=-1,f.addClass("sg-event--ghost md-whiteframe-3dp ng-hide");var t=a.$on("calendar:dragstart",i),u=a.$on("calendar:drag",k),v=a.$on("calendar:dragend",j);b.$on("$destroy",function(){t(),u(),v()})}return{restrict:"A",require:["^sgCalendarDay","^sgCalendarScrollView"],link:f}}a.$inject=["$rootScope","$timeout","CalendarSettings","Calendar","Component"],angular.module("SOGo.SchedulerUI").directive("sgCalendarGhost",a)}(),function(){"use strict";function a(){return{restrict:"E",scope:{blocks:"=sgBlocks",day:"@sgDay",clickBlock:"&sgClick"},template:["'].join("")}}angular.module("SOGo.SchedulerUI").directive("sgCalendarMonthDay",a)}(),function(){"use strict";function a(){function a(a,b){var c=_.has(b,"sgCalendarGhost")?"":"::";return['
','
",' {{ '+c+"block.component.startHour }}",' {{'+c+"block.component.c_priority}}"," {{ "+c+"block.component.summary }}",' ',' ',' ',' ',' '," ","
"].join("")}function b(a,b,c){_.has(c,"sgCalendarGhost")||(a.block.userState&&b.addClass("sg-event--"+a.block.userState),a.block.component&&(b.addClass("bg-folder"+a.block.component.pid),0===a.block.component.c_isopaque&&b.addClass("sg-event--transparent"),0===a.block.component.c_status&&b.addClass("sg-event--cancelled")))}return{restrict:"E",scope:{block:"=sgBlock",clickBlock:"&sgClick"},replace:!0,template:a,link:b}}angular.module("SOGo.SchedulerUI").directive("sgCalendarMonthEvent",a)}(),function(){"use strict";function a(a,c,d,e,f,g,h,i,j){return{restrict:"A",scope:{type:"@sgCalendarScrollView"},controller:b,link:function(b,d,e,g){function k(){m=new l(d,n),"monthly"!=n&&j.ready().then(function(){var a,b,c;j.defaults.SOGoDayStartTime&&(a=j.defaults.SOGoDayStartTime.split(":"),b=document.getElementById("hour"+parseInt(a[0])),c=parseInt(a[1])*m.quarterHeight,m.element.scrollTop=b.offsetTop+c)}),g.quarterHeight=m.quarterHeight}function l(b,d){this.$element=b,this.element=b[0],this.type=d,this.quarterHeight=this.getQuarterHeight(),this.scrollStep=6*this.quarterHeight,this.dayNumbers=this.getDayNumbers(),this.maxX=this.getMaxColumns(),this.deregisterDragStart=a.$on("calendar:dragstart",angular.bind(this,this.onDragStart)),this.deregisterDragStop=a.$on("calendar:dragend",angular.bind(this,this.onDragEnd)),this.bindedUpdateCoordinates=angular.bind(this,this.updateCoordinates),this.bindedUpdateFromPointerHandler=angular.bind(this,this.updateFromPointerHandler),this.updateCoordinates(),angular.element(c).on("resize",this.bindedUpdateCoordinates)}var m,n,o=!1;m=null,n=b.type,o="multicolumndayview"==d.attr("sg-view"),g.isMultiColumn=o,f(k),b.$on("$destroy",function(){m&&m.$destroy()}),l.prototype={$destroy:function(){this.deregisterDragStart(),this.deregisterDragStop(),this.$element.off("mousemove",this.bindedUpdateFromPointerHandler),angular.element(c).off("resize",this.bindedUpdateCoordinates)},onDragStart:function(){this.$element.on("mousemove",this.bindedUpdateFromPointerHandler),this.updateCoordinates(),this.updateFromPointerHandler()},onDragEnd:function(){this.$element.off("mousemove",this.bindedUpdateFromPointerHandler),h.$view=null},getQuarterHeight:function(){var a,b,c=null;return a=document.getElementById("hour0"),b=document.getElementById("hour23"),a&&b&&(c=(b.offsetTop-a.offsetTop)/92),c},getDayDimensions:function(a){var b,c,d,e,f,g,h;return c=b=d=e=0,f=this.element.getElementsByClassName("day"),f.length>0&&(g=f[0].getBoundingClientRect(),c=g.height,b=g.width,d=g.left-a,h=f[0].getElementsByClassName("sg-calendar-tile-header"),h.length>0&&(e=h[0].clientHeight)),{height:c,width:b,offset:{left:d,top:e}}},getDayNumbers:function(){var a;return a=this.element.getElementsByTagName("sg-calendar-day"),_.map(a,function(a,b){return o?b:parseInt(a.attributes["sg-day-number"].value)})},getMaxColumns:function(){var a,b=0;return"monthly"==this.type?(a=this.element.getElementsByTagName("md-grid-list")[0],b=parseInt(a.attributes["md-cols"].value)-1):b=this.element.getElementsByClassName("day").length-1,b},updateCoordinates:function(){var a,b;a=this.element.getBoundingClientRect(),b=this.getDayDimensions(a.left),angular.extend(this,{coordinates:{x:a.left,y:a.top},dayHeight:b.height,dayWidth:b.width,daysOffset:b.offset.left,topOffset:b.offset.top})},updateFromPointerHandler:function(){var a,b,c,d,e,f;a=i.$ghost.pointerHandler,this.coordinates&&a&&(b=a.getContainerBasedCoordinates(this),b&&(h.$view=this,c=(new Date).getTime(),(!this.lastScroll||c>this.lastScroll+100)&&(this.lastScroll=c,d=b.y-this.scrollStep,d<0?(e=-this.element.scrollTop,d0&&(this.element.scrollTop+=f)))))}}}}}function b(a){this.type=a.type}a.$inject=["$rootScope","$window","$document","$q","$timeout","$mdGesture","Calendar","Component","Preferences"],b.$inject=["$scope"],angular.module("SOGo.SchedulerUI").directive("sgCalendarScrollView",a)}(),function(){"use strict";function a(){return{restrict:"E",require:"ngModel",scope:{ngModel:"="},replace:!0,template:['"].join("")}}angular.module("SOGo.SchedulerUI").directive("sgCategoryStylesheet",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g){function h(h,i,j,k){function m(){var a,b,c,d,e,f,g,j,k,l;h.block.length<3||(a=h.block.component,b=h.block.dayIndex,c=_.findIndex(a.blocks,["dayIndex",b]),d=0===c,e=c===a.blocks.length-1,f=angular.element('
'),f.addClass("bdr-folder"+a.pid),a.c_isallday||"SG-CALENDAR-MONTH-DAY"===i[0].parentNode.tagName?(d&&(g=angular.element('
').append(f),i.append(g)),e&&(j=angular.element('
').append(f.clone()),i.append(j))):(d&&(k=angular.element('
').append(f),i.append(k)),e&&(l=angular.element('
').append(f.clone()),i.append(l))))}function n(a){var b,c;a.stopPropagation(),b="move-event",h.block&&h.block.component?"dragGrip-top"==a.target.className||"dragGrip-left"==a.target.className?b="change-start":"dragGrip-bottom"!=a.target.className&&"dragGrip-right"!=a.target.className||(b="change-end"):b="change-end",c=new t(b),c.initFromEvent(a),g.$ghost.pointerHandler=c,angular.element(document).one("mouseup",q),angular.element(document).on("mousemove",p)}function o(b){var f,j,m,n,o,p,q,r,s;m=i.hasClass("clickableHourCell"),n="SG-CALENDAR-MONTH-DAY"==i[0].parentNode.tagName||i.hasClass("clickableDayCell"),s=k.calendarData(),h.block&&h.block.component?f=h.block:(o=k.dayString.parseDate(d.$mdDateLocaleProvider,"%Y-%m-%e"),p={type:"appointment",pid:s?s.pid:e.$defaultCalendar(),summary:l("New Event"),startDate:o,isAllDay:m?0:1},q=new g(p),f={component:q,dayNumber:k.dayNumber,length:0},f.component.blocks=[f]),j="multiday",n?j="monthly":f.component.c_isallday&&(j="multiday-allday"),_.forEach(f.component.blocks,function(a){a.dragging=!0}),r=g.$ghost.pointerHandler,r.prepareWithEventType(j),r.initFromBlock(f),s&&r.initFromCalendar(s),g.$ghost.component=f.component,c.debug("emit calendar:dragstart "+j),a.$emit("calendar:dragstart")}function p(a){var c=g.$ghost.pointerHandler;b(function(){c.updateFromEvent(a)})}function q(b){var c,d;c=h.block,d=g.$ghost.pointerHandler,angular.element(document).off("mousemove",p),d.dragHasStarted&&(a.$emit("calendar:dragend"),d.dragHasStarted=!1),c&&c.component&&_.forEach(c.component.blocks,function(a){a.dragging=!1})}function r(){}function s(a){this.setEventType(a)}function t(a){this.dragMode=a}if(h.block){if(!h.block.component.editable||h.block.userState)return void i.removeClass("sg-draggable-calendar-block");m()}i.on("mousedown",n),h.$on("$destroy",function(){i.off("mousedown",n),i.off("mousemove",p)}),r.prototype={x:-1,y:-1,getDelta:function(a){var b=new r;return b.x=this.x-a.x,b.y=this.y-a.y,e.$view&&(b.days=e.$view.dayNumbers[this.x]-e.$view.dayNumbers[a.x]),b},getDistance:function(a){var b=this.getDelta(a);return Math.sqrt(b.x*b.x+b.y*b.y)},clone:function(){var a=new r;return a.x=this.x,a.y=this.y,a}},s.prototype={dayNumber:-1,weekDay:-1,start:-1,duration:-1,eventType:null,setEventType:function(a){this.eventType=a},initFromBlock:function(a){var b=-1;"monthly"===this.eventType?(this.start=0,this.duration=a.component.blocks.length*f.EventDragDayLength):(this.start=a.component.blocks[0].start,this.duration=_.sumBy(a.component.blocks,function(a){var c,d;return d=a.dayNumber,c=b<0?0:d-b-1,b=d,a.length+c*f.EventDragDayLength}))},initFromCalendar:function(a){this.dayNumber=a},getDelta:function(a){var b=new s;return b.dayNumber=this.dayNumber-a.dayNumber,b.start=this.start-a.start,b.duration=this.duration-a.duration,b},_quartersToHM:function(a){var b=15*a,c=Math.floor(b/60);c<10&&(c="0"+c);var d=b%60;return d<10&&(d="0"+d),""+c+":"+d},getStartTime:function(){return this._quartersToHM(this.start)},getEndTime:function(){var a=(this.start+this.duration)%f.EventDragDayLength;return this._quartersToHM(a)},clone:function(){var a=new s;return a.dayNumber=this.dayNumber,a.start=this.start,a.duration=this.duration,a}},t.prototype={originalCoordinates:null,currentCoordinates:null,originalViewCoordinates:null,currentViewCoordinates:null,originalEventCoordinates:null,currentEventCoordinates:null,originalCalendar:null,dragHasStarted:!1,getEventViewCoordinates:null,initFromBlock:function(a){this.currentEventCoordinates=new s(this.eventType),this.originalEventCoordinates=new s(this.eventType),this.originalEventCoordinates.initFromBlock(a)},initFromEvent:function(a){this.currentCoordinates=new r,this.updateFromEvent(a),this.originalCoordinates=this.currentCoordinates.clone()},initFromCalendar:function(a){this.originalCalendar=a,this.currentEventCoordinates.initFromCalendar(a.index),this.originalEventCoordinates.initFromCalendar(a.index)},updateFromEvent:function(a){if(this.currentCoordinates.x=a.pageX,this.currentCoordinates.y=a.pageY,this.dragHasStarted&&e.$view){var b=this.getEventViewCoordinates(e.$view);this.originalViewCoordinates||(this.originalViewCoordinates=this.getEventViewCoordinates(e.$view,this.originalCoordinates),g.$ghost.component.isNew&&(this.setTimeFromQuarters(g.$ghost.component.start,this.originalViewCoordinates.y),c.debug("new event start date "+g.$ghost.component.start))),this.currentViewCoordinates&&b&&b.x==this.currentViewCoordinates.x&&b.y==this.currentViewCoordinates.y||(this.currentViewCoordinates=b,this.originalViewCoordinates&&(b||(this.currentViewCoordinates=this.originalViewCoordinates.clone()),this.updateEventCoordinates()))}else if(this.originalCoordinates&&this.currentCoordinates&&!this.dragHasStarted){var d=this.getDistance();d>3&&(this.dragHasStarted=!0,o(a))}},updateEventCoordinates:function(){var b,d=this.currentViewCoordinates.getDelta(this.originalViewCoordinates),g=d.days*f.EventDragDayLength+d.y;c.debug("quarters delta "+g),angular.isUndefined(this.originalEventCoordinates.start)?(this.originalEventCoordinates.dayNumber=e.$view.dayNumbers[this.originalViewCoordinates.x],this.originalEventCoordinates.start=this.originalViewCoordinates.y):this.originalEventCoordinates.dayNumber<0&&(this.originalEventCoordinates.dayNumber=e.$view.dayNumbers[h.block.component.blocks[0].dayIndex]),this.currentEventCoordinates.dayNumber=this.originalEventCoordinates.dayNumber,"move-event"==this.dragMode?(this.currentEventCoordinates.start=this.originalEventCoordinates.start+g,this.currentEventCoordinates.duration=this.originalEventCoordinates.duration):"change-start"==this.dragMode?(b=this.originalEventCoordinates.duration-g,b>0?(this.currentEventCoordinates.start=this.originalEventCoordinates.start+g,this.currentEventCoordinates.duration=b):b<0&&(this.currentEventCoordinates.start=this.originalEventCoordinates.start+this.originalEventCoordinates.duration,this.currentEventCoordinates.duration=-b)):"change-end"==this.dragMode&&(b=this.originalEventCoordinates.duration+g,b>0?(this.currentEventCoordinates.start=this.originalEventCoordinates.start,this.currentEventCoordinates.duration=b):b<0&&(this.currentEventCoordinates.start=this.originalEventCoordinates.start+b,this.currentEventCoordinates.duration=-b));var i;this.currentEventCoordinates.start<0?(i=Math.ceil(-this.currentEventCoordinates.start/f.EventDragDayLength),this.currentEventCoordinates.start+=i*f.EventDragDayLength,this.currentEventCoordinates.dayNumber-=i):this.currentEventCoordinates.start>=f.EventDragDayLength&&(i=Math.floor(this.currentEventCoordinates.start/f.EventDragDayLength),this.currentEventCoordinates.start-=i*f.EventDragDayLength,this.currentEventCoordinates.dayNumber+=i),c.debug("event coordinates "+JSON.stringify(this.currentEventCoordinates)),a.$emit("calendar:drag"); +},getContainerBasedCoordinates:function(a,b){var c=b||this.currentCoordinates,d=c.getDelta(a.coordinates),e=a.element;return(d.xe.clientWidth||d.y<0||d.y>e.clientHeight)&&(d=null),d},prepareWithEventType:function(a){var b={multiday:this.getEventMultiDayViewCoordinates,"multiday-allday":this.getEventMultiDayAllDayViewCoordinates,monthly:this.getEventMonthlyViewCoordinates,unknown:null},c=b[a];this.eventType=a,this.getEventViewCoordinates=c},getEventMultiDayViewCoordinates:function(a,b){var c=this.getEventMultiDayAllDayViewCoordinates(a,b);if(c){var d=a.quarterHeight,e=this.getContainerBasedCoordinates(a,b);e.y+=a.element.scrollTop,c.y=Math.floor((e.y-f.EventDragHorizontalOffset)/d);var g=f.EventDragDayLength-1;c.y<0?c.y=0:c.y>g&&(c.y=g)}return c},getEventMultiDayAllDayViewCoordinates:function(a,b){var c,d=this.getContainerBasedCoordinates(a,b);if(d){c=new r;var f=a.dayWidth,g=a.daysOffset;c.x=Math.floor((d.x-g)/f);var h=0,i=e.$view.maxX;if("move-event"!=this.dragMode){var j=k.calendarData();j&&(h=i=j.index)}c.xi&&(c.x=i),c.y=0}else c=null;return c},getEventMonthlyViewCoordinates:function(a,b){var c,d=this.getContainerBasedCoordinates(a,b);if(d){c=new r;var e=a.maxX,f=0,g=a.dayWidth,h=a.daysOffset,i=a.dayHeight,j=Math.floor((d.y-f)/i);j<0&&(j=0),c.x=Math.floor((d.x-h)/g),c.x<0?c.x=0:c.x>e&&(c.x=e),c.x+=(e+1)*j,c.y=0}else c=null;return c},getDistance:function(){return this.currentCoordinates.getDistance(this.originalCoordinates)},setTimeFromQuarters:function(a,b){var c,d;c=Math.floor(b/4),d=b%4*15,a.setHours(c,d)}}}return{restrict:"CA",require:"^sgCalendarDay",link:h}}a.$inject=["$rootScope","$timeout","$log","Preferences","Calendar","CalendarSettings","Component"],angular.module("SOGo.SchedulerUI").directive("sgDraggableCalendarBlock",a)}(),function(){"use strict";function a(){function a(a,b,c,d){function e(){return b.find("sg-calendar-day")}function f(){return d.quarterHeight}var g=a.$watch(f,function(b){if(b){g(),a.quarterHeight=b;var c=a.$watch(e,function(b){b.length&&(c(),a.days=b,a.updateLine())})}})}return{restrict:"C",require:"^^sgCalendarScrollView",link:a,controller:b}}function b(a,b,c){function d(b){var d=new Date,h=d.getDayString(),i=d.getHours(),j=4*a.quarterHeight,k=d.getMinutes(),l=a.quarterHeight/15,m=parseInt(i*j+k*l-1);(b||h!=a.nowDay)&&(a.lineElement&&a.lineElement.remove(),a.lineElement=e(h,a.days),a.nowDay=h),a.lineElement&&(a.lineElement.css("top",m+"px"),f=c(angular.bind(g,a.updateLine),6e4))}function e(a,c){var d=angular.element("");return h.isMultiColumn?c&&c[0].attributes["sg-day"].value==a&&b.append(d):_.forEach(c,function(b){b.attributes["sg-day"].value==a&&angular.element(b).find("div").eq(0).append(d)}),d}var f,g=this,h=b.controller("sgCalendarScrollView");a.nowDay=null,a.lineElement=null,a.updateLine=d,a.$on("$destroy",function(){f&&c.cancel(f)})}b.$inject=["$scope","$element","$timeout"],angular.module("SOGo.SchedulerUI").directive("sgNowLine",a)}(); //# sourceMappingURL=Scheduler.services.js.map \ No newline at end of file diff --git a/UI/WebServerResources/js/Scheduler.services.js.map b/UI/WebServerResources/js/Scheduler.services.js.map index 7f000c80f..916c4872d 100644 --- a/UI/WebServerResources/js/Scheduler.services.js.map +++ b/UI/WebServerResources/js/Scheduler.services.js.map @@ -1 +1 @@ -{"version":3,"sources":["Scheduler/Calendar.service.js","Scheduler/Component.service.js","Scheduler/CalendarController.js","Scheduler/CalendarListController.js","Scheduler/CalendarsController.js","Scheduler/ComponentController.js","Scheduler/sgCalendarDay.directive.js","Scheduler/sgCalendarDayBlock.directive.js","Scheduler/sgCalendarDayTable.directive.js","Scheduler/sgCalendarGhost.directive.js","Scheduler/sgCalendarMonthDay.directive.js","Scheduler/sgCalendarMonthEvent.directive.js","Scheduler/sgCalendarScrollView.directive.js","Scheduler/sgCategoryStylesheet.directive.js","Scheduler/sgDraggableCalendarBlock.directive.js","Scheduler/sgNowLine.directive.js"],"names":["Calendar","futureCalendarData","this","init","name","id","newCalendarData","$$resource","create","$unwrap","$factory","$q","$timeout","$log","Settings","Resource","Preferences","Component","Acl","angular","extend","activeUser","$Preferences","$Component","$$Acl","$view","module","e","value","EventDragDayLength","EventDragHorizontalOffset","factory","$defaultCalendar","calendar","defaultCalendar","defaults","SOGoDefaultCalendar","_","find","$findAll","active","$add","list","sibling","i","isWebCalendar","$webcalendars","isSubscription","$subscriptions","$calendars","o","localeCompare","indexOf","map","splice","ready","then","settings","FoldersOrder","saveFoldersOrder","flatMap","$reloadAll","data","writable","_this","forEach","push","isUndefined","fetch","calendars","union","filter","isOwned","acls","objectCreator","calendarData","group","$get","$getIndex","$subscribe","uid","path","userResource","$addWebCalendar","url","d","defer","urls","webCalendarURL","reject","post","isEditable","isRemote","owner","login","debug","JSON","stringify","undefined","resolve","response","status","promise","reloadWebCalendars","promises","$error","l","statusText","all","$deleteComponents","components","component","isDefined","pid","uids","folders","prototype","color","$acl","isSuperUser","$shadowData","$omit","$id","when","$futureCalendarData","getClassName","base","$rename","$save","$delete","remove","$reset","key","save","error","setCredentials","username","password","export","download","type","$setActivation","$getComponent","componentId","recurrenceId","$find","isError","isObject","futureComponentData","newComponentData","newguid","isNew","Component_STATUS","Card","Gravatar","STATUS","$Card","$gravatar","timeFormat","$query","search","$queryEvents","sort","asc","filterpopup","$queryTasks","$refreshTimeout","$ghost","EventsFilterState","TasksFilterState","EventsSortingState","parseInt","TasksSortingState","show_completed","ShowCompletedTasks","$categories","SOGoCalendarCategoriesColors","SOGoTimeFormat","constant","NOT_LOADED","DELAYED_LOADING","LOADING","LOADED","DELAYED_MS","$selectedCount","count","$events","event","selected","length","$tasks","task","$startRefreshTimeout","cancel","refreshViewCheck","SOGoRefreshViewCheck","f","bind","$filter","timeInterval","$isLoading","$loaded","options","now","Date","day","getDate","month","getMonth","year","getFullYear","queryKey","capitalize","params","otherType","dirty","keys","$unwrapCollection","calendarId","occurrenceId","join","filterCategories","query","re","RegExp","category","saveSelectedList","componentType","$eventsBlocksForView","view","date","firstDayOfWeek","viewAction","startDate","endDate","SOGoFirstDayOfWeek","beginOfWeek","setTime","getTime","addDays","setDate","setMonth","endOfWeek","$eventsBlocks","j","dayDates","dayNumbers","deferred","toLowerCase","sd","getDayString","ed","views","reduceComponent","associateComponent","objects","eventData","componentData","zipObject","eventsFields","start","c_startdate","hour","getHourString","blocks","categories","block","nbr","isFirst","$views","viewIndex","viewData","allDayBlocks","reduce","events","flatten","days","dayIndex","dayNumber","calendarName","fields","invokeMap","$resetGhost","pointerHandler","startHour","endHour","$parseDate","dateString","time","substring","split","no_time","repeat","alarm","action","quantity","unit","reference","relation","delta","isString","setMinutes","Math","round","getMinutes","end","minutesTo","setDelta","dueDate","due","completedDate","completed","c_category","$isRecurrent","byDayMask","occurrence","frequency","byday","toString","interval","monthdays","months","until","$hasCustomRepeat","hasCustomRepeat","classification","units","M","H","D","W","match","exec","SOGoCalendarDefaultReminder","$hasAlarm","sendAppointmentNotifications","SOGoAppointmentSendEMailNotifications","destinationCalendar","updateFreeBusy","b","isReadOnly","isEditableOccurrence","isInvitation","userHasRSVP","isInvitationOccurrence","enablePercentComplete","coversFreeBusy","quarter","freebusy","updateFreeBusyCoverage","roundedStart","roundedEnd","startQuarter","endQuarter","daysUpTo","index","hourKey","currentDay","dayKey","getHours","beginOfDay","addMinutes","attendees","attendee","image","email","updateFreeBusyAttendee","sday","eday","c_folder","addAttendee","card","$isList","expandable","container","c_name","listId","refs","ref","c_cn","$preferredEmail","role","partstat","c_uid","hasAttendee","emails","deleteAttendee","findIndex","currentAttendee","canRemindAttendeesByEmail","addAttachUrl","attachUrl","attachUrls","deleteAttachUrl","$addDueDate","toISOString","$deleteDueDate","$addStartDate","$deleteStartDate","$reply","reply","delegatedTo","$adjust","every","values","v","extraAttributes","dlp","$mdDateLocaleProvider","format","startTime","endTime","dueTime","stringWithSeparator","organizer","occurrenceOnly","$futureComponentData","copy","repeatDescription","localizedString","toUpperCase","alarmDescription","copyTo","destination","moveTo","CalendarController","$scope","$rootScope","$state","$stateParams","sgHotkeys","stateEventsBlocks","_registerHotkeys","createHotkey","description","callback","changeDate","args","changeView","_goToPeriod","registerHotkey","$event","direction","vm","selectedDate","_formatDate","setHours","$dateFormat","replace","toggleAllDays","expandedAllDays","updateView","asDate","newDate","element","currentTarget","attr","go","deregisterCalendarsList","hotkeys","$on","deregisterHotkey","$inject","controller","CalendarListController","$mdDialog","focus","Dialog","searchMode","newComponent","selectComponentType","reload","unselectComponents","mode","multiple","selectAll","toggleComponentSelection","preventDefault","stopPropagation","confirmDeleteSelectedComponents","confirm","ok","$emit","openEvent","openComponent","openTask","viewable","templateUrl","show","parent","document","body","targetEvent","clickOutsideToClose","escapeToClose","controllerAs","locals","stateComponent","baseComponent","updateComponentFromGhost","RecurrentComponentDialogController","updateThisOccurrence","hide","onComponentAdjustError","updateAllOccurrences","message","AttendeeConflictDialogController","conflictError","ignoreConflicts","coordinates","calendarNumber","activeCalendars","currentEventCoordinates","summary","isAllDay","duration","finally","getDelta","originalEventCoordinates","originalCalendar","isException","template","filteredBy","field","sortedBy","cancelSearch","selectedList","SelectedList","CalendarsController","$window","$mdToast","FileUploader","User","stateCalendars","_sortableAccept","sourceItemHandleScope","destSortableScope","destItemScope","sortableScope","_sortableEnd","toggleSortableMode","sortableMode","resetSort","newCalendar","ev","prompt","UserLogin","addWebCalendar","WebCalendarAuthDialogController","scope","parts","hostname","title","formatted","authenticate","form","$valid","required","reason","$setValidity","inputType","confirmDelete","folder","catch","alert","importCalendar","CalendarImportDialogController","filterByExtension","item","isTextFile","test","position","hideDelay","uploader","ApplicationBaseURL","autoUpload","queueLimit","filters","fn","onSuccessItem","headers","msg","imported","simple","content","onErrorItem","close","showOnly","showAll","showLinks","LinksDialogController","showProperties","PropertiesDialogController","srcCalendar","saveProperties","$watch","editFolder","editMode","revertEditing","renameFolder","share","$users","usersWithACL","users","subscribeToFolder","service","sortableCalendars","scrollableContainer","containment","orderChanged","accept","SOGoCalendarCategories","asCSSIdentifier","pick","newList","oldList","commonList","ids","intersectionBy","oldObject","isEqual","ComponentController","AddressBook","Alarm","Account","cardFilter","$filterAll","$cards","newMessageWithAllRecipients","recipients","_newMessage","newMessageWithRecipient","accounts","account","$getMailboxes","mailboxes","$newMessage","editable","to","subject","stateAccount","stateMessage","edit","editAllOccurrences","c","getAlarms","replyAllOccurrences","deleteOccurrence","deleteAllOccurrences","toggleRawSource","ComponentRawSourceDialogController","copySelectedComponent","moveSelectedComponent","calendarService","ComponentEditorController","toggleRecurrenceEditor","showRecurrenceEditor","toggleAttendeesEditor","showAttendeesEditor","isValidEmail","searchText","removeAttendee","priorityLevel","priority","attendeeConflictError","getDays","hours","addStartDate","oldStartDate","addDueDate","oldDueDate","adjustStartTime","valueOf","oldEndDate","adjustEndTime","adjustDueTime","attendeesEditor","sgCalendarDay","restrict","dayString","sgCalendarDayController","directive","sgCalendarDayBlock","CalendarSettings","tElem","tAttrs","p","has","link","iElement","attrs","pc","left","right","siblings","css","c_isallday","addClass","userState","c_isopaque","c_status","clickBlock","sgCalendarDayTable","sgCalendarGhost","ctrls","initGhost","calendarDayCtrl","originalCalendarNumber","hideGhost","forEachRight","domElement","classList","removeClass","updateGhost","showGhost","isRelative","durationLeft","maxDuration","scrollViewCtrl","getStartTime","quarterHeight","topOffset","getEndTime","quartersToHM","quarters","minutes","mins","floor","deregisterDragStart","deregisterDrag","deregisterDragEnd","require","sgCalendarMonthDay","sgCalendarMonthEvent","sgCalendarScrollView","$document","$mdGesture","sgCalendarScrollViewController","initView","sgScrollView","hourCell","quartersOffset","SOGoDayStartTime","getElementById","scrollTop","offsetTop","$element","getQuarterHeight","scrollStep","getDayNumbers","maxX","getMaxColumns","onDragStart","deregisterDragStop","onDragEnd","bindedUpdateCoordinates","updateCoordinates","bindedUpdateFromPointerHandler","updateFromPointerHandler","on","isMultiColumn","$destroy","off","hour0","hour23","height","getDayDimensions","viewLeft","width","leftOffset","nodes","domRect","tileHeader","getElementsByClassName","getBoundingClientRect","clientHeight","offset","top","getElementsByTagName","el","attributes","mdGridList","max","dayDimensions","x","y","dayHeight","dayWidth","daysOffset","pointerCoordinates","scrollY","minY","getContainerBasedCoordinates","lastScroll","sgCategoryStylesheet","ngModel","sgDraggableCalendarBlock","initGrips","blockIndex","isFirstBlock","isLastBlock","dragGrip","leftGrip","rightGrip","topGrip","bottomGrip","parentNode","tagName","append","clone","onDragDetect","dragMode","target","className","SOGoEventDragPointerHandler","initFromEvent","one","onDrag","dragStart","eventType","isHourCell","isMonthly","newData","hasClass","parseDate","dragging","prepareWithEventType","initFromBlock","initFromCalendar","updateFromEvent","pointer","dragHasStarted","SOGoCoordinates","SOGoEventDragEventCoordinates","setEventType","otherCoordinates","getDistance","sqrt","weekDay","prevDayNumber","sumBy","currentDayNumber","_quartersToHM","originalCoordinates","currentCoordinates","originalViewCoordinates","currentViewCoordinates","getEventViewCoordinates","pageX","pageY","newEventCoordinates","setTimeFromQuarters","updateEventCoordinates","distance","newDuration","deltaQuarters","deltaDays","ceil","clientWidth","methods","multiday","getEventMultiDayViewCoordinates","multiday-allday","getEventMultiDayAllDayViewCoordinates","monthly","getEventMonthlyViewCoordinates","unknown","method","pxCoordinates","maxY","minX","daysTopOffset","daysY","sgNowLine","iAttr","sgCalendarScrollViewCtrl","_getDays","_getView","_unwatchView","_unwatchDays","updateLine","sgNowLineController","_updateLine","force","nowDay","hourHeight","minuteHeight","lineElement","_addLine","updater","$lineElement","dayElement","eq"],"mappings":"CAEA,WACE,YAOA,SAASA,GAASC,GAGhB,GADAC,KAAKC,KAAKF,GACNC,KAAKE,OAASF,KAAKG,GAAI,CAEzB,GAAIC,GAAkBN,EAASO,WAAWC,OAAO,eAAgBN,KAAKE,KACtEF,MAAKO,QAAQH,IASjBN,EAASU,UAAY,KAAM,WAAY,OAAQ,aAAc,WAAY,cAAe,YAAa,MAAO,SAASC,EAAIC,EAAUC,EAAMC,EAAUC,EAAUC,EAAaC,EAAWC,GAanL,MAZAC,SAAQC,OAAOpB,GACbW,GAAIA,EACJC,SAAUA,EACVC,KAAMA,EACNN,WAAY,GAAIQ,GAASD,EAASO,WAAW,aAAe,WAAYP,EAASO,cACjFC,aAAcN,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AAQhmB,GACxB,GAAIsmB,GAAev2B,QAAQmb,QAAQ,gBAcnC,OAZIwQ,GAAe0C,cAEbpe,GAAQA,EAAK,GAAGwf,WAAW,UAAUhvB,OAASw1B,GAChD1I,EAAS8D,OAAOkF,GAGlBr1B,EAAE4B,QAAQmN,EAAM,SAASumB,GACnBA,EAAW/G,WAAW,UAAUhvB,OAASw1B,GAC3Cj2B,QAAQmb,QAAQqb,GAAYr1B,KAAK,OAAOs1B,GAAG,GAAGpF,OAAOkF,KAIpDA,EAtDT,GAAkBD,GAAdzzB,EAAQ9D,KACR4sB,EAAiB4B,EAAS3R,WAAW,uBAEzCrC,GAAO0c,OAAS,KAChB1c,EAAO6c,YAAc,KACrB7c,EAAOsc,WAAaE,EAEpBxc,EAAOkC,IAAI,WAAY,WACjB6a,GACF72B,EAASqL,OAAOwrB,KAXtBR,EAAoBna,SAAW,SAAU,WAAY,YA4DrD3b,QACGO,OAAO,oBACP+oB,UAAU,YAAagM","file":"Scheduler.services.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Calendar\n * @constructor\n * @param {object} futureCalendarData - either an object literal or a promise\n */\n function Calendar(futureCalendarData) {\n // Data is immediately available\n this.init(futureCalendarData);\n if (this.name && !this.id) {\n // Create a new calendar on the server\n var newCalendarData = Calendar.$$resource.create('createFolder', this.name);\n this.$unwrap(newCalendarData);\n }\n }\n\n /**\n * @memberof Calendar\n * @desc The factory we'll use to register with Angular\n * @returns the Calendar constructor\n */\n Calendar.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Component', 'Acl', function($q, $timeout, $log, Settings, Resource, Preferences, Component, Acl) {\n angular.extend(Calendar, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Calendar', Settings.activeUser()),\n $Preferences: Preferences,\n $Component: Component,\n $$Acl: Acl,\n activeUser: Settings.activeUser(),\n $view: null\n });\n\n return Calendar; // return constructor\n }];\n\n /**\n * @module SOGo.SchedulerUI\n * @desc Factory registration of Calendar in Angular module.\n */\n try {\n angular.module('SOGo.SchedulerUI');\n }\n catch(e) {\n angular.module('SOGo.SchedulerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.SchedulerUI')\n .value('CalendarSettings', {\n EventDragDayLength: 24 * 4, // hour quarters\n EventDragHorizontalOffset: 3 // pixels\n })\n .factory('Calendar', Calendar.$factory);\n\n /**\n * @memberof Calendar\n * @desc Return the default calendar id according to the user's defaults.\n * @returns a calendar id\n */\n Calendar.$defaultCalendar = function() {\n var defaultCalendar = Calendar.$Preferences.defaults.SOGoDefaultCalendar,\n calendar;\n\n if (defaultCalendar == 'first') {\n calendar = _.find(Calendar.$findAll(null, true), function(calendar) {\n return calendar.active;\n });\n if (calendar)\n return calendar.id;\n }\n\n return 'personal';\n };\n\n /**\n * @memberof Calendar\n * @desc Add a new calendar to the static list of calendars\n * @param {Calendar} calendar - an Calendar object instance\n */\n Calendar.$add = function(calendar) {\n // Insert new calendar at proper index\n var list, sibling, i;\n\n if (calendar.isWebCalendar)\n list = this.$webcalendars;\n else if (calendar.isSubscription)\n list = this.$subscriptions;\n else\n list = this.$calendars;\n\n sibling = _.find(list, function(o) {\n return (calendar.id == 'personal' ||\n (o.id != 'personal' &&\n o.name.localeCompare(calendar.name) === 1));\n });\n i = sibling ? _.indexOf(_.map(list, 'id'), sibling.id) : 1;\n list.splice(i, 0, calendar);\n\n this.$Preferences.ready().then(function() {\n if (Calendar.$Preferences.settings.Calendar.FoldersOrder)\n // Save list order\n Calendar.saveFoldersOrder(_.flatMap(Calendar.$findAll(), 'id')).then(function() {\n // Refresh list of calendars to fetch links associated to new calendar\n Calendar.$reloadAll();\n });\n });\n };\n\n /**\n * @memberof Calendar\n * @desc Set or get the list of calendars. Will instanciate a new Calendar object for each item.\n * @param {object[]} [data] - the metadata of the calendars\n * @param {bool} [writable] - if true, returns only the list of writable calendars\n * @returns the list of calendars\n */\n Calendar.$findAll = function(data, writable) {\n var _this = this;\n if (data) {\n this.$calendars = [];\n this.$subscriptions = [];\n this.$webcalendars = [];\n // Instanciate Calendar objects\n angular.forEach(data, function(o, i) {\n var calendar = new Calendar(o);\n if (calendar.isWebCalendar)\n _this.$webcalendars.push(calendar);\n else if (calendar.isSubscription)\n _this.$subscriptions.push(calendar);\n else\n _this.$calendars.push(calendar);\n });\n }\n else if (angular.isUndefined(this.$calendars)) {\n this.$calendars = [];\n this.$subscriptions = [];\n this.$webcalendars = [];\n return Calendar.$$resource.fetch('calendarslist').then(function(data) {\n return Calendar.$findAll(data.calendars, writable);\n });\n }\n\n if (writable) {\n return _.union(this.$calendars, _.filter(this.$subscriptions, function(calendar) {\n return calendar.isOwned || calendar.acls.objectCreator;\n }));\n }\n\n return _.union(this.$calendars, this.$subscriptions, this.$webcalendars);\n };\n\n /**\n * @memberof Calendar\n * @desc Reload the list of known calendars.\n */\n Calendar.$reloadAll = function() {\n var _this = this;\n\n Calendar.$$resource.fetch('calendarslist').then(function(data) {\n _.forEach(data.calendars, function(calendarData) {\n var group, calendar;\n\n if (calendarData.isWebCalendar)\n group = _this.$webcalendars;\n else if (calendarData.isSubscription)\n group = _this.$subscriptions;\n else\n group = _this.$calendars;\n\n calendar = _.find(group, function(o) { return o.id == calendarData.id; });\n if (calendar)\n calendar.init(calendarData);\n });\n });\n };\n\n /**\n * @memberof Calendar\n * @desc Find a calendar among local instances (personal calendars, subscriptions and Web calendars).\n * @param {string} id - the calendar ID\n * @returns an object literal of the matching Calendar instance\n */\n Calendar.$get = function(id) {\n var calendar;\n\n calendar = _.find(Calendar.$calendars, function(o) { return o.id == id; });\n if (!calendar)\n calendar = _.find(Calendar.$subscriptions, function(o) { return o.id == id; });\n if (!calendar)\n calendar = _.find(Calendar.$webcalendars, function(o) { return o.id == id; });\n\n return calendar;\n };\n\n /**\n * @memberof Calendar\n * @desc Find a calendar among local instances (personal calendars, subscriptions and Web calendars).\n * @param {string} id - the calendar ID\n * @returns an object literal of the matching Calendar instance\n */\n Calendar.$getIndex = function(id) {\n var i;\n\n i = _.indexOf(_.map(Calendar.$calendars, 'id'), id);\n if (i < 0)\n i = _.indexOf(_.map(Calendar.$subscriptions, 'id'), id);\n if (i < 0)\n i = _.indexOf(_.map(Calendar.$webcalendars, 'id'), id);\n\n return i;\n };\n\n /**\n * @memberOf Calendar\n * @desc Subscribe to another user's calendar and add it to the list of calendars.\n * @param {string} uid - user id\n * @param {string} path - path of folder for specified user\n * @returns a promise of the HTTP query result\n */\n Calendar.$subscribe = function(uid, path) {\n var _this = this;\n return Calendar.$$resource.userResource(uid).fetch(path, 'subscribe').then(function(calendarData) {\n var calendar = new Calendar(angular.extend({ active: 1 }, calendarData));\n if (!_.find(_this.$subscriptions, function(o) {\n return o.id == calendarData.id;\n })) {\n Calendar.$add(calendar);\n }\n return calendar;\n });\n };\n\n /**\n * @memberOf Calendar\n * @desc Subscribe to a remote Web calendar\n * @param {string} url - URL of .ics file\n * @returns a promise of the HTTP query result\n */\n Calendar.$addWebCalendar = function(url) {\n var _this = this,\n d = Calendar.$q.defer();\n\n if (_.find(_this.$webcalendars, function(o) {\n return o.urls.webCalendarURL == url;\n })) {\n // Already subscribed\n d.reject();\n }\n else {\n Calendar.$$resource.post(null, 'addWebCalendar', { url: url }).then(function(calendarData) {\n angular.extend(calendarData, {\n isWebCalendar: true,\n isEditable: true,\n isRemote: false,\n owner: Calendar.activeUser.login,\n urls: { webCalendarURL: url }\n });\n var calendar = new Calendar(calendarData);\n Calendar.$$resource.fetch(calendar.id, 'reload').then(function(data) {\n // TODO: show a toast of the reload status\n Calendar.$log.debug(JSON.stringify(data, undefined, 2));\n Calendar.$add(calendar);\n d.resolve();\n }, function(response) {\n if (response.status == 401) {\n // Web calendar requires authentication\n d.resolve(calendar);\n }\n else {\n d.reject();\n }\n });\n }, d.reject);\n }\n\n return d.promise;\n };\n\n /**\n * @function reloadWebCalendars\n * @memberof Calendar\n * @desc Reload all Web calendars\n * @return a promise combining the results of all HTTP operations\n */\n Calendar.reloadWebCalendars = function() {\n var promises = [];\n\n _.forEach(this.$webcalendars, function(calendar) {\n var promise = Calendar.$$resource.fetch(calendar.id, 'reload');\n promise.then(function(data) {\n calendar.$error = false;\n }, function(response) {\n calendar.$error = l(response.statusText);\n });\n promises.push(promise);\n });\n\n return Calendar.$q.all(promises);\n };\n\n /**\n * @function $deleteComponents\n * @memberof Calendar\n * @desc Delete multiple components from calendar.\n * @return a promise of the HTTP operation\n */\n Calendar.$deleteComponents = function(components) {\n var _this = this, calendars = {}, promises = [];\n\n _.forEach(components, function(component) {\n if (!angular.isDefined(calendars[component.pid]))\n calendars[component.pid] = [];\n calendars[component.pid].push(component.id);\n });\n\n _.forEach(calendars, function(uids, pid) {\n promises.push(Calendar.$$resource.post(pid, 'batchDelete', {uids: uids}));\n });\n\n return Calendar.$q.all(promises);\n };\n\n /**\n * @function saveFoldersOrder\n * @desc Save to the user's settings the current calendars order.\n * @param {string[]} folders - the folders IDs\n * @returns a promise of the HTTP operation\n */\n Calendar.saveFoldersOrder = function(folders) {\n return this.$$resource.post(null, 'saveFoldersOrder', { folders: folders }).then(function() {\n Calendar.$Preferences.settings.Calendar.FoldersOrder = folders;\n if (!folders)\n // Calendars order was reset; reload list\n return Calendar.$$resource.fetch('calendarslist').then(function(data) {\n return Calendar.$findAll(data.calendars);\n });\n });\n };\n\n /**\n * @function init\n * @memberof Calendar.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of calendar\n */\n Calendar.prototype.init = function(data) {\n this.color = this.color || '#AAAAAA';\n this.active = 1;\n angular.extend(this, data);\n if (this.id) {\n this.$acl = new Calendar.$$Acl('Calendar/' + this.id);\n }\n // Add 'isOwned' and 'isSubscription' attributes based on active user (TODO: add it server-side?)\n this.isOwned = Calendar.activeUser.isSuperUser || this.owner == Calendar.activeUser.login;\n this.isSubscription = !this.isRemote && this.owner != Calendar.activeUser.login;\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function $id\n * @memberof Calendar.prototype\n * @desc Resolve the calendar id.\n * @returns a promise of the calendar id\n */\n Calendar.prototype.$id = function() {\n if (this.id) {\n // Object already unwrapped\n return Calendar.$q.when(this.id);\n }\n else {\n // Wait until object is unwrapped\n return this.$futureCalendarData.then(function(calendar) {\n return calendar.id;\n });\n }\n };\n\n /**\n * @function getClassName\n * @memberof Calendar.prototype\n * @desc Return the calendar CSS class name based on its ID.\n * @returns a string representing the foreground CSS class name\n */\n Calendar.prototype.getClassName = function(base) {\n if (angular.isUndefined(base))\n base = 'fg';\n return base + '-folder' + this.id;\n };\n\n /**\n * @function $rename\n * @memberof Calendar.prototype\n * @desc Rename the calendar and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$rename = function() {\n var _this = this,\n i,\n calendars;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Calendar.$q.when();\n }\n\n if (this.isWebCalendar)\n calendars = Calendar.$webcalendars;\n else if (this.isSubscription)\n calendars = Calendar.$subscriptions;\n else\n calendars = Calendar.$calendars;\n\n i = _.indexOf(_.map(calendars, 'id'), this.id);\n if (i > -1) {\n return this.$save().then(function() {\n calendars.splice(i, 1);\n Calendar.$add(_this);\n });\n }\n else {\n return Calendar.$q.reject();\n }\n };\n\n /**\n * @function $delete\n * @memberof Calendar.prototype\n * @desc Delete the calendar from the server and the static list of calendars.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$delete = function() {\n var _this = this,\n list,\n promise;\n\n if (this.isSubscription) {\n promise = Calendar.$$resource.fetch(this.id, 'unsubscribe');\n list = Calendar.$subscriptions;\n }\n else {\n promise = Calendar.$$resource.remove(this.id);\n if (this.isWebCalendar)\n list = Calendar.$webcalendars;\n else\n list = Calendar.$calendars;\n }\n\n return promise.then(function() {\n var i = _.indexOf(_.map(list, 'id'), _this.id);\n list.splice(i, 1);\n });\n };\n\n /**\n * @function $reset\n * @memberof Calendar.prototype\n * @desc Reset the original state the calendar's data.\n */\n Calendar.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$') {\n delete _this[key];\n }\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Calendar.prototype\n * @desc Save the calendar properties to the server.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$save = function() {\n var _this = this;\n\n return Calendar.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n return data;\n }, function(data) {\n Calendar.$log.error(JSON.stringify(data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return data;\n });\n };\n\n /**\n * @function setCredentials\n * @memberof Calendar.prototype\n * @desc Set the credentials for a Web calendar that requires authentication\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.setCredentials = function(username, password) {\n var _this = this,\n d = Calendar.$q.defer();\n\n Calendar.$$resource.post(this.id, 'set-credentials', { username: username, password: password }).then(function() {\n Calendar.$$resource.fetch(_this.id, 'reload').then(function(data) {\n Calendar.$add(_this);\n d.resolve();\n }, function(response) {\n if (response.status == 401) {\n // Authentication failed\n d.reject(l('Wrong username or password'));\n }\n else {\n d.reject(response.statusText);\n }\n });\n }, d.reject);\n\n return d.promise;\n };\n\n /**\n * @function export\n * @memberof Calendar.prototype\n * @desc Export the calendar\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.export = function() {\n return Calendar.$$resource.download(this.id + '.ics', 'export', null, {type: 'application/octet-stream'});\n };\n\n /**\n * @function $setActivation\n * @memberof Calendar.prototype\n * @desc Either activate or deactivate the calendar.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$setActivation = function() {\n return Calendar.$$resource.fetch(this.id, (this.active?'':'de') + 'activateFolder');\n };\n\n /**\n * @function $getComponent\n * @memberof Calendar.prototype\n * @desc Fetch a component attributes from the server.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$getComponent = function(componentId, recurrenceId) {\n return Calendar.$Component.$find(this.id, componentId, recurrenceId);\n };\n\n /**\n * @function $unwrap\n * @memberof Calendar.prototype\n * @desc Unwrap a promise\n * @param {promise} futureCalendarData - a promise of the Calendar's data\n */\n Calendar.prototype.$unwrap = function(futureCalendarData) {\n var _this = this;\n\n // Expose and resolve the promise\n this.$futureCalendarData = futureCalendarData.then(function(data) {\n return Calendar.$timeout(function() {\n // Extend Calendar instance with received data\n _this.init(data);\n return _this;\n });\n }, function(data) {\n _this.isError = true;\n if (angular.isObject(data)) {\n Calendar.$timeout(function() {\n angular.extend(_this, data);\n });\n }\n });\n };\n\n /**\n * @function $omit\n * @memberof Calendar.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Calendar instance\n */\n Calendar.prototype.$omit = function() {\n var calendar = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key[0] != '$') {\n calendar[key] = value;\n }\n });\n return calendar;\n };\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Component\n * @constructor\n * @param {object} futureComponentData - either an object literal or a promise\n */\n function Component(futureComponentData) {\n // Data is immediately available\n if (typeof futureComponentData.then !== 'function') {\n this.init(futureComponentData);\n if (this.pid && !this.id) {\n // Prepare for the creation of a new component;\n // Get UID from the server.\n var newComponentData = Component.$$resource.newguid(this.pid);\n this.$unwrap(newComponentData);\n this.isNew = true;\n }\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureComponentData);\n }\n }\n\n /**\n * @memberof Component\n * @desc The factory we'll use to register with Angular\n * @returns the Component constructor\n */\n Component.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgComponent_STATUS', 'Preferences', 'Card', 'Gravatar', 'Resource', function($q, $timeout, $log, Settings, Component_STATUS, Preferences, Card, Gravatar, Resource) {\n angular.extend(Component, {\n STATUS: Component_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $Preferences: Preferences,\n $Card: Card,\n $gravatar: Gravatar,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Calendar', Settings.activeUser()),\n timeFormat: \"%H:%M\",\n // Filter parameters common to events and tasks\n $query: { value: '', search: 'title_Category_Location' },\n // Filter paramaters specific to events\n $queryEvents: { sort: 'start', asc: 1, filterpopup: 'view_next7' },\n // Filter parameters specific to tasks\n $queryTasks: { sort: 'status', asc: 1, filterpopup: 'view_incomplete' },\n $refreshTimeout: null,\n $ghost: {}\n });\n Preferences.ready().then(function() {\n // Initialize filter parameters from user's settings\n if (Preferences.settings.Calendar.EventsFilterState)\n Component.$queryEvents.filterpopup = Preferences.settings.Calendar.EventsFilterState;\n if (Preferences.settings.Calendar.TasksFilterState)\n Component.$queryTasks.filterpopup = Preferences.settings.Calendar.TasksFilterState;\n if (Preferences.settings.Calendar.EventsSortingState) {\n Component.$queryEvents.sort = Preferences.settings.Calendar.EventsSortingState[0];\n Component.$queryEvents.asc = parseInt(Preferences.settings.Calendar.EventsSortingState[1]);\n }\n if (Preferences.settings.Calendar.TasksSortingState) {\n Component.$queryTasks.sort = Preferences.settings.Calendar.TasksSortingState[0];\n Component.$queryTasks.asc = parseInt(Preferences.settings.Calendar.TasksSortingState[1]);\n }\n Component.$queryTasks.show_completed = parseInt(Preferences.settings.ShowCompletedTasks);\n // Initialize categories from user's defaults\n Component.$categories = Preferences.defaults.SOGoCalendarCategoriesColors;\n // Initialize time format from user's defaults\n if (Preferences.defaults.SOGoTimeFormat) {\n Component.timeFormat = Preferences.defaults.SOGoTimeFormat;\n }\n });\n\n return Component; // return constructor\n }];\n\n /**\n * @module SOGo.SchedulerUI\n * @desc Factory registration of Component in Angular module.\n */\n try {\n angular.module('SOGo.SchedulerUI');\n }\n catch(e) {\n angular.module('SOGo.SchedulerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.SchedulerUI')\n .constant('sgComponent_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Component', Component.$factory);\n\n /**\n * @function $selectedCount\n * @memberof Component\n * @desc Return the number of events or tasks selected by the user.\n * @returns the number of selected events or tasks\n */\n Component.$selectedCount = function() {\n var count;\n\n count = 0;\n if (Component.$events) {\n count += (_.filter(Component.$events, function(event) { return event.selected; })).length;\n }\n if (Component.$tasks) {\n count += (_.filter(Component.$tasks, function(task) { return task.selected; })).length;\n }\n return count;\n };\n\n /**\n * @function $startRefreshTimeout\n * @memberof Component\n * @desc Starts the refresh timeout for the current selected component type, for all calendars\n */\n Component.$startRefreshTimeout = function(type) {\n var _this = this;\n\n if (Component.$refreshTimeout)\n Component.$timeout.cancel(Component.$refreshTimeout);\n\n Component.$Preferences.ready().then(function() {\n // Restart the refresh timer, if needed\n var refreshViewCheck = Component.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Component.$filter, type);\n Component.$refreshTimeout = Component.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Component\n * @returns true if the components list is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Component.$isLoading = function() {\n return Component.$loaded == Component.STATUS.LOADING;\n };\n\n /**\n * @function $filter\n * @memberof Component\n * @desc Search for components matching some criterias\n * @param {string} type - either 'events' or 'tasks'\n * @param {object} [options] - additional options to the query\n * @returns a collection of Components instances\n */\n Component.$filter = function(type, options) {\n var _this = this,\n now = new Date(),\n day = now.getDate(),\n month = now.getMonth() + 1,\n year = now.getFullYear(),\n queryKey = '$query' + type.capitalize(),\n params = {\n day: '' + year + (month < 10?'0':'') + month + (day < 10?'0':'') + day,\n };\n\n Component.$startRefreshTimeout(type);\n\n return this.$Preferences.ready().then(function() {\n var futureComponentData,\n dirty = false,\n otherType;\n\n angular.extend(_this.$query, params);\n\n if (options) {\n _.forEach(_.keys(options), function(key) {\n // Query parameters common to events and tasks are compared\n dirty |= (_this.$query[key] && options[key] != Component.$query[key]);\n if (key == 'reload' && options[key])\n dirty = true;\n // Update either the common parameters or the type-specific parameters\n else if (angular.isDefined(_this.$query[key]))\n _this.$query[key] = options[key];\n else\n _this[queryKey][key] = options[key];\n });\n }\n\n // Perform query with both common and type-specific parameters\n futureComponentData = _this.$$resource.fetch(null, type + 'list',\n angular.extend(_this[queryKey], _this.$query));\n\n // Invalidate cached results of other type if $query has changed\n otherType = (type == 'tasks')? '$events' : '$tasks';\n if (dirty) {\n delete Component[otherType];\n Component.$log.debug('force reload of ' + otherType);\n }\n\n return _this.$unwrapCollection(type, futureComponentData);\n });\n };\n\n /**\n * @function $find\n * @desc Fetch a component from a specific calendar.\n * @param {string} calendarId - the calendar ID\n * @param {string} componentId - the component ID\n * @param {string} [occurrenceId] - the component ID\n * @see {@link Calendar.$getComponent}\n */\n Component.$find = function(calendarId, componentId, occurrenceId) {\n var futureComponentData, path = [calendarId, componentId];\n\n if (occurrenceId)\n path.push(occurrenceId);\n\n futureComponentData = this.$$resource.fetch(path.join('/'), 'view');\n\n return new Component(futureComponentData);\n };\n\n /**\n * @function filterCategories\n * @desc Search for categories matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Component.filterCategories = function(query) {\n var re = new RegExp(query, 'i');\n return _.filter(_.keys(Component.$categories), function(category) {\n return category.search(re) != -1;\n });\n };\n\n /**\n * @function saveSelectedList\n * @desc Save to the user's settings the currently selected list.\n * @param {string} componentType - either \"events\" or \"tasks\"\n * @returns a promise of the HTTP operation\n */\n Component.saveSelectedList = function(componentType) {\n return this.$$resource.post(null, 'saveSelectedList', { list: componentType + 'ListView' });\n };\n\n /**\n * @function $eventsBlocksForView\n * @desc Events blocks for a specific week\n * @param {string} view - Either 'day' or 'week'\n * @param {Date} type - Date of any day of the desired period\n * @returns a promise of a collection of objects describing the events blocks\n */\n Component.$eventsBlocksForView = function(view, date) {\n var _this = this;\n\n return Component.$Preferences.ready().then(function(data) {\n var firstDayOfWeek, viewAction, startDate, endDate, params;\n firstDayOfWeek = Component.$Preferences.defaults.SOGoFirstDayOfWeek;\n\n if (view == 'day') {\n viewAction = 'dayView';\n startDate = endDate = date;\n }\n else if (view == 'multicolumnday') {\n viewAction = 'multicolumndayView';\n startDate = endDate = date;\n }\n else if (view == 'week') {\n viewAction = 'weekView';\n startDate = date.beginOfWeek(firstDayOfWeek);\n endDate = new Date();\n endDate.setTime(startDate.getTime());\n endDate.addDays(6);\n }\n else if (view == 'month') {\n viewAction = 'monthView';\n startDate = date;\n startDate.setDate(1);\n startDate = startDate.beginOfWeek(firstDayOfWeek);\n endDate = new Date();\n endDate.setTime(date.getTime());\n endDate.setMonth(endDate.getMonth() + 1);\n endDate.addDays(-1);\n endDate = endDate.endOfWeek(firstDayOfWeek);\n }\n return _this.$eventsBlocks(viewAction, startDate, endDate);\n });\n };\n\n /**\n * @function $eventsBlocks\n * @desc Events blocks for a specific view and period\n * @param {string} view - Either 'day', 'multicolumnday', 'week' or 'month'\n * @param {Date} startDate - period's start date\n * @param {Date} endDate - period's end date\n * @returns a promise of a collection of objects describing the events blocks\n */\n Component.$eventsBlocks = function(view, startDate, endDate) {\n var params, futureComponentData, i, j, dayDates = [], dayNumbers = [],\n deferred = Component.$q.defer();\n\n params = { view: view.toLowerCase(), sd: startDate.getDayString(), ed: endDate.getDayString() };\n futureComponentData = this.$$resource.fetch(null, 'eventsblocks', params);\n futureComponentData.then(function(views) {\n var reduceComponent, associateComponent;\n\n reduceComponent = function(objects, eventData, i) {\n var componentData = _.zipObject(this.eventsFields, eventData),\n start = new Date(componentData.c_startdate * 1000),\n component;\n componentData.hour = start.getHourString();\n componentData.blocks = [];\n component = new Component(componentData);\n // Filter out categories for which there's no associated color\n component.categories = _.filter(component.categories, function(name) {\n return Component.$Preferences.defaults.SOGoCalendarCategoriesColors[name];\n });\n objects.push(component);\n return objects;\n };\n\n associateComponent = function(block) {\n this[block.nbr].blocks.push(block); // Associate block to component\n block.component = this[block.nbr]; // Associate component to block\n block.isFirst = (this[block.nbr].blocks.length == 1);\n };\n\n Component.$views = [];\n Component.$timeout(function() {\n _.forEach(views, function(data, viewIndex) {\n var components = [], blocks = {}, allDayBlocks = {}, viewData;\n\n // Change some attributes names\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_folder'), 1, 'pid');\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_name'), 1, 'id');\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_recurrence_id'), 1, 'occurrenceId');\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_title'), 1, 'summary');\n\n // Instantiate Component objects\n _.reduce(data.events, _.bind(reduceComponent, data), components);\n\n // Associate Component objects to blocks positions\n _.forEach(_.flatten(data.blocks), _.bind(associateComponent, components));\n\n // Associate Component objects to all-day blocks positions\n _.forEach(_.flatten(data.allDayBlocks), _.bind(associateComponent, components));\n\n // Build array of dates\n if (dayDates.length === 0) {\n dayDates = _.flatMap(data.days, 'date');\n dayNumbers = _.flatMap(data.days, 'number');\n }\n\n // Convert array of blocks to an object literal with date strings as keys\n for (i = 0; i < data.blocks.length; i++) {\n for (j = 0; j < data.blocks[i].length; j++) {\n data.blocks[i][j].dayIndex = i + (viewIndex * data.blocks.length);\n data.blocks[i][j].dayNumber = dayNumbers[i];\n }\n blocks[dayDates[i]] = data.blocks[i];\n }\n\n // Convert array of all-day blocks to object with days as keys\n for (i = 0; i < data.allDayBlocks.length; i++) {\n for (j = 0; j < data.allDayBlocks[i].length; j++) {\n data.allDayBlocks[i][j].dayIndex = i + (viewIndex * data.allDayBlocks.length);\n data.allDayBlocks[i][j].dayNumber = dayNumbers[i];\n }\n allDayBlocks[dayDates[i]] = data.allDayBlocks[i];\n }\n\n // \"blocks\" is now an object literal with the following structure:\n // { day: [\n // { start: number,\n // length: number,\n // siblings: number,\n // realSiblings: number,\n // position: number,\n // nbr: number,\n // component: Component },\n // .. ],\n // .. }\n //\n // Where day is a string with format YYYYMMDD\n\n Component.$log.debug('blocks ready (' + _.flatten(data.blocks).length + ')');\n Component.$log.debug('all day blocks ready (' + _.flatten(data.allDayBlocks).length + ')');\n\n // Save the blocks to the object model\n viewData = { blocks: blocks, allDayBlocks: allDayBlocks };\n if (data.id && data.calendarName) {\n // The multicolumnday view also includes calendar information\n viewData.id = data.id;\n viewData.calendarName = data.calendarName;\n }\n Component.$views.push(viewData);\n });\n\n deferred.resolve(Component.$views);\n });\n }, deferred.reject);\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapCollection\n * @desc Unwrap a promise and instanciate new Component objects using received data.\n * @param {string} type - either 'events' or 'tasks'\n * @param {promise} futureComponentData - a promise of the components' metadata\n * @returns a promise of the HTTP operation\n */\n Component.$unwrapCollection = function(type, futureComponentData) {\n var _this = this,\n components = [];\n\n // Components list is not loaded yet\n Component.$loaded = Component.STATUS.DELAYED_LOADING;\n Component.$timeout(function() {\n if (Component.$loaded != Component.STATUS.LOADED)\n Component.$loaded = Component.STATUS.LOADING;\n }, Component.STATUS.DELAYED_MS);\n\n return futureComponentData.then(function(data) {\n return Component.$timeout(function() {\n var fields = _.invokeMap(data.fields, 'toLowerCase');\n fields.splice(_.indexOf(fields, 'c_folder'), 1, 'pid');\n fields.splice(_.indexOf(fields, 'c_name'), 1, 'id');\n fields.splice(_.indexOf(fields, 'c_recurrence_id'), 1, 'occurrenceId');\n\n // Instanciate Component objects\n _.reduce(data[type], function(components, componentData, i) {\n var data = _.zipObject(fields, componentData), component;\n component = new Component(data);\n // Filter out categories for which there's no associated color\n component.categories = _.filter(component.categories, function(name) {\n return Component.$Preferences.defaults.SOGoCalendarCategoriesColors[name];\n });\n components.push(component);\n return components;\n }, components);\n\n Component.$log.debug('list of ' + type + ' ready (' + components.length + ')');\n\n // Save the list of components to the object model\n Component['$' + type] = components;\n\n Component.$loaded = Component.STATUS.LOADED;\n\n return components;\n });\n });\n };\n\n /**\n * @function $resetGhost\n * @desc Prepare the ghost object for the next drag by resetting appropriate attributes\n */\n Component.$resetGhost = function() {\n this.$ghost.pointerHandler = null;\n this.$ghost.component = null;\n this.$ghost.startHour = null;\n this.$ghost.endHour = null;\n };\n\n /**\n * @function $parseDate\n * @desc Parse a date string with format YYYY-MM-DDTHH:MM\n * @param {string} dateString - the string representing the date\n * @param {object} [options] - additional options (use {no_time: true} to ignore the time)\n * @returns a date object\n */\n Component.$parseDate = function(dateString, options) {\n var date, time;\n\n date = dateString.substring(0,10).split('-');\n\n if (options && options.no_time)\n return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]));\n\n time = dateString.substring(11,16).split(':');\n\n return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]),\n parseInt(time[0]), parseInt(time[1]), 0, 0);\n };\n\n /**\n * @function init\n * @memberof Component.prototype\n * @desc Extend instance with required attributes and new data.\n * @param {object} data - attributes of component\n */\n Component.prototype.init = function(data) {\n var _this = this;\n\n this.categories = [];\n this.repeat = {};\n this.alarm = { action: 'display', quantity: 5, unit: 'MINUTES', reference: 'BEFORE', relation: 'START' };\n this.status = 'not-specified';\n this.delta = 60;\n angular.extend(this, data);\n\n if (this.component == 'vevent')\n this.type = 'appointment';\n else if (this.component == 'vtodo')\n this.type = 'task';\n\n if (this.startDate) {\n if (angular.isString(this.startDate))\n // Ex: 2015-10-25T22:34:51+00:00\n this.start = Component.$parseDate(this.startDate);\n else\n // Date object\n this.start = this.startDate;\n }\n else if (this.type == 'appointment') {\n this.start = new Date();\n this.start.setMinutes(Math.round(this.start.getMinutes()/15)*15);\n }\n\n if (this.endDate) {\n this.end = Component.$parseDate(this.endDate);\n this.delta = this.start.minutesTo(this.end);\n }\n else if (this.type == 'appointment') {\n this.setDelta(this.delta);\n }\n\n if (this.dueDate)\n this.due = Component.$parseDate(this.dueDate);\n\n if (this.completedDate)\n this.completed = Component.$parseDate(this.completedDate);\n else if (this.type == 'task')\n this.completed = new Date();\n\n if (this.c_category)\n this.categories = _.invokeMap(this.c_category, 'asCSSIdentifier');\n\n // Parse recurrence rule definition and initialize default values\n this.$isRecurrent = angular.isDefined(data.repeat);\n if (this.repeat.days) {\n var byDayMask = _.find(this.repeat.days, function(o) {\n return angular.isDefined(o.occurrence);\n });\n if (byDayMask) {\n if (this.repeat.frequency == 'yearly')\n this.repeat.year = { byday: true };\n this.repeat.month = {\n type: 'byday',\n occurrence: byDayMask.occurrence.toString(),\n day: byDayMask.day\n };\n }\n }\n else {\n this.repeat.days = [];\n }\n if (angular.isUndefined(this.repeat.frequency))\n this.repeat.frequency = 'never';\n if (angular.isUndefined(this.repeat.interval))\n this.repeat.interval = 1;\n if (angular.isUndefined(this.repeat.month))\n this.repeat.month = { occurrence: '1', day: 'SU', type: 'bymonthday' };\n if (angular.isUndefined(this.repeat.monthdays))\n // TODO: initialize this.repeat.monthdays with month day of start date\n this.repeat.monthdays = [];\n if (angular.isUndefined(this.repeat.months))\n // TODO: initialize this.repeat.months with month of start date\n this.repeat.months = [];\n if (angular.isUndefined(this.repeat.year))\n this.repeat.year = {};\n if (this.repeat.count)\n this.repeat.end = 'count';\n else if (this.repeat.until) {\n this.repeat.end = 'until';\n this.repeat.until = Component.$parseDate(this.repeat.until, { no_time: true });\n }\n else\n this.repeat.end = 'never';\n this.$hasCustomRepeat = this.hasCustomRepeat();\n\n if (this.isNew) {\n // Set default values\n Component.$Preferences.ready().then(function() {\n var type = (_this.type == 'appointment')? 'Events' : 'Tasks';\n\n // Set default classification\n _this.classification = Component.$Preferences.defaults['SOGoCalendar' + type + 'DefaultClassification'].toLowerCase();\n\n // Set default alarm\n var units = { M: 'MINUTES', H: 'HOURS', D: 'DAYS', W: 'WEEKS' };\n var match = /-PT?([0-9]+)([MHDW])/.exec(Component.$Preferences.defaults.SOGoCalendarDefaultReminder);\n if (match) {\n _this.$hasAlarm = true;\n _this.alarm.quantity = parseInt(match[1]);\n _this.alarm.unit = units[match[2]];\n }\n\n // Set notitifications\n _this.sendAppointmentNotifications = Component.$Preferences.defaults.SOGoAppointmentSendEMailNotifications;\n });\n }\n else {\n this.$hasAlarm = angular.isDefined(data.alarm);\n }\n\n // Allow the component to be moved to a different calendar\n this.destinationCalendar = this.pid;\n\n // if (this.organizer && this.organizer.email) {\n // this.organizer.$image = Component.$gravatar(this.organizer.email, 32);\n // }\n\n // Load freebusy of attendees\n this.updateFreeBusy();\n\n this.selected = false;\n };\n\n /**\n * @function hasCustomRepeat\n * @memberof Component.prototype\n * @desc Check if the component has a custom recurrence rule.\n * @returns true if the recurrence rule requires the full recurrence editor\n */\n Component.prototype.hasCustomRepeat = function() {\n var b = angular.isDefined(this.repeat) &&\n (this.repeat.interval > 1 ||\n this.repeat.days && this.repeat.days.length > 0 ||\n this.repeat.monthdays && this.repeat.monthdays.length > 0 ||\n this.repeat.months && this.repeat.months.length > 0);\n return b;\n };\n\n /**\n * @function isEditable\n * @memberof Component.prototype\n * @desc Check if the component is editable and not an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isEditable = function() {\n return (!this.occurrenceId && !this.isReadOnly);\n };\n\n /**\n * @function isEditableOccurrence\n * @memberof Component.prototype\n * @desc Check if the component is editable and an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isEditableOccurrence = function() {\n return (this.occurrenceId && !this.isReadOnly);\n };\n\n /**\n * @function isInvitation\n * @memberof Component.prototype\n * @desc Check if the component an invitation and not an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isInvitation = function() {\n return (!this.occurrenceId && this.userHasRSVP);\n };\n\n /**\n * @function isInvitationOccurrence\n * @memberof Component.prototype\n * @desc Check if the component an invitation and an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isInvitationOccurrence = function() {\n return (this.occurrenceId && this.userHasRSVP);\n };\n\n /**\n * @function isReadOnly\n * @memberof Component.prototype\n * @desc Check if the component is not editable and not an invitation\n * @returns true or false\n */\n Component.prototype.isReadOnly = function() {\n return (this.isReadOnly && !this.userHasRSVP);\n };\n\n /**\n * @function enablePercentComplete\n * @memberof Component.prototype\n * @desc Check if the percent completion should be enabled with respect to the\n * component's type and status.\n * @returns true if the percent completion should be displayed\n */\n Component.prototype.enablePercentComplete = function() {\n return (this.type == 'task' &&\n this.status != 'not-specified' &&\n this.status != 'cancelled');\n };\n\n /**\n * @function coversFreeBusy\n * @memberof Component.prototype\n * @desc Check if a specific quarter matches the component's period\n * @returns true if the quarter covers the component's period\n */\n Component.prototype.coversFreeBusy = function(day, hour, quarter) {\n var b = (angular.isDefined(this.freebusy[day]) &&\n angular.isDefined(this.freebusy[day][hour]) &&\n this.freebusy[day][hour][quarter] == 1);\n return b;\n };\n\n /**\n * @function updateFreeBusyCoverage\n * @memberof Component.prototype\n * @desc Build a 15-minute-based representation of the component's period.\n * @returns an object literal hashed by days and hours and arrays of four 1's and 0's\n */\n Component.prototype.updateFreeBusyCoverage = function() {\n var _this = this, freebusy = {};\n\n if (this.start && this.end) {\n var roundedStart = new Date(this.start.getTime()),\n roundedEnd = new Date(this.end.getTime()),\n startQuarter = parseInt(roundedStart.getMinutes()/15 + 0.5),\n endQuarter = parseInt(roundedEnd.getMinutes()/15 + 0.5);\n roundedStart.setMinutes(15*startQuarter);\n roundedEnd.setMinutes(15*endQuarter);\n\n _.forEach(roundedStart.daysUpTo(roundedEnd), function(date, index) {\n var currentDay = date.getDate(),\n dayKey = date.getDayString(),\n hourKey;\n if (dayKey == _this.start.getDayString()) {\n hourKey = date.getHours().toString();\n freebusy[dayKey] = {};\n freebusy[dayKey][hourKey] = [];\n while (startQuarter > 0) {\n freebusy[dayKey][hourKey].push(0);\n startQuarter--;\n }\n }\n else {\n date = date.beginOfDay();\n freebusy[dayKey] = {};\n }\n while (date.getTime() < _this.end.getTime() &&\n date.getDate() == currentDay) {\n hourKey = date.getHours().toString();\n if (angular.isUndefined(freebusy[dayKey][hourKey]))\n freebusy[dayKey][hourKey] = [];\n freebusy[dayKey][hourKey].push(1);\n date.addMinutes(15);\n }\n });\n return freebusy;\n }\n };\n\n /**\n * @function updateFreeBusy\n * @memberof Component.prototype\n * @desc Update the freebusy coverage representation and the attendees freebusy information\n */\n Component.prototype.updateFreeBusy = function() {\n var _this = this;\n\n this.freebusy = this.updateFreeBusyCoverage();\n\n if (this.attendees) {\n _.forEach(this.attendees, function(attendee) {\n attendee.image = Component.$gravatar(attendee.email, 32);\n _this.updateFreeBusyAttendee(attendee);\n });\n }\n };\n\n /**\n * @function setDelta\n * @memberof Component.prototype\n * @desc Set the end time to the specified number of minutes after the start time.\n * @param {number} delta - the number of minutes\n */\n Component.prototype.setDelta = function(delta) {\n this.delta = delta;\n this.end = new Date(this.start.getTime());\n this.end.setMinutes(Math.round(this.end.getMinutes()/15)*15);\n this.end.addMinutes(this.delta);\n };\n\n /**\n * @function updateFreeBusyAttendee\n * @memberof Component.prototype\n * @desc Update the freebusy information for the component's period for a specific attendee.\n * @param {Object} card - an Card object instance of the attendee\n */\n Component.prototype.updateFreeBusyAttendee = function(attendee) {\n var params, url, days;\n if (attendee.uid) {\n params =\n {\n sday: this.start.getDayString(),\n eday: this.end.getDayString()\n };\n url = ['..', '..', attendee.uid, 'freebusy.ifb'];\n days = _.map(this.start.daysUpTo(this.end), function(day) { return day.getDayString(); });\n\n if (angular.isUndefined(attendee.freebusy))\n attendee.freebusy = {};\n\n // Fetch FreeBusy information\n Component.$$resource.fetch(url.join('/'), 'ajaxRead', params).then(function(data) {\n _.forEach(days, function(day) {\n var hour;\n\n if (angular.isUndefined(attendee.freebusy[day]))\n attendee.freebusy[day] = {};\n\n if (angular.isUndefined(data[day]))\n data[day] = {};\n\n for (var i = 0; i <= 23; i++) {\n hour = i.toString();\n if (data[day][hour])\n attendee.freebusy[day][hour] = [\n data[day][hour][\"0\"],\n data[day][hour][\"15\"],\n data[day][hour][\"30\"],\n data[day][hour][\"45\"]\n ];\n else\n attendee.freebusy[day][hour] = [0, 0, 0, 0];\n }\n });\n });\n }\n };\n\n /**\n * @function getClassName\n * @memberof Component.prototype\n * @desc Return the component CSS class name based on its container (calendar) ID.\n * @param {string} [base] - the prefix to add to the class name (defaults to \"fg\")\n * @returns a string representing the foreground CSS class name\n */\n Component.prototype.getClassName = function(base) {\n if (angular.isUndefined(base))\n base = 'fg';\n return base + '-folder' + (this.destinationCalendar || this.c_folder || this.pid);\n };\n\n /**\n * @function addAttendee\n * @memberof Component.prototype\n * @desc Add an attendee and fetch his freebusy info.\n * @param {Object} card - an Card object instance to be added to the attendees list\n */\n Component.prototype.addAttendee = function(card) {\n var _this = this, attendee, list, url, params;\n if (card) {\n if (card.$isList({expandable: true})) {\n // Decompose list members\n list = Component.$Card.$find(card.container, card.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n attendee = {\n name: ref.c_cn,\n email: ref.$preferredEmail(),\n role: 'req-participant',\n partstat: 'needs-action',\n uid: ref.c_uid\n };\n if (!_.find(_this.attendees, function(o) {\n return o.email == attendee.email;\n })) {\n // Contact is not already an attendee, add it\n attendee.image = Component.$gravatar(attendee.email, 32);\n if (_this.attendees)\n _this.attendees.push(attendee);\n else\n _this.attendees = [attendee];\n _this.updateFreeBusyAttendee(attendee);\n }\n });\n });\n }\n else {\n // Single contact\n attendee = {\n name: card.c_cn,\n email: card.$preferredEmail(),\n role: 'req-participant',\n partstat: 'needs-action',\n uid: card.c_uid\n };\n if (!_.find(this.attendees, function(o) {\n return o.email == attendee.email;\n })) {\n attendee.image = Component.$gravatar(attendee.email, 32);\n if (this.attendees)\n this.attendees.push(attendee);\n else\n this.attendees = [attendee];\n this.updateFreeBusyAttendee(attendee);\n }\n }\n }\n };\n\n /**\n * @function hasAttendee\n * @memberof Component.prototype\n * @desc Verify if one of the email addresses of a Card instance matches an attendee.\n * @param {Object} card - an Card object instance\n * @returns true if the Card matches an attendee\n */\n Component.prototype.hasAttendee = function(card) {\n var attendee = _.find(this.attendees, function(attendee) {\n return _.find(card.emails, function(email) {\n return email.value == attendee.email;\n });\n });\n return angular.isDefined(attendee);\n };\n\n /**\n * @function deleteAttendee\n * @memberof Component.prototype\n * @desc Remove an attendee from the component\n * @param {Object} attendee - an object literal defining an attendee\n */\n Component.prototype.deleteAttendee = function(attendee) {\n var index = _.findIndex(this.attendees, function(currentAttendee) {\n return currentAttendee.email == attendee.email;\n });\n this.attendees.splice(index, 1);\n };\n\n /**\n * @function canRemindAttendeesByEmail\n * @memberof Component.prototype\n * @desc Verify if the component's reminder must be send by email and if it has at least one attendee.\n * @returns true if attendees can receive a reminder by email\n */\n Component.prototype.canRemindAttendeesByEmail = function() {\n return this.alarm.action == 'email' &&\n !this.isReadOnly &&\n this.attendees && this.attendees.length > 0;\n };\n\n /**\n * @function addAttachUrl\n * @memberof Component.prototype\n * @desc Add a new attach URL if not already defined\n * @param {string} attachUrl - the URL\n * @returns the number of values in the list of attach URLs\n */\n Component.prototype.addAttachUrl = function(attachUrl) {\n if (angular.isUndefined(this.attachUrls)) {\n this.attachUrls = [{value: attachUrl}];\n }\n else {\n for (var i = 0; i < this.attachUrls.length; i++) {\n if (this.attachUrls[i].value == attachUrl) {\n break;\n }\n }\n if (i == this.attachUrls.length)\n this.attachUrls.push({value: attachUrl});\n }\n return this.attachUrls.length - 1;\n };\n\n /**\n * @function deleteAttachUrl\n * @memberof Component.prototype\n * @desc Remove an attach URL\n * @param {number} index - the URL index in the list of attach URLs\n */\n Component.prototype.deleteAttachUrl = function(index) {\n if (index > -1 && this.attachUrls.length > index) {\n this.attachUrls.splice(index, 1);\n }\n };\n\n /**\n * @function $addDueDate\n * @memberof Component.prototype\n * @desc Add a due date\n */\n Component.prototype.$addDueDate = function() {\n this.due = new Date();\n this.due.setMinutes(Math.round(this.due.getMinutes()/15)*15);\n this.dueDate = this.due.toISOString();\n };\n\n /**\n * @function $deleteDueDate\n * @memberof Component.prototype\n * @desc Delete a due date\n */\n Component.prototype.$deleteDueDate = function() {\n delete this.due;\n delete this.dueDate;\n };\n\n /**\n * @function $addStartDate\n * @memberof Component.prototype\n * @desc Add a start date\n */\n Component.prototype.$addStartDate = function() {\n this.start = new Date();\n this.start.setMinutes(Math.round(this.start.getMinutes()/15)*15);\n };\n\n /**\n * @function $deleteStartDate\n * @memberof Component.prototype\n * @desc Delete a start date\n */\n Component.prototype.$deleteStartDate = function() {\n delete this.start;\n delete this.startDate;\n };\n\n /**\n * @function $reset\n * @memberof Component.prototype\n * @desc Reset the original state the component's data.\n */\n Component.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$') {\n delete _this[key];\n }\n });\n this.init(this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $reply\n * @memberof Component.prototype\n * @desc Reply to an invitation.\n * @returns a promise of the HTTP operation\n */\n Component.prototype.$reply = function() {\n var _this = this, data, path = [this.pid, this.id];\n\n if (this.occurrenceId)\n path.push(this.occurrenceId);\n\n data = {\n reply: this.reply,\n delegatedTo: this.delegatedTo,\n alarm: this.$hasAlarm? this.alarm : {}\n };\n\n return Component.$$resource.save(path.join('/'), data, { action: 'rsvpAppointment' })\n .then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n return data;\n });\n };\n\n /**\n * @function $adjust\n * @memberof Component.prototype\n * @desc Adjust the start, day, and/or duration of the component\n * @returns a promise of the HTTP operation\n */\n Component.prototype.$adjust = function(params) {\n var path = [this.pid, this.id];\n\n if (_.every(_.values(params), function(v) { return v === 0; }))\n // No changes\n return Component.$q.when();\n\n if (this.occurrenceId)\n path.push(this.occurrenceId);\n\n Component.$log.debug('adjust ' + path.join('/') + ' ' + JSON.stringify(params));\n\n return Component.$$resource.save(path.join('/'), params, { action: 'adjust' });\n };\n\n /**\n * @function $save\n * @memberof Component.prototype\n * @desc Save the component to the server.\n * @param {object} extraAttributes - additional attributes to send to the server\n */\n Component.prototype.$save = function(extraAttributes) {\n var _this = this, options, path, component, date, dlp;\n\n component = this.$omit();\n dlp = Component.$Preferences.$mdDateLocaleProvider;\n\n // Format dates and times\n component.startDate = component.start ? component.start.format(dlp, '%Y-%m-%d') : '';\n component.startTime = component.start ? component.start.format(dlp, '%H:%M') : '';\n component.endDate = component.end ? component.end.format(dlp, '%Y-%m-%d') : '';\n component.endTime = component.end ? component.end.format(dlp, '%H:%M') : '';\n component.dueDate = component.due ? component.due.format(dlp, '%Y-%m-%d') : '';\n component.dueTime = component.due ? component.due.format(dlp, '%H:%M') : '';\n component.completedDate = component.completed ? component.completed.format(dlp, '%Y-%m-%d') : '';\n\n // Update recurrence definition depending on selections\n if (this.$hasCustomRepeat) {\n if (this.repeat.frequency == 'monthly' && this.repeat.month.type && this.repeat.month.type == 'byday' ||\n this.repeat.frequency == 'yearly' && this.repeat.year.byday) {\n // BYDAY mask for a monthly or yearly recurrence\n delete component.repeat.monthdays;\n component.repeat.days = [{ day: this.repeat.month.day, occurrence: this.repeat.month.occurrence.toString() }];\n }\n else if ((this.repeat.frequency == 'monthly' || this.repeat.frequency == 'yearly') &&\n this.repeat.month.type) {\n // montly recurrence by month days or yearly by month\n delete component.repeat.days;\n }\n }\n else if (this.repeat.frequency && this.repeat.frequency != 'never') {\n component.repeat = { frequency: this.repeat.frequency };\n }\n if (this.repeat.frequency) {\n if (this.repeat.end == 'until' && this.repeat.until)\n component.repeat.until = this.repeat.until.stringWithSeparator('-');\n else if (this.repeat.end == 'count' && this.repeat.count)\n component.repeat.count = this.repeat.count;\n else {\n delete component.repeat.until;\n delete component.repeat.count;\n }\n }\n else {\n delete component.repeat;\n }\n\n // Check status\n if (this.status == 'not-specified')\n delete component.status;\n else if (this.status != 'completed')\n delete component.completedDate;\n\n // Verify alarm\n if (this.$hasAlarm) {\n if (this.alarm.action && this.alarm.action == 'email' &&\n !(this.attendees && this.attendees.length > 0)) {\n // No attendees; email reminder must be sent to organizer only\n component.alarm.attendees = 0;\n component.alarm.organizer = 1;\n }\n }\n else {\n component.alarm = {};\n }\n\n // Build URL\n path = [this.pid, this.id];\n\n if (this.isNew)\n options = { action: 'saveAs' + this.type.capitalize() };\n\n if (this.occurrenceId)\n path.push(this.occurrenceId);\n\n angular.extend(component, extraAttributes);\n\n return Component.$$resource.save(path.join('/'), component, options)\n .then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n return data;\n });\n };\n\n /**\n * @function $delete\n * @memberof Component.prototype\n * @desc Delete the component from the server.\n * @param {boolean} occurrenceOnly - delete this occurrence only\n */\n Component.prototype.remove = function(occurrenceOnly) {\n var _this = this, path = [this.pid, this.id];\n\n if (occurrenceOnly && this.occurrenceId)\n path.push(this.occurrenceId);\n\n return Component.$$resource.remove(path.join('/'));\n };\n\n /**\n * @function $unwrap\n * @memberof Component.prototype\n * @desc Unwrap a promise.\n * @param {promise} futureComponentData - a promise of some of the Component's data\n */\n Component.prototype.$unwrap = function(futureComponentData) {\n var _this = this;\n\n // Expose the promise\n this.$futureComponentData = futureComponentData;\n\n // Resolve the promise\n this.$futureComponentData.then(function(data) {\n _this.init(data);\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n Component.$log.error(_this.error);\n });\n };\n\n /**\n * @function $omit\n * @memberof Component.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Component instance\n */\n Component.prototype.$omit = function() {\n var component = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key[0] != '$' &&\n key != 'blocks') {\n component[key] = angular.copy(value);\n }\n });\n\n return component;\n };\n\n /**\n * @function repeatDescription\n * @memberof Component.prototype\n * @desc Return a localized description of the recurrence definition\n * @return a localized string\n */\n Component.prototype.repeatDescription = function() {\n var localizedString = null;\n if (this.repeat)\n localizedString = l('repeat_' + this.repeat.frequency.toUpperCase());\n\n return localizedString;\n };\n\n /**\n * @function alarmDescription\n * @memberof Component.prototype\n * @desc Return a localized description of the reminder definition\n * @return a localized string\n */\n Component.prototype.alarmDescription = function() {\n var key, localizedString = null;\n if (this.alarm) {\n key = ['reminder' + this.alarm.quantity, this.alarm.unit, this.alarm.reference].join('_');\n localizedString = l(key);\n if (key === localizedString)\n // No localized string for this reminder definition\n localizedString = [this.alarm.quantity,\n l('reminder_' + this.alarm.unit),\n l('reminder_' + this.alarm.reference)].join(' ');\n }\n\n return localizedString;\n };\n\n /**\n * @function copyTo\n * @memberof Component.prototype\n * @desc Copy an event to a calendar\n * @param {string} calendar - a target calendar UID\n * @returns a promise of the HTTP operation\n */\n Component.prototype.copyTo = function(calendar) {\n return Component.$$resource.post(this.pid + '/' + this.id, 'copy', {destination: calendar});\n };\n\n /**\n * @function moveTo\n * @memberof Component.prototype\n * @desc Move an event to a calendar\n * @param {string} calendar - a target calendar UID\n * @returns a promise of the HTTP operation\n */\n Component.prototype.moveTo = function(calendar) {\n return Component.$$resource.post(this.pid + '/' + this.id, 'move', {destination: calendar});\n };\n\n Component.prototype.toString = function() {\n return '[Component ' + this.id + ']';\n };\n\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint loopfunc: true */\n 'use strict';\n\n /**\n * @ngInject\n */\n CalendarController.$inject = ['$scope', '$rootScope', '$state', '$stateParams', 'sgHotkeys', 'Calendar', 'Component', 'Preferences', 'stateEventsBlocks'];\n function CalendarController($scope, $rootScope, $state, $stateParams, sgHotkeys, Calendar, Component, Preferences, stateEventsBlocks) {\n var vm = this, deregisterCalendarsList, hotkeys = [];\n\n // Make the toolbar state of all-day events persistent\n if (angular.isUndefined(CalendarController.expandedAllDays))\n CalendarController.expandedAllDays = false;\n\n vm.selectedDate = $stateParams.day.asDate();\n vm.expandedAllDays = CalendarController.expandedAllDays;\n vm.toggleAllDays = toggleAllDays;\n vm.views = stateEventsBlocks;\n vm.changeDate = changeDate;\n vm.changeView = changeView;\n\n\n _registerHotkeys(hotkeys);\n\n Preferences.ready().then(function() {\n _formatDate(vm.selectedDate);\n });\n\n // Refresh current view when the list of calendars is modified\n deregisterCalendarsList = $rootScope.$on('calendars:list', updateView);\n\n $scope.$on('$destroy', function() {\n // Destroy event listener when the controller is being deactivated\n deregisterCalendarsList();\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_today'),\n description: l('Today'),\n callback: changeDate,\n args: new Date()\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_dayview'),\n description: l('Day'),\n callback: changeView,\n args: 'day'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_weekview'),\n description: l('Week'),\n callback: changeView,\n args: 'week'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_monthview'),\n description: l('Month'),\n callback: changeView,\n args: 'month'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_multicolumndayview'),\n description: l('Multicolumn Day View'),\n callback: changeView,\n args: 'multicolumnday'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'left',\n description: l('Move backward'),\n callback: _goToPeriod,\n args: -1\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'right',\n description: l('Move forward'),\n callback: _goToPeriod,\n args: +1\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n\n function _goToPeriod($event, direction) {\n var date;\n\n if ($stateParams.view == 'week') {\n date = vm.selectedDate.beginOfWeek(Preferences.defaults.SOGoFirstDayOfWeek).addDays(7 * direction);\n }\n else if ($stateParams.view == 'month') {\n date = vm.selectedDate;\n date.setDate(1);\n date.setMonth(date.getMonth() + direction);\n }\n else {\n date = vm.selectedDate.addDays(direction);\n }\n\n changeDate($event, date);\n }\n\n function _formatDate(date) {\n if ($stateParams.view == 'month') {\n date.setDate(1);\n date.setHours(12);\n date.$dateFormat = '%B %Y';\n }\n else if ($stateParams.view == 'week') {\n date.setTime(date.beginOfWeek(Preferences.defaults.SOGoFirstDayOfWeek).getTime());\n date.$dateFormat = l('Week %d').replace('%d', '%U');\n }\n else {\n date.$dateFormat = '%A';\n }\n }\n\n // Expand or collapse all-day events\n function toggleAllDays() {\n CalendarController.expandedAllDays = !CalendarController.expandedAllDays;\n vm.expandedAllDays = CalendarController.expandedAllDays;\n }\n\n function updateView() {\n // The list of calendars has changed; update the views\n // See stateEventsBlocks in Scheduler.app.js\n Component.$eventsBlocksForView($stateParams.view, $stateParams.day.asDate()).then(function(data) {\n var i, j, view;\n for (i = 0; i < data.length; i++) {\n view = data[i];\n if (vm.views[i]) {\n _.forEach(view.allDayBlocks, function(blocks, day) {\n vm.views[i].allDayBlocks[day] = blocks;\n });\n _.forEach(view.blocks, function(blocks, day) {\n vm.views[i].blocks[day] = blocks;\n });\n }\n else {\n vm.views[i] = view;\n }\n if (view.id) {\n // Note: this can't be done in Component service since it would make Component dependent on\n // the Calendar service and create a circular dependency\n vm.views[i].calendar = new Calendar({ id: view.id, name: view.calendarName });\n }\n }\n // Remove previous views\n for (j = vm.views.length; j >= i; j--)\n vm.views.splice(j, 1);\n });\n }\n\n // Change calendar's date\n function changeDate($event, newDate) {\n var date = newDate? newDate.getDayString() : angular.element($event.currentTarget).attr('date');\n if (newDate)\n _formatDate(newDate);\n $state.go('calendars.view', { day: date });\n }\n\n // Change calendar's view\n function changeView($event, view) {\n $state.go('calendars.view', { view: view });\n }\n}\n\n angular\n .module('SOGo.SchedulerUI') \n .controller('CalendarController', CalendarController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n CalendarListController.$inject = ['$rootScope', '$scope', '$timeout', '$state', '$mdDialog', 'sgHotkeys', 'sgFocus', 'Dialog', 'Preferences', 'Calendar', 'Component'];\n function CalendarListController($rootScope, $scope, $timeout, $state, $mdDialog, sgHotkeys, focus, Dialog, Preferences, Calendar, Component) {\n var vm = this, hotkeys = [];\n\n vm.component = Component;\n vm.componentType = 'events';\n vm.selectedList = 0;\n vm.selectComponentType = selectComponentType;\n vm.unselectComponents = unselectComponents;\n vm.selectAll = selectAll;\n vm.searchMode = searchMode;\n vm.toggleComponentSelection = toggleComponentSelection;\n vm.confirmDeleteSelectedComponents = confirmDeleteSelectedComponents;\n vm.openEvent = openEvent;\n vm.openTask = openTask;\n vm.newComponent = newComponent;\n vm.filterpopup = filterpopup;\n vm.filter = filter;\n vm.filteredBy = filteredBy;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.reload = reload;\n vm.cancelSearch = cancelSearch;\n vm.mode = { search: false, multiple: 0 };\n\n\n _registerHotkeys(hotkeys);\n\n // Select list based on user's settings\n Preferences.ready().then(function() {\n var type = 'events';\n if (Preferences.settings.Calendar.SelectedList == 'tasksListView') {\n vm.selectedList = 1;\n type = 'tasks';\n }\n selectComponentType(type, { reload: true });\n });\n\n // Refresh current list when the list of calendars is modified\n $rootScope.$on('calendars:list', function() {\n Component.$filter(vm.componentType, { reload: true });\n });\n\n // Update the component being dragged\n $rootScope.$on('calendar:dragend', updateComponentFromGhost);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_create_event'),\n description: l('Create a new event'),\n callback: newComponent,\n args: 'appointment'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_create_task'),\n description: l('Create a new task'),\n callback: newComponent,\n args: 'task'\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n // Switch between components tabs\n function selectComponentType(type, options) {\n if (options && options.reload || vm.componentType != type) {\n if (angular.isUndefined(Component['$' + type]))\n Component.$filter(type);\n vm.unselectComponents();\n vm.componentType = type;\n Component.saveSelectedList(type);\n }\n }\n\n function unselectComponents() {\n _.forEach(Component['$' + vm.componentType], function(component) {\n component.selected = false;\n });\n vm.mode.multiple = 0;\n }\n\n function selectAll() {\n _.forEach(Component['$' + vm.componentType], function(component) {\n component.selected = true;\n });\n vm.mode.multiple = Component['$' + vm.componentType].length;\n }\n\n function toggleComponentSelection($event, component) {\n component.selected = !component.selected;\n vm.mode.multiple += component.selected? 1 : -1;\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function confirmDeleteSelectedComponents() {\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected components?'),\n { ok: l('Delete') })\n .then(function() {\n // User confirmed the deletion\n var components = _.filter(Component['$' + vm.componentType], function(component) {\n return component.selected;\n });\n Calendar.$deleteComponents(components).then(function() {\n vm.mode.multiple = 0;\n $rootScope.$emit('calendars:list');\n });\n });\n }\n\n function openEvent($event, event) {\n openComponent($event, event, 'appointment');\n }\n\n function openTask($event, task) {\n openComponent($event, task, 'task');\n }\n\n function openComponent($event, component, type) {\n if (component.viewable) {\n // UI/Templates/SchedulerUI/UIxAppointmentViewTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskViewTemplate.wox\n var templateUrl = 'UIx' + type.capitalize() + 'ViewTemplate';\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n }\n }\n\n function newComponent($event, type, baseComponent) {\n var component;\n\n if (baseComponent) {\n component = baseComponent;\n }\n else {\n component = new Component({ pid: Calendar.$defaultCalendar(), type: type });\n }\n\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = 'UIx' + type.capitalize() + 'EditorTemplate';\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n }\n\n // Adjust component or create new component through drag'n'drop\n function updateComponentFromGhost($event) {\n var component, pointerHandler, coordinates, delta, params, calendarNumber, activeCalendars;\n\n component = Component.$ghost.component;\n pointerHandler = Component.$ghost.pointerHandler;\n\n if (component.isNew) {\n coordinates = pointerHandler.currentEventCoordinates;\n component.summary = '';\n if (component.isAllDay)\n coordinates.duration -= 96;\n component.setDelta(coordinates.duration * 15);\n newComponent(null, 'appointment', component).finally(function() {\n $timeout(function() {\n Component.$resetGhost();\n });\n });\n }\n else {\n delta = pointerHandler.currentEventCoordinates.getDelta(pointerHandler.originalEventCoordinates);\n params = {\n days: delta.dayNumber,\n start: delta.start * 15,\n duration: delta.duration * 15\n };\n if (pointerHandler.originalCalendar && delta.dayNumber !== 0) {\n // The day number actually represents the destination calendar among the active calendars\n calendarNumber = pointerHandler.currentEventCoordinates.dayNumber;\n activeCalendars = _.filter(Calendar.$findAll(), { active: 1 });\n params.destination = activeCalendars[calendarNumber].id;\n params.days = 0;\n }\n if (component.isException || !component.occurrenceId)\n // Component is an exception to a recurrence or is not recurrent;\n // Immediately perform the adjustments\n component.$adjust(params).then(function() {\n $rootScope.$emit('calendars:list');\n }, function(response) {\n onComponentAdjustError(response, component, params);\n }).finally(function() {\n $timeout(function() {\n Component.$resetGhost();\n });\n });\n else if (component.occurrenceId) {\n $mdDialog.show({\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n component: component,\n params: params\n },\n template: [\n '',\n ' ',\n '

' + l('editRepeatingItem') + '

',\n '
',\n ' ',\n ' ' + l('button_thisOccurrenceOnly') + '',\n ' ' + l('button_allOccurrences') + '',\n ' ',\n '
'\n ].join(''),\n controller: RecurrentComponentDialogController\n }).then(function() {\n $rootScope.$emit('calendars:list');\n }).finally(function() {\n $timeout(function() {\n Component.$resetGhost();\n });\n });\n }\n }\n\n /**\n * @ngInject\n */\n RecurrentComponentDialogController.$inject = ['$scope', '$mdDialog', 'component', 'params'];\n function RecurrentComponentDialogController($scope, $mdDialog, component, params) {\n $scope.updateThisOccurrence = function() {\n component.$adjust(params).then($mdDialog.hide, function(response) {\n $mdDialog.cancel().then(function() {\n onComponentAdjustError(response, component, params);\n });\n });\n };\n $scope.updateAllOccurrences = function() {\n delete component.occurrenceId;\n component.$adjust(params).then($mdDialog.hide, function(response) {\n $mdDialog.cancel().then(function() {\n onComponentAdjustError(response, component, params);\n });\n });\n };\n }\n\n function onComponentAdjustError(response, component, params) {\n if (response.status == 403 &&\n response.data && response.data.message && angular.isObject(response.data.message)) {\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxAttendeeConflictDialog',\n controller: AttendeeConflictDialogController,\n controllerAs: '$AttendeeConflictDialogController',\n locals: {\n component: component,\n params: params,\n conflictError: response.data.message\n }\n }).then(function() {\n $rootScope.$emit('calendars:list');\n });\n }\n }\n\n /**\n * @ngInject\n */\n AttendeeConflictDialogController.$inject = ['$scope', '$mdDialog', 'component', 'params', 'conflictError'];\n function AttendeeConflictDialogController($scope, $mdDialog, component, params, conflictError) {\n var vm = this;\n\n vm.conflictError = conflictError;\n vm.cancel = $mdDialog.cancel;\n vm.save = save;\n\n function save() {\n component.$adjust(angular.extend({ ignoreConflicts: true }, params)).then($mdDialog.hide);\n }\n }\n }\n\n function filterpopup() {\n return Component['$query' + vm.componentType.capitalize()].filterpopup;\n }\n\n function filter(filterpopup) {\n Component.$filter(vm.componentType, { filterpopup: filterpopup });\n }\n\n function filteredBy(filterpopup) {\n return Component['$query' + vm.componentType.capitalize()].filterpopup == filterpopup;\n }\n\n function sort(field) {\n Component.$filter(vm.componentType, { sort: field });\n }\n\n function sortedBy(field) {\n return Component['$query' + vm.componentType.capitalize()].sort == field;\n }\n\n function reload() {\n Calendar.reloadWebCalendars().finally(function() {\n $rootScope.$emit('calendars:list');\n });\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n Component.$filter(vm.componentType, { value: '' });\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .controller('CalendarListController', CalendarListController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n CalendarsController.$inject = ['$rootScope', '$scope', '$window', '$mdDialog', '$log', '$mdToast', 'FileUploader', 'sgFocus', 'Dialog', 'sgSettings', 'Preferences', 'Calendar', 'User', 'stateCalendars'];\n function CalendarsController($rootScope, $scope, $window, $mdDialog, $log, $mdToast, FileUploader, focus, Dialog, Settings, Preferences, Calendar, User, stateCalendars) {\n var vm = this;\n\n vm.activeUser = Settings.activeUser;\n vm.service = Calendar;\n vm.newCalendar = newCalendar;\n vm.addWebCalendar = addWebCalendar;\n vm.confirmDelete = confirmDelete;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.renameFolder = renameFolder;\n vm.share = share;\n vm.importCalendar = importCalendar;\n vm.showOnly = showOnly;\n vm.showAll = showAll;\n vm.showLinks = showLinks;\n vm.showProperties = showProperties;\n vm.subscribeToFolder = subscribeToFolder;\n // vm.today = today;\n\n vm.filter = { name: '' };\n vm.sortableMode = false;\n vm.toggleSortableMode = toggleSortableMode;\n vm.resetSort = resetSort;\n vm.sortableCalendars = {\n scrollableContainer: '#sidenav-content',\n containment: 'md-list',\n orderChanged: _sortableEnd,\n accept: _sortableAccept\n };\n\n Preferences.ready().then(function() {\n vm.categories = _.map(Preferences.defaults.SOGoCalendarCategories, function(name) {\n return { id: name.asCSSIdentifier(),\n name: name,\n color: Preferences.defaults.SOGoCalendarCategoriesColors[name]\n };\n });\n });\n\n // Dispatch the event named 'calendars:list' when a calendar is activated or deactivated or\n // when the color of a calendar is changed\n $scope.$watch(\n function() {\n return _.union(\n _.map(Calendar.$calendars, function(o) { return _.pick(o, ['id', 'active', 'color']); }),\n _.map(Calendar.$subscriptions, function(o) { return _.pick(o, ['id', 'active', 'color']); }),\n _.map(Calendar.$webcalendars, function(o) { return _.pick(o, ['id', 'active', 'color']); })\n );\n },\n function(newList, oldList) {\n var commonList, ids, promises;\n\n // Identify which calendar has changed\n commonList = _.intersectionBy(newList, oldList, 'id');\n ids = _.map(_.filter(commonList, function(o) {\n var oldObject = _.find(oldList, { id: o.id });\n return !_.isEqual(o, oldObject);\n }), 'id');\n promises = [];\n\n if (ids.length > 0) {\n $log.debug(ids.join(', ') + ' changed');\n _.forEach(ids, function(id) {\n var calendar = Calendar.$get(id);\n promises.push(calendar.$setActivation());\n });\n }\n if (promises.length > 0 || commonList.length != newList.length || commonList.length != oldList.length)\n Calendar.$q.all(promises).then(function() {\n $rootScope.$emit('calendars:list');\n });\n },\n true // compare for object equality\n );\n\n /**\n * Only allow to sort items within the same list.\n */\n function _sortableAccept(sourceItemHandleScope, destSortableScope, destItemScope) {\n return sourceItemHandleScope.sortableScope.element[0] == destSortableScope.element[0];\n }\n\n function _sortableEnd() {\n Calendar.saveFoldersOrder(_.flatMap(Calendar.$findAll(), 'id'));\n }\n\n function toggleSortableMode() {\n vm.sortableMode = !vm.sortableMode;\n vm.filter.name = '';\n }\n\n function resetSort() {\n Calendar.saveFoldersOrder();\n }\n\n function newCalendar(ev) {\n Dialog.prompt(l('New calendar'), l('Name of the Calendar'))\n .then(function(name) {\n var calendar = new Calendar(\n {\n name: name,\n isEditable: true,\n isRemote: false,\n owner: UserLogin\n }\n );\n calendar.$id().then(function() {\n Calendar.$add(calendar);\n });\n });\n }\n\n function addWebCalendar() {\n Dialog.prompt(l('Subscribe to a web calendar...'), l('URL of the Calendar'), {inputType: 'url'})\n .then(function(url) {\n Calendar.$addWebCalendar(url).then(function(calendar) {\n if (angular.isObject(calendar)) {\n // Web calendar requires HTTP authentication\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: 'UIxWebCalendarAuthDialog',\n controller: WebCalendarAuthDialogController,\n controllerAs: '$WebCalendarAuthDialogController',\n locals: {\n url: url,\n calendar: calendar\n }\n });\n }\n });\n });\n\n /**\n * @ngInject\n */\n WebCalendarAuthDialogController.$inject = ['scope', '$mdDialog', 'url', 'calendar'];\n function WebCalendarAuthDialogController(scope, $mdDialog, url, calendar) {\n var vm = this,\n parts = url.split(\"/\"),\n hostname = parts[2];\n\n vm.title = l(\"Please identify yourself to %{0}\").formatted(hostname);\n vm.authenticate = function(form) {\n if (form.$valid || !form.$error.required) {\n calendar.setCredentials(vm.username, vm.password).then(function(message) {\n $mdDialog.hide();\n }, function(reason) {\n form.password.$setValidity('credentials', false);\n });\n }\n };\n vm.cancel = function() {\n $mdDialog.cancel();\n };\n }\n }\n\n function confirmDelete(folder) {\n if (folder.isSubscription) {\n // Unsubscribe without confirmation\n folder.$delete()\n .catch(function(data, status) {\n Dialog.alert(l('An error occured while deleting the calendar \"%{0}\".', folder.name),\n l(data.error));\n });\n }\n else {\n Dialog.confirm(l('Warning'), l('Are you sure you want to delete the calendar \"%{0}\"?', folder.name),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete()\n .catch(function(data, status) {\n Dialog.alert(l('An error occured while deleting the calendar \"%{0}\".', folder.name),\n l(data.error));\n });\n });\n }\n }\n\n function importCalendar($event, folder) {\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: 'UIxCalendarImportDialog',\n controller: CalendarImportDialogController,\n controllerAs: '$CalendarImportDialogController',\n locals: {\n folder: folder\n }\n });\n\n /**\n * @ngInject\n */\n CalendarImportDialogController.$inject = ['scope', '$mdDialog', 'folder'];\n function CalendarImportDialogController(scope, $mdDialog, folder) {\n var vm = this;\n\n vm.uploader = new FileUploader({\n url: ApplicationBaseURL + [folder.id, 'import'].join('/'),\n autoUpload: true,\n queueLimit: 1,\n filters: [{ name: filterByExtension, fn: filterByExtension }],\n onSuccessItem: function(item, response, status, headers) {\n var msg;\n\n $mdDialog.hide();\n\n if (response.imported === 0)\n msg = l('No event was imported.');\n else {\n msg = l('A total of %{0} events were imported in the calendar.', response.imported);\n $rootScope.$emit('calendars:list');\n }\n\n $mdToast.show(\n $mdToast.simple()\n .content(msg)\n .position('top right')\n .hideDelay(3000));\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('An error occurred while importing calendar.') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n }\n });\n\n vm.close = function() {\n $mdDialog.hide();\n };\n\n function filterByExtension(item) {\n var isTextFile = item.type.indexOf('text') === 0 ||\n /\\.(ics)$/.test(item.name);\n\n if (!isTextFile)\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('Select an iCalendar file (.ics).') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n\n return isTextFile;\n }\n }\n }\n\n function showOnly(calendar) {\n _.forEach(Calendar.$findAll(), function(o) {\n if (calendar.id == o.id)\n o.active = 1;\n else\n o.active = 0;\n });\n }\n\n function showAll() {\n _.forEach(Calendar.$findAll(), function(o) { o.active = 1; });\n }\n\n function showLinks(calendar) {\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: calendar.id + '/links',\n controller: LinksDialogController,\n controllerAs: 'links',\n locals: {\n calendar: calendar\n }\n });\n \n /**\n * @ngInject\n */\n LinksDialogController.$inject = ['$mdDialog', 'calendar'];\n function LinksDialogController($mdDialog, calendar) {\n var vm = this;\n vm.calendar = calendar;\n vm.close = close;\n\n function close() {\n $mdDialog.hide();\n }\n }\n }\n\n function showProperties(calendar) {\n var color = calendar.color;\n $mdDialog.show({\n templateUrl: calendar.id + '/properties',\n controller: PropertiesDialogController,\n controllerAs: 'properties',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcCalendar: calendar\n }\n }).catch(function() {\n // Restore original color when cancelling or closing the dialog\n calendar.color = color;\n });\n \n /**\n * @ngInject\n */\n PropertiesDialogController.$inject = ['$scope', '$mdDialog', 'srcCalendar'];\n function PropertiesDialogController($scope, $mdDialog, srcCalendar) {\n var vm = this;\n\n vm.calendar = new Calendar(srcCalendar.$omit());\n vm.saveProperties = saveProperties;\n vm.close = close;\n\n $scope.$watch(function() { return vm.calendar.color; }, function() {\n srcCalendar.color = vm.calendar.color;\n });\n\n function saveProperties() {\n vm.calendar.$save();\n // Refresh list instance\n srcCalendar.init(vm.calendar.$omit());\n $mdDialog.hide();\n }\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function editFolder(folder) {\n vm.calendarName = folder.name;\n vm.editMode = folder.id;\n focus('calendarName_' + folder.id);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function renameFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function share(calendar) {\n calendar.$acl.$users().then(function() {\n $mdDialog.show({\n templateUrl: calendar.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: calendar.$acl.users,\n User: User,\n folder: calendar\n }\n });\n });\n }\n\n // Callback of sgSubscribe directive\n function subscribeToFolder(calendarData) {\n $log.debug('subscribeToFolder ' + calendarData.owner + calendarData.name);\n Calendar.$subscribe(calendarData.owner, calendarData.name).then(function(data) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Successfully subscribed to calendar'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n // function today() {\n // var fragments = $window.location.hash.split('/'),\n // state = fragments[1],\n // view = fragments[2],\n // now = new Date(),\n // path = ['#', state, view, now.getDayString()];\n // $window.location = path.join('/');\n // }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .controller('CalendarsController', CalendarsController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n ComponentController.$inject = ['$rootScope', '$mdDialog', 'Calendar', 'Component', 'AddressBook', 'Alarm', 'Account', 'stateComponent'];\n function ComponentController($rootScope, $mdDialog, Calendar, Component, AddressBook, Alarm, Account, stateComponent) {\n var vm = this, component;\n\n vm.calendarService = Calendar;\n vm.service = Component;\n vm.component = stateComponent;\n vm.close = close;\n vm.cardFilter = cardFilter;\n vm.newMessageWithAllRecipients = newMessageWithAllRecipients;\n vm.newMessageWithRecipient = newMessageWithRecipient;\n vm.edit = edit;\n vm.editAllOccurrences = editAllOccurrences;\n vm.reply = reply;\n vm.replyAllOccurrences = replyAllOccurrences;\n vm.deleteOccurrence = deleteOccurrence;\n vm.deleteAllOccurrences = deleteAllOccurrences;\n vm.toggleRawSource = toggleRawSource;\n vm.copySelectedComponent = copySelectedComponent;\n vm.moveSelectedComponent = moveSelectedComponent;\n\n // Load all attributes of component\n if (angular.isUndefined(vm.component.$futureComponentData)) {\n component = Calendar.$get(vm.component.pid).$getComponent(vm.component.id, vm.component.occurrenceId);\n component.$futureComponentData.then(function() {\n vm.component = component;\n vm.organizer = [vm.component.organizer];\n });\n }\n\n function close() {\n $mdDialog.hide();\n }\n\n // Autocomplete cards for attendees\n function cardFilter($query) {\n AddressBook.$filterAll($query);\n return AddressBook.$cards;\n }\n\n function newMessageWithAllRecipients($event) {\n var recipients = _.map(vm.component.attendees, function(attendee) {\n return attendee.name + \" <\" + attendee.email + \">\";\n });\n _newMessage($event, recipients);\n }\n\n function newMessageWithRecipient($event, name, email) {\n _newMessage($event, [name + \" <\" + email + \">\"]);\n }\n\n function _newMessage($event, recipients) {\n Account.$findAll().then(function(accounts) {\n var account = _.find(accounts, function(o) {\n if (o.id === 0)\n return o;\n });\n\n // We must initialize the Account with its mailbox\n // list before proceeding with message's creation\n account.$getMailboxes().then(function(mailboxes) {\n account.$newMessage().then(function(message) {\n angular.extend(message.editable, { to: recipients, subject: vm.component.summary });\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: '../Mail/UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: account,\n stateMessage: message\n }\n });\n });\n });\n });\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function edit() {\n var type = (vm.component.component == 'vevent')? 'Appointment':'Task';\n $mdDialog.hide().then(function() {\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = 'UIx' + type + 'EditorTemplate';\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: vm.component\n }\n });\n });\n }\n\n function editAllOccurrences() {\n component = Calendar.$get(vm.component.pid).$getComponent(vm.component.id);\n component.$futureComponentData.then(function() {\n vm.component = component;\n edit();\n });\n }\n\n function reply(component) {\n var c = component || vm.component;\n\n c.$reply().then(function() {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n Alarm.getAlarms();\n });\n }\n\n function replyAllOccurrences() {\n // Retrieve master event\n component = Calendar.$get(vm.component.pid).$getComponent(vm.component.id);\n component.$futureComponentData.then(function() {\n // Propagate the participant status and alarm to the master event\n component.reply = vm.component.reply;\n component.delegatedTo = vm.component.delegatedTo;\n component.$hasAlarm = vm.component.$hasAlarm;\n component.alarm = vm.component.alarm;\n // Send reply to the server\n reply(component);\n });\n }\n\n function deleteOccurrence() {\n vm.component.remove(true).then(function() {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n });\n }\n\n function deleteAllOccurrences() {\n vm.component.remove().then(function() {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n });\n }\n\n function toggleRawSource($event) {\n Calendar.$$resource.post(vm.component.pid + '/' + vm.component.id, \"raw\").then(function(data) {\n $mdDialog.hide();\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n template: [\n '',\n ' ',\n '
',\n            '  
',\n ' ',\n ' ' + l('Close') + '',\n ' ',\n '
'\n ].join(''),\n controller: ComponentRawSourceDialogController,\n locals: { data: data }\n });\n\n /**\n * @ngInject\n */\n ComponentRawSourceDialogController.$inject = ['scope', '$mdDialog', 'data'];\n function ComponentRawSourceDialogController(scope, $mdDialog, data) {\n scope.data = data;\n scope.close = function() {\n $mdDialog.hide();\n };\n }\n });\n }\n\n function copySelectedComponent(calendar) {\n vm.component.copyTo(calendar).then(function() {\n $mdDialog.hide();\n $rootScope.$emit('calendars:list');\n });\n }\n\n function moveSelectedComponent(calendar) {\n vm.component.moveTo(calendar).then(function() {\n $mdDialog.hide();\n $rootScope.$emit('calendars:list');\n });\n }\n }\n\n /**\n * @ngInject\n */\n ComponentEditorController.$inject = ['$rootScope', '$scope', '$log', '$timeout', '$mdDialog', 'User', 'Calendar', 'Component', 'AddressBook', 'Card', 'Alarm', 'stateComponent'];\n function ComponentEditorController($rootScope, $scope, $log, $timeout, $mdDialog, User, Calendar, Component, AddressBook, Card, Alarm, stateComponent) {\n var vm = this, component, oldStartDate, oldEndDate, oldDueDate;\n\n vm.service = Calendar;\n vm.component = stateComponent;\n vm.categories = {};\n vm.showRecurrenceEditor = vm.component.$hasCustomRepeat;\n vm.toggleRecurrenceEditor = toggleRecurrenceEditor;\n vm.showAttendeesEditor = false;\n vm.toggleAttendeesEditor = toggleAttendeesEditor;\n //vm.searchText = null;\n vm.cardFilter = cardFilter;\n vm.addAttendee = addAttendee;\n vm.removeAttendee = removeAttendee;\n vm.addAttachUrl = addAttachUrl;\n vm.priorityLevel = priorityLevel;\n vm.cancel = cancel;\n vm.save = save;\n vm.attendeeConflictError = false;\n vm.attendeesEditor = {\n days: getDays(),\n hours: getHours()\n };\n vm.addStartDate = addStartDate;\n vm.addDueDate = addDueDate;\n\n // Synchronize start and end dates\n vm.adjustStartTime = adjustStartTime;\n vm.adjustEndTime = adjustEndTime;\n vm.adjustDueTime = adjustDueTime;\n\n if (vm.component.start)\n oldStartDate = new Date(vm.component.start.getTime());\n if (vm.component.end)\n oldEndDate = new Date(vm.component.end.getTime());\n if (vm.component.due)\n oldDueDate = new Date(vm.component.due.getTime());\n\n function addAttachUrl() {\n var i = vm.component.addAttachUrl('');\n focus('attachUrl_' + i);\n }\n\n function toggleRecurrenceEditor() {\n vm.showRecurrenceEditor = !vm.showRecurrenceEditor;\n vm.component.$hasCustomRepeat = vm.showRecurrenceEditor;\n }\n\n function toggleAttendeesEditor() {\n vm.showAttendeesEditor = !vm.showAttendeesEditor;\n }\n\n // Autocomplete cards for attendees\n function cardFilter($query) {\n AddressBook.$filterAll($query);\n return AddressBook.$cards;\n }\n\n function addAttendee(card) {\n if (angular.isString(card)) {\n // User pressed \"Enter\" in search field, adding a non-matching card\n if (card.isValidEmail()) {\n vm.component.addAttendee(new Card({ emails: [{ value: card }] }));\n vm.searchText = '';\n }\n }\n else {\n vm.component.addAttendee(card);\n }\n }\n\n function removeAttendee(attendee) {\n vm.component.deleteAttendee(attendee);\n if (vm.component.attendees.length === 0)\n vm.showAttendeesEditor = false;\n }\n\n function priorityLevel() {\n if (vm.component && vm.component.priority) {\n if (vm.component.priority > 5)\n return l('low');\n else if (vm.component.priority > 4)\n return l('normal');\n else\n return l('high');\n }\n }\n\n function save(form, options) {\n if (form.$valid) {\n vm.component.$save(options)\n .then(function(data) {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n Alarm.getAlarms();\n }, function(response) {\n if (response.status == 403 &&\n response.data && response.data.message &&\n angular.isObject(response.data.message))\n vm.attendeeConflictError = response.data.message;\n });\n }\n }\n\n function cancel() {\n vm.component.$reset();\n if (vm.component.isNew) {\n // Cancelling the creation of a component\n vm.component = null;\n }\n $mdDialog.cancel();\n }\n\n function getDays() {\n var days = [];\n\n if (vm.component.start && vm.component.end)\n days = vm.component.start.daysUpTo(vm.component.end);\n\n return _.map(days, function(date) {\n return { stringWithSeparator: date.stringWithSeparator(),\n getDayString: date.getDayString() };\n });\n }\n\n function getHours() {\n var hours = [];\n for (var i = 0; i <= 23; i++) {\n hours.push(i.toString());\n }\n return hours;\n }\n\n function addStartDate() {\n vm.component.$addStartDate();\n oldStartDate = new Date(vm.component.start.getTime());\n }\n\n function addDueDate() {\n vm.component.$addDueDate();\n oldDueDate = new Date(vm.component.due.getTime());\n }\n\n function adjustStartTime() {\n if (vm.component.start) {\n // Preserve the delta between the start and end dates\n var delta;\n delta = oldStartDate.valueOf() - vm.component.start.valueOf();\n if (delta !== 0) {\n oldStartDate = new Date(vm.component.start.getTime());\n if (vm.component.type === 'appointment') {\n vm.component.end = new Date(vm.component.start.getTime());\n vm.component.end.addMinutes(vm.component.delta);\n oldEndDate = new Date(vm.component.end.getTime());\n }\n updateFreeBusy();\n }\n }\n }\n\n function adjustEndTime() {\n if (vm.component.end) {\n // The end date must be after the start date\n var delta = oldEndDate.valueOf() - vm.component.end.valueOf();\n if (delta !== 0) {\n delta = vm.component.start.minutesTo(vm.component.end);\n if (delta < 0)\n vm.component.end = new Date(oldEndDate.getTime());\n else {\n vm.component.delta = delta;\n oldEndDate = new Date(vm.component.end.getTime());\n }\n updateFreeBusy();\n }\n }\n }\n\n function adjustDueTime() {\n oldDueDate = new Date(vm.component.due.getTime());\n }\n\n function updateFreeBusy() {\n vm.attendeesEditor.days = getDays();\n vm.component.updateFreeBusy();\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .controller('ComponentController', ComponentController)\n .controller('ComponentEditorController', ComponentEditorController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgCalendarDay - An element that represents a day in the calendar's view\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {string} sgDay - the day of the events to display (YYYYMMDD)\n * @param {string} sgDayString - the day in ISO8601 format (YYYY-MM-DDTHH:MM+-HH:MM)\n * @param {number} sgDayNumber - the day index within the calendar's view\n *\n * @example:\n\n \n ..\n \n */\n function sgCalendarDay() {\n return {\n restrict: 'E',\n scope: {\n day: '@sgDay',\n dayNumber: '@sgDayNumber',\n dayString: '@sgDayString',\n calendar: '@sgCalendar'\n },\n controller: sgCalendarDayController\n };\n }\n\n /**\n * @ngInject\n */\n sgCalendarDayController.$inject = ['$scope', 'Calendar'];\n function sgCalendarDayController($scope, Calendar) {\n // Expose some scope variables to the controller\n // See the sgCalendarDayTable directive\n this.day = $scope.day;\n this.dayNumber = $scope.dayNumber;\n this.dayString = $scope.dayString;\n this.calendarData = function() {\n var pid, index, activeCalendars;\n if ($scope.calendar) {\n // A calendar is associated to the day; identify its index among active calendars\n pid = $scope.calendar;\n activeCalendars = _.filter(Calendar.$findAll(), { active: 1 });\n index = _.findIndex(activeCalendars, function(calendar) {\n return calendar.id == pid;\n });\n return { pid: pid, index: index };\n }\n\n return null;\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarDay', sgCalendarDay);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarDayBlock - An event block to be displayed in a week\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {object} sgBlock - the event block definition\n * @param {function} sgClick - the function to call when clicking on a block.\n * Two variables are available: clickEvent (the event that triggered the mouse click),\n * and clickComponent (a Component object)\n *\n * @example:\n\n \n */\n sgCalendarDayBlock.$inject = ['CalendarSettings'];\n function sgCalendarDayBlock(CalendarSettings) {\n return {\n restrict: 'E',\n scope: {\n block: '=sgBlock',\n clickBlock: '&sgClick'\n },\n replace: true,\n template: template,\n link: link\n };\n\n function template(tElem, tAttrs) {\n var p = _.has(tAttrs, 'sgCalendarGhost')? '' : '::';\n\n return [\n '
',\n '
',\n // Categories color stripes\n '
',\n '
',\n // Priority\n ' {{'+p+'block.component.c_priority}}',\n // Summary\n ' {{ '+p+'block.component.summary }}',\n ' ',\n // Component is reccurent\n ' ',\n // Component has an alarm\n ' ',\n // Component is confidential\n ' ',\n // Component is private\n ' ',\n ' ',\n // Location\n '
',\n ' place {{'+p+'block.component.c_location}}',\n '
',\n '
',\n '
',\n '
{{ block.startHour }}
',\n '
{{ block.endHour }}
',\n '
'\n ].join('');\n }\n\n function link(scope, iElement, attrs) {\n var pc, left, right;\n\n if (!_.has(attrs, 'sgCalendarGhost')) {\n\n // Compute overlapping (2%)\n pc = 100 / scope.block.siblings;\n left = scope.block.position * pc;\n right = 100 - (scope.block.position + 1) * pc;\n if (pc < 100) {\n if (left > 0)\n left -= 2;\n if (right > 0)\n right -= 2;\n }\n\n // Add some padding (2%)\n if (left === 0)\n left = 2;\n if (right === 0)\n right = 2;\n\n // Set position\n iElement.css('left', left + '%');\n iElement.css('right', right + '%');\n if (!scope.block.component || !scope.block.component.c_isallday) {\n iElement.addClass('starts' + scope.block.start);\n iElement.addClass('lasts' + scope.block.length);\n }\n\n // Add class for user's participation state\n if (scope.block.userState)\n iElement.addClass('sg-event--' + scope.block.userState);\n\n if (scope.block.component) {\n // Set background color\n iElement.addClass('bg-folder' + scope.block.component.pid);\n iElement.addClass('contrast-bdr-folder' + scope.block.component.pid);\n\n // Add class for transparency\n if (scope.block.component.c_isopaque === 0)\n iElement.addClass('sg-event--transparent');\n\n // Add class for cancelled event\n if (scope.block.component.c_status === 0)\n iElement.addClass('sg-event--cancelled');\n }\n\n }\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarDayBlock', sgCalendarDayBlock);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarDayTable - Build list of blocks for a specific day\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {object} sgBlocks - the events blocks definitions for the current view\n * @param {string} sgDay - the day of the events to display\n * @param {function} sgClick - the function to call when clicking on a block.\n * Two variables are available: event (the event that triggered the mouse click),\n * and component (a Component object)\n *\n * @example:\n\n \n */\n function sgCalendarDayTable() {\n return {\n restrict: 'E',\n scope: {\n blocks: '=sgBlocks',\n day: '@sgDay',\n clickBlock: '&sgClick'\n },\n template: [\n ''\n ].join('')\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarDayTable', sgCalendarDayTable);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarBlock - Applied to an event ghost block to be displayed while dragging an event block. Each day of the\n * calendar's view must have a ghost block.\n * @memberof SOGo.SchedulerUI\n * @restrict attribute\n *\n * @example:\n\n /\n */\n sgCalendarGhost.$inject = ['$rootScope', '$timeout', 'CalendarSettings', 'Calendar', 'Component'];\n function sgCalendarGhost($rootScope, $timeout, CalendarSettings, Calendar, Component) {\n return {\n restrict: 'A',\n require: ['^sgCalendarDay', '^sgCalendarScrollView'],\n link: link\n };\n\n function link(scope, iElement, attrs, ctrls) {\n var domElement, calendarDayCtrl, scrollViewCtrl, calendarNumber, originalCalendarNumber;\n\n domElement = iElement[0];\n calendarDayCtrl = ctrls[0];\n scrollViewCtrl = ctrls[1];\n calendarNumber = -1;\n\n iElement.addClass('sg-event--ghost md-whiteframe-3dp ng-hide');\n\n // Listen on drag gestures\n var deregisterDragStart = $rootScope.$on('calendar:dragstart', initGhost);\n var deregisterDrag = $rootScope.$on('calendar:drag', updateGhost);\n var deregisterDragEnd = $rootScope.$on('calendar:dragend', hideGhost);\n\n // Deregister listeners on destroy\n scope.$on('$destroy', function() {\n deregisterDragStart();\n deregisterDrag();\n deregisterDragEnd();\n });\n\n function initGhost() {\n var pid, calendarData, userState;\n\n // Expose ghost block to the scope\n scope.block = Component.$ghost;\n\n calendarData = calendarDayCtrl.calendarData();\n if (calendarData) {\n // A calendar is associated to the day; this is a special multicolumn day view\n calendarNumber = calendarData.index;\n pid = calendarData.pid;\n originalCalendarNumber = scope.block.pointerHandler.originalCalendar.index;\n }\n\n if (!pid)\n pid = scope.block.component.pid;\n\n // Add class for user's participation state\n userState = scope.block.component.blocks[0].userState;\n if (userState)\n iElement.addClass('sg-event--' + userState);\n\n // Set background color\n iElement.addClass('bg-folder' + pid);\n }\n\n function hideGhost() {\n // Remove background color\n _.forEachRight(domElement.classList, function(c) {\n if (/^bg-folder/.test(c))\n iElement.removeClass(c);\n });\n // Hide ghost\n iElement.addClass('ng-hide');\n }\n\n function updateGhost() {\n // From SOGoEventDragGhostController._updateGhosts\n var showGhost, isRelative, isAllDay, currentDay,\n start, duration, durationLeft, maxDuration;\n\n showGhost = false;\n\n if (Calendar.$view && Calendar.$view.type == scrollViewCtrl.type) {\n // The view of the dragging block is the scrolling view of this ghost block\n\n isRelative = scrollViewCtrl.type === 'multiday-allday';\n isAllDay = scope.block.component.c_isallday;\n currentDay = scope.block.pointerHandler.currentEventCoordinates.dayNumber;\n start = scope.block.pointerHandler.currentEventCoordinates.start;\n durationLeft = scope.block.pointerHandler.currentEventCoordinates.duration;\n maxDuration = CalendarSettings.EventDragDayLength - start;\n\n if (angular.isUndefined(durationLeft))\n return;\n duration = durationLeft;\n if (duration > maxDuration)\n duration = maxDuration;\n\n if (currentDay > -1 && // pointer is inside viewport\n ((calendarNumber < 0 && // day is not associated to a calendar\n currentDay == calendarDayCtrl.dayNumber) || // pointer is inside ghost's day\n currentDay == calendarNumber && // pointer is inside ghost's calendar\n (originalCalendarNumber == calendarNumber || // still inside original calendar\n !scope.block.component.isException) // not an exception, event can be moved to a\n // different calendar\n )) {\n // This ghost block (day) is the first of the dragging event\n showGhost = true;\n if (!isRelative) {\n if (!isAllDay)\n // Show start hour and set the vertical position\n scope.block.startHour = getStartTime(start);\n // Set the height\n if (Calendar.$view.quarterHeight) {\n iElement.css('top', (start * Calendar.$view.quarterHeight) + 'px');\n iElement.css('height', (duration * Calendar.$view.quarterHeight) + 'px');\n }\n else\n iElement.css('top', Calendar.$view.topOffset + 'px');\n }\n iElement.removeClass('fg-folder' + scope.block.component.pid);\n iElement.removeClass('sg-event--ghost--last');\n iElement.addClass('sg-event--ghost--first');\n scope.block.isFirst = true;\n }\n\n durationLeft -= duration;\n currentDay++;\n\n // Search a subsequent block that matches the current ghost's day\n while (!showGhost && durationLeft && currentDay <= calendarDayCtrl.dayNumber) {\n duration = durationLeft;\n if (duration > CalendarSettings.EventDragDayLength)\n duration = CalendarSettings.EventDragDayLength;\n if (currentDay > -1 && currentDay == calendarDayCtrl.dayNumber) {\n // The dragging event overlaps this current ghost's day\n showGhost = true;\n if (!isRelative) {\n iElement.css('top', Calendar.$view.topOffset + 'px');\n // Set the height\n if (Calendar.$view.quarterHeight)\n iElement.css('height', (duration * Calendar.$view.quarterHeight) + 'px');\n }\n iElement.removeClass('sg-event--ghost--first');\n iElement.removeClass('sg-event--ghost--last');\n // Trick for all-day events: set the foreground color to the background color so the event's title\n // is not visible but the div size remains identical.\n iElement.addClass('fg-folder' + scope.block.component.pid);\n }\n durationLeft -= duration;\n currentDay++;\n start = 0;\n }\n if (!durationLeft) {\n // Reached last ghost block\n if (isRelative) {\n iElement.addClass('sg-event--ghost--last');\n }\n else if (!isAllDay) {\n // Set the end date\n scope.block.endHour = getEndTime(start, duration);\n }\n }\n }\n\n if (showGhost)\n iElement.removeClass('ng-hide');\n else\n iElement.addClass('ng-hide');\n }\n\n function quartersToHM(quarters) {\n var minutes, hours, mins;\n\n minutes = quarters * 15;\n hours = Math.floor(minutes / 60);\n if (hours < 10)\n hours = \"0\" + hours;\n mins = minutes % 60;\n if (mins < 10)\n mins = \"0\" + mins;\n\n return \"\" + hours + \":\" + mins;\n }\n\n function getStartTime(start) {\n return quartersToHM(start);\n }\n\n function getEndTime(start, duration) {\n var end = (start + duration) % CalendarSettings.EventDragDayLength;\n return quartersToHM(end);\n }\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarGhost', sgCalendarGhost);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarMonthDay - Build list of blocks for a specific day in a month\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {object} sgBlocks - the events blocks definitions for the current view\n * @param {string} sgDay - the day of the events to display\n * @param {function} sgClick - the function to call when clicking on a block.\n * Two variables are available: event (the event that triggered the mouse click),\n * and component (a Component object)\n *\n * @example:\n\n \n */\n function sgCalendarMonthDay() {\n return {\n restrict: 'E',\n scope: {\n blocks: '=sgBlocks',\n day: '@sgDay',\n clickBlock: '&sgClick'\n },\n template: [\n ''\n ].join('')\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarMonthDay', sgCalendarMonthDay);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarMonthEvent - An event block to be displayed in a month\n * @memberof SOGo.Common\n * @restrict element\n * @param {object} sgBlock - the event block definition\n * @ngInject\n * @example:\n\n \n */\n function sgCalendarMonthEvent() {\n return {\n restrict: 'E',\n scope: {\n block: '=sgBlock',\n clickBlock: '&sgClick'\n },\n replace: true,\n template: template,\n link: link\n };\n\n function template(tElem, tAttrs) {\n var p = _.has(tAttrs, 'sgCalendarGhost')? '' : '::';\n\n return [\n '
',\n // Categories color stripes\n '
',\n ' {{ '+p+'block.component.startHour }}',\n // Priority\n ' {{'+p+'block.component.c_priority}}',\n // Summary\n ' {{ '+p+'block.component.summary }}',\n ' ',\n // Component is reccurent\n ' ',\n // Component has an alarm\n ' ',\n // Component is confidential\n ' ',\n // Component is private\n ' ',\n ' ',\n '
'\n ].join('');\n }\n\n function link(scope, iElement, attrs) {\n if (!_.has(attrs, 'sgCalendarGhost')) {\n\n // Add class for user's participation state\n if (scope.block.userState)\n iElement.addClass('sg-event--' + scope.block.userState);\n\n if (scope.block.component) {\n // Set background color\n iElement.addClass('bg-folder' + scope.block.component.pid);\n\n // Add class for transparency\n if (scope.block.component.c_isopaque === 0)\n iElement.addClass('sg-event--transparent');\n\n // Add class for cancelled event\n if (scope.block.component.c_status === 0)\n iElement.addClass('sg-event--cancelled');\n }\n\n }\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarMonthEvent', sgCalendarMonthEvent);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgCalendarScrollView - scrollable view that contains draggable elements\n * @memberof SOGo.SchedulerUI\n * @restrict attribute\n * @param {string} sgCalendarScrollView - the view type (multiday, multiday-allday, or monthly)\n *\n * @example:\n\n \n ..\n \n */\n sgCalendarScrollView.$inject = ['$rootScope', '$window', '$document', '$q', '$timeout', '$mdGesture', 'Calendar', 'Component', 'Preferences'];\n function sgCalendarScrollView($rootScope, $window, $document, $q, $timeout, $mdGesture, Calendar, Component, Preferences) {\n return {\n restrict: 'A',\n scope: {\n type: '@sgCalendarScrollView'\n },\n controller: sgCalendarScrollViewController,\n link: function(scope, element, attrs, controller) {\n var view, type, isMultiColumn = false;\n\n view = null;\n type = scope.type; // multiday, multiday-allday, monthly, unknown?\n isMultiColumn = (element.attr('sg-view') == 'multicolumndayview');\n\n // Expose isMultiColumn in the controller\n // See sgNowLine directive\n controller.isMultiColumn = isMultiColumn;\n\n // Update the \"view\" object literal once the Angular template has been transformed\n $timeout(initView);\n\n // Deregister listeners when destroying the view\n scope.$on('$destroy', function() {\n if (view) {\n view.$destroy();\n }\n });\n\n function initView() {\n view = new sgScrollView(element, type);\n\n if (type != 'monthly')\n // Scroll to the day start hour defined in the user's defaults\n Preferences.ready().then(function() {\n var time, hourCell, quartersOffset;\n if (Preferences.defaults.SOGoDayStartTime) {\n time = Preferences.defaults.SOGoDayStartTime.split(':');\n hourCell = document.getElementById('hour' + parseInt(time[0]));\n quartersOffset = parseInt(time[1]) * view.quarterHeight;\n view.element.scrollTop = hourCell.offsetTop + quartersOffset;\n }\n });\n\n // Expose quarter height to the controller\n // See sgNowLine directive\n controller.quarterHeight = view.quarterHeight;\n }\n\n /**\n * sgScrollView\n */\n function sgScrollView($element, type) {\n this.$element = $element;\n this.element = $element[0];\n this.type = type;\n this.quarterHeight = this.getQuarterHeight();\n this.scrollStep = 6 * this.quarterHeight;\n this.dayNumbers = this.getDayNumbers();\n this.maxX = this.getMaxColumns();\n\n // Listen to dragstart and dragend events\n this.deregisterDragStart = $rootScope.$on('calendar:dragstart', angular.bind(this, this.onDragStart));\n this.deregisterDragStop = $rootScope.$on('calendar:dragend', angular.bind(this, this.onDragEnd));\n\n this.bindedUpdateCoordinates = angular.bind(this, this.updateCoordinates);\n this.bindedUpdateFromPointerHandler = angular.bind(this, this.updateFromPointerHandler);\n\n // Compute coordinates of view element; recompute it on window resize\n this.updateCoordinates();\n angular.element($window).on('resize', this.bindedUpdateCoordinates);\n }\n\n sgScrollView.prototype = {\n\n $destroy: function() {\n this.deregisterDragStart();\n this.deregisterDragStop();\n this.$element.off('mousemove', this.bindedUpdateFromPointerHandler);\n angular.element($window).off('resize', this.bindedUpdateCoordinates);\n },\n\n onDragStart: function() {\n this.$element.on('mousemove', this.bindedUpdateFromPointerHandler);\n this.updateCoordinates();\n this.updateFromPointerHandler();\n },\n\n onDragEnd: function() {\n this.$element.off('mousemove', this.bindedUpdateFromPointerHandler);\n Calendar.$view = null;\n },\n\n getQuarterHeight: function() {\n var hour0, hour23, height = null;\n\n hour0 = document.getElementById('hour0');\n hour23 = document.getElementById('hour23');\n if (hour0 && hour23)\n height = ((hour23.offsetTop - hour0.offsetTop) / (23 * 4));\n\n return height;\n },\n\n\n getDayDimensions: function(viewLeft) {\n var width, height, leftOffset, topOffset, nodes, domRect, tileHeader;\n\n height = width = leftOffset = topOffset = 0;\n nodes = this.element.getElementsByClassName('day');\n\n if (nodes.length > 0) {\n domRect = nodes[0].getBoundingClientRect();\n height = domRect.height;\n width = domRect.width;\n leftOffset = domRect.left - viewLeft;\n tileHeader = nodes[0].getElementsByClassName('sg-calendar-tile-header');\n if (tileHeader.length > 0)\n topOffset = tileHeader[0].clientHeight;\n }\n\n return { height: height, width: width, offset: { left: leftOffset, top: topOffset } };\n },\n\n\n getDayNumbers: function() {\n var viewType = null, days, total, sum;\n\n days = this.element.getElementsByTagName('sg-calendar-day');\n\n return _.map(days, function(el, index) {\n if (isMultiColumn)\n return index;\n else\n return parseInt(el.attributes['sg-day-number'].value);\n });\n },\n\n\n getMaxColumns: function() {\n var mdGridList, max = 0;\n\n if (this.type == 'monthly') {\n mdGridList = this.element.getElementsByTagName('md-grid-list')[0];\n max = parseInt(mdGridList.attributes['md-cols'].value) - 1;\n }\n else {\n max = this.element.getElementsByClassName('day').length - 1;\n }\n\n return max;\n },\n\n // View has been resized;\n // Compute the view's origins (x, y), a day's dimensions and left margin.\n updateCoordinates: function() {\n var domRect, dayDimensions;\n\n domRect = this.element.getBoundingClientRect();\n dayDimensions = this.getDayDimensions(domRect.left);\n\n angular.extend(this, {\n coordinates: {\n x: domRect.left,\n y: domRect.top\n },\n dayHeight: dayDimensions.height,\n dayWidth: dayDimensions.width,\n daysOffset: dayDimensions.offset.left,\n topOffset: dayDimensions.offset.top\n });\n },\n\n\n // From SOGoScrollController.updateFromPointerHandler\n updateFromPointerHandler: function() {\n var pointerHandler, pointerCoordinates, now, scrollY, minY, delta;\n\n pointerHandler = Component.$ghost.pointerHandler;\n if (this.coordinates && pointerHandler) {\n pointerCoordinates = pointerHandler.getContainerBasedCoordinates(this);\n\n if (pointerCoordinates) {\n // Pointer is inside view; Adjust scrollbar if necessary\n Calendar.$view = this;\n now = new Date().getTime();\n if (!this.lastScroll || now > this.lastScroll + 100) {\n this.lastScroll = now;\n scrollY = pointerCoordinates.y - this.scrollStep;\n if (scrollY < 0) {\n minY = -this.element.scrollTop;\n if (scrollY < minY)\n scrollY = minY;\n this.element.scrollTop += scrollY;\n }\n else {\n scrollY = pointerCoordinates.y + this.scrollStep;\n delta = scrollY - this.element.clientHeight;\n if (delta > 0) {\n this.element.scrollTop += delta;\n }\n }\n }\n }\n }\n }\n\n\n };\n }\n };\n }\n\n sgCalendarScrollViewController.$inject = ['$scope'];\n function sgCalendarScrollViewController($scope) {\n // Expose the view type to the controller\n // See sgCalendarGhost directive\n this.type = $scope.type;\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarScrollView', sgCalendarScrollView);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgCategoryStylesheet - Add CSS stylesheet for a category's color\n * @memberof SOGo.SchedulerUI\n * @restrict attribute\n * @param {object} ngModel - the object literal describing the category\n * @example:\n\n \n */\n function sgCategoryStylesheet() {\n return {\n restrict: 'E',\n require: 'ngModel',\n scope: {\n ngModel: '='\n },\n replace: true,\n template: [\n ''\n ].join('')\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCategoryStylesheet', sgCategoryStylesheet);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgDraggableCalendarBlock - Make an element draggable\n * @memberof SOGo.SchedulerUI\n * @restrict class or attribute\n *\n * @example:\n\n
\n */\n sgDraggableCalendarBlock.$inject = ['$rootScope', '$timeout', '$log', 'Preferences', 'Calendar', 'CalendarSettings', 'Component'];\n function sgDraggableCalendarBlock($rootScope, $timeout, $log, Preferences, Calendar, CalendarSettings, Component) {\n return {\n restrict: 'CA',\n require: '^sgCalendarDay',\n link: link\n };\n\n function link(scope, element, attrs, calendarDayCtrl) {\n if (scope.block) {\n if (scope.block.component.editable && !scope.block.userState) {\n // Add dragging grips to existing event block\n initGrips();\n }\n else {\n element.removeClass('sg-draggable-calendar-block');\n return;\n }\n }\n\n // Start dragging on mousedown\n element.on('mousedown', onDragDetect);\n\n // Deregister listeners when removing the element from the DOM\n scope.$on('$destroy', function() {\n element.off('mousedown', onDragDetect);\n element.off('mousemove', onDrag);\n });\n\n function initGrips() {\n var component, dayIndex, blockIndex, isFirstBlock, isLastBlock,\n dragGrip, leftGrip, rightGrip, topGrip, bottomGrip;\n\n component = scope.block.component;\n dayIndex = scope.block.dayIndex;\n blockIndex = _.findIndex(component.blocks, ['dayIndex', dayIndex]);\n isFirstBlock = (blockIndex === 0);\n isLastBlock = (blockIndex === component.blocks.length - 1);\n\n dragGrip = angular.element('
');\n dragGrip.addClass('bdr-folder' + component.pid);\n\n if (component.c_isallday ||\n element[0].parentNode.tagName === 'SG-CALENDAR-MONTH-DAY') {\n if (isFirstBlock) {\n leftGrip = angular.element('
').append(dragGrip);\n element.append(leftGrip);\n }\n if (isLastBlock) {\n rightGrip = angular.element('
').append(dragGrip.clone());\n element.append(rightGrip);\n }\n }\n else {\n if (isFirstBlock) {\n topGrip = angular.element('
').append(dragGrip);\n element.append(topGrip);\n }\n if (isLastBlock) {\n bottomGrip = angular.element('
').append(dragGrip.clone());\n element.append(bottomGrip);\n }\n }\n }\n\n function onDragDetect(ev) {\n var dragMode, pointerHandler;\n\n ev.stopPropagation();\n\n dragMode = 'move-event';\n\n if (scope.block && scope.block.component) {\n // Move or resize existing component\n if (ev.target.className == 'dragGrip-top' ||\n ev.target.className == 'dragGrip-left')\n dragMode = 'change-start';\n else if (ev.target.className == 'dragGrip-bottom' ||\n ev.target.className == 'dragGrip-right' )\n dragMode = 'change-end';\n }\n else {\n // Create new component from dragging\n dragMode = 'change-end';\n }\n\n // Initialize pointer handler\n pointerHandler = new SOGoEventDragPointerHandler(dragMode);\n pointerHandler.initFromEvent(ev);\n\n // Update Component.$ghost\n Component.$ghost.pointerHandler = pointerHandler;\n\n // Stop dragging on the next \"mouseup\"\n angular.element(document).one('mouseup', onDragEnd);\n\n // Listen to mousemove and start dragging when mouse has moved from at least 3 pixels\n angular.element(document).on('mousemove', onDrag);\n }\n\n function dragStart(ev) {\n var block, eventType, isHourCell, isMonthly, startDate, newData, newComponent, pointerHandler, calendarData;\n\n isHourCell = element.hasClass('clickableHourCell');\n isMonthly = (element[0].parentNode.tagName == 'SG-CALENDAR-MONTH-DAY') ||\n element.hasClass('clickableDayCell');\n\n calendarData = calendarDayCtrl.calendarData();\n\n if (scope.block && scope.block.component) {\n // Move or resize existing component\n block = scope.block;\n }\n else {\n // Create new component from dragging\n startDate = calendarDayCtrl.dayString.parseDate(Preferences.$mdDateLocaleProvider, '%Y-%m-%e');\n newData = {\n type: 'appointment',\n pid: calendarData? calendarData.pid : Calendar.$defaultCalendar(),\n summary: l('New Event'),\n startDate: startDate,\n isAllDay: isHourCell? 0 : 1\n };\n newComponent = new Component(newData);\n block = {\n component: newComponent,\n dayNumber: calendarDayCtrl.dayNumber,\n length: 0\n };\n block.component.blocks = [block];\n }\n\n // Determine event type\n eventType = 'multiday';\n if (isMonthly)\n eventType = 'monthly';\n else if (block.component.c_isallday)\n eventType = 'multiday-allday';\n\n // Mark all blocks as being dragged\n _.forEach(block.component.blocks, function(b) {\n b.dragging = true;\n });\n\n // Update pointer handler\n pointerHandler = Component.$ghost.pointerHandler;\n pointerHandler.prepareWithEventType(eventType);\n pointerHandler.initFromBlock(block);\n if (calendarData)\n // When the day is associated to a calendar, the day number becomes the calendar index\n // among the active calendars\n pointerHandler.initFromCalendar(calendarData);\n\n // Update Component.$ghost\n Component.$ghost.component = block.component;\n\n $log.debug('emit calendar:dragstart ' + eventType);\n $rootScope.$emit('calendar:dragstart');\n }\n\n function onDrag(ev) {\n var pointerHandler = Component.$ghost.pointerHandler;\n\n // Update\n // - currentCoordinates\n // - currentViewCoordinates\n // - currentEventCoordinates\n $timeout(function() {\n pointerHandler.updateFromEvent(ev);\n });\n }\n\n function onDragEnd(ev) {\n var block, pointer;\n\n block = scope.block;\n pointer = Component.$ghost.pointerHandler;\n\n // Deregister mouse events\n angular.element(document).off('mousemove', onDrag);\n\n if (pointer.dragHasStarted) {\n $rootScope.$emit('calendar:dragend');\n pointer.dragHasStarted = false;\n }\n\n // Unmark all blocks as being dragged\n if (block && block.component)\n _.forEach(block.component.blocks, function(b) {\n b.dragging = false;\n });\n }\n\n /**\n * SOGoCoordinates\n */\n function SOGoCoordinates() {\n }\n\n SOGoCoordinates.prototype = {\n x: -1,\n y: -1,\n\n getDelta: function SC_getDelta(otherCoordinates) {\n var delta = new SOGoCoordinates();\n delta.x = this.x - otherCoordinates.x;\n delta.y = this.y - otherCoordinates.y;\n\n if (Calendar.$view) {\n delta.days = Calendar.$view.dayNumbers[this.x] - Calendar.$view.dayNumbers[otherCoordinates.x];\n }\n\n return delta;\n },\n\n getDistance: function SC_getDistance(otherCoordinates) {\n var delta = this.getDelta(otherCoordinates);\n\n return Math.sqrt(delta.x * delta.x + delta.y * delta.y);\n },\n\n clone: function SC_clone() {\n var coordinates = new SOGoCoordinates();\n coordinates.x = this.x;\n coordinates.y = this.y;\n\n return coordinates;\n }\n };\n\n /**\n * SOGoEventDragEventCoordinates\n */\n function SOGoEventDragEventCoordinates(eventType) {\n this.setEventType(eventType);\n }\n\n SOGoEventDragEventCoordinates.prototype = {\n dayNumber: -1,\n weekDay: -1,\n start: -1,\n duration: -1,\n\n eventType: null,\n\n setEventType: function(eventType) {\n this.eventType = eventType;\n },\n\n initFromBlock: function(block) {\n var prevDayNumber = -1;\n\n if (this.eventType === 'monthly') {\n this.start = 0;\n this.duration = block.component.blocks.length * CalendarSettings.EventDragDayLength;\n }\n else {\n // Get the start (first quarter) from the event's first block\n // Compute overall length\n this.start = block.component.blocks[0].start;\n this.duration = _.sumBy(block.component.blocks, function(b) {\n var delta, currentDayNumber;\n\n currentDayNumber = b.dayNumber;\n if (prevDayNumber < 0)\n delta = 0;\n else\n delta = currentDayNumber - prevDayNumber - 1;\n prevDayNumber = currentDayNumber;\n\n return b.length + delta * CalendarSettings.EventDragDayLength;\n });\n }\n },\n\n initFromCalendar: function(calendarNumber) {\n this.dayNumber = calendarNumber;\n },\n\n getDelta: function(otherCoordinates) {\n var delta = new SOGoEventDragEventCoordinates();\n delta.dayNumber = (this.dayNumber - otherCoordinates.dayNumber);\n delta.start = (this.start - otherCoordinates.start);\n delta.duration = (this.duration - otherCoordinates.duration);\n\n return delta;\n },\n\n _quartersToHM: function(quarters) {\n var minutes = quarters * 15;\n var hours = Math.floor(minutes / 60);\n if (hours < 10)\n hours = \"0\" + hours;\n var mins = minutes % 60;\n if (mins < 10)\n mins = \"0\" + mins;\n\n return \"\" + hours + \":\" + mins;\n },\n\n getStartTime: function() {\n return this._quartersToHM(this.start);\n },\n\n getEndTime: function() {\n var end = (this.start + this.duration) % CalendarSettings.EventDragDayLength;\n return this._quartersToHM(end);\n },\n\n clone: function() {\n var coordinates = new SOGoEventDragEventCoordinates();\n coordinates.dayNumber = this.dayNumber;\n coordinates.start = this.start;\n coordinates.duration = this.duration;\n\n return coordinates;\n }\n };\n\n /**\n * SOGoEventDragPointerHandler\n */\n function SOGoEventDragPointerHandler(dragMode) {\n this.dragMode = dragMode;\n }\n\n SOGoEventDragPointerHandler.prototype = {\n // Pointer absolute xy coordinates within page\n originalCoordinates: null,\n currentCoordinates: null,\n\n // Pointer relative xy coordinates within view (row-column)\n originalViewCoordinates: null,\n currentViewCoordinates: null,\n\n // Event start-duration coordinates\n originalEventCoordinates: null,\n currentEventCoordinates: null,\n\n originalCalendar: null,\n\n dragHasStarted: false,\n\n // Function to return the day and quarter coordinates of the pointer cursor\n // within the day view\n getEventViewCoordinates: null,\n\n initFromBlock: function SEDPH_initFromBlock(block) {\n this.currentEventCoordinates = new SOGoEventDragEventCoordinates(this.eventType);\n this.originalEventCoordinates = new SOGoEventDragEventCoordinates(this.eventType);\n this.originalEventCoordinates.initFromBlock(block);\n },\n\n initFromEvent: function SEDPH_initFromEvent(event) {\n this.currentCoordinates = new SOGoCoordinates();\n this.updateFromEvent(event);\n this.originalCoordinates = this.currentCoordinates.clone();\n },\n\n initFromCalendar: function SEDPH_initFromCalendar(calendarData) {\n this.originalCalendar = calendarData;\n this.currentEventCoordinates.initFromCalendar(calendarData.index);\n this.originalEventCoordinates.initFromCalendar(calendarData.index);\n },\n\n // Method continuously called while dragging\n updateFromEvent: function SEDPH_updateFromEvent(event) {\n // Event here is a DOM event, not a calendar event!\n this.currentCoordinates.x = event.pageX;\n this.currentCoordinates.y = event.pageY;\n\n // From SOGoEventDragGhostController.updateFromPointerHandler\n if (this.dragHasStarted && Calendar.$view) {\n var newEventCoordinates = this.getEventViewCoordinates(Calendar.$view);\n if (!this.originalViewCoordinates) {\n this.originalViewCoordinates = this.getEventViewCoordinates(Calendar.$view, this.originalCoordinates);\n if (Component.$ghost.component.isNew) {\n this.setTimeFromQuarters(Component.$ghost.component.start, this.originalViewCoordinates.y);\n $log.debug('new event start date ' + Component.$ghost.component.start);\n }\n }\n if (!this.currentViewCoordinates ||\n !newEventCoordinates ||\n newEventCoordinates.x != this.currentViewCoordinates.x ||\n newEventCoordinates.y != this.currentViewCoordinates.y) {\n this.currentViewCoordinates = newEventCoordinates;\n if (this.originalViewCoordinates) {\n if (!newEventCoordinates) {\n this.currentViewCoordinates = this.originalViewCoordinates.clone();\n }\n this.updateEventCoordinates();\n }\n }\n }\n else if (this.originalCoordinates &&\n this.currentCoordinates &&\n !this.dragHasStarted) {\n var distance = this.getDistance();\n if (distance > 3) {\n this.dragHasStarted = true;\n dragStart(event);\n }\n }\n },\n\n // SOGoEventDragGhostController._updateCoordinates\n // Extend this.currentCoordinates with start, dayNumber and duration\n updateEventCoordinates: function SEDGC__updateCoordinates() {\n var newDuration;\n\n // Compute delta wrt to position of mouse at dragstart on the day/quarter grid\n var delta = this.currentViewCoordinates.getDelta(this.originalViewCoordinates);\n var deltaQuarters = delta.days * CalendarSettings.EventDragDayLength + delta.y;\n $log.debug('quarters delta ' + deltaQuarters);\n\n if (angular.isUndefined(this.originalEventCoordinates.start)) {\n // Creating new appointment from DnD\n this.originalEventCoordinates.dayNumber = Calendar.$view.dayNumbers[this.originalViewCoordinates.x];\n this.originalEventCoordinates.start = this.originalViewCoordinates.y;\n }\n else if (this.originalEventCoordinates.dayNumber < 0) {\n this.originalEventCoordinates.dayNumber = Calendar.$view.dayNumbers[scope.block.component.blocks[0].dayIndex];\n }\n // if (currentView == \"multicolumndayview\")\n // this._updateMulticolumnViewDayNumber_SEDGC();\n // else\n this.currentEventCoordinates.dayNumber = this.originalEventCoordinates.dayNumber;\n\n if (this.dragMode == \"move-event\") {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start + deltaQuarters;\n this.currentEventCoordinates.duration = this.originalEventCoordinates.duration;\n }\n else {\n if (this.dragMode == \"change-start\") {\n newDuration = this.originalEventCoordinates.duration - deltaQuarters;\n if (newDuration > 0) {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start + deltaQuarters;\n this.currentEventCoordinates.duration = newDuration;\n }\n else if (newDuration < 0) {\n this.currentEventCoordinates.start = (this.originalEventCoordinates.start + this.originalEventCoordinates.duration);\n this.currentEventCoordinates.duration = -newDuration;\n }\n }\n else if (this.dragMode == \"change-end\") {\n newDuration = this.originalEventCoordinates.duration + deltaQuarters;\n if (newDuration > 0) {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start;\n this.currentEventCoordinates.duration = newDuration;\n }\n else if (newDuration < 0) {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start + newDuration;\n this.currentEventCoordinates.duration = -newDuration;\n }\n }\n }\n\n var deltaDays;\n if (this.currentEventCoordinates.start < 0) {\n deltaDays = Math.ceil(-this.currentEventCoordinates.start / CalendarSettings.EventDragDayLength);\n this.currentEventCoordinates.start += deltaDays * CalendarSettings.EventDragDayLength;\n this.currentEventCoordinates.dayNumber -= deltaDays;\n }\n else if (this.currentEventCoordinates.start >= CalendarSettings.EventDragDayLength) {\n deltaDays = Math.floor(this.currentEventCoordinates.start / CalendarSettings.EventDragDayLength);\n this.currentEventCoordinates.start -= deltaDays * CalendarSettings.EventDragDayLength;\n this.currentEventCoordinates.dayNumber += deltaDays;\n }\n\n $log.debug('event coordinates ' + JSON.stringify(this.currentEventCoordinates));\n $rootScope.$emit('calendar:drag');\n },\n\n // SOGoEventDragPointerHandler.getContainerBasedCoordinates\n getContainerBasedCoordinates: function SEDPH_getCBC(view, pointerCoordinates) {\n var currentCoordinates = pointerCoordinates || this.currentCoordinates;\n var coordinates = currentCoordinates.getDelta(view.coordinates);\n var container = view.element;\n\n if (coordinates.x < view.daysOffset || coordinates.x > container.clientWidth ||\n coordinates.y < 0 || coordinates.y > container.clientHeight)\n coordinates = null;\n\n return coordinates;\n },\n\n prepareWithEventType: function SEDPH_prepareWithEventType(eventType) {\n var methods = { \"multiday\": this.getEventMultiDayViewCoordinates,\n \"multiday-allday\": this.getEventMultiDayAllDayViewCoordinates,\n \"monthly\": this.getEventMonthlyViewCoordinates,\n \"unknown\": null };\n var method = methods[eventType];\n this.eventType = eventType;\n this.getEventViewCoordinates = method;\n },\n\n getEventMultiDayViewCoordinates: function SEDPH_gEMultiDayViewC(view, pointerCoordinates) {\n /* x = day; y = quarter */\n var coordinates = this.getEventMultiDayAllDayViewCoordinates(view, pointerCoordinates); // get the x coordinate\n if (coordinates) {\n var quarterHeight = view.quarterHeight;\n var pxCoordinates = this.getContainerBasedCoordinates(view, pointerCoordinates);\n pxCoordinates.y += view.element.scrollTop;\n\n coordinates.y = Math.floor((pxCoordinates.y - CalendarSettings.EventDragHorizontalOffset) / quarterHeight);\n var maxY = CalendarSettings.EventDragDayLength - 1;\n if (coordinates.y < 0)\n coordinates.y = 0;\n else if (coordinates.y > maxY)\n coordinates.y = maxY;\n }\n\n return coordinates;\n },\n getEventMultiDayAllDayViewCoordinates: function SEDPH_gEMultiDayADVC(view, pointerCoordinates) {\n /* x = day; y = quarter */\n var coordinates;\n\n var pxCoordinates = this.getContainerBasedCoordinates(view, pointerCoordinates);\n if (pxCoordinates) {\n coordinates = new SOGoCoordinates();\n\n var dayWidth = view.dayWidth;\n var daysOffset = view.daysOffset;\n\n coordinates.x = Math.floor((pxCoordinates.x - daysOffset) / dayWidth);\n var minX = 0;\n var maxX = Calendar.$view.maxX;\n if (this.dragMode != 'move-event') {\n var calendarData = calendarDayCtrl.calendarData();\n if (calendarData)\n // Resizing an event can't span a different day when in multicolumn view\n minX = maxX = calendarData.index;\n }\n if (coordinates.x < minX)\n coordinates.x = minX;\n else if (coordinates.x > maxX)\n coordinates.x = maxX;\n coordinates.y = 0;\n }\n else {\n coordinates = null;\n }\n\n return coordinates;\n },\n getEventMonthlyViewCoordinates: function SEDPH_gEMonthlyViewC(view, pointerCoordinates) {\n /* x = day; y = quarter */\n var coordinates;\n\n var pxCoordinates = this.getContainerBasedCoordinates(view, pointerCoordinates);\n if (pxCoordinates) {\n coordinates = new SOGoCoordinates();\n\n var maxX = view.maxX;\n var daysTopOffset = 0;\n var dayWidth = view.dayWidth;\n var daysOffset = view.daysOffset;\n var dayHeight = view.dayHeight;\n var daysY = Math.floor((pxCoordinates.y - daysTopOffset) / dayHeight);\n if (daysY < 0)\n daysY = 0;\n\n coordinates.x = Math.floor((pxCoordinates.x - daysOffset) / dayWidth);\n if (coordinates.x < 0)\n coordinates.x = 0;\n else if (coordinates.x > maxX)\n coordinates.x = maxX;\n coordinates.x += (maxX + 1) * daysY;\n coordinates.y = 0;\n }\n else {\n coordinates = null;\n }\n\n return coordinates;\n },\n\n getDistance: function SEDPH_getDistance() {\n return this.currentCoordinates.getDistance(this.originalCoordinates);\n },\n\n setTimeFromQuarters: function SEDPH_setTimeFromQuarters(date, quarters) {\n var hours, minutes;\n hours = Math.floor(quarters / 4);\n minutes = (quarters % 4) * 15;\n date.setHours(hours, minutes);\n }\n };\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgDraggableCalendarBlock', sgDraggableCalendarBlock);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgNowLine - Now line to be displayed on top of current day\n * @restrict class\n */\n function sgNowLine() {\n return {\n restrict: 'C',\n require: '^^sgCalendarScrollView',\n link: link,\n controller: sgNowLineController\n };\n\n function link(scope, iElement, iAttr, sgCalendarScrollViewCtrl) {\n function _getDays() {\n return iElement.find('sg-calendar-day');\n }\n function _getView() {\n return sgCalendarScrollViewCtrl.quarterHeight;\n }\n\n // We need to wait for the view to be compiled\n var _unwatchView = scope.$watch(_getView, function(quarterHeight) {\n if (quarterHeight) {\n _unwatchView(); // self release\n scope.quarterHeight = quarterHeight;\n // We need to wait for the days to be compiled\n var _unwatchDays = scope.$watch(_getDays, function(days) {\n if (days.length) {\n _unwatchDays(); // self release\n scope.days = days;\n // Draw the line\n scope.updateLine();\n }\n });\n }\n });\n }\n }\n\n /**\n * @ngInject\n */\n sgNowLineController.$inject = ['$scope', '$element', '$timeout'];\n function sgNowLineController($scope, $element, $timeout) {\n var _this = this, updater,\n scrollViewCtrl = $element.controller('sgCalendarScrollView');\n\n $scope.nowDay = null;\n $scope.lineElement = null;\n $scope.updateLine = _updateLine;\n\n $scope.$on('$destroy', function() {\n if (updater)\n $timeout.cancel(updater);\n });\n\n\n function _updateLine(force) {\n var now = new Date(), // TODO: adjust to user's timezone\n nowDay = now.getDayString(),\n hours = now.getHours(),\n hourHeight = $scope.quarterHeight * 4,\n minutes = now.getMinutes(),\n minuteHeight = $scope.quarterHeight/15,\n position = parseInt(hours * hourHeight +\n minutes * minuteHeight -\n 1);\n\n if (force || nowDay != $scope.nowDay) {\n if ($scope.lineElement)\n $scope.lineElement.remove();\n $scope.lineElement = _addLine(nowDay, $scope.days);\n $scope.nowDay = nowDay;\n }\n\n if ($scope.lineElement) {\n // Current day is displayed\n $scope.lineElement.css('top', position + \"px\");\n // Update line every minute\n updater = $timeout(angular.bind(_this, $scope.updateLine), 60000);\n }\n }\n\n function _addLine(nowDay, days) {\n var $lineElement = angular.element('');\n\n if (scrollViewCtrl.isMultiColumn) {\n // In multicolumn day view, the line must go over all columns\n if (days && days[0].attributes['sg-day'].value == nowDay)\n $element.append($lineElement);\n }\n else\n _.forEach(days, function(dayElement) {\n if (dayElement.attributes['sg-day'].value == nowDay) {\n angular.element(dayElement).find('div').eq(0).append($lineElement);\n }\n });\n\n return $lineElement;\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgNowLine', sgNowLine);\n})();\n"]} \ No newline at end of file +{"version":3,"sources":["Scheduler/Calendar.service.js","Scheduler/Component.service.js","Scheduler/CalendarController.js","Scheduler/CalendarListController.js","Scheduler/CalendarsController.js","Scheduler/ComponentController.js","Scheduler/sgCalendarDay.directive.js","Scheduler/sgCalendarDayBlock.directive.js","Scheduler/sgCalendarDayTable.directive.js","Scheduler/sgCalendarGhost.directive.js","Scheduler/sgCalendarMonthDay.directive.js","Scheduler/sgCalendarMonthEvent.directive.js","Scheduler/sgCalendarScrollView.directive.js","Scheduler/sgCategoryStylesheet.directive.js","Scheduler/sgDraggableCalendarBlock.directive.js","Scheduler/sgNowLine.directive.js"],"names":["Calendar","futureCalendarData","this","init","name","id","newCalendarData","$$resource","create","$unwrap","$factory","$q","$timeout","$log","Settings","Resource","Preferences","Component","Acl","angular","extend","activeUser","$Preferences","$Component","$$Acl","$view","module","e","value","EventDragDayLength","EventDragHorizontalOffset","factory","$defaultCalendar","calendar","defaultCalendar","defaults","SOGoDefaultCalendar","_","find","$findAll","active","$add","list","sibling","i","isWebCalendar","$webcalendars","isSubscription","$subscriptions","$calendars","o","localeCompare","indexOf","map","splice","ready","then","settings","FoldersOrder","saveFoldersOrder","flatMap","$reloadAll","data","writable","_this","forEach","push","isUndefined","fetch","calendars","union","filter","isOwned","acls","objectCreator","calendarData","group","$get","$getIndex","$subscribe","uid","path","userResource","$addWebCalendar","url","d","defer","urls","webCalendarURL","reject","post","isEditable","isRemote","owner","login","debug","JSON","stringify","undefined","resolve","response","status","promise","reloadWebCalendars","promises","$error","l","statusText","all","$deleteComponents","components","component","isDefined","pid","uids","folders","prototype","color","$acl","isSuperUser","$shadowData","$omit","$id","when","$futureCalendarData","getClassName","base","$rename","$save","$delete","remove","$reset","key","save","error","setCredentials","username","password","export","download","type","$setActivation","$getComponent","componentId","recurrenceId","$find","isError","isObject","futureComponentData","newComponentData","newguid","isNew","Component_STATUS","Card","Gravatar","STATUS","$Card","$gravatar","timeFormat","$query","search","$queryEvents","sort","asc","filterpopup","$queryTasks","$refreshTimeout","$ghost","EventsFilterState","TasksFilterState","EventsSortingState","parseInt","TasksSortingState","show_completed","ShowCompletedTasks","$categories","SOGoCalendarCategoriesColors","SOGoTimeFormat","constant","NOT_LOADED","DELAYED_LOADING","LOADING","LOADED","DELAYED_MS","$selectedCount","count","$events","event","selected","length","$tasks","task","$startRefreshTimeout","cancel","refreshViewCheck","SOGoRefreshViewCheck","f","bind","$filter","timeInterval","$isLoading","$loaded","options","now","Date","day","getDate","month","getMonth","year","getFullYear","queryKey","capitalize","params","otherType","dirty","keys","$unwrapCollection","calendarId","occurrenceId","join","filterCategories","query","re","RegExp","category","saveSelectedList","componentType","$eventsBlocksForView","view","date","firstDayOfWeek","viewAction","startDate","endDate","SOGoFirstDayOfWeek","beginOfWeek","setTime","getTime","addDays","setDate","setMonth","endOfWeek","$eventsBlocks","j","dayDates","dayNumbers","deferred","toLowerCase","sd","getDayString","ed","views","reduceComponent","associateComponent","objects","eventData","componentData","zipObject","eventsFields","start","c_startdate","hour","getHourString","blocks","categories","block","nbr","isFirst","$views","viewIndex","viewData","allDayBlocks","reduce","events","flatten","days","dayIndex","dayNumber","calendarName","fields","invokeMap","$resetGhost","pointerHandler","startHour","endHour","$parseDate","dateString","time","substring","split","no_time","repeat","alarm","action","quantity","unit","reference","relation","delta","isString","setMinutes","Math","round","getMinutes","end","minutesTo","setDelta","dueDate","due","completedDate","completed","c_category","$isRecurrent","byDayMask","occurrence","frequency","byday","toString","interval","monthdays","months","until","$hasCustomRepeat","hasCustomRepeat","classification","units","M","H","D","W","match","exec","SOGoCalendarDefaultReminder","$hasAlarm","sendAppointmentNotifications","SOGoAppointmentSendEMailNotifications","destinationCalendar","updateFreeBusy","b","isReadOnly","isEditableOccurrence","isInvitation","userHasRSVP","isInvitationOccurrence","enablePercentComplete","coversFreeBusy","quarter","freebusy","updateFreeBusyCoverage","roundedStart","roundedEnd","startQuarter","endQuarter","daysUpTo","index","hourKey","currentDay","dayKey","getHours","beginOfDay","addMinutes","attendees","attendee","image","email","updateFreeBusyAttendee","sday","eday","c_folder","addAttendee","card","$isList","expandable","container","c_name","listId","refs","ref","c_cn","$preferredEmail","role","partstat","c_uid","hasAttendee","emails","deleteAttendee","findIndex","currentAttendee","canRemindAttendeesByEmail","addAttachUrl","attachUrl","attachUrls","deleteAttachUrl","$addDueDate","toISOString","$deleteDueDate","$addStartDate","$deleteStartDate","$reply","reply","delegatedTo","$adjust","every","values","v","extraAttributes","dlp","$mdDateLocaleProvider","format","startTime","endTime","dueTime","stringWithSeparator","organizer","occurrenceOnly","$futureComponentData","copy","repeatDescription","localizedString","toUpperCase","alarmDescription","copyTo","destination","moveTo","CalendarController","$scope","$rootScope","$state","$stateParams","sgHotkeys","stateEventsBlocks","_registerHotkeys","createHotkey","description","callback","changeDate","args","changeView","_goToPeriod","registerHotkey","$event","direction","vm","selectedDate","_formatDate","setHours","$dateFormat","replace","toggleAllDays","expandedAllDays","updateView","asDate","newDate","element","currentTarget","attr","go","deregisterCalendarsList","hotkeys","$on","deregisterHotkey","$inject","controller","CalendarListController","$mdDialog","focus","Dialog","searchMode","newComponent","selectComponentType","reload","unselectComponents","mode","multiple","selectAll","toggleComponentSelection","preventDefault","stopPropagation","confirmDeleteSelectedComponents","confirm","ok","$emit","openEvent","openComponent","openTask","viewable","templateUrl","show","parent","document","body","targetEvent","clickOutsideToClose","escapeToClose","controllerAs","locals","stateComponent","baseComponent","updateComponentFromGhost","RecurrentComponentDialogController","updateThisOccurrence","hide","onComponentAdjustError","updateAllOccurrences","message","AttendeeConflictDialogController","conflictError","ignoreConflicts","coordinates","calendarNumber","activeCalendars","currentEventCoordinates","summary","isAllDay","duration","finally","getDelta","originalEventCoordinates","originalCalendar","isException","template","filteredBy","field","sortedBy","cancelSearch","selectedList","SelectedList","CalendarsController","$window","$mdToast","FileUploader","User","stateCalendars","_sortableAccept","sourceItemHandleScope","destSortableScope","destItemScope","sortableScope","_sortableEnd","toggleSortableMode","sortableMode","resetSort","newCalendar","ev","prompt","UserLogin","addWebCalendar","WebCalendarAuthDialogController","scope","parts","hostname","title","formatted","authenticate","form","$valid","required","reason","$setValidity","inputType","confirmDelete","folder","catch","alert","importCalendar","CalendarImportDialogController","filterByExtension","item","isTextFile","test","position","hideDelay","uploader","ApplicationBaseURL","autoUpload","queueLimit","filters","fn","onSuccessItem","headers","msg","imported","simple","content","onErrorItem","close","showOnly","showAll","showLinks","LinksDialogController","showProperties","PropertiesDialogController","srcCalendar","saveProperties","$watch","editFolder","editMode","revertEditing","renameFolder","share","$users","usersWithACL","users","subscribeToFolder","service","sortableCalendars","scrollableContainer","containment","orderChanged","accept","SOGoCalendarCategories","asCSSIdentifier","pick","newList","oldList","commonList","ids","intersectionBy","oldObject","isEqual","ComponentController","AddressBook","Alarm","Account","cardFilter","$filterAll","$cards","newMessageWithAllRecipients","recipients","_newMessage","newMessageWithRecipient","accounts","account","$getMailboxes","mailboxes","$newMessage","editable","to","subject","stateAccount","stateMessage","edit","editAllOccurrences","c","getAlarms","replyAllOccurrences","deleteOccurrence","deleteAllOccurrences","toggleRawSource","ComponentRawSourceDialogController","copySelectedComponent","moveSelectedComponent","calendarService","ComponentEditorController","toggleRecurrenceEditor","showRecurrenceEditor","toggleAttendeesEditor","showAttendeesEditor","isValidEmail","searchText","removeAttendee","priorityLevel","priority","attendeeConflictError","getDays","hours","addStartDate","oldStartDate","addDueDate","oldDueDate","adjustStartTime","valueOf","oldEndDate","adjustEndTime","adjustDueTime","attendeesEditor","sgCalendarDay","restrict","dayString","sgCalendarDayController","directive","sgCalendarDayBlock","CalendarSettings","tElem","tAttrs","p","has","link","iElement","attrs","pc","left","right","siblings","css","c_isallday","addClass","userState","c_isopaque","c_status","clickBlock","sgCalendarDayTable","sgCalendarGhost","ctrls","initGhost","calendarDayCtrl","originalCalendarNumber","hideGhost","forEachRight","domElement","classList","removeClass","updateGhost","showGhost","isRelative","durationLeft","maxDuration","scrollViewCtrl","getStartTime","quarterHeight","topOffset","getEndTime","quartersToHM","quarters","minutes","mins","floor","deregisterDragStart","deregisterDrag","deregisterDragEnd","require","sgCalendarMonthDay","sgCalendarMonthEvent","sgCalendarScrollView","$document","$mdGesture","sgCalendarScrollViewController","initView","sgScrollView","hourCell","quartersOffset","SOGoDayStartTime","getElementById","scrollTop","offsetTop","$element","getQuarterHeight","scrollStep","getDayNumbers","maxX","getMaxColumns","onDragStart","deregisterDragStop","onDragEnd","bindedUpdateCoordinates","updateCoordinates","bindedUpdateFromPointerHandler","updateFromPointerHandler","on","isMultiColumn","$destroy","off","hour0","hour23","height","getDayDimensions","viewLeft","width","leftOffset","nodes","domRect","tileHeader","getElementsByClassName","getBoundingClientRect","clientHeight","offset","top","getElementsByTagName","el","attributes","mdGridList","max","dayDimensions","x","y","dayHeight","dayWidth","daysOffset","pointerCoordinates","scrollY","minY","getContainerBasedCoordinates","lastScroll","sgCategoryStylesheet","ngModel","sgDraggableCalendarBlock","initGrips","blockIndex","isFirstBlock","isLastBlock","dragGrip","leftGrip","rightGrip","topGrip","bottomGrip","parentNode","tagName","append","clone","onDragDetect","dragMode","target","className","SOGoEventDragPointerHandler","initFromEvent","one","onDrag","dragStart","eventType","isHourCell","isMonthly","newData","hasClass","parseDate","dragging","prepareWithEventType","initFromBlock","initFromCalendar","updateFromEvent","pointer","dragHasStarted","SOGoCoordinates","SOGoEventDragEventCoordinates","setEventType","otherCoordinates","getDistance","sqrt","weekDay","prevDayNumber","sumBy","currentDayNumber","_quartersToHM","originalCoordinates","currentCoordinates","originalViewCoordinates","currentViewCoordinates","getEventViewCoordinates","pageX","pageY","newEventCoordinates","setTimeFromQuarters","updateEventCoordinates","distance","newDuration","deltaQuarters","deltaDays","ceil","clientWidth","methods","multiday","getEventMultiDayViewCoordinates","multiday-allday","getEventMultiDayAllDayViewCoordinates","monthly","getEventMonthlyViewCoordinates","unknown","method","pxCoordinates","maxY","minX","daysTopOffset","daysY","sgNowLine","iAttr","sgCalendarScrollViewCtrl","_getDays","_getView","_unwatchView","_unwatchDays","updateLine","sgNowLineController","_updateLine","force","nowDay","hourHeight","minuteHeight","lineElement","_addLine","updater","$lineElement","dayElement","eq"],"mappings":"CAEA,WACE,YAOA,SAASA,GAASC,GAGhB,GADAC,KAAKC,KAAKF,GACNC,KAAKE,OAASF,KAAKG,GAAI,CAEzB,GAAIC,GAAkBN,EAASO,WAAWC,OAAO,eAAgBN,KAAKE,KACtEF,MAAKO,QAAQH,IASjBN,EAASU,UAAY,KAAM,WAAY,OAAQ,aAAc,WAAY,cAAe,YAAa,MAAO,SAASC,EAAIC,EAAUC,EAAMC,EAAUC,EAAUC,EAAaC,EAAWC,GAanL,MAZAC,SAAQC,OAAOpB,GACbW,GAAIA,EACJC,SAAUA,EACVC,KAAMA,EACNN,WAAY,GAAIQ,GAASD,EAASO,WAAW,aAAe,WAAYP,EAASO,cACjFC,aAAcN,EACdO,WAAYN,EACZO,MAAON,EACPG,WAAYP,EAASO,aACrBI,MAAO,OAGFzB,GAOT,KACEmB,QAAQO,OAAO,oBAEjB,MAAMC,GACJR,QAAQO,OAAO,oBAAqB,gBAEtCP,QAAQO,OAAO,oBACZE,MAAM,oBACLC,mBAAoB,GACpBC,0BAA2B,IAE5BC,QAAQ,WAAY/B,EAASU,UAOhCV,EAASgC,iBAAmB,WAC1B,GACIC,GADAC,EAAkBlC,EAASsB,aAAaa,SAASC,mBAGrD,OAAuB,SAAnBF,IACFD,EAAWI,EAAEC,KAAKtC,EAASuC,SAAS,MAAM,GAAO,SAASN,GACxD,MAAOA,GAASO,UAGTP,EAAS5B,GAGb,YAQTL,EAASyC,KAAO,SAASR,GAEvB,GAAIS,GAAMC,EAASC,CAGjBF,GADET,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,EAAOkC,IAAI,WAAY,WACjB6a,GACF72B,EAASqL,OAAOwrB,KAXtBR,EAAoBna,SAAW,SAAU,WAAY,YA4DrD3b,QACGO,OAAO,oBACP+oB,UAAU,YAAagM","file":"Scheduler.services.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Calendar\n * @constructor\n * @param {object} futureCalendarData - either an object literal or a promise\n */\n function Calendar(futureCalendarData) {\n // Data is immediately available\n this.init(futureCalendarData);\n if (this.name && !this.id) {\n // Create a new calendar on the server\n var newCalendarData = Calendar.$$resource.create('createFolder', this.name);\n this.$unwrap(newCalendarData);\n }\n }\n\n /**\n * @memberof Calendar\n * @desc The factory we'll use to register with Angular\n * @returns the Calendar constructor\n */\n Calendar.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Component', 'Acl', function($q, $timeout, $log, Settings, Resource, Preferences, Component, Acl) {\n angular.extend(Calendar, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Calendar', Settings.activeUser()),\n $Preferences: Preferences,\n $Component: Component,\n $$Acl: Acl,\n activeUser: Settings.activeUser(),\n $view: null\n });\n\n return Calendar; // return constructor\n }];\n\n /**\n * @module SOGo.SchedulerUI\n * @desc Factory registration of Calendar in Angular module.\n */\n try {\n angular.module('SOGo.SchedulerUI');\n }\n catch(e) {\n angular.module('SOGo.SchedulerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.SchedulerUI')\n .value('CalendarSettings', {\n EventDragDayLength: 24 * 4, // hour quarters\n EventDragHorizontalOffset: 3 // pixels\n })\n .factory('Calendar', Calendar.$factory);\n\n /**\n * @memberof Calendar\n * @desc Return the default calendar id according to the user's defaults.\n * @returns a calendar id\n */\n Calendar.$defaultCalendar = function() {\n var defaultCalendar = Calendar.$Preferences.defaults.SOGoDefaultCalendar,\n calendar;\n\n if (defaultCalendar == 'first') {\n calendar = _.find(Calendar.$findAll(null, true), function(calendar) {\n return calendar.active;\n });\n if (calendar)\n return calendar.id;\n }\n\n return 'personal';\n };\n\n /**\n * @memberof Calendar\n * @desc Add a new calendar to the static list of calendars\n * @param {Calendar} calendar - an Calendar object instance\n */\n Calendar.$add = function(calendar) {\n // Insert new calendar at proper index\n var list, sibling, i;\n\n if (calendar.isWebCalendar)\n list = this.$webcalendars;\n else if (calendar.isSubscription)\n list = this.$subscriptions;\n else\n list = this.$calendars;\n\n sibling = _.find(list, function(o) {\n return (calendar.id == 'personal' ||\n (o.id != 'personal' &&\n o.name.localeCompare(calendar.name) === 1));\n });\n i = sibling ? _.indexOf(_.map(list, 'id'), sibling.id) : 1;\n list.splice(i, 0, calendar);\n\n this.$Preferences.ready().then(function() {\n if (Calendar.$Preferences.settings.Calendar.FoldersOrder)\n // Save list order\n Calendar.saveFoldersOrder(_.flatMap(Calendar.$findAll(), 'id')).then(function() {\n // Refresh list of calendars to fetch links associated to new calendar\n Calendar.$reloadAll();\n });\n });\n };\n\n /**\n * @memberof Calendar\n * @desc Set or get the list of calendars. Will instanciate a new Calendar object for each item.\n * @param {object[]} [data] - the metadata of the calendars\n * @param {bool} [writable] - if true, returns only the list of writable calendars\n * @returns the list of calendars\n */\n Calendar.$findAll = function(data, writable) {\n var _this = this;\n if (data) {\n this.$calendars = [];\n this.$subscriptions = [];\n this.$webcalendars = [];\n // Instanciate Calendar objects\n angular.forEach(data, function(o, i) {\n var calendar = new Calendar(o);\n if (calendar.isWebCalendar)\n _this.$webcalendars.push(calendar);\n else if (calendar.isSubscription)\n _this.$subscriptions.push(calendar);\n else\n _this.$calendars.push(calendar);\n });\n }\n else if (angular.isUndefined(this.$calendars)) {\n this.$calendars = [];\n this.$subscriptions = [];\n this.$webcalendars = [];\n return Calendar.$$resource.fetch('calendarslist').then(function(data) {\n return Calendar.$findAll(data.calendars, writable);\n });\n }\n\n if (writable) {\n return _.union(this.$calendars, _.filter(this.$subscriptions, function(calendar) {\n return calendar.isOwned || calendar.acls.objectCreator;\n }));\n }\n\n return _.union(this.$calendars, this.$subscriptions, this.$webcalendars);\n };\n\n /**\n * @memberof Calendar\n * @desc Reload the list of known calendars.\n */\n Calendar.$reloadAll = function() {\n var _this = this;\n\n Calendar.$$resource.fetch('calendarslist').then(function(data) {\n _.forEach(data.calendars, function(calendarData) {\n var group, calendar;\n\n if (calendarData.isWebCalendar)\n group = _this.$webcalendars;\n else if (calendarData.isSubscription)\n group = _this.$subscriptions;\n else\n group = _this.$calendars;\n\n calendar = _.find(group, function(o) { return o.id == calendarData.id; });\n if (calendar)\n calendar.init(calendarData);\n });\n });\n };\n\n /**\n * @memberof Calendar\n * @desc Find a calendar among local instances (personal calendars, subscriptions and Web calendars).\n * @param {string} id - the calendar ID\n * @returns an object literal of the matching Calendar instance\n */\n Calendar.$get = function(id) {\n var calendar;\n\n calendar = _.find(Calendar.$calendars, function(o) { return o.id == id; });\n if (!calendar)\n calendar = _.find(Calendar.$subscriptions, function(o) { return o.id == id; });\n if (!calendar)\n calendar = _.find(Calendar.$webcalendars, function(o) { return o.id == id; });\n\n return calendar;\n };\n\n /**\n * @memberof Calendar\n * @desc Find a calendar among local instances (personal calendars, subscriptions and Web calendars).\n * @param {string} id - the calendar ID\n * @returns an object literal of the matching Calendar instance\n */\n Calendar.$getIndex = function(id) {\n var i;\n\n i = _.indexOf(_.map(Calendar.$calendars, 'id'), id);\n if (i < 0)\n i = _.indexOf(_.map(Calendar.$subscriptions, 'id'), id);\n if (i < 0)\n i = _.indexOf(_.map(Calendar.$webcalendars, 'id'), id);\n\n return i;\n };\n\n /**\n * @memberOf Calendar\n * @desc Subscribe to another user's calendar and add it to the list of calendars.\n * @param {string} uid - user id\n * @param {string} path - path of folder for specified user\n * @returns a promise of the HTTP query result\n */\n Calendar.$subscribe = function(uid, path) {\n var _this = this;\n return Calendar.$$resource.userResource(uid).fetch(path, 'subscribe').then(function(calendarData) {\n var calendar = new Calendar(angular.extend({ active: 1 }, calendarData));\n if (!_.find(_this.$subscriptions, function(o) {\n return o.id == calendarData.id;\n })) {\n Calendar.$add(calendar);\n }\n return calendar;\n });\n };\n\n /**\n * @memberOf Calendar\n * @desc Subscribe to a remote Web calendar\n * @param {string} url - URL of .ics file\n * @returns a promise of the HTTP query result\n */\n Calendar.$addWebCalendar = function(url) {\n var _this = this,\n d = Calendar.$q.defer();\n\n if (_.find(_this.$webcalendars, function(o) {\n return o.urls.webCalendarURL == url;\n })) {\n // Already subscribed\n d.reject();\n }\n else {\n Calendar.$$resource.post(null, 'addWebCalendar', { url: url }).then(function(calendarData) {\n angular.extend(calendarData, {\n isWebCalendar: true,\n isEditable: true,\n isRemote: false,\n owner: Calendar.activeUser.login,\n urls: { webCalendarURL: url }\n });\n var calendar = new Calendar(calendarData);\n Calendar.$$resource.fetch(calendar.id, 'reload').then(function(data) {\n // TODO: show a toast of the reload status\n Calendar.$log.debug(JSON.stringify(data, undefined, 2));\n Calendar.$add(calendar);\n d.resolve();\n }, function(response) {\n if (response.status == 401) {\n // Web calendar requires authentication\n d.resolve(calendar);\n }\n else {\n d.reject();\n }\n });\n }, d.reject);\n }\n\n return d.promise;\n };\n\n /**\n * @function reloadWebCalendars\n * @memberof Calendar\n * @desc Reload all Web calendars\n * @return a promise combining the results of all HTTP operations\n */\n Calendar.reloadWebCalendars = function() {\n var promises = [];\n\n _.forEach(this.$webcalendars, function(calendar) {\n var promise = Calendar.$$resource.fetch(calendar.id, 'reload');\n promise.then(function(data) {\n calendar.$error = false;\n }, function(response) {\n calendar.$error = l(response.statusText);\n });\n promises.push(promise);\n });\n\n return Calendar.$q.all(promises);\n };\n\n /**\n * @function $deleteComponents\n * @memberof Calendar\n * @desc Delete multiple components from calendar.\n * @return a promise of the HTTP operation\n */\n Calendar.$deleteComponents = function(components) {\n var _this = this, calendars = {}, promises = [];\n\n _.forEach(components, function(component) {\n if (!angular.isDefined(calendars[component.pid]))\n calendars[component.pid] = [];\n calendars[component.pid].push(component.id);\n });\n\n _.forEach(calendars, function(uids, pid) {\n promises.push(Calendar.$$resource.post(pid, 'batchDelete', {uids: uids}));\n });\n\n return Calendar.$q.all(promises);\n };\n\n /**\n * @function saveFoldersOrder\n * @desc Save to the user's settings the current calendars order.\n * @param {string[]} folders - the folders IDs\n * @returns a promise of the HTTP operation\n */\n Calendar.saveFoldersOrder = function(folders) {\n return this.$$resource.post(null, 'saveFoldersOrder', { folders: folders }).then(function() {\n Calendar.$Preferences.settings.Calendar.FoldersOrder = folders;\n if (!folders)\n // Calendars order was reset; reload list\n return Calendar.$$resource.fetch('calendarslist').then(function(data) {\n return Calendar.$findAll(data.calendars);\n });\n });\n };\n\n /**\n * @function init\n * @memberof Calendar.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of calendar\n */\n Calendar.prototype.init = function(data) {\n this.color = this.color || '#AAAAAA';\n this.active = 1;\n angular.extend(this, data);\n if (this.id) {\n this.$acl = new Calendar.$$Acl('Calendar/' + this.id);\n }\n // Add 'isOwned' and 'isSubscription' attributes based on active user (TODO: add it server-side?)\n this.isOwned = Calendar.activeUser.isSuperUser || this.owner == Calendar.activeUser.login;\n this.isSubscription = !this.isRemote && this.owner != Calendar.activeUser.login;\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function $id\n * @memberof Calendar.prototype\n * @desc Resolve the calendar id.\n * @returns a promise of the calendar id\n */\n Calendar.prototype.$id = function() {\n if (this.id) {\n // Object already unwrapped\n return Calendar.$q.when(this.id);\n }\n else {\n // Wait until object is unwrapped\n return this.$futureCalendarData.then(function(calendar) {\n return calendar.id;\n });\n }\n };\n\n /**\n * @function getClassName\n * @memberof Calendar.prototype\n * @desc Return the calendar CSS class name based on its ID.\n * @returns a string representing the foreground CSS class name\n */\n Calendar.prototype.getClassName = function(base) {\n if (angular.isUndefined(base))\n base = 'fg';\n return base + '-folder' + this.id;\n };\n\n /**\n * @function $rename\n * @memberof Calendar.prototype\n * @desc Rename the calendar and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$rename = function() {\n var _this = this,\n i,\n calendars;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Calendar.$q.when();\n }\n\n if (this.isWebCalendar)\n calendars = Calendar.$webcalendars;\n else if (this.isSubscription)\n calendars = Calendar.$subscriptions;\n else\n calendars = Calendar.$calendars;\n\n i = _.indexOf(_.map(calendars, 'id'), this.id);\n if (i > -1) {\n return this.$save().then(function() {\n calendars.splice(i, 1);\n Calendar.$add(_this);\n });\n }\n else {\n return Calendar.$q.reject();\n }\n };\n\n /**\n * @function $delete\n * @memberof Calendar.prototype\n * @desc Delete the calendar from the server and the static list of calendars.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$delete = function() {\n var _this = this,\n list,\n promise;\n\n if (this.isSubscription) {\n promise = Calendar.$$resource.fetch(this.id, 'unsubscribe');\n list = Calendar.$subscriptions;\n }\n else {\n promise = Calendar.$$resource.remove(this.id);\n if (this.isWebCalendar)\n list = Calendar.$webcalendars;\n else\n list = Calendar.$calendars;\n }\n\n return promise.then(function() {\n var i = _.indexOf(_.map(list, 'id'), _this.id);\n list.splice(i, 1);\n });\n };\n\n /**\n * @function $reset\n * @memberof Calendar.prototype\n * @desc Reset the original state the calendar's data.\n */\n Calendar.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$') {\n delete _this[key];\n }\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Calendar.prototype\n * @desc Save the calendar properties to the server.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$save = function() {\n var _this = this;\n\n return Calendar.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n return data;\n }, function(data) {\n Calendar.$log.error(JSON.stringify(data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return data;\n });\n };\n\n /**\n * @function setCredentials\n * @memberof Calendar.prototype\n * @desc Set the credentials for a Web calendar that requires authentication\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.setCredentials = function(username, password) {\n var _this = this,\n d = Calendar.$q.defer();\n\n Calendar.$$resource.post(this.id, 'set-credentials', { username: username, password: password }).then(function() {\n Calendar.$$resource.fetch(_this.id, 'reload').then(function(data) {\n Calendar.$add(_this);\n d.resolve();\n }, function(response) {\n if (response.status == 401) {\n // Authentication failed\n d.reject(l('Wrong username or password'));\n }\n else {\n d.reject(response.statusText);\n }\n });\n }, d.reject);\n\n return d.promise;\n };\n\n /**\n * @function export\n * @memberof Calendar.prototype\n * @desc Export the calendar\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.export = function() {\n return Calendar.$$resource.download(this.id + '.ics', 'export', null, {type: 'application/octet-stream'});\n };\n\n /**\n * @function $setActivation\n * @memberof Calendar.prototype\n * @desc Either activate or deactivate the calendar.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$setActivation = function() {\n return Calendar.$$resource.fetch(this.id, (this.active?'':'de') + 'activateFolder');\n };\n\n /**\n * @function $getComponent\n * @memberof Calendar.prototype\n * @desc Fetch a component attributes from the server.\n * @returns a promise of the HTTP operation\n */\n Calendar.prototype.$getComponent = function(componentId, recurrenceId) {\n return Calendar.$Component.$find(this.id, componentId, recurrenceId);\n };\n\n /**\n * @function $unwrap\n * @memberof Calendar.prototype\n * @desc Unwrap a promise\n * @param {promise} futureCalendarData - a promise of the Calendar's data\n */\n Calendar.prototype.$unwrap = function(futureCalendarData) {\n var _this = this;\n\n // Expose and resolve the promise\n this.$futureCalendarData = futureCalendarData.then(function(data) {\n return Calendar.$timeout(function() {\n // Extend Calendar instance with received data\n _this.init(data);\n return _this;\n });\n }, function(data) {\n _this.isError = true;\n if (angular.isObject(data)) {\n Calendar.$timeout(function() {\n angular.extend(_this, data);\n });\n }\n });\n };\n\n /**\n * @function $omit\n * @memberof Calendar.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Calendar instance\n */\n Calendar.prototype.$omit = function() {\n var calendar = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key[0] != '$') {\n calendar[key] = value;\n }\n });\n return calendar;\n };\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Component\n * @constructor\n * @param {object} futureComponentData - either an object literal or a promise\n */\n function Component(futureComponentData) {\n // Data is immediately available\n if (typeof futureComponentData.then !== 'function') {\n this.init(futureComponentData);\n if (this.pid && !this.id) {\n // Prepare for the creation of a new component;\n // Get UID from the server.\n var newComponentData = Component.$$resource.newguid(this.pid);\n this.$unwrap(newComponentData);\n this.isNew = true;\n }\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureComponentData);\n }\n }\n\n /**\n * @memberof Component\n * @desc The factory we'll use to register with Angular\n * @returns the Component constructor\n */\n Component.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgComponent_STATUS', 'Preferences', 'Card', 'Gravatar', 'Resource', function($q, $timeout, $log, Settings, Component_STATUS, Preferences, Card, Gravatar, Resource) {\n angular.extend(Component, {\n STATUS: Component_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $Preferences: Preferences,\n $Card: Card,\n $gravatar: Gravatar,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Calendar', Settings.activeUser()),\n timeFormat: \"%H:%M\",\n // Filter parameters common to events and tasks\n $query: { value: '', search: 'title_Category_Location' },\n // Filter paramaters specific to events\n $queryEvents: { sort: 'start', asc: 1, filterpopup: 'view_next7' },\n // Filter parameters specific to tasks\n $queryTasks: { sort: 'status', asc: 1, filterpopup: 'view_incomplete' },\n $refreshTimeout: null,\n $ghost: {}\n });\n Preferences.ready().then(function() {\n // Initialize filter parameters from user's settings\n if (Preferences.settings.Calendar.EventsFilterState)\n Component.$queryEvents.filterpopup = Preferences.settings.Calendar.EventsFilterState;\n if (Preferences.settings.Calendar.TasksFilterState)\n Component.$queryTasks.filterpopup = Preferences.settings.Calendar.TasksFilterState;\n if (Preferences.settings.Calendar.EventsSortingState) {\n Component.$queryEvents.sort = Preferences.settings.Calendar.EventsSortingState[0];\n Component.$queryEvents.asc = parseInt(Preferences.settings.Calendar.EventsSortingState[1]);\n }\n if (Preferences.settings.Calendar.TasksSortingState) {\n Component.$queryTasks.sort = Preferences.settings.Calendar.TasksSortingState[0];\n Component.$queryTasks.asc = parseInt(Preferences.settings.Calendar.TasksSortingState[1]);\n }\n Component.$queryTasks.show_completed = parseInt(Preferences.settings.ShowCompletedTasks);\n // Initialize categories from user's defaults\n Component.$categories = Preferences.defaults.SOGoCalendarCategoriesColors;\n // Initialize time format from user's defaults\n if (Preferences.defaults.SOGoTimeFormat) {\n Component.timeFormat = Preferences.defaults.SOGoTimeFormat;\n }\n });\n\n return Component; // return constructor\n }];\n\n /**\n * @module SOGo.SchedulerUI\n * @desc Factory registration of Component in Angular module.\n */\n try {\n angular.module('SOGo.SchedulerUI');\n }\n catch(e) {\n angular.module('SOGo.SchedulerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.SchedulerUI')\n .constant('sgComponent_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Component', Component.$factory);\n\n /**\n * @function $selectedCount\n * @memberof Component\n * @desc Return the number of events or tasks selected by the user.\n * @returns the number of selected events or tasks\n */\n Component.$selectedCount = function() {\n var count;\n\n count = 0;\n if (Component.$events) {\n count += (_.filter(Component.$events, function(event) { return event.selected; })).length;\n }\n if (Component.$tasks) {\n count += (_.filter(Component.$tasks, function(task) { return task.selected; })).length;\n }\n return count;\n };\n\n /**\n * @function $startRefreshTimeout\n * @memberof Component\n * @desc Starts the refresh timeout for the current selected component type, for all calendars\n */\n Component.$startRefreshTimeout = function(type) {\n var _this = this;\n\n if (Component.$refreshTimeout)\n Component.$timeout.cancel(Component.$refreshTimeout);\n\n Component.$Preferences.ready().then(function() {\n // Restart the refresh timer, if needed\n var refreshViewCheck = Component.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Component.$filter, type);\n Component.$refreshTimeout = Component.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Component\n * @returns true if the components list is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Component.$isLoading = function() {\n return Component.$loaded == Component.STATUS.LOADING;\n };\n\n /**\n * @function $filter\n * @memberof Component\n * @desc Search for components matching some criterias\n * @param {string} type - either 'events' or 'tasks'\n * @param {object} [options] - additional options to the query\n * @returns a collection of Components instances\n */\n Component.$filter = function(type, options) {\n var _this = this,\n now = new Date(),\n day = now.getDate(),\n month = now.getMonth() + 1,\n year = now.getFullYear(),\n queryKey = '$query' + type.capitalize(),\n params = {\n day: '' + year + (month < 10?'0':'') + month + (day < 10?'0':'') + day,\n };\n\n Component.$startRefreshTimeout(type);\n\n return this.$Preferences.ready().then(function() {\n var futureComponentData,\n dirty = false,\n otherType;\n\n angular.extend(_this.$query, params);\n\n if (options) {\n _.forEach(_.keys(options), function(key) {\n // Query parameters common to events and tasks are compared\n dirty |= (_this.$query[key] && options[key] != Component.$query[key]);\n if (key == 'reload' && options[key])\n dirty = true;\n // Update either the common parameters or the type-specific parameters\n else if (angular.isDefined(_this.$query[key]))\n _this.$query[key] = options[key];\n else\n _this[queryKey][key] = options[key];\n });\n }\n\n // Perform query with both common and type-specific parameters\n futureComponentData = _this.$$resource.fetch(null, type + 'list',\n angular.extend(_this[queryKey], _this.$query));\n\n // Invalidate cached results of other type if $query has changed\n otherType = (type == 'tasks')? '$events' : '$tasks';\n if (dirty) {\n delete Component[otherType];\n Component.$log.debug('force reload of ' + otherType);\n }\n\n return _this.$unwrapCollection(type, futureComponentData);\n });\n };\n\n /**\n * @function $find\n * @desc Fetch a component from a specific calendar.\n * @param {string} calendarId - the calendar ID\n * @param {string} componentId - the component ID\n * @param {string} [occurrenceId] - the component ID\n * @see {@link Calendar.$getComponent}\n */\n Component.$find = function(calendarId, componentId, occurrenceId) {\n var futureComponentData, path = [calendarId, componentId];\n\n if (occurrenceId)\n path.push(occurrenceId);\n\n futureComponentData = this.$$resource.fetch(path.join('/'), 'view');\n\n return new Component(futureComponentData);\n };\n\n /**\n * @function filterCategories\n * @desc Search for categories matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Component.filterCategories = function(query) {\n var re = new RegExp(query, 'i');\n return _.filter(_.keys(Component.$categories), function(category) {\n return category.search(re) != -1;\n });\n };\n\n /**\n * @function saveSelectedList\n * @desc Save to the user's settings the currently selected list.\n * @param {string} componentType - either \"events\" or \"tasks\"\n * @returns a promise of the HTTP operation\n */\n Component.saveSelectedList = function(componentType) {\n return this.$$resource.post(null, 'saveSelectedList', { list: componentType + 'ListView' });\n };\n\n /**\n * @function $eventsBlocksForView\n * @desc Events blocks for a specific week\n * @param {string} view - Either 'day' or 'week'\n * @param {Date} type - Date of any day of the desired period\n * @returns a promise of a collection of objects describing the events blocks\n */\n Component.$eventsBlocksForView = function(view, date) {\n var _this = this;\n\n return Component.$Preferences.ready().then(function(data) {\n var firstDayOfWeek, viewAction, startDate, endDate, params;\n firstDayOfWeek = Component.$Preferences.defaults.SOGoFirstDayOfWeek;\n\n if (view == 'day') {\n viewAction = 'dayView';\n startDate = endDate = date;\n }\n else if (view == 'multicolumnday') {\n viewAction = 'multicolumndayView';\n startDate = endDate = date;\n }\n else if (view == 'week') {\n viewAction = 'weekView';\n startDate = date.beginOfWeek(firstDayOfWeek);\n endDate = new Date();\n endDate.setTime(startDate.getTime());\n endDate.addDays(6);\n }\n else if (view == 'month') {\n viewAction = 'monthView';\n startDate = date;\n startDate.setDate(1);\n startDate = startDate.beginOfWeek(firstDayOfWeek);\n endDate = new Date();\n endDate.setTime(date.getTime());\n endDate.setMonth(endDate.getMonth() + 1);\n endDate.addDays(-1);\n endDate = endDate.endOfWeek(firstDayOfWeek);\n }\n return _this.$eventsBlocks(viewAction, startDate, endDate);\n });\n };\n\n /**\n * @function $eventsBlocks\n * @desc Events blocks for a specific view and period\n * @param {string} view - Either 'day', 'multicolumnday', 'week' or 'month'\n * @param {Date} startDate - period's start date\n * @param {Date} endDate - period's end date\n * @returns a promise of a collection of objects describing the events blocks\n */\n Component.$eventsBlocks = function(view, startDate, endDate) {\n var params, futureComponentData, i, j, dayDates = [], dayNumbers = [],\n deferred = Component.$q.defer();\n\n params = { view: view.toLowerCase(), sd: startDate.getDayString(), ed: endDate.getDayString() };\n futureComponentData = this.$$resource.fetch(null, 'eventsblocks', params);\n futureComponentData.then(function(views) {\n var reduceComponent, associateComponent;\n\n reduceComponent = function(objects, eventData, i) {\n var componentData = _.zipObject(this.eventsFields, eventData),\n start = new Date(componentData.c_startdate * 1000),\n component;\n componentData.hour = start.getHourString();\n componentData.blocks = [];\n component = new Component(componentData);\n // Filter out categories for which there's no associated color\n component.categories = _.filter(component.categories, function(name) {\n return Component.$Preferences.defaults.SOGoCalendarCategoriesColors[name];\n });\n objects.push(component);\n return objects;\n };\n\n associateComponent = function(block) {\n this[block.nbr].blocks.push(block); // Associate block to component\n block.component = this[block.nbr]; // Associate component to block\n block.isFirst = (this[block.nbr].blocks.length == 1);\n };\n\n Component.$views = [];\n Component.$timeout(function() {\n _.forEach(views, function(data, viewIndex) {\n var components = [], blocks = {}, allDayBlocks = {}, viewData;\n\n // Change some attributes names\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_folder'), 1, 'pid');\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_name'), 1, 'id');\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_recurrence_id'), 1, 'occurrenceId');\n data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_title'), 1, 'summary');\n\n // Instantiate Component objects\n _.reduce(data.events, _.bind(reduceComponent, data), components);\n\n // Associate Component objects to blocks positions\n _.forEach(_.flatten(data.blocks), _.bind(associateComponent, components));\n\n // Associate Component objects to all-day blocks positions\n _.forEach(_.flatten(data.allDayBlocks), _.bind(associateComponent, components));\n\n // Build array of dates\n if (dayDates.length === 0) {\n dayDates = _.flatMap(data.days, 'date');\n dayNumbers = _.flatMap(data.days, 'number');\n }\n\n // Convert array of blocks to an object literal with date strings as keys\n for (i = 0; i < data.blocks.length; i++) {\n for (j = 0; j < data.blocks[i].length; j++) {\n data.blocks[i][j].dayIndex = i + (viewIndex * data.blocks.length);\n data.blocks[i][j].dayNumber = dayNumbers[i];\n }\n blocks[dayDates[i]] = data.blocks[i];\n }\n\n // Convert array of all-day blocks to object with days as keys\n for (i = 0; i < data.allDayBlocks.length; i++) {\n for (j = 0; j < data.allDayBlocks[i].length; j++) {\n data.allDayBlocks[i][j].dayIndex = i + (viewIndex * data.allDayBlocks.length);\n data.allDayBlocks[i][j].dayNumber = dayNumbers[i];\n }\n allDayBlocks[dayDates[i]] = data.allDayBlocks[i];\n }\n\n // \"blocks\" is now an object literal with the following structure:\n // { day: [\n // { start: number,\n // length: number,\n // siblings: number,\n // realSiblings: number,\n // position: number,\n // nbr: number,\n // component: Component },\n // .. ],\n // .. }\n //\n // Where day is a string with format YYYYMMDD\n\n Component.$log.debug('blocks ready (' + _.flatten(data.blocks).length + ')');\n Component.$log.debug('all day blocks ready (' + _.flatten(data.allDayBlocks).length + ')');\n\n // Save the blocks to the object model\n viewData = { blocks: blocks, allDayBlocks: allDayBlocks };\n if (data.id && data.calendarName) {\n // The multicolumnday view also includes calendar information\n viewData.id = data.id;\n viewData.calendarName = data.calendarName;\n }\n Component.$views.push(viewData);\n });\n\n deferred.resolve(Component.$views);\n });\n }, deferred.reject);\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapCollection\n * @desc Unwrap a promise and instanciate new Component objects using received data.\n * @param {string} type - either 'events' or 'tasks'\n * @param {promise} futureComponentData - a promise of the components' metadata\n * @returns a promise of the HTTP operation\n */\n Component.$unwrapCollection = function(type, futureComponentData) {\n var _this = this,\n components = [];\n\n // Components list is not loaded yet\n Component.$loaded = Component.STATUS.DELAYED_LOADING;\n Component.$timeout(function() {\n if (Component.$loaded != Component.STATUS.LOADED)\n Component.$loaded = Component.STATUS.LOADING;\n }, Component.STATUS.DELAYED_MS);\n\n return futureComponentData.then(function(data) {\n return Component.$timeout(function() {\n var fields = _.invokeMap(data.fields, 'toLowerCase');\n fields.splice(_.indexOf(fields, 'c_folder'), 1, 'pid');\n fields.splice(_.indexOf(fields, 'c_name'), 1, 'id');\n fields.splice(_.indexOf(fields, 'c_recurrence_id'), 1, 'occurrenceId');\n\n // Instanciate Component objects\n _.reduce(data[type], function(components, componentData, i) {\n var data = _.zipObject(fields, componentData), component;\n component = new Component(data);\n // Filter out categories for which there's no associated color\n component.categories = _.filter(component.categories, function(name) {\n return Component.$Preferences.defaults.SOGoCalendarCategoriesColors[name];\n });\n components.push(component);\n return components;\n }, components);\n\n Component.$log.debug('list of ' + type + ' ready (' + components.length + ')');\n\n // Save the list of components to the object model\n Component['$' + type] = components;\n\n Component.$loaded = Component.STATUS.LOADED;\n\n return components;\n });\n });\n };\n\n /**\n * @function $resetGhost\n * @desc Prepare the ghost object for the next drag by resetting appropriate attributes\n */\n Component.$resetGhost = function() {\n this.$ghost.pointerHandler = null;\n this.$ghost.component = null;\n this.$ghost.startHour = null;\n this.$ghost.endHour = null;\n };\n\n /**\n * @function $parseDate\n * @desc Parse a date string with format YYYY-MM-DDTHH:MM\n * @param {string} dateString - the string representing the date\n * @param {object} [options] - additional options (use {no_time: true} to ignore the time)\n * @returns a date object\n */\n Component.$parseDate = function(dateString, options) {\n var date, time;\n\n date = dateString.substring(0,10).split('-');\n\n if (options && options.no_time)\n return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]));\n\n time = dateString.substring(11,16).split(':');\n\n return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]),\n parseInt(time[0]), parseInt(time[1]), 0, 0);\n };\n\n /**\n * @function init\n * @memberof Component.prototype\n * @desc Extend instance with required attributes and new data.\n * @param {object} data - attributes of component\n */\n Component.prototype.init = function(data) {\n var _this = this;\n\n this.categories = [];\n this.repeat = {};\n this.alarm = { action: 'display', quantity: 5, unit: 'MINUTES', reference: 'BEFORE', relation: 'START' };\n this.status = 'not-specified';\n this.delta = 60;\n angular.extend(this, data);\n\n if (this.component == 'vevent')\n this.type = 'appointment';\n else if (this.component == 'vtodo')\n this.type = 'task';\n\n if (this.startDate) {\n if (angular.isString(this.startDate))\n // Ex: 2015-10-25T22:34:51+00:00\n this.start = Component.$parseDate(this.startDate);\n else\n // Date object\n this.start = this.startDate;\n }\n else if (this.type == 'appointment') {\n this.start = new Date();\n this.start.setMinutes(Math.round(this.start.getMinutes()/15)*15);\n }\n\n if (this.endDate) {\n this.end = Component.$parseDate(this.endDate);\n this.delta = this.start.minutesTo(this.end);\n }\n else if (this.type == 'appointment') {\n this.setDelta(this.delta);\n }\n\n if (this.dueDate)\n this.due = Component.$parseDate(this.dueDate);\n\n if (this.completedDate)\n this.completed = Component.$parseDate(this.completedDate);\n else if (this.type == 'task')\n this.completed = new Date();\n\n if (this.c_category)\n this.categories = _.invokeMap(this.c_category, 'asCSSIdentifier');\n\n // Parse recurrence rule definition and initialize default values\n this.$isRecurrent = angular.isDefined(data.repeat);\n if (this.repeat.days) {\n var byDayMask = _.find(this.repeat.days, function(o) {\n return angular.isDefined(o.occurrence);\n });\n if (byDayMask) {\n if (this.repeat.frequency == 'yearly')\n this.repeat.year = { byday: true };\n this.repeat.month = {\n type: 'byday',\n occurrence: byDayMask.occurrence.toString(),\n day: byDayMask.day\n };\n }\n }\n else {\n this.repeat.days = [];\n }\n if (angular.isUndefined(this.repeat.frequency))\n this.repeat.frequency = 'never';\n if (angular.isUndefined(this.repeat.interval))\n this.repeat.interval = 1;\n if (angular.isUndefined(this.repeat.month))\n this.repeat.month = { occurrence: '1', day: 'SU', type: 'bymonthday' };\n if (angular.isUndefined(this.repeat.monthdays))\n // TODO: initialize this.repeat.monthdays with month day of start date\n this.repeat.monthdays = [];\n if (angular.isUndefined(this.repeat.months))\n // TODO: initialize this.repeat.months with month of start date\n this.repeat.months = [];\n if (angular.isUndefined(this.repeat.year))\n this.repeat.year = {};\n if (this.repeat.count)\n this.repeat.end = 'count';\n else if (this.repeat.until) {\n this.repeat.end = 'until';\n this.repeat.until = Component.$parseDate(this.repeat.until, { no_time: true });\n }\n else\n this.repeat.end = 'never';\n this.$hasCustomRepeat = this.hasCustomRepeat();\n\n if (this.isNew) {\n // Set default values\n Component.$Preferences.ready().then(function() {\n var type = (_this.type == 'appointment')? 'Events' : 'Tasks';\n\n // Set default classification\n _this.classification = Component.$Preferences.defaults['SOGoCalendar' + type + 'DefaultClassification'].toLowerCase();\n\n // Set default alarm\n var units = { M: 'MINUTES', H: 'HOURS', D: 'DAYS', W: 'WEEKS' };\n var match = /-PT?([0-9]+)([MHDW])/.exec(Component.$Preferences.defaults.SOGoCalendarDefaultReminder);\n if (match) {\n _this.$hasAlarm = true;\n _this.alarm.quantity = parseInt(match[1]);\n _this.alarm.unit = units[match[2]];\n }\n\n // Set notitifications\n _this.sendAppointmentNotifications = Component.$Preferences.defaults.SOGoAppointmentSendEMailNotifications;\n });\n }\n else {\n this.$hasAlarm = angular.isDefined(data.alarm);\n }\n\n // Allow the component to be moved to a different calendar\n this.destinationCalendar = this.pid;\n\n // if (this.organizer && this.organizer.email) {\n // this.organizer.$image = Component.$gravatar(this.organizer.email, 32);\n // }\n\n // Load freebusy of attendees\n this.updateFreeBusy();\n\n this.selected = false;\n };\n\n /**\n * @function hasCustomRepeat\n * @memberof Component.prototype\n * @desc Check if the component has a custom recurrence rule.\n * @returns true if the recurrence rule requires the full recurrence editor\n */\n Component.prototype.hasCustomRepeat = function() {\n var b = angular.isDefined(this.repeat) &&\n (this.repeat.interval > 1 ||\n this.repeat.days && this.repeat.days.length > 0 ||\n this.repeat.monthdays && this.repeat.monthdays.length > 0 ||\n this.repeat.months && this.repeat.months.length > 0);\n return b;\n };\n\n /**\n * @function isEditable\n * @memberof Component.prototype\n * @desc Check if the component is editable and not an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isEditable = function() {\n return (!this.occurrenceId && !this.isReadOnly);\n };\n\n /**\n * @function isEditableOccurrence\n * @memberof Component.prototype\n * @desc Check if the component is editable and an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isEditableOccurrence = function() {\n return (this.occurrenceId && !this.isReadOnly);\n };\n\n /**\n * @function isInvitation\n * @memberof Component.prototype\n * @desc Check if the component an invitation and not an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isInvitation = function() {\n return (!this.occurrenceId && this.userHasRSVP);\n };\n\n /**\n * @function isInvitationOccurrence\n * @memberof Component.prototype\n * @desc Check if the component an invitation and an occurrence of a recurrent component\n * @returns true or false\n */\n Component.prototype.isInvitationOccurrence = function() {\n return (this.occurrenceId && this.userHasRSVP);\n };\n\n /**\n * @function isReadOnly\n * @memberof Component.prototype\n * @desc Check if the component is not editable and not an invitation\n * @returns true or false\n */\n Component.prototype.isReadOnly = function() {\n return (this.isReadOnly && !this.userHasRSVP);\n };\n\n /**\n * @function enablePercentComplete\n * @memberof Component.prototype\n * @desc Check if the percent completion should be enabled with respect to the\n * component's type and status.\n * @returns true if the percent completion should be displayed\n */\n Component.prototype.enablePercentComplete = function() {\n return (this.type == 'task' &&\n this.status != 'not-specified' &&\n this.status != 'cancelled');\n };\n\n /**\n * @function coversFreeBusy\n * @memberof Component.prototype\n * @desc Check if a specific quarter matches the component's period\n * @returns true if the quarter covers the component's period\n */\n Component.prototype.coversFreeBusy = function(day, hour, quarter) {\n var b = (angular.isDefined(this.freebusy[day]) &&\n angular.isDefined(this.freebusy[day][hour]) &&\n this.freebusy[day][hour][quarter] == 1);\n return b;\n };\n\n /**\n * @function updateFreeBusyCoverage\n * @memberof Component.prototype\n * @desc Build a 15-minute-based representation of the component's period.\n * @returns an object literal hashed by days and hours and arrays of four 1's and 0's\n */\n Component.prototype.updateFreeBusyCoverage = function() {\n var _this = this, freebusy = {};\n\n if (this.start && this.end) {\n var roundedStart = new Date(this.start.getTime()),\n roundedEnd = new Date(this.end.getTime()),\n startQuarter = parseInt(roundedStart.getMinutes()/15 + 0.5),\n endQuarter = parseInt(roundedEnd.getMinutes()/15 + 0.5);\n roundedStart.setMinutes(15*startQuarter);\n roundedEnd.setMinutes(15*endQuarter);\n\n _.forEach(roundedStart.daysUpTo(roundedEnd), function(date, index) {\n var currentDay = date.getDate(),\n dayKey = date.getDayString(),\n hourKey;\n if (dayKey == _this.start.getDayString()) {\n hourKey = date.getHours().toString();\n freebusy[dayKey] = {};\n freebusy[dayKey][hourKey] = [];\n while (startQuarter > 0) {\n freebusy[dayKey][hourKey].push(0);\n startQuarter--;\n }\n }\n else {\n date = date.beginOfDay();\n freebusy[dayKey] = {};\n }\n while (date.getTime() < _this.end.getTime() &&\n date.getDate() == currentDay) {\n hourKey = date.getHours().toString();\n if (angular.isUndefined(freebusy[dayKey][hourKey]))\n freebusy[dayKey][hourKey] = [];\n freebusy[dayKey][hourKey].push(1);\n date.addMinutes(15);\n }\n });\n return freebusy;\n }\n };\n\n /**\n * @function updateFreeBusy\n * @memberof Component.prototype\n * @desc Update the freebusy coverage representation and the attendees freebusy information\n */\n Component.prototype.updateFreeBusy = function() {\n var _this = this;\n\n this.freebusy = this.updateFreeBusyCoverage();\n\n if (this.attendees) {\n _.forEach(this.attendees, function(attendee) {\n attendee.image = Component.$gravatar(attendee.email, 32);\n _this.updateFreeBusyAttendee(attendee);\n });\n }\n };\n\n /**\n * @function setDelta\n * @memberof Component.prototype\n * @desc Set the end time to the specified number of minutes after the start time.\n * @param {number} delta - the number of minutes\n */\n Component.prototype.setDelta = function(delta) {\n this.delta = delta;\n this.end = new Date(this.start.getTime());\n this.end.setMinutes(Math.round(this.end.getMinutes()/15)*15);\n this.end.addMinutes(this.delta);\n };\n\n /**\n * @function updateFreeBusyAttendee\n * @memberof Component.prototype\n * @desc Update the freebusy information for the component's period for a specific attendee.\n * @param {Object} card - an Card object instance of the attendee\n */\n Component.prototype.updateFreeBusyAttendee = function(attendee) {\n var params, url, days;\n if (attendee.uid) {\n params =\n {\n sday: this.start.getDayString(),\n eday: this.end.getDayString()\n };\n url = ['..', '..', attendee.uid, 'freebusy.ifb'];\n days = _.map(this.start.daysUpTo(this.end), function(day) { return day.getDayString(); });\n\n if (angular.isUndefined(attendee.freebusy))\n attendee.freebusy = {};\n\n // Fetch FreeBusy information\n Component.$$resource.fetch(url.join('/'), 'ajaxRead', params).then(function(data) {\n _.forEach(days, function(day) {\n var hour;\n\n if (angular.isUndefined(attendee.freebusy[day]))\n attendee.freebusy[day] = {};\n\n if (angular.isUndefined(data[day]))\n data[day] = {};\n\n for (var i = 0; i <= 23; i++) {\n hour = i.toString();\n if (data[day][hour])\n attendee.freebusy[day][hour] = [\n data[day][hour][\"0\"],\n data[day][hour][\"15\"],\n data[day][hour][\"30\"],\n data[day][hour][\"45\"]\n ];\n else\n attendee.freebusy[day][hour] = [0, 0, 0, 0];\n }\n });\n });\n }\n };\n\n /**\n * @function getClassName\n * @memberof Component.prototype\n * @desc Return the component CSS class name based on its container (calendar) ID.\n * @param {string} [base] - the prefix to add to the class name (defaults to \"fg\")\n * @returns a string representing the foreground CSS class name\n */\n Component.prototype.getClassName = function(base) {\n if (angular.isUndefined(base))\n base = 'fg';\n return base + '-folder' + (this.destinationCalendar || this.c_folder || this.pid);\n };\n\n /**\n * @function addAttendee\n * @memberof Component.prototype\n * @desc Add an attendee and fetch his freebusy info.\n * @param {Object} card - an Card object instance to be added to the attendees list\n */\n Component.prototype.addAttendee = function(card) {\n var _this = this, attendee, list, url, params;\n if (card) {\n if (card.$isList({expandable: true})) {\n // Decompose list members\n list = Component.$Card.$find(card.container, card.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n attendee = {\n name: ref.c_cn,\n email: ref.$preferredEmail(),\n role: 'req-participant',\n partstat: 'needs-action',\n uid: ref.c_uid\n };\n if (!_.find(_this.attendees, function(o) {\n return o.email == attendee.email;\n })) {\n // Contact is not already an attendee, add it\n attendee.image = Component.$gravatar(attendee.email, 32);\n if (_this.attendees)\n _this.attendees.push(attendee);\n else\n _this.attendees = [attendee];\n _this.updateFreeBusyAttendee(attendee);\n }\n });\n });\n }\n else {\n // Single contact\n attendee = {\n name: card.c_cn,\n email: card.$preferredEmail(),\n role: 'req-participant',\n partstat: 'needs-action',\n uid: card.c_uid\n };\n if (!_.find(this.attendees, function(o) {\n return o.email == attendee.email;\n })) {\n attendee.image = Component.$gravatar(attendee.email, 32);\n if (this.attendees)\n this.attendees.push(attendee);\n else\n this.attendees = [attendee];\n this.updateFreeBusyAttendee(attendee);\n }\n }\n }\n };\n\n /**\n * @function hasAttendee\n * @memberof Component.prototype\n * @desc Verify if one of the email addresses of a Card instance matches an attendee.\n * @param {Object} card - an Card object instance\n * @returns true if the Card matches an attendee\n */\n Component.prototype.hasAttendee = function(card) {\n var attendee = _.find(this.attendees, function(attendee) {\n return _.find(card.emails, function(email) {\n return email.value == attendee.email;\n });\n });\n return angular.isDefined(attendee);\n };\n\n /**\n * @function deleteAttendee\n * @memberof Component.prototype\n * @desc Remove an attendee from the component\n * @param {Object} attendee - an object literal defining an attendee\n */\n Component.prototype.deleteAttendee = function(attendee) {\n var index = _.findIndex(this.attendees, function(currentAttendee) {\n return currentAttendee.email == attendee.email;\n });\n this.attendees.splice(index, 1);\n };\n\n /**\n * @function canRemindAttendeesByEmail\n * @memberof Component.prototype\n * @desc Verify if the component's reminder must be send by email and if it has at least one attendee.\n * @returns true if attendees can receive a reminder by email\n */\n Component.prototype.canRemindAttendeesByEmail = function() {\n return this.alarm.action == 'email' &&\n !this.isReadOnly &&\n this.attendees && this.attendees.length > 0;\n };\n\n /**\n * @function addAttachUrl\n * @memberof Component.prototype\n * @desc Add a new attach URL if not already defined\n * @param {string} attachUrl - the URL\n * @returns the number of values in the list of attach URLs\n */\n Component.prototype.addAttachUrl = function(attachUrl) {\n if (angular.isUndefined(this.attachUrls)) {\n this.attachUrls = [{value: attachUrl}];\n }\n else {\n for (var i = 0; i < this.attachUrls.length; i++) {\n if (this.attachUrls[i].value == attachUrl) {\n break;\n }\n }\n if (i == this.attachUrls.length)\n this.attachUrls.push({value: attachUrl});\n }\n return this.attachUrls.length - 1;\n };\n\n /**\n * @function deleteAttachUrl\n * @memberof Component.prototype\n * @desc Remove an attach URL\n * @param {number} index - the URL index in the list of attach URLs\n */\n Component.prototype.deleteAttachUrl = function(index) {\n if (index > -1 && this.attachUrls.length > index) {\n this.attachUrls.splice(index, 1);\n }\n };\n\n /**\n * @function $addDueDate\n * @memberof Component.prototype\n * @desc Add a due date\n */\n Component.prototype.$addDueDate = function() {\n this.due = new Date();\n this.due.setMinutes(Math.round(this.due.getMinutes()/15)*15);\n this.dueDate = this.due.toISOString();\n };\n\n /**\n * @function $deleteDueDate\n * @memberof Component.prototype\n * @desc Delete a due date\n */\n Component.prototype.$deleteDueDate = function() {\n delete this.due;\n delete this.dueDate;\n };\n\n /**\n * @function $addStartDate\n * @memberof Component.prototype\n * @desc Add a start date\n */\n Component.prototype.$addStartDate = function() {\n this.start = new Date();\n this.start.setMinutes(Math.round(this.start.getMinutes()/15)*15);\n };\n\n /**\n * @function $deleteStartDate\n * @memberof Component.prototype\n * @desc Delete a start date\n */\n Component.prototype.$deleteStartDate = function() {\n delete this.start;\n delete this.startDate;\n };\n\n /**\n * @function $reset\n * @memberof Component.prototype\n * @desc Reset the original state the component's data.\n */\n Component.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$') {\n delete _this[key];\n }\n });\n this.init(this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $reply\n * @memberof Component.prototype\n * @desc Reply to an invitation.\n * @returns a promise of the HTTP operation\n */\n Component.prototype.$reply = function() {\n var _this = this, data, path = [this.pid, this.id];\n\n if (this.occurrenceId)\n path.push(this.occurrenceId);\n\n data = {\n reply: this.reply,\n delegatedTo: this.delegatedTo,\n alarm: this.$hasAlarm? this.alarm : {}\n };\n\n return Component.$$resource.save(path.join('/'), data, { action: 'rsvpAppointment' })\n .then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n return data;\n });\n };\n\n /**\n * @function $adjust\n * @memberof Component.prototype\n * @desc Adjust the start, day, and/or duration of the component\n * @returns a promise of the HTTP operation\n */\n Component.prototype.$adjust = function(params) {\n var path = [this.pid, this.id];\n\n if (_.every(_.values(params), function(v) { return v === 0; }))\n // No changes\n return Component.$q.when();\n\n if (this.occurrenceId)\n path.push(this.occurrenceId);\n\n Component.$log.debug('adjust ' + path.join('/') + ' ' + JSON.stringify(params));\n\n return Component.$$resource.save(path.join('/'), params, { action: 'adjust' });\n };\n\n /**\n * @function $save\n * @memberof Component.prototype\n * @desc Save the component to the server.\n * @param {object} extraAttributes - additional attributes to send to the server\n */\n Component.prototype.$save = function(extraAttributes) {\n var _this = this, options, path, component, date, dlp;\n\n component = this.$omit();\n dlp = Component.$Preferences.$mdDateLocaleProvider;\n\n // Format dates and times\n component.startDate = component.start ? component.start.format(dlp, '%Y-%m-%d') : '';\n component.startTime = component.start ? component.start.format(dlp, '%H:%M') : '';\n component.endDate = component.end ? component.end.format(dlp, '%Y-%m-%d') : '';\n component.endTime = component.end ? component.end.format(dlp, '%H:%M') : '';\n component.dueDate = component.due ? component.due.format(dlp, '%Y-%m-%d') : '';\n component.dueTime = component.due ? component.due.format(dlp, '%H:%M') : '';\n component.completedDate = component.completed ? component.completed.format(dlp, '%Y-%m-%d') : '';\n\n // Update recurrence definition depending on selections\n if (this.$hasCustomRepeat) {\n if (this.repeat.frequency == 'monthly' && this.repeat.month.type && this.repeat.month.type == 'byday' ||\n this.repeat.frequency == 'yearly' && this.repeat.year.byday) {\n // BYDAY mask for a monthly or yearly recurrence\n delete component.repeat.monthdays;\n component.repeat.days = [{ day: this.repeat.month.day, occurrence: this.repeat.month.occurrence.toString() }];\n }\n else if ((this.repeat.frequency == 'monthly' || this.repeat.frequency == 'yearly') &&\n this.repeat.month.type) {\n // montly recurrence by month days or yearly by month\n delete component.repeat.days;\n }\n }\n else if (this.repeat.frequency && this.repeat.frequency != 'never') {\n component.repeat = { frequency: this.repeat.frequency };\n }\n if (this.repeat.frequency) {\n if (this.repeat.end == 'until' && this.repeat.until)\n component.repeat.until = this.repeat.until.stringWithSeparator('-');\n else if (this.repeat.end == 'count' && this.repeat.count)\n component.repeat.count = this.repeat.count;\n else {\n delete component.repeat.until;\n delete component.repeat.count;\n }\n }\n else {\n delete component.repeat;\n }\n\n // Check status\n if (this.status == 'not-specified')\n delete component.status;\n else if (this.status != 'completed')\n delete component.completedDate;\n\n // Verify alarm\n if (this.$hasAlarm) {\n if (this.alarm.action && this.alarm.action == 'email' &&\n !(this.attendees && this.attendees.length > 0)) {\n // No attendees; email reminder must be sent to organizer only\n component.alarm.attendees = 0;\n component.alarm.organizer = 1;\n }\n }\n else {\n component.alarm = {};\n }\n\n // Build URL\n path = [this.pid, this.id];\n\n if (this.isNew)\n options = { action: 'saveAs' + this.type.capitalize() };\n\n if (this.occurrenceId)\n path.push(this.occurrenceId);\n\n angular.extend(component, extraAttributes);\n\n return Component.$$resource.save(path.join('/'), component, options)\n .then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n return data;\n });\n };\n\n /**\n * @function $delete\n * @memberof Component.prototype\n * @desc Delete the component from the server.\n * @param {boolean} occurrenceOnly - delete this occurrence only\n */\n Component.prototype.remove = function(occurrenceOnly) {\n var _this = this, path = [this.pid, this.id];\n\n if (occurrenceOnly && this.occurrenceId)\n path.push(this.occurrenceId);\n\n return Component.$$resource.remove(path.join('/'));\n };\n\n /**\n * @function $unwrap\n * @memberof Component.prototype\n * @desc Unwrap a promise.\n * @param {promise} futureComponentData - a promise of some of the Component's data\n */\n Component.prototype.$unwrap = function(futureComponentData) {\n var _this = this;\n\n // Expose the promise\n this.$futureComponentData = futureComponentData;\n\n // Resolve the promise\n this.$futureComponentData.then(function(data) {\n _this.init(data);\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n Component.$log.error(_this.error);\n });\n };\n\n /**\n * @function $omit\n * @memberof Component.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Component instance\n */\n Component.prototype.$omit = function() {\n var component = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key[0] != '$' &&\n key != 'blocks') {\n component[key] = angular.copy(value);\n }\n });\n\n return component;\n };\n\n /**\n * @function repeatDescription\n * @memberof Component.prototype\n * @desc Return a localized description of the recurrence definition\n * @return a localized string\n */\n Component.prototype.repeatDescription = function() {\n var localizedString = null;\n if (this.repeat)\n localizedString = l('repeat_' + this.repeat.frequency.toUpperCase());\n\n return localizedString;\n };\n\n /**\n * @function alarmDescription\n * @memberof Component.prototype\n * @desc Return a localized description of the reminder definition\n * @return a localized string\n */\n Component.prototype.alarmDescription = function() {\n var key, localizedString = null;\n if (this.alarm) {\n key = ['reminder' + this.alarm.quantity, this.alarm.unit, this.alarm.reference].join('_');\n localizedString = l(key);\n if (key === localizedString)\n // No localized string for this reminder definition\n localizedString = [this.alarm.quantity,\n l('reminder_' + this.alarm.unit),\n l('reminder_' + this.alarm.reference)].join(' ');\n }\n\n return localizedString;\n };\n\n /**\n * @function copyTo\n * @memberof Component.prototype\n * @desc Copy an event to a calendar\n * @param {string} calendar - a target calendar UID\n * @returns a promise of the HTTP operation\n */\n Component.prototype.copyTo = function(calendar) {\n return Component.$$resource.post(this.pid + '/' + this.id, 'copy', {destination: calendar});\n };\n\n /**\n * @function moveTo\n * @memberof Component.prototype\n * @desc Move an event to a calendar\n * @param {string} calendar - a target calendar UID\n * @returns a promise of the HTTP operation\n */\n Component.prototype.moveTo = function(calendar) {\n return Component.$$resource.post(this.pid + '/' + this.id, 'move', {destination: calendar});\n };\n\n Component.prototype.toString = function() {\n return '[Component ' + this.id + ']';\n };\n\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint loopfunc: true */\n 'use strict';\n\n /**\n * @ngInject\n */\n CalendarController.$inject = ['$scope', '$rootScope', '$state', '$stateParams', 'sgHotkeys', 'Calendar', 'Component', 'Preferences', 'stateEventsBlocks'];\n function CalendarController($scope, $rootScope, $state, $stateParams, sgHotkeys, Calendar, Component, Preferences, stateEventsBlocks) {\n var vm = this, deregisterCalendarsList, hotkeys = [];\n\n // Make the toolbar state of all-day events persistent\n if (angular.isUndefined(CalendarController.expandedAllDays))\n CalendarController.expandedAllDays = false;\n\n vm.selectedDate = $stateParams.day.asDate();\n vm.expandedAllDays = CalendarController.expandedAllDays;\n vm.toggleAllDays = toggleAllDays;\n vm.views = stateEventsBlocks;\n vm.changeDate = changeDate;\n vm.changeView = changeView;\n\n\n _registerHotkeys(hotkeys);\n\n Preferences.ready().then(function() {\n _formatDate(vm.selectedDate);\n });\n\n // Refresh current view when the list of calendars is modified\n deregisterCalendarsList = $rootScope.$on('calendars:list', updateView);\n\n $scope.$on('$destroy', function() {\n // Destroy event listener when the controller is being deactivated\n deregisterCalendarsList();\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_today'),\n description: l('Today'),\n callback: changeDate,\n args: new Date()\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_dayview'),\n description: l('Day'),\n callback: changeView,\n args: 'day'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_weekview'),\n description: l('Week'),\n callback: changeView,\n args: 'week'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_monthview'),\n description: l('Month'),\n callback: changeView,\n args: 'month'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_multicolumndayview'),\n description: l('Multicolumn Day View'),\n callback: changeView,\n args: 'multicolumnday'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'left',\n description: l('Move backward'),\n callback: _goToPeriod,\n args: -1\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'right',\n description: l('Move forward'),\n callback: _goToPeriod,\n args: +1\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n\n function _goToPeriod($event, direction) {\n var date;\n\n if ($stateParams.view == 'week') {\n date = vm.selectedDate.beginOfWeek(Preferences.defaults.SOGoFirstDayOfWeek).addDays(7 * direction);\n }\n else if ($stateParams.view == 'month') {\n date = vm.selectedDate;\n date.setDate(1);\n date.setMonth(date.getMonth() + direction);\n }\n else {\n date = vm.selectedDate.addDays(direction);\n }\n\n changeDate($event, date);\n }\n\n function _formatDate(date) {\n if ($stateParams.view == 'month') {\n date.setDate(1);\n date.setHours(12);\n date.$dateFormat = '%B %Y';\n }\n else if ($stateParams.view == 'week') {\n date.setTime(date.beginOfWeek(Preferences.defaults.SOGoFirstDayOfWeek).getTime());\n date.$dateFormat = l('Week %d').replace('%d', '%U');\n }\n else {\n date.$dateFormat = '%A';\n }\n }\n\n // Expand or collapse all-day events\n function toggleAllDays() {\n CalendarController.expandedAllDays = !CalendarController.expandedAllDays;\n vm.expandedAllDays = CalendarController.expandedAllDays;\n }\n\n function updateView() {\n // The list of calendars has changed; update the views\n // See stateEventsBlocks in Scheduler.app.js\n Component.$eventsBlocksForView($stateParams.view, $stateParams.day.asDate()).then(function(data) {\n var i, j, view;\n for (i = 0; i < data.length; i++) {\n view = data[i];\n if (vm.views[i]) {\n _.forEach(view.allDayBlocks, function(blocks, day) {\n vm.views[i].allDayBlocks[day] = blocks;\n });\n _.forEach(view.blocks, function(blocks, day) {\n vm.views[i].blocks[day] = blocks;\n });\n }\n else {\n vm.views[i] = view;\n }\n if (view.id) {\n // Note: this can't be done in Component service since it would make Component dependent on\n // the Calendar service and create a circular dependency\n vm.views[i].calendar = new Calendar({ id: view.id, name: view.calendarName });\n }\n }\n // Remove previous views\n for (j = vm.views.length; j >= i; j--)\n vm.views.splice(j, 1);\n });\n }\n\n // Change calendar's date\n function changeDate($event, newDate) {\n var date = newDate? newDate.getDayString() : angular.element($event.currentTarget).attr('date');\n if (newDate)\n _formatDate(newDate);\n $state.go('calendars.view', { day: date });\n }\n\n // Change calendar's view\n function changeView($event, view) {\n $state.go('calendars.view', { view: view });\n }\n}\n\n angular\n .module('SOGo.SchedulerUI') \n .controller('CalendarController', CalendarController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n CalendarListController.$inject = ['$rootScope', '$scope', '$timeout', '$state', '$mdDialog', 'sgHotkeys', 'sgFocus', 'Dialog', 'Preferences', 'Calendar', 'Component'];\n function CalendarListController($rootScope, $scope, $timeout, $state, $mdDialog, sgHotkeys, focus, Dialog, Preferences, Calendar, Component) {\n var vm = this, hotkeys = [];\n\n vm.component = Component;\n vm.componentType = 'events';\n vm.selectedList = 0;\n vm.selectComponentType = selectComponentType;\n vm.unselectComponents = unselectComponents;\n vm.selectAll = selectAll;\n vm.searchMode = searchMode;\n vm.toggleComponentSelection = toggleComponentSelection;\n vm.confirmDeleteSelectedComponents = confirmDeleteSelectedComponents;\n vm.openEvent = openEvent;\n vm.openTask = openTask;\n vm.newComponent = newComponent;\n vm.filterpopup = filterpopup;\n vm.filter = filter;\n vm.filteredBy = filteredBy;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.reload = reload;\n vm.cancelSearch = cancelSearch;\n vm.mode = { search: false, multiple: 0 };\n\n\n _registerHotkeys(hotkeys);\n\n // Select list based on user's settings\n Preferences.ready().then(function() {\n var type = 'events';\n if (Preferences.settings.Calendar.SelectedList == 'tasksListView') {\n vm.selectedList = 1;\n type = 'tasks';\n }\n selectComponentType(type, { reload: true });\n });\n\n // Refresh current list when the list of calendars is modified\n $rootScope.$on('calendars:list', function() {\n Component.$filter(vm.componentType, { reload: true });\n });\n\n // Update the component being dragged\n $rootScope.$on('calendar:dragend', updateComponentFromGhost);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_create_event'),\n description: l('Create a new event'),\n callback: newComponent,\n args: 'appointment'\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_create_task'),\n description: l('Create a new task'),\n callback: newComponent,\n args: 'task'\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n // Switch between components tabs\n function selectComponentType(type, options) {\n if (options && options.reload || vm.componentType != type) {\n if (angular.isUndefined(Component['$' + type]))\n Component.$filter(type);\n vm.unselectComponents();\n vm.componentType = type;\n Component.saveSelectedList(type);\n }\n }\n\n function unselectComponents() {\n _.forEach(Component['$' + vm.componentType], function(component) {\n component.selected = false;\n });\n vm.mode.multiple = 0;\n }\n\n function selectAll() {\n _.forEach(Component['$' + vm.componentType], function(component) {\n component.selected = true;\n });\n vm.mode.multiple = Component['$' + vm.componentType].length;\n }\n\n function toggleComponentSelection($event, component) {\n component.selected = !component.selected;\n vm.mode.multiple += component.selected? 1 : -1;\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function confirmDeleteSelectedComponents() {\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected components?'),\n { ok: l('Delete') })\n .then(function() {\n // User confirmed the deletion\n var components = _.filter(Component['$' + vm.componentType], function(component) {\n return component.selected;\n });\n Calendar.$deleteComponents(components).then(function() {\n vm.mode.multiple = 0;\n $rootScope.$emit('calendars:list');\n });\n });\n }\n\n function openEvent($event, event) {\n openComponent($event, event, 'appointment');\n }\n\n function openTask($event, task) {\n openComponent($event, task, 'task');\n }\n\n function openComponent($event, component, type) {\n if (component.viewable) {\n // UI/Templates/SchedulerUI/UIxAppointmentViewTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskViewTemplate.wox\n var templateUrl = 'UIx' + type.capitalize() + 'ViewTemplate';\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n }\n }\n\n function newComponent($event, type, baseComponent) {\n var component;\n\n if (baseComponent) {\n component = baseComponent;\n }\n else {\n component = new Component({ pid: Calendar.$defaultCalendar(), type: type });\n }\n\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = 'UIx' + type.capitalize() + 'EditorTemplate';\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n }\n\n // Adjust component or create new component through drag'n'drop\n function updateComponentFromGhost($event) {\n var component, pointerHandler, coordinates, delta, params, calendarNumber, activeCalendars;\n\n component = Component.$ghost.component;\n pointerHandler = Component.$ghost.pointerHandler;\n\n if (component.isNew) {\n coordinates = pointerHandler.currentEventCoordinates;\n component.summary = '';\n if (component.isAllDay)\n coordinates.duration -= 96;\n component.setDelta(coordinates.duration * 15);\n newComponent(null, 'appointment', component).finally(function() {\n $timeout(function() {\n Component.$resetGhost();\n });\n });\n }\n else {\n delta = pointerHandler.currentEventCoordinates.getDelta(pointerHandler.originalEventCoordinates);\n params = {\n days: delta.dayNumber,\n start: delta.start * 15,\n duration: delta.duration * 15\n };\n if (pointerHandler.originalCalendar && delta.dayNumber !== 0) {\n // The day number actually represents the destination calendar among the active calendars\n calendarNumber = pointerHandler.currentEventCoordinates.dayNumber;\n activeCalendars = _.filter(Calendar.$findAll(), { active: 1 });\n params.destination = activeCalendars[calendarNumber].id;\n params.days = 0;\n }\n if (component.isException || !component.occurrenceId)\n // Component is an exception to a recurrence or is not recurrent;\n // Immediately perform the adjustments\n component.$adjust(params).then(function() {\n $rootScope.$emit('calendars:list');\n }, function(response) {\n onComponentAdjustError(response, component, params);\n }).finally(function() {\n $timeout(function() {\n Component.$resetGhost();\n });\n });\n else if (component.occurrenceId) {\n $mdDialog.show({\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n component: component,\n params: params\n },\n template: [\n '',\n ' ',\n '

' + l('editRepeatingItem') + '

',\n '
',\n ' ',\n ' ' + l('button_thisOccurrenceOnly') + '',\n ' ' + l('button_allOccurrences') + '',\n ' ',\n '
'\n ].join(''),\n controller: RecurrentComponentDialogController\n }).then(function() {\n $rootScope.$emit('calendars:list');\n }).finally(function() {\n $timeout(function() {\n Component.$resetGhost();\n });\n });\n }\n }\n\n /**\n * @ngInject\n */\n RecurrentComponentDialogController.$inject = ['$scope', '$mdDialog', 'component', 'params'];\n function RecurrentComponentDialogController($scope, $mdDialog, component, params) {\n $scope.updateThisOccurrence = function() {\n component.$adjust(params).then($mdDialog.hide, function(response) {\n $mdDialog.cancel().then(function() {\n onComponentAdjustError(response, component, params);\n });\n });\n };\n $scope.updateAllOccurrences = function() {\n delete component.occurrenceId;\n component.$adjust(params).then($mdDialog.hide, function(response) {\n $mdDialog.cancel().then(function() {\n onComponentAdjustError(response, component, params);\n });\n });\n };\n }\n\n function onComponentAdjustError(response, component, params) {\n if (response.status == 403 &&\n response.data && response.data.message && angular.isObject(response.data.message)) {\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxAttendeeConflictDialog',\n controller: AttendeeConflictDialogController,\n controllerAs: '$AttendeeConflictDialogController',\n locals: {\n component: component,\n params: params,\n conflictError: response.data.message\n }\n }).then(function() {\n $rootScope.$emit('calendars:list');\n });\n }\n }\n\n /**\n * @ngInject\n */\n AttendeeConflictDialogController.$inject = ['$scope', '$mdDialog', 'component', 'params', 'conflictError'];\n function AttendeeConflictDialogController($scope, $mdDialog, component, params, conflictError) {\n var vm = this;\n\n vm.conflictError = conflictError;\n vm.cancel = $mdDialog.cancel;\n vm.save = save;\n\n function save() {\n component.$adjust(angular.extend({ ignoreConflicts: true }, params)).then($mdDialog.hide);\n }\n }\n }\n\n function filterpopup() {\n return Component['$query' + vm.componentType.capitalize()].filterpopup;\n }\n\n function filter(filterpopup) {\n Component.$filter(vm.componentType, { filterpopup: filterpopup });\n }\n\n function filteredBy(filterpopup) {\n return Component['$query' + vm.componentType.capitalize()].filterpopup == filterpopup;\n }\n\n function sort(field) {\n Component.$filter(vm.componentType, { sort: field });\n }\n\n function sortedBy(field) {\n return Component['$query' + vm.componentType.capitalize()].sort == field;\n }\n\n function reload() {\n Calendar.reloadWebCalendars().finally(function() {\n $rootScope.$emit('calendars:list');\n });\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n Component.$filter(vm.componentType, { value: '' });\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .controller('CalendarListController', CalendarListController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n CalendarsController.$inject = ['$rootScope', '$scope', '$window', '$mdDialog', '$log', '$mdToast', 'FileUploader', 'sgFocus', 'Dialog', 'sgSettings', 'Preferences', 'Calendar', 'User', 'stateCalendars'];\n function CalendarsController($rootScope, $scope, $window, $mdDialog, $log, $mdToast, FileUploader, focus, Dialog, Settings, Preferences, Calendar, User, stateCalendars) {\n var vm = this;\n\n vm.activeUser = Settings.activeUser;\n vm.service = Calendar;\n vm.newCalendar = newCalendar;\n vm.addWebCalendar = addWebCalendar;\n vm.confirmDelete = confirmDelete;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.renameFolder = renameFolder;\n vm.share = share;\n vm.importCalendar = importCalendar;\n vm.showOnly = showOnly;\n vm.showAll = showAll;\n vm.showLinks = showLinks;\n vm.showProperties = showProperties;\n vm.subscribeToFolder = subscribeToFolder;\n // vm.today = today;\n\n vm.filter = { name: '' };\n vm.sortableMode = false;\n vm.toggleSortableMode = toggleSortableMode;\n vm.resetSort = resetSort;\n vm.sortableCalendars = {\n scrollableContainer: '#sidenav-content',\n containment: 'md-list',\n orderChanged: _sortableEnd,\n accept: _sortableAccept\n };\n\n Preferences.ready().then(function() {\n vm.categories = _.map(Preferences.defaults.SOGoCalendarCategories, function(name) {\n return { id: name.asCSSIdentifier(),\n name: name,\n color: Preferences.defaults.SOGoCalendarCategoriesColors[name]\n };\n });\n });\n\n // Dispatch the event named 'calendars:list' when a calendar is activated or deactivated or\n // when the color of a calendar is changed\n $scope.$watch(\n function() {\n return _.union(\n _.map(Calendar.$calendars, function(o) { return _.pick(o, ['id', 'active', 'color']); }),\n _.map(Calendar.$subscriptions, function(o) { return _.pick(o, ['id', 'active', 'color']); }),\n _.map(Calendar.$webcalendars, function(o) { return _.pick(o, ['id', 'active', 'color']); })\n );\n },\n function(newList, oldList) {\n var commonList, ids, promises;\n\n // Identify which calendar has changed\n commonList = _.intersectionBy(newList, oldList, 'id');\n ids = _.map(_.filter(commonList, function(o) {\n var oldObject = _.find(oldList, { id: o.id });\n return !_.isEqual(o, oldObject);\n }), 'id');\n promises = [];\n\n if (ids.length > 0) {\n $log.debug(ids.join(', ') + ' changed');\n _.forEach(ids, function(id) {\n var calendar = Calendar.$get(id);\n promises.push(calendar.$setActivation());\n });\n }\n if (promises.length > 0 || commonList.length != newList.length || commonList.length != oldList.length)\n Calendar.$q.all(promises).then(function() {\n $rootScope.$emit('calendars:list');\n });\n },\n true // compare for object equality\n );\n\n /**\n * Only allow to sort items within the same list.\n */\n function _sortableAccept(sourceItemHandleScope, destSortableScope, destItemScope) {\n return sourceItemHandleScope.sortableScope.element[0] == destSortableScope.element[0];\n }\n\n function _sortableEnd() {\n Calendar.saveFoldersOrder(_.flatMap(Calendar.$findAll(), 'id'));\n }\n\n function toggleSortableMode() {\n vm.sortableMode = !vm.sortableMode;\n vm.filter.name = '';\n }\n\n function resetSort() {\n Calendar.saveFoldersOrder();\n }\n\n function newCalendar(ev) {\n Dialog.prompt(l('New calendar'), l('Name of the Calendar'))\n .then(function(name) {\n var calendar = new Calendar(\n {\n name: name,\n isEditable: true,\n isRemote: false,\n owner: UserLogin\n }\n );\n calendar.$id().then(function() {\n Calendar.$add(calendar);\n });\n });\n }\n\n function addWebCalendar() {\n Dialog.prompt(l('Subscribe to a web calendar...'), l('URL of the Calendar'), {inputType: 'url'})\n .then(function(url) {\n Calendar.$addWebCalendar(url).then(function(calendar) {\n if (angular.isObject(calendar)) {\n // Web calendar requires HTTP authentication\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: 'UIxWebCalendarAuthDialog',\n controller: WebCalendarAuthDialogController,\n controllerAs: '$WebCalendarAuthDialogController',\n locals: {\n url: url,\n calendar: calendar\n }\n });\n }\n });\n });\n\n /**\n * @ngInject\n */\n WebCalendarAuthDialogController.$inject = ['scope', '$mdDialog', 'url', 'calendar'];\n function WebCalendarAuthDialogController(scope, $mdDialog, url, calendar) {\n var vm = this,\n parts = url.split(\"/\"),\n hostname = parts[2];\n\n vm.title = l(\"Please identify yourself to %{0}\").formatted(hostname);\n vm.authenticate = function(form) {\n if (form.$valid || !form.$error.required) {\n calendar.setCredentials(vm.username, vm.password).then(function(message) {\n $mdDialog.hide();\n }, function(reason) {\n form.password.$setValidity('credentials', false);\n });\n }\n };\n vm.cancel = function() {\n $mdDialog.cancel();\n };\n }\n }\n\n function confirmDelete(folder) {\n if (folder.isSubscription) {\n // Unsubscribe without confirmation\n folder.$delete()\n .catch(function(data, status) {\n Dialog.alert(l('An error occured while deleting the calendar \"%{0}\".', folder.name),\n l(data.error));\n });\n }\n else {\n Dialog.confirm(l('Warning'), l('Are you sure you want to delete the calendar \"%{0}\"?', folder.name),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete()\n .catch(function(data, status) {\n Dialog.alert(l('An error occured while deleting the calendar \"%{0}\".', folder.name),\n l(data.error));\n });\n });\n }\n }\n\n function importCalendar($event, folder) {\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: 'UIxCalendarImportDialog',\n controller: CalendarImportDialogController,\n controllerAs: '$CalendarImportDialogController',\n locals: {\n folder: folder\n }\n });\n\n /**\n * @ngInject\n */\n CalendarImportDialogController.$inject = ['scope', '$mdDialog', 'folder'];\n function CalendarImportDialogController(scope, $mdDialog, folder) {\n var vm = this;\n\n vm.uploader = new FileUploader({\n url: ApplicationBaseURL + [folder.id, 'import'].join('/'),\n autoUpload: true,\n queueLimit: 1,\n filters: [{ name: filterByExtension, fn: filterByExtension }],\n onSuccessItem: function(item, response, status, headers) {\n var msg;\n\n $mdDialog.hide();\n\n if (response.imported === 0)\n msg = l('No event was imported.');\n else {\n msg = l('A total of %{0} events were imported in the calendar.', response.imported);\n $rootScope.$emit('calendars:list');\n }\n\n $mdToast.show(\n $mdToast.simple()\n .content(msg)\n .position('top right')\n .hideDelay(3000));\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('An error occurred while importing calendar.') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n }\n });\n\n vm.close = function() {\n $mdDialog.hide();\n };\n\n function filterByExtension(item) {\n var isTextFile = item.type.indexOf('text') === 0 ||\n /\\.(ics)$/.test(item.name);\n\n if (!isTextFile)\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('Select an iCalendar file (.ics).') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n\n return isTextFile;\n }\n }\n }\n\n function showOnly(calendar) {\n _.forEach(Calendar.$findAll(), function(o) {\n if (calendar.id == o.id)\n o.active = 1;\n else\n o.active = 0;\n });\n }\n\n function showAll() {\n _.forEach(Calendar.$findAll(), function(o) { o.active = 1; });\n }\n\n function showLinks(calendar) {\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: calendar.id + '/links',\n controller: LinksDialogController,\n controllerAs: 'links',\n locals: {\n calendar: calendar\n }\n });\n \n /**\n * @ngInject\n */\n LinksDialogController.$inject = ['$mdDialog', 'calendar'];\n function LinksDialogController($mdDialog, calendar) {\n var vm = this;\n vm.calendar = calendar;\n vm.close = close;\n\n function close() {\n $mdDialog.hide();\n }\n }\n }\n\n function showProperties(calendar) {\n var color = calendar.color;\n $mdDialog.show({\n templateUrl: calendar.id + '/properties',\n controller: PropertiesDialogController,\n controllerAs: 'properties',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcCalendar: calendar\n }\n }).catch(function() {\n // Restore original color when cancelling or closing the dialog\n calendar.color = color;\n });\n \n /**\n * @ngInject\n */\n PropertiesDialogController.$inject = ['$scope', '$mdDialog', 'srcCalendar'];\n function PropertiesDialogController($scope, $mdDialog, srcCalendar) {\n var vm = this;\n\n vm.calendar = new Calendar(srcCalendar.$omit());\n vm.saveProperties = saveProperties;\n vm.close = close;\n\n $scope.$watch(function() { return vm.calendar.color; }, function() {\n srcCalendar.color = vm.calendar.color;\n });\n\n function saveProperties() {\n vm.calendar.$save();\n // Refresh list instance\n srcCalendar.init(vm.calendar.$omit());\n $mdDialog.hide();\n }\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function editFolder(folder) {\n vm.calendarName = folder.name;\n vm.editMode = folder.id;\n focus('calendarName_' + folder.id);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function renameFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function share(calendar) {\n calendar.$acl.$users().then(function() {\n $mdDialog.show({\n templateUrl: calendar.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: calendar.$acl.users,\n User: User,\n folder: calendar\n }\n });\n });\n }\n\n // Callback of sgSubscribe directive\n function subscribeToFolder(calendarData) {\n $log.debug('subscribeToFolder ' + calendarData.owner + calendarData.name);\n Calendar.$subscribe(calendarData.owner, calendarData.name).then(function(data) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Successfully subscribed to calendar'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n // function today() {\n // var fragments = $window.location.hash.split('/'),\n // state = fragments[1],\n // view = fragments[2],\n // now = new Date(),\n // path = ['#', state, view, now.getDayString()];\n // $window.location = path.join('/');\n // }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .controller('CalendarsController', CalendarsController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n ComponentController.$inject = ['$rootScope', '$mdDialog', 'Calendar', 'Component', 'AddressBook', 'Alarm', 'Account', 'stateComponent'];\n function ComponentController($rootScope, $mdDialog, Calendar, Component, AddressBook, Alarm, Account, stateComponent) {\n var vm = this, component;\n\n vm.calendarService = Calendar;\n vm.service = Component;\n vm.component = stateComponent;\n vm.close = close;\n vm.cardFilter = cardFilter;\n vm.newMessageWithAllRecipients = newMessageWithAllRecipients;\n vm.newMessageWithRecipient = newMessageWithRecipient;\n vm.edit = edit;\n vm.editAllOccurrences = editAllOccurrences;\n vm.reply = reply;\n vm.replyAllOccurrences = replyAllOccurrences;\n vm.deleteOccurrence = deleteOccurrence;\n vm.deleteAllOccurrences = deleteAllOccurrences;\n vm.toggleRawSource = toggleRawSource;\n vm.copySelectedComponent = copySelectedComponent;\n vm.moveSelectedComponent = moveSelectedComponent;\n\n // Load all attributes of component\n if (angular.isUndefined(vm.component.$futureComponentData)) {\n component = Calendar.$get(vm.component.pid).$getComponent(vm.component.id, vm.component.occurrenceId);\n component.$futureComponentData.then(function() {\n vm.component = component;\n vm.organizer = [vm.component.organizer];\n });\n }\n\n function close() {\n $mdDialog.hide();\n }\n\n // Autocomplete cards for attendees\n function cardFilter($query) {\n AddressBook.$filterAll($query);\n return AddressBook.$cards;\n }\n\n function newMessageWithAllRecipients($event) {\n var recipients = _.map(vm.component.attendees, function(attendee) {\n return attendee.name + \" <\" + attendee.email + \">\";\n });\n _newMessage($event, recipients);\n }\n\n function newMessageWithRecipient($event, name, email) {\n _newMessage($event, [name + \" <\" + email + \">\"]);\n }\n\n function _newMessage($event, recipients) {\n Account.$findAll().then(function(accounts) {\n var account = _.find(accounts, function(o) {\n if (o.id === 0)\n return o;\n });\n\n // We must initialize the Account with its mailbox\n // list before proceeding with message's creation\n account.$getMailboxes().then(function(mailboxes) {\n account.$newMessage().then(function(message) {\n angular.extend(message.editable, { to: recipients, subject: vm.component.summary });\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: '../Mail/UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: account,\n stateMessage: message\n }\n });\n });\n });\n });\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function edit() {\n var type = (vm.component.component == 'vevent')? 'Appointment':'Task';\n $mdDialog.hide().then(function() {\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = 'UIx' + type + 'EditorTemplate';\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: vm.component\n }\n });\n });\n }\n\n function editAllOccurrences() {\n component = Calendar.$get(vm.component.pid).$getComponent(vm.component.id);\n component.$futureComponentData.then(function() {\n vm.component = component;\n edit();\n });\n }\n\n function reply(component) {\n var c = component || vm.component;\n\n c.$reply().then(function() {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n Alarm.getAlarms();\n });\n }\n\n function replyAllOccurrences() {\n // Retrieve master event\n component = Calendar.$get(vm.component.pid).$getComponent(vm.component.id);\n component.$futureComponentData.then(function() {\n // Propagate the participant status and alarm to the master event\n component.reply = vm.component.reply;\n component.delegatedTo = vm.component.delegatedTo;\n component.$hasAlarm = vm.component.$hasAlarm;\n component.alarm = vm.component.alarm;\n // Send reply to the server\n reply(component);\n });\n }\n\n function deleteOccurrence() {\n vm.component.remove(true).then(function() {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n });\n }\n\n function deleteAllOccurrences() {\n vm.component.remove().then(function() {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n });\n }\n\n function toggleRawSource($event) {\n Calendar.$$resource.post(vm.component.pid + '/' + vm.component.id, \"raw\").then(function(data) {\n $mdDialog.hide();\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n template: [\n '',\n ' ',\n '
',\n            '  
',\n ' ',\n ' ' + l('Close') + '',\n ' ',\n '
'\n ].join(''),\n controller: ComponentRawSourceDialogController,\n locals: { data: data }\n });\n\n /**\n * @ngInject\n */\n ComponentRawSourceDialogController.$inject = ['scope', '$mdDialog', 'data'];\n function ComponentRawSourceDialogController(scope, $mdDialog, data) {\n scope.data = data;\n scope.close = function() {\n $mdDialog.hide();\n };\n }\n });\n }\n\n function copySelectedComponent(calendar) {\n vm.component.copyTo(calendar).then(function() {\n $mdDialog.hide();\n $rootScope.$emit('calendars:list');\n });\n }\n\n function moveSelectedComponent(calendar) {\n vm.component.moveTo(calendar).then(function() {\n $mdDialog.hide();\n $rootScope.$emit('calendars:list');\n });\n }\n }\n\n /**\n * @ngInject\n */\n ComponentEditorController.$inject = ['$rootScope', '$scope', '$log', '$timeout', '$mdDialog', 'User', 'Calendar', 'Component', 'AddressBook', 'Card', 'Alarm', 'stateComponent'];\n function ComponentEditorController($rootScope, $scope, $log, $timeout, $mdDialog, User, Calendar, Component, AddressBook, Card, Alarm, stateComponent) {\n var vm = this, component, oldStartDate, oldEndDate, oldDueDate;\n\n vm.service = Calendar;\n vm.component = stateComponent;\n vm.categories = {};\n vm.showRecurrenceEditor = vm.component.$hasCustomRepeat;\n vm.toggleRecurrenceEditor = toggleRecurrenceEditor;\n vm.showAttendeesEditor = false;\n vm.toggleAttendeesEditor = toggleAttendeesEditor;\n //vm.searchText = null;\n vm.cardFilter = cardFilter;\n vm.addAttendee = addAttendee;\n vm.removeAttendee = removeAttendee;\n vm.addAttachUrl = addAttachUrl;\n vm.priorityLevel = priorityLevel;\n vm.cancel = cancel;\n vm.save = save;\n vm.attendeeConflictError = false;\n vm.attendeesEditor = {\n days: getDays(),\n hours: getHours()\n };\n vm.addStartDate = addStartDate;\n vm.addDueDate = addDueDate;\n\n // Synchronize start and end dates\n vm.adjustStartTime = adjustStartTime;\n vm.adjustEndTime = adjustEndTime;\n vm.adjustDueTime = adjustDueTime;\n\n if (vm.component.start)\n oldStartDate = new Date(vm.component.start.getTime());\n if (vm.component.end)\n oldEndDate = new Date(vm.component.end.getTime());\n if (vm.component.due)\n oldDueDate = new Date(vm.component.due.getTime());\n\n function addAttachUrl() {\n var i = vm.component.addAttachUrl('');\n focus('attachUrl_' + i);\n }\n\n function toggleRecurrenceEditor() {\n vm.showRecurrenceEditor = !vm.showRecurrenceEditor;\n vm.component.$hasCustomRepeat = vm.showRecurrenceEditor;\n }\n\n function toggleAttendeesEditor() {\n vm.showAttendeesEditor = !vm.showAttendeesEditor;\n }\n\n // Autocomplete cards for attendees\n function cardFilter($query) {\n AddressBook.$filterAll($query);\n return AddressBook.$cards;\n }\n\n function addAttendee(card) {\n if (angular.isString(card)) {\n // User pressed \"Enter\" in search field, adding a non-matching card\n if (card.isValidEmail()) {\n vm.component.addAttendee(new Card({ emails: [{ value: card }] }));\n vm.searchText = '';\n }\n }\n else {\n vm.component.addAttendee(card);\n }\n }\n\n function removeAttendee(attendee) {\n vm.component.deleteAttendee(attendee);\n if (vm.component.attendees.length === 0)\n vm.showAttendeesEditor = false;\n }\n\n function priorityLevel() {\n if (vm.component && vm.component.priority) {\n if (vm.component.priority > 5)\n return l('low');\n else if (vm.component.priority > 4)\n return l('normal');\n else\n return l('high');\n }\n }\n\n function save(form, options) {\n if (form.$valid) {\n vm.component.$save(options)\n .then(function(data) {\n $rootScope.$emit('calendars:list');\n $mdDialog.hide();\n Alarm.getAlarms();\n }, function(response) {\n if (response.status == 403 &&\n response.data && response.data.message &&\n angular.isObject(response.data.message))\n vm.attendeeConflictError = response.data.message;\n });\n }\n }\n\n function cancel() {\n vm.component.$reset();\n if (vm.component.isNew) {\n // Cancelling the creation of a component\n vm.component = null;\n }\n $mdDialog.cancel();\n }\n\n function getDays() {\n var days = [];\n\n if (vm.component.start && vm.component.end)\n days = vm.component.start.daysUpTo(vm.component.end);\n\n return _.map(days, function(date) {\n return { stringWithSeparator: date.stringWithSeparator(),\n getDayString: date.getDayString() };\n });\n }\n\n function getHours() {\n var hours = [];\n for (var i = 0; i <= 23; i++) {\n hours.push(i.toString());\n }\n return hours;\n }\n\n function addStartDate() {\n vm.component.$addStartDate();\n oldStartDate = new Date(vm.component.start.getTime());\n }\n\n function addDueDate() {\n vm.component.$addDueDate();\n oldDueDate = new Date(vm.component.due.getTime());\n }\n\n function adjustStartTime() {\n if (vm.component.start) {\n // Preserve the delta between the start and end dates\n var delta;\n delta = oldStartDate.valueOf() - vm.component.start.valueOf();\n if (delta !== 0) {\n oldStartDate = new Date(vm.component.start.getTime());\n if (vm.component.type === 'appointment') {\n vm.component.end = new Date(vm.component.start.getTime());\n vm.component.end.addMinutes(vm.component.delta);\n oldEndDate = new Date(vm.component.end.getTime());\n }\n updateFreeBusy();\n }\n }\n }\n\n function adjustEndTime() {\n if (vm.component.end) {\n // The end date must be after the start date\n var delta = oldEndDate.valueOf() - vm.component.end.valueOf();\n if (delta !== 0) {\n delta = vm.component.start.minutesTo(vm.component.end);\n if (delta < 0)\n vm.component.end = new Date(oldEndDate.getTime());\n else {\n vm.component.delta = delta;\n oldEndDate = new Date(vm.component.end.getTime());\n }\n updateFreeBusy();\n }\n }\n }\n\n function adjustDueTime() {\n oldDueDate = new Date(vm.component.due.getTime());\n }\n\n function updateFreeBusy() {\n vm.attendeesEditor.days = getDays();\n vm.component.updateFreeBusy();\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .controller('ComponentController', ComponentController)\n .controller('ComponentEditorController', ComponentEditorController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgCalendarDay - An element that represents a day in the calendar's view\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {string} sgDay - the day of the events to display (YYYYMMDD)\n * @param {string} sgDayString - the day in ISO8601 format (YYYY-MM-DDTHH:MM+-HH:MM)\n * @param {number} sgDayNumber - the day index within the calendar's view\n *\n * @example:\n\n \n ..\n \n */\n function sgCalendarDay() {\n return {\n restrict: 'E',\n scope: {\n day: '@sgDay',\n dayNumber: '@sgDayNumber',\n dayString: '@sgDayString',\n calendar: '@sgCalendar'\n },\n controller: sgCalendarDayController\n };\n }\n\n /**\n * @ngInject\n */\n sgCalendarDayController.$inject = ['$scope', 'Calendar'];\n function sgCalendarDayController($scope, Calendar) {\n // Expose some scope variables to the controller\n // See the sgCalendarDayTable directive\n this.day = $scope.day;\n this.dayNumber = $scope.dayNumber;\n this.dayString = $scope.dayString;\n this.calendarData = function() {\n var pid, index, activeCalendars;\n if ($scope.calendar) {\n // A calendar is associated to the day; identify its index among active calendars\n pid = $scope.calendar;\n activeCalendars = _.filter(Calendar.$findAll(), { active: 1 });\n index = _.findIndex(activeCalendars, function(calendar) {\n return calendar.id == pid;\n });\n return { pid: pid, index: index };\n }\n\n return null;\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarDay', sgCalendarDay);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarDayBlock - An event block to be displayed in a week\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {object} sgBlock - the event block definition\n * @param {function} sgClick - the function to call when clicking on a block.\n * Two variables are available: clickEvent (the event that triggered the mouse click),\n * and clickComponent (a Component object)\n *\n * @example:\n\n \n */\n sgCalendarDayBlock.$inject = ['CalendarSettings'];\n function sgCalendarDayBlock(CalendarSettings) {\n return {\n restrict: 'E',\n scope: {\n block: '=sgBlock',\n clickBlock: '&sgClick'\n },\n replace: true,\n template: template,\n link: link\n };\n\n function template(tElem, tAttrs) {\n var p = _.has(tAttrs, 'sgCalendarGhost')? '' : '::';\n\n return [\n '
',\n '
',\n // Categories color stripes\n '
',\n '
',\n // Priority\n ' {{'+p+'block.component.c_priority}}',\n // Summary\n ' {{ '+p+'block.component.summary }}',\n ' ',\n // Component is reccurent\n ' ',\n // Component has an alarm\n ' ',\n // Component is confidential\n ' ',\n // Component is private\n ' ',\n ' ',\n // Location\n '
',\n ' place {{'+p+'block.component.c_location}}',\n '
',\n '
',\n '
',\n '
{{ block.startHour }}
',\n '
{{ block.endHour }}
',\n '
'\n ].join('');\n }\n\n function link(scope, iElement, attrs) {\n var pc, left, right;\n\n if (!_.has(attrs, 'sgCalendarGhost')) {\n\n // Compute overlapping (2%)\n pc = 100 / scope.block.siblings;\n left = scope.block.position * pc;\n right = 100 - (scope.block.position + 1) * pc;\n if (pc < 100) {\n if (left > 0)\n left -= 2;\n if (right > 0)\n right -= 2;\n }\n\n // Add some padding (2%)\n if (left === 0)\n left = 2;\n if (right === 0)\n right = 2;\n\n // Set position\n iElement.css('left', left + '%');\n iElement.css('right', right + '%');\n if (!scope.block.component || !scope.block.component.c_isallday) {\n iElement.addClass('starts' + scope.block.start);\n iElement.addClass('lasts' + scope.block.length);\n }\n\n // Add class for user's participation state\n if (scope.block.userState)\n iElement.addClass('sg-event--' + scope.block.userState);\n\n if (scope.block.component) {\n // Set background color\n iElement.addClass('bg-folder' + scope.block.component.pid);\n iElement.addClass('contrast-bdr-folder' + scope.block.component.pid);\n\n // Add class for transparency\n if (scope.block.component.c_isopaque === 0)\n iElement.addClass('sg-event--transparent');\n\n // Add class for cancelled event\n if (scope.block.component.c_status === 0)\n iElement.addClass('sg-event--cancelled');\n }\n\n }\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarDayBlock', sgCalendarDayBlock);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarDayTable - Build list of blocks for a specific day\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {object} sgBlocks - the events blocks definitions for the current view\n * @param {string} sgDay - the day of the events to display\n * @param {function} sgClick - the function to call when clicking on a block.\n * Two variables are available: event (the event that triggered the mouse click),\n * and component (a Component object)\n *\n * @example:\n\n \n */\n function sgCalendarDayTable() {\n return {\n restrict: 'E',\n scope: {\n blocks: '=sgBlocks',\n day: '@sgDay',\n clickBlock: '&sgClick'\n },\n template: [\n ''\n ].join('')\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarDayTable', sgCalendarDayTable);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarBlock - Applied to an event ghost block to be displayed while dragging an event block. Each day of the\n * calendar's view must have a ghost block.\n * @memberof SOGo.SchedulerUI\n * @restrict attribute\n *\n * @example:\n\n /\n */\n sgCalendarGhost.$inject = ['$rootScope', '$timeout', 'CalendarSettings', 'Calendar', 'Component'];\n function sgCalendarGhost($rootScope, $timeout, CalendarSettings, Calendar, Component) {\n return {\n restrict: 'A',\n require: ['^sgCalendarDay', '^sgCalendarScrollView'],\n link: link\n };\n\n function link(scope, iElement, attrs, ctrls) {\n var domElement, calendarDayCtrl, scrollViewCtrl, calendarNumber, originalCalendarNumber;\n\n domElement = iElement[0];\n calendarDayCtrl = ctrls[0];\n scrollViewCtrl = ctrls[1];\n calendarNumber = -1;\n\n iElement.addClass('sg-event--ghost md-whiteframe-3dp ng-hide');\n\n // Listen on drag gestures\n var deregisterDragStart = $rootScope.$on('calendar:dragstart', initGhost);\n var deregisterDrag = $rootScope.$on('calendar:drag', updateGhost);\n var deregisterDragEnd = $rootScope.$on('calendar:dragend', hideGhost);\n\n // Deregister listeners on destroy\n scope.$on('$destroy', function() {\n deregisterDragStart();\n deregisterDrag();\n deregisterDragEnd();\n });\n\n function initGhost() {\n var pid, calendarData, userState;\n\n // Expose ghost block to the scope\n scope.block = Component.$ghost;\n\n calendarData = calendarDayCtrl.calendarData();\n if (calendarData) {\n // A calendar is associated to the day; this is a special multicolumn day view\n calendarNumber = calendarData.index;\n pid = calendarData.pid;\n originalCalendarNumber = scope.block.pointerHandler.originalCalendar.index;\n }\n\n if (!pid)\n pid = scope.block.component.pid;\n\n // Add class for user's participation state\n userState = scope.block.component.blocks[0].userState;\n if (userState)\n iElement.addClass('sg-event--' + userState);\n\n // Set background color\n iElement.addClass('bg-folder' + pid);\n }\n\n function hideGhost() {\n // Remove background color\n _.forEachRight(domElement.classList, function(c) {\n if (/^bg-folder/.test(c))\n iElement.removeClass(c);\n });\n // Hide ghost\n iElement.addClass('ng-hide');\n }\n\n function updateGhost() {\n // From SOGoEventDragGhostController._updateGhosts\n var showGhost, isRelative, isAllDay, currentDay,\n start, duration, durationLeft, maxDuration;\n\n showGhost = false;\n\n if (Calendar.$view && Calendar.$view.type == scrollViewCtrl.type) {\n // The view of the dragging block is the scrolling view of this ghost block\n\n isRelative = scrollViewCtrl.type === 'multiday-allday';\n isAllDay = scope.block.component.c_isallday;\n currentDay = scope.block.pointerHandler.currentEventCoordinates.dayNumber;\n start = scope.block.pointerHandler.currentEventCoordinates.start;\n durationLeft = scope.block.pointerHandler.currentEventCoordinates.duration;\n maxDuration = CalendarSettings.EventDragDayLength - start;\n\n if (angular.isUndefined(durationLeft))\n return;\n duration = durationLeft;\n if (duration > maxDuration)\n duration = maxDuration;\n\n if (currentDay > -1 && // pointer is inside viewport\n ((calendarNumber < 0 && // day is not associated to a calendar\n currentDay == calendarDayCtrl.dayNumber) || // pointer is inside ghost's day\n currentDay == calendarNumber && // pointer is inside ghost's calendar\n (originalCalendarNumber == calendarNumber || // still inside original calendar\n !scope.block.component.isException) // not an exception, event can be moved to a\n // different calendar\n )) {\n // This ghost block (day) is the first of the dragging event\n showGhost = true;\n if (!isRelative) {\n if (!isAllDay)\n // Show start hour and set the vertical position\n scope.block.startHour = getStartTime(start);\n // Set the height\n if (Calendar.$view.quarterHeight) {\n iElement.css('top', (start * Calendar.$view.quarterHeight) + 'px');\n iElement.css('height', (duration * Calendar.$view.quarterHeight) + 'px');\n }\n else\n iElement.css('top', Calendar.$view.topOffset + 'px');\n }\n iElement.removeClass('fg-folder' + scope.block.component.pid);\n iElement.removeClass('sg-event--ghost--last');\n iElement.addClass('sg-event--ghost--first');\n scope.block.isFirst = true;\n }\n\n durationLeft -= duration;\n currentDay++;\n\n // Search a subsequent block that matches the current ghost's day\n while (!showGhost && durationLeft && currentDay <= calendarDayCtrl.dayNumber) {\n duration = durationLeft;\n if (duration > CalendarSettings.EventDragDayLength)\n duration = CalendarSettings.EventDragDayLength;\n if (currentDay > -1 && currentDay == calendarDayCtrl.dayNumber) {\n // The dragging event overlaps this current ghost's day\n showGhost = true;\n if (!isRelative) {\n iElement.css('top', Calendar.$view.topOffset + 'px');\n // Set the height\n if (Calendar.$view.quarterHeight)\n iElement.css('height', (duration * Calendar.$view.quarterHeight) + 'px');\n }\n iElement.removeClass('sg-event--ghost--first');\n iElement.removeClass('sg-event--ghost--last');\n // Trick for all-day events: set the foreground color to the background color so the event's title\n // is not visible but the div size remains identical.\n iElement.addClass('fg-folder' + scope.block.component.pid);\n }\n durationLeft -= duration;\n currentDay++;\n start = 0;\n }\n if (!durationLeft) {\n // Reached last ghost block\n if (isRelative) {\n iElement.addClass('sg-event--ghost--last');\n }\n else if (!isAllDay) {\n // Set the end date\n scope.block.endHour = getEndTime(start, duration);\n }\n }\n }\n\n if (showGhost)\n iElement.removeClass('ng-hide');\n else\n iElement.addClass('ng-hide');\n }\n\n function quartersToHM(quarters) {\n var minutes, hours, mins;\n\n minutes = quarters * 15;\n hours = Math.floor(minutes / 60);\n if (hours < 10)\n hours = \"0\" + hours;\n mins = minutes % 60;\n if (mins < 10)\n mins = \"0\" + mins;\n\n return \"\" + hours + \":\" + mins;\n }\n\n function getStartTime(start) {\n return quartersToHM(start);\n }\n\n function getEndTime(start, duration) {\n var end = (start + duration) % CalendarSettings.EventDragDayLength;\n return quartersToHM(end);\n }\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarGhost', sgCalendarGhost);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarMonthDay - Build list of blocks for a specific day in a month\n * @memberof SOGo.SchedulerUI\n * @restrict element\n * @param {object} sgBlocks - the events blocks definitions for the current view\n * @param {string} sgDay - the day of the events to display\n * @param {function} sgClick - the function to call when clicking on a block.\n * Two variables are available: event (the event that triggered the mouse click),\n * and component (a Component object)\n *\n * @example:\n\n \n */\n function sgCalendarMonthDay() {\n return {\n restrict: 'E',\n scope: {\n blocks: '=sgBlocks',\n day: '@sgDay',\n clickBlock: '&sgClick'\n },\n template: [\n ''\n ].join('')\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarMonthDay', sgCalendarMonthDay);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgCalendarMonthEvent - An event block to be displayed in a month\n * @memberof SOGo.Common\n * @restrict element\n * @param {object} sgBlock - the event block definition\n * @ngInject\n * @example:\n\n \n */\n function sgCalendarMonthEvent() {\n return {\n restrict: 'E',\n scope: {\n block: '=sgBlock',\n clickBlock: '&sgClick'\n },\n replace: true,\n template: template,\n link: link\n };\n\n function template(tElem, tAttrs) {\n var p = _.has(tAttrs, 'sgCalendarGhost')? '' : '::';\n\n return [\n '
',\n // Categories color stripes\n '
',\n ' {{ '+p+'block.component.startHour }}',\n // Priority\n ' {{'+p+'block.component.c_priority}}',\n // Summary\n ' {{ '+p+'block.component.summary }}',\n ' ',\n // Component is reccurent\n ' ',\n // Component has an alarm\n ' ',\n // Component is confidential\n ' ',\n // Component is private\n ' ',\n ' ',\n '
'\n ].join('');\n }\n\n function link(scope, iElement, attrs) {\n if (!_.has(attrs, 'sgCalendarGhost')) {\n\n // Add class for user's participation state\n if (scope.block.userState)\n iElement.addClass('sg-event--' + scope.block.userState);\n\n if (scope.block.component) {\n // Set background color\n iElement.addClass('bg-folder' + scope.block.component.pid);\n\n // Add class for transparency\n if (scope.block.component.c_isopaque === 0)\n iElement.addClass('sg-event--transparent');\n\n // Add class for cancelled event\n if (scope.block.component.c_status === 0)\n iElement.addClass('sg-event--cancelled');\n }\n\n }\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarMonthEvent', sgCalendarMonthEvent);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgCalendarScrollView - scrollable view that contains draggable elements\n * @memberof SOGo.SchedulerUI\n * @restrict attribute\n * @param {string} sgCalendarScrollView - the view type (multiday, multiday-allday, or monthly)\n *\n * @example:\n\n \n ..\n \n */\n sgCalendarScrollView.$inject = ['$rootScope', '$window', '$document', '$q', '$timeout', '$mdGesture', 'Calendar', 'Component', 'Preferences'];\n function sgCalendarScrollView($rootScope, $window, $document, $q, $timeout, $mdGesture, Calendar, Component, Preferences) {\n return {\n restrict: 'A',\n scope: {\n type: '@sgCalendarScrollView'\n },\n controller: sgCalendarScrollViewController,\n link: function(scope, element, attrs, controller) {\n var view, type, isMultiColumn = false;\n\n view = null;\n type = scope.type; // multiday, multiday-allday, monthly, unknown?\n isMultiColumn = (element.attr('sg-view') == 'multicolumndayview');\n\n // Expose isMultiColumn in the controller\n // See sgNowLine directive\n controller.isMultiColumn = isMultiColumn;\n\n // Update the \"view\" object literal once the Angular template has been transformed\n $timeout(initView);\n\n // Deregister listeners when destroying the view\n scope.$on('$destroy', function() {\n if (view) {\n view.$destroy();\n }\n });\n\n function initView() {\n view = new sgScrollView(element, type);\n\n if (type != 'monthly')\n // Scroll to the day start hour defined in the user's defaults\n Preferences.ready().then(function() {\n var time, hourCell, quartersOffset;\n if (Preferences.defaults.SOGoDayStartTime) {\n time = Preferences.defaults.SOGoDayStartTime.split(':');\n hourCell = document.getElementById('hour' + parseInt(time[0]));\n quartersOffset = parseInt(time[1]) * view.quarterHeight;\n view.element.scrollTop = hourCell.offsetTop + quartersOffset;\n }\n });\n\n // Expose quarter height to the controller\n // See sgNowLine directive\n controller.quarterHeight = view.quarterHeight;\n }\n\n /**\n * sgScrollView\n */\n function sgScrollView($element, type) {\n this.$element = $element;\n this.element = $element[0];\n this.type = type;\n this.quarterHeight = this.getQuarterHeight();\n this.scrollStep = 6 * this.quarterHeight;\n this.dayNumbers = this.getDayNumbers();\n this.maxX = this.getMaxColumns();\n\n // Listen to dragstart and dragend events\n this.deregisterDragStart = $rootScope.$on('calendar:dragstart', angular.bind(this, this.onDragStart));\n this.deregisterDragStop = $rootScope.$on('calendar:dragend', angular.bind(this, this.onDragEnd));\n\n this.bindedUpdateCoordinates = angular.bind(this, this.updateCoordinates);\n this.bindedUpdateFromPointerHandler = angular.bind(this, this.updateFromPointerHandler);\n\n // Compute coordinates of view element; recompute it on window resize\n this.updateCoordinates();\n angular.element($window).on('resize', this.bindedUpdateCoordinates);\n }\n\n sgScrollView.prototype = {\n\n $destroy: function() {\n this.deregisterDragStart();\n this.deregisterDragStop();\n this.$element.off('mousemove', this.bindedUpdateFromPointerHandler);\n angular.element($window).off('resize', this.bindedUpdateCoordinates);\n },\n\n onDragStart: function() {\n this.$element.on('mousemove', this.bindedUpdateFromPointerHandler);\n this.updateCoordinates();\n this.updateFromPointerHandler();\n },\n\n onDragEnd: function() {\n this.$element.off('mousemove', this.bindedUpdateFromPointerHandler);\n Calendar.$view = null;\n },\n\n getQuarterHeight: function() {\n var hour0, hour23, height = null;\n\n hour0 = document.getElementById('hour0');\n hour23 = document.getElementById('hour23');\n if (hour0 && hour23)\n height = ((hour23.offsetTop - hour0.offsetTop) / (23 * 4));\n\n return height;\n },\n\n\n getDayDimensions: function(viewLeft) {\n var width, height, leftOffset, topOffset, nodes, domRect, tileHeader;\n\n height = width = leftOffset = topOffset = 0;\n nodes = this.element.getElementsByClassName('day');\n\n if (nodes.length > 0) {\n domRect = nodes[0].getBoundingClientRect();\n height = domRect.height;\n width = domRect.width;\n leftOffset = domRect.left - viewLeft;\n tileHeader = nodes[0].getElementsByClassName('sg-calendar-tile-header');\n if (tileHeader.length > 0)\n topOffset = tileHeader[0].clientHeight;\n }\n\n return { height: height, width: width, offset: { left: leftOffset, top: topOffset } };\n },\n\n\n getDayNumbers: function() {\n var viewType = null, days, total, sum;\n\n days = this.element.getElementsByTagName('sg-calendar-day');\n\n return _.map(days, function(el, index) {\n if (isMultiColumn)\n return index;\n else\n return parseInt(el.attributes['sg-day-number'].value);\n });\n },\n\n\n getMaxColumns: function() {\n var mdGridList, max = 0;\n\n if (this.type == 'monthly') {\n mdGridList = this.element.getElementsByTagName('md-grid-list')[0];\n max = parseInt(mdGridList.attributes['md-cols'].value) - 1;\n }\n else {\n max = this.element.getElementsByClassName('day').length - 1;\n }\n\n return max;\n },\n\n // View has been resized;\n // Compute the view's origins (x, y), a day's dimensions and left margin.\n updateCoordinates: function() {\n var domRect, dayDimensions;\n\n domRect = this.element.getBoundingClientRect();\n dayDimensions = this.getDayDimensions(domRect.left);\n\n angular.extend(this, {\n coordinates: {\n x: domRect.left,\n y: domRect.top\n },\n dayHeight: dayDimensions.height,\n dayWidth: dayDimensions.width,\n daysOffset: dayDimensions.offset.left,\n topOffset: dayDimensions.offset.top\n });\n },\n\n\n // From SOGoScrollController.updateFromPointerHandler\n updateFromPointerHandler: function() {\n var pointerHandler, pointerCoordinates, now, scrollY, minY, delta;\n\n pointerHandler = Component.$ghost.pointerHandler;\n if (this.coordinates && pointerHandler) {\n pointerCoordinates = pointerHandler.getContainerBasedCoordinates(this);\n\n if (pointerCoordinates) {\n // Pointer is inside view; Adjust scrollbar if necessary\n Calendar.$view = this;\n now = new Date().getTime();\n if (!this.lastScroll || now > this.lastScroll + 100) {\n this.lastScroll = now;\n scrollY = pointerCoordinates.y - this.scrollStep;\n if (scrollY < 0) {\n minY = -this.element.scrollTop;\n if (scrollY < minY)\n scrollY = minY;\n this.element.scrollTop += scrollY;\n }\n else {\n scrollY = pointerCoordinates.y + this.scrollStep;\n delta = scrollY - this.element.clientHeight;\n if (delta > 0) {\n this.element.scrollTop += delta;\n }\n }\n }\n }\n }\n }\n\n\n };\n }\n };\n }\n\n sgCalendarScrollViewController.$inject = ['$scope'];\n function sgCalendarScrollViewController($scope) {\n // Expose the view type to the controller\n // See sgCalendarGhost directive\n this.type = $scope.type;\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCalendarScrollView', sgCalendarScrollView);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgCategoryStylesheet - Add CSS stylesheet for a category's color\n * @memberof SOGo.SchedulerUI\n * @restrict attribute\n * @param {object} ngModel - the object literal describing the category\n * @example:\n\n \n */\n function sgCategoryStylesheet() {\n return {\n restrict: 'E',\n require: 'ngModel',\n scope: {\n ngModel: '='\n },\n replace: true,\n template: [\n ''\n ].join('')\n };\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgCategoryStylesheet', sgCategoryStylesheet);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgDraggableCalendarBlock - Make an element draggable\n * @memberof SOGo.SchedulerUI\n * @restrict class or attribute\n *\n * @example:\n\n
\n */\n sgDraggableCalendarBlock.$inject = ['$rootScope', '$timeout', '$log', 'Preferences', 'Calendar', 'CalendarSettings', 'Component'];\n function sgDraggableCalendarBlock($rootScope, $timeout, $log, Preferences, Calendar, CalendarSettings, Component) {\n return {\n restrict: 'CA',\n require: '^sgCalendarDay',\n link: link\n };\n\n function link(scope, element, attrs, calendarDayCtrl) {\n if (scope.block) {\n if (scope.block.component.editable && !scope.block.userState) {\n // Add dragging grips to existing event block\n initGrips();\n }\n else {\n element.removeClass('sg-draggable-calendar-block');\n return;\n }\n }\n\n // Start dragging on mousedown\n element.on('mousedown', onDragDetect);\n\n // Deregister listeners when removing the element from the DOM\n scope.$on('$destroy', function() {\n element.off('mousedown', onDragDetect);\n element.off('mousemove', onDrag);\n });\n\n function initGrips() {\n var component, dayIndex, blockIndex, isFirstBlock, isLastBlock,\n dragGrip, leftGrip, rightGrip, topGrip, bottomGrip;\n\n // Don't show grips for blocks of less than 45 minutes\n if (scope.block.length < 3) return;\n\n component = scope.block.component;\n dayIndex = scope.block.dayIndex;\n blockIndex = _.findIndex(component.blocks, ['dayIndex', dayIndex]);\n isFirstBlock = (blockIndex === 0);\n isLastBlock = (blockIndex === component.blocks.length - 1);\n\n dragGrip = angular.element('
');\n dragGrip.addClass('bdr-folder' + component.pid);\n\n if (component.c_isallday ||\n element[0].parentNode.tagName === 'SG-CALENDAR-MONTH-DAY') {\n if (isFirstBlock) {\n leftGrip = angular.element('
').append(dragGrip);\n element.append(leftGrip);\n }\n if (isLastBlock) {\n rightGrip = angular.element('
').append(dragGrip.clone());\n element.append(rightGrip);\n }\n }\n else {\n if (isFirstBlock) {\n topGrip = angular.element('
').append(dragGrip);\n element.append(topGrip);\n }\n if (isLastBlock) {\n bottomGrip = angular.element('
').append(dragGrip.clone());\n element.append(bottomGrip);\n }\n }\n }\n\n function onDragDetect(ev) {\n var dragMode, pointerHandler;\n\n ev.stopPropagation();\n\n dragMode = 'move-event';\n\n if (scope.block && scope.block.component) {\n // Move or resize existing component\n if (ev.target.className == 'dragGrip-top' ||\n ev.target.className == 'dragGrip-left')\n dragMode = 'change-start';\n else if (ev.target.className == 'dragGrip-bottom' ||\n ev.target.className == 'dragGrip-right' )\n dragMode = 'change-end';\n }\n else {\n // Create new component from dragging\n dragMode = 'change-end';\n }\n\n // Initialize pointer handler\n pointerHandler = new SOGoEventDragPointerHandler(dragMode);\n pointerHandler.initFromEvent(ev);\n\n // Update Component.$ghost\n Component.$ghost.pointerHandler = pointerHandler;\n\n // Stop dragging on the next \"mouseup\"\n angular.element(document).one('mouseup', onDragEnd);\n\n // Listen to mousemove and start dragging when mouse has moved from at least 3 pixels\n angular.element(document).on('mousemove', onDrag);\n }\n\n function dragStart(ev) {\n var block, eventType, isHourCell, isMonthly, startDate, newData, newComponent, pointerHandler, calendarData;\n\n isHourCell = element.hasClass('clickableHourCell');\n isMonthly = (element[0].parentNode.tagName == 'SG-CALENDAR-MONTH-DAY') ||\n element.hasClass('clickableDayCell');\n\n calendarData = calendarDayCtrl.calendarData();\n\n if (scope.block && scope.block.component) {\n // Move or resize existing component\n block = scope.block;\n }\n else {\n // Create new component from dragging\n startDate = calendarDayCtrl.dayString.parseDate(Preferences.$mdDateLocaleProvider, '%Y-%m-%e');\n newData = {\n type: 'appointment',\n pid: calendarData? calendarData.pid : Calendar.$defaultCalendar(),\n summary: l('New Event'),\n startDate: startDate,\n isAllDay: isHourCell? 0 : 1\n };\n newComponent = new Component(newData);\n block = {\n component: newComponent,\n dayNumber: calendarDayCtrl.dayNumber,\n length: 0\n };\n block.component.blocks = [block];\n }\n\n // Determine event type\n eventType = 'multiday';\n if (isMonthly)\n eventType = 'monthly';\n else if (block.component.c_isallday)\n eventType = 'multiday-allday';\n\n // Mark all blocks as being dragged\n _.forEach(block.component.blocks, function(b) {\n b.dragging = true;\n });\n\n // Update pointer handler\n pointerHandler = Component.$ghost.pointerHandler;\n pointerHandler.prepareWithEventType(eventType);\n pointerHandler.initFromBlock(block);\n if (calendarData)\n // When the day is associated to a calendar, the day number becomes the calendar index\n // among the active calendars\n pointerHandler.initFromCalendar(calendarData);\n\n // Update Component.$ghost\n Component.$ghost.component = block.component;\n\n $log.debug('emit calendar:dragstart ' + eventType);\n $rootScope.$emit('calendar:dragstart');\n }\n\n function onDrag(ev) {\n var pointerHandler = Component.$ghost.pointerHandler;\n\n // Update\n // - currentCoordinates\n // - currentViewCoordinates\n // - currentEventCoordinates\n $timeout(function() {\n pointerHandler.updateFromEvent(ev);\n });\n }\n\n function onDragEnd(ev) {\n var block, pointer;\n\n block = scope.block;\n pointer = Component.$ghost.pointerHandler;\n\n // Deregister mouse events\n angular.element(document).off('mousemove', onDrag);\n\n if (pointer.dragHasStarted) {\n $rootScope.$emit('calendar:dragend');\n pointer.dragHasStarted = false;\n }\n\n // Unmark all blocks as being dragged\n if (block && block.component)\n _.forEach(block.component.blocks, function(b) {\n b.dragging = false;\n });\n }\n\n /**\n * SOGoCoordinates\n */\n function SOGoCoordinates() {\n }\n\n SOGoCoordinates.prototype = {\n x: -1,\n y: -1,\n\n getDelta: function SC_getDelta(otherCoordinates) {\n var delta = new SOGoCoordinates();\n delta.x = this.x - otherCoordinates.x;\n delta.y = this.y - otherCoordinates.y;\n\n if (Calendar.$view) {\n delta.days = Calendar.$view.dayNumbers[this.x] - Calendar.$view.dayNumbers[otherCoordinates.x];\n }\n\n return delta;\n },\n\n getDistance: function SC_getDistance(otherCoordinates) {\n var delta = this.getDelta(otherCoordinates);\n\n return Math.sqrt(delta.x * delta.x + delta.y * delta.y);\n },\n\n clone: function SC_clone() {\n var coordinates = new SOGoCoordinates();\n coordinates.x = this.x;\n coordinates.y = this.y;\n\n return coordinates;\n }\n };\n\n /**\n * SOGoEventDragEventCoordinates\n */\n function SOGoEventDragEventCoordinates(eventType) {\n this.setEventType(eventType);\n }\n\n SOGoEventDragEventCoordinates.prototype = {\n dayNumber: -1,\n weekDay: -1,\n start: -1,\n duration: -1,\n\n eventType: null,\n\n setEventType: function(eventType) {\n this.eventType = eventType;\n },\n\n initFromBlock: function(block) {\n var prevDayNumber = -1;\n\n if (this.eventType === 'monthly') {\n this.start = 0;\n this.duration = block.component.blocks.length * CalendarSettings.EventDragDayLength;\n }\n else {\n // Get the start (first quarter) from the event's first block\n // Compute overall length\n this.start = block.component.blocks[0].start;\n this.duration = _.sumBy(block.component.blocks, function(b) {\n var delta, currentDayNumber;\n\n currentDayNumber = b.dayNumber;\n if (prevDayNumber < 0)\n delta = 0;\n else\n delta = currentDayNumber - prevDayNumber - 1;\n prevDayNumber = currentDayNumber;\n\n return b.length + delta * CalendarSettings.EventDragDayLength;\n });\n }\n },\n\n initFromCalendar: function(calendarNumber) {\n this.dayNumber = calendarNumber;\n },\n\n getDelta: function(otherCoordinates) {\n var delta = new SOGoEventDragEventCoordinates();\n delta.dayNumber = (this.dayNumber - otherCoordinates.dayNumber);\n delta.start = (this.start - otherCoordinates.start);\n delta.duration = (this.duration - otherCoordinates.duration);\n\n return delta;\n },\n\n _quartersToHM: function(quarters) {\n var minutes = quarters * 15;\n var hours = Math.floor(minutes / 60);\n if (hours < 10)\n hours = \"0\" + hours;\n var mins = minutes % 60;\n if (mins < 10)\n mins = \"0\" + mins;\n\n return \"\" + hours + \":\" + mins;\n },\n\n getStartTime: function() {\n return this._quartersToHM(this.start);\n },\n\n getEndTime: function() {\n var end = (this.start + this.duration) % CalendarSettings.EventDragDayLength;\n return this._quartersToHM(end);\n },\n\n clone: function() {\n var coordinates = new SOGoEventDragEventCoordinates();\n coordinates.dayNumber = this.dayNumber;\n coordinates.start = this.start;\n coordinates.duration = this.duration;\n\n return coordinates;\n }\n };\n\n /**\n * SOGoEventDragPointerHandler\n */\n function SOGoEventDragPointerHandler(dragMode) {\n this.dragMode = dragMode;\n }\n\n SOGoEventDragPointerHandler.prototype = {\n // Pointer absolute xy coordinates within page\n originalCoordinates: null,\n currentCoordinates: null,\n\n // Pointer relative xy coordinates within view (row-column)\n originalViewCoordinates: null,\n currentViewCoordinates: null,\n\n // Event start-duration coordinates\n originalEventCoordinates: null,\n currentEventCoordinates: null,\n\n originalCalendar: null,\n\n dragHasStarted: false,\n\n // Function to return the day and quarter coordinates of the pointer cursor\n // within the day view\n getEventViewCoordinates: null,\n\n initFromBlock: function SEDPH_initFromBlock(block) {\n this.currentEventCoordinates = new SOGoEventDragEventCoordinates(this.eventType);\n this.originalEventCoordinates = new SOGoEventDragEventCoordinates(this.eventType);\n this.originalEventCoordinates.initFromBlock(block);\n },\n\n initFromEvent: function SEDPH_initFromEvent(event) {\n this.currentCoordinates = new SOGoCoordinates();\n this.updateFromEvent(event);\n this.originalCoordinates = this.currentCoordinates.clone();\n },\n\n initFromCalendar: function SEDPH_initFromCalendar(calendarData) {\n this.originalCalendar = calendarData;\n this.currentEventCoordinates.initFromCalendar(calendarData.index);\n this.originalEventCoordinates.initFromCalendar(calendarData.index);\n },\n\n // Method continuously called while dragging\n updateFromEvent: function SEDPH_updateFromEvent(event) {\n // Event here is a DOM event, not a calendar event!\n this.currentCoordinates.x = event.pageX;\n this.currentCoordinates.y = event.pageY;\n\n // From SOGoEventDragGhostController.updateFromPointerHandler\n if (this.dragHasStarted && Calendar.$view) {\n var newEventCoordinates = this.getEventViewCoordinates(Calendar.$view);\n if (!this.originalViewCoordinates) {\n this.originalViewCoordinates = this.getEventViewCoordinates(Calendar.$view, this.originalCoordinates);\n if (Component.$ghost.component.isNew) {\n this.setTimeFromQuarters(Component.$ghost.component.start, this.originalViewCoordinates.y);\n $log.debug('new event start date ' + Component.$ghost.component.start);\n }\n }\n if (!this.currentViewCoordinates ||\n !newEventCoordinates ||\n newEventCoordinates.x != this.currentViewCoordinates.x ||\n newEventCoordinates.y != this.currentViewCoordinates.y) {\n this.currentViewCoordinates = newEventCoordinates;\n if (this.originalViewCoordinates) {\n if (!newEventCoordinates) {\n this.currentViewCoordinates = this.originalViewCoordinates.clone();\n }\n this.updateEventCoordinates();\n }\n }\n }\n else if (this.originalCoordinates &&\n this.currentCoordinates &&\n !this.dragHasStarted) {\n var distance = this.getDistance();\n if (distance > 3) {\n this.dragHasStarted = true;\n dragStart(event);\n }\n }\n },\n\n // SOGoEventDragGhostController._updateCoordinates\n // Extend this.currentCoordinates with start, dayNumber and duration\n updateEventCoordinates: function SEDGC__updateCoordinates() {\n var newDuration;\n\n // Compute delta wrt to position of mouse at dragstart on the day/quarter grid\n var delta = this.currentViewCoordinates.getDelta(this.originalViewCoordinates);\n var deltaQuarters = delta.days * CalendarSettings.EventDragDayLength + delta.y;\n $log.debug('quarters delta ' + deltaQuarters);\n\n if (angular.isUndefined(this.originalEventCoordinates.start)) {\n // Creating new appointment from DnD\n this.originalEventCoordinates.dayNumber = Calendar.$view.dayNumbers[this.originalViewCoordinates.x];\n this.originalEventCoordinates.start = this.originalViewCoordinates.y;\n }\n else if (this.originalEventCoordinates.dayNumber < 0) {\n this.originalEventCoordinates.dayNumber = Calendar.$view.dayNumbers[scope.block.component.blocks[0].dayIndex];\n }\n // if (currentView == \"multicolumndayview\")\n // this._updateMulticolumnViewDayNumber_SEDGC();\n // else\n this.currentEventCoordinates.dayNumber = this.originalEventCoordinates.dayNumber;\n\n if (this.dragMode == \"move-event\") {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start + deltaQuarters;\n this.currentEventCoordinates.duration = this.originalEventCoordinates.duration;\n }\n else {\n if (this.dragMode == \"change-start\") {\n newDuration = this.originalEventCoordinates.duration - deltaQuarters;\n if (newDuration > 0) {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start + deltaQuarters;\n this.currentEventCoordinates.duration = newDuration;\n }\n else if (newDuration < 0) {\n this.currentEventCoordinates.start = (this.originalEventCoordinates.start + this.originalEventCoordinates.duration);\n this.currentEventCoordinates.duration = -newDuration;\n }\n }\n else if (this.dragMode == \"change-end\") {\n newDuration = this.originalEventCoordinates.duration + deltaQuarters;\n if (newDuration > 0) {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start;\n this.currentEventCoordinates.duration = newDuration;\n }\n else if (newDuration < 0) {\n this.currentEventCoordinates.start = this.originalEventCoordinates.start + newDuration;\n this.currentEventCoordinates.duration = -newDuration;\n }\n }\n }\n\n var deltaDays;\n if (this.currentEventCoordinates.start < 0) {\n deltaDays = Math.ceil(-this.currentEventCoordinates.start / CalendarSettings.EventDragDayLength);\n this.currentEventCoordinates.start += deltaDays * CalendarSettings.EventDragDayLength;\n this.currentEventCoordinates.dayNumber -= deltaDays;\n }\n else if (this.currentEventCoordinates.start >= CalendarSettings.EventDragDayLength) {\n deltaDays = Math.floor(this.currentEventCoordinates.start / CalendarSettings.EventDragDayLength);\n this.currentEventCoordinates.start -= deltaDays * CalendarSettings.EventDragDayLength;\n this.currentEventCoordinates.dayNumber += deltaDays;\n }\n\n $log.debug('event coordinates ' + JSON.stringify(this.currentEventCoordinates));\n $rootScope.$emit('calendar:drag');\n },\n\n // SOGoEventDragPointerHandler.getContainerBasedCoordinates\n getContainerBasedCoordinates: function SEDPH_getCBC(view, pointerCoordinates) {\n var currentCoordinates = pointerCoordinates || this.currentCoordinates;\n var coordinates = currentCoordinates.getDelta(view.coordinates);\n var container = view.element;\n\n if (coordinates.x < view.daysOffset || coordinates.x > container.clientWidth ||\n coordinates.y < 0 || coordinates.y > container.clientHeight)\n coordinates = null;\n\n return coordinates;\n },\n\n prepareWithEventType: function SEDPH_prepareWithEventType(eventType) {\n var methods = { \"multiday\": this.getEventMultiDayViewCoordinates,\n \"multiday-allday\": this.getEventMultiDayAllDayViewCoordinates,\n \"monthly\": this.getEventMonthlyViewCoordinates,\n \"unknown\": null };\n var method = methods[eventType];\n this.eventType = eventType;\n this.getEventViewCoordinates = method;\n },\n\n getEventMultiDayViewCoordinates: function SEDPH_gEMultiDayViewC(view, pointerCoordinates) {\n /* x = day; y = quarter */\n var coordinates = this.getEventMultiDayAllDayViewCoordinates(view, pointerCoordinates); // get the x coordinate\n if (coordinates) {\n var quarterHeight = view.quarterHeight;\n var pxCoordinates = this.getContainerBasedCoordinates(view, pointerCoordinates);\n pxCoordinates.y += view.element.scrollTop;\n\n coordinates.y = Math.floor((pxCoordinates.y - CalendarSettings.EventDragHorizontalOffset) / quarterHeight);\n var maxY = CalendarSettings.EventDragDayLength - 1;\n if (coordinates.y < 0)\n coordinates.y = 0;\n else if (coordinates.y > maxY)\n coordinates.y = maxY;\n }\n\n return coordinates;\n },\n getEventMultiDayAllDayViewCoordinates: function SEDPH_gEMultiDayADVC(view, pointerCoordinates) {\n /* x = day; y = quarter */\n var coordinates;\n\n var pxCoordinates = this.getContainerBasedCoordinates(view, pointerCoordinates);\n if (pxCoordinates) {\n coordinates = new SOGoCoordinates();\n\n var dayWidth = view.dayWidth;\n var daysOffset = view.daysOffset;\n\n coordinates.x = Math.floor((pxCoordinates.x - daysOffset) / dayWidth);\n var minX = 0;\n var maxX = Calendar.$view.maxX;\n if (this.dragMode != 'move-event') {\n var calendarData = calendarDayCtrl.calendarData();\n if (calendarData)\n // Resizing an event can't span a different day when in multicolumn view\n minX = maxX = calendarData.index;\n }\n if (coordinates.x < minX)\n coordinates.x = minX;\n else if (coordinates.x > maxX)\n coordinates.x = maxX;\n coordinates.y = 0;\n }\n else {\n coordinates = null;\n }\n\n return coordinates;\n },\n getEventMonthlyViewCoordinates: function SEDPH_gEMonthlyViewC(view, pointerCoordinates) {\n /* x = day; y = quarter */\n var coordinates;\n\n var pxCoordinates = this.getContainerBasedCoordinates(view, pointerCoordinates);\n if (pxCoordinates) {\n coordinates = new SOGoCoordinates();\n\n var maxX = view.maxX;\n var daysTopOffset = 0;\n var dayWidth = view.dayWidth;\n var daysOffset = view.daysOffset;\n var dayHeight = view.dayHeight;\n var daysY = Math.floor((pxCoordinates.y - daysTopOffset) / dayHeight);\n if (daysY < 0)\n daysY = 0;\n\n coordinates.x = Math.floor((pxCoordinates.x - daysOffset) / dayWidth);\n if (coordinates.x < 0)\n coordinates.x = 0;\n else if (coordinates.x > maxX)\n coordinates.x = maxX;\n coordinates.x += (maxX + 1) * daysY;\n coordinates.y = 0;\n }\n else {\n coordinates = null;\n }\n\n return coordinates;\n },\n\n getDistance: function SEDPH_getDistance() {\n return this.currentCoordinates.getDistance(this.originalCoordinates);\n },\n\n setTimeFromQuarters: function SEDPH_setTimeFromQuarters(date, quarters) {\n var hours, minutes;\n hours = Math.floor(quarters / 4);\n minutes = (quarters % 4) * 15;\n date.setHours(hours, minutes);\n }\n };\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgDraggableCalendarBlock', sgDraggableCalendarBlock);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /*\n * sgNowLine - Now line to be displayed on top of current day\n * @restrict class\n */\n function sgNowLine() {\n return {\n restrict: 'C',\n require: '^^sgCalendarScrollView',\n link: link,\n controller: sgNowLineController\n };\n\n function link(scope, iElement, iAttr, sgCalendarScrollViewCtrl) {\n function _getDays() {\n return iElement.find('sg-calendar-day');\n }\n function _getView() {\n return sgCalendarScrollViewCtrl.quarterHeight;\n }\n\n // We need to wait for the view to be compiled\n var _unwatchView = scope.$watch(_getView, function(quarterHeight) {\n if (quarterHeight) {\n _unwatchView(); // self release\n scope.quarterHeight = quarterHeight;\n // We need to wait for the days to be compiled\n var _unwatchDays = scope.$watch(_getDays, function(days) {\n if (days.length) {\n _unwatchDays(); // self release\n scope.days = days;\n // Draw the line\n scope.updateLine();\n }\n });\n }\n });\n }\n }\n\n /**\n * @ngInject\n */\n sgNowLineController.$inject = ['$scope', '$element', '$timeout'];\n function sgNowLineController($scope, $element, $timeout) {\n var _this = this, updater,\n scrollViewCtrl = $element.controller('sgCalendarScrollView');\n\n $scope.nowDay = null;\n $scope.lineElement = null;\n $scope.updateLine = _updateLine;\n\n $scope.$on('$destroy', function() {\n if (updater)\n $timeout.cancel(updater);\n });\n\n\n function _updateLine(force) {\n var now = new Date(), // TODO: adjust to user's timezone\n nowDay = now.getDayString(),\n hours = now.getHours(),\n hourHeight = $scope.quarterHeight * 4,\n minutes = now.getMinutes(),\n minuteHeight = $scope.quarterHeight/15,\n position = parseInt(hours * hourHeight +\n minutes * minuteHeight -\n 1);\n\n if (force || nowDay != $scope.nowDay) {\n if ($scope.lineElement)\n $scope.lineElement.remove();\n $scope.lineElement = _addLine(nowDay, $scope.days);\n $scope.nowDay = nowDay;\n }\n\n if ($scope.lineElement) {\n // Current day is displayed\n $scope.lineElement.css('top', position + \"px\");\n // Update line every minute\n updater = $timeout(angular.bind(_this, $scope.updateLine), 60000);\n }\n }\n\n function _addLine(nowDay, days) {\n var $lineElement = angular.element('');\n\n if (scrollViewCtrl.isMultiColumn) {\n // In multicolumn day view, the line must go over all columns\n if (days && days[0].attributes['sg-day'].value == nowDay)\n $element.append($lineElement);\n }\n else\n _.forEach(days, function(dayElement) {\n if (dayElement.attributes['sg-day'].value == nowDay) {\n angular.element(dayElement).find('div').eq(0).append($lineElement);\n }\n });\n\n return $lineElement;\n }\n }\n\n angular\n .module('SOGo.SchedulerUI')\n .directive('sgNowLine', sgNowLine);\n})();\n"]} \ No newline at end of file