7f664c6d479a3248c0f42eff98e6836464761c17
[tine20] / tine20 / Calendar / js / MainScreenCenterPanel.js
1 /* 
2  * Tine 2.0
3  * 
4  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
5  * @author      Cornelius Weiss <c.weiss@metaways.de>
6  * @copyright   Copyright (c) 2007-2013 Metaways Infosystems GmbH (http://www.metaways.de)
7  */
8
9 /* global Ext, Tine */
10
11 Ext.ns('Tine.Calendar');
12
13 Tine.Calendar.MainScreenCenterPanel = Ext.extend(Ext.Panel, {
14     /**
15      * @cfg {String} activeView
16      */
17     activeView: 'weekSheet',
18     
19     startDate: new Date().clearTime(),
20     
21     /**
22      * $property Object view -> startdate
23      */
24     startDates: null,
25     
26     /**
27      * @cfg {String} loadMaskText
28      * _('Loading events, please wait...')
29      */
30     loadMaskText: 'Loading events, please wait...',
31     
32     /**
33      * @cfg {Number} autoRefreshInterval (seconds)
34      */
35     autoRefreshInterval: 300,
36     
37     /**
38      * @property autoRefreshTask
39      * @type Ext.util.DelayedTask
40      */
41     autoRefreshTask: null,
42     
43     /**
44      * add records from other applications using the split add button
45      * - activated by default
46      * 
47      * @type Bool
48      * @property splitAddButton
49      */
50     splitAddButton: true,
51     
52     /**
53      * default print mode
54      * 
55      * @type String {sheet|grid}
56      * @property defaultPrintMode
57      */
58     defaultPrintMode: 'sheet',
59     
60     periodRe: /^(day|week|month|year)/i,
61     presentationRe: /(sheet|grid)$/i,
62     
63     calendarPanels: {},
64     
65     border: false,
66     layout: 'border',
67     
68     stateful: true,
69     stateId: 'cal-mainscreen',
70     stateEvents: ['changeview'],
71     
72     getState: function () {
73         return Ext.copyTo({}, this, 'activeView');
74     },
75     
76     applyState: Ext.emptyFn,
77     
78     initComponent: function () {
79         var me = this;
80         
81         this.addEvents(
82         /**
83          * @event changeview
84          * fired if an event got clicked
85          * @param {Tine.Calendar.MainScreenCenterPanel} mspanel
86          * @param {String} view
87          */
88         'changeview');
89         
90         this.recordClass = Tine.Calendar.Model.Event;
91         
92         this.app = Tine.Tinebase.appMgr.get('Calendar');
93         
94         // init some translations
95         this.i18nRecordName = this.app.i18n.n_hidden(this.recordClass.getMeta('recordName'), this.recordClass.getMeta('recordsName'), 1);
96         this.i18nRecordsName = this.app.i18n._hidden(this.recordClass.getMeta('recordsName'));
97         this.i18nContainerName = this.app.i18n.n_hidden(this.recordClass.getMeta('containerName'), this.recordClass.getMeta('containersName'), 1);
98         this.i18nContainersName = this.app.i18n._hidden(this.recordClass.getMeta('containersName'));
99         
100         this.loadMaskText = this.app.i18n._hidden(this.loadMaskText);
101         
102         var state = Ext.state.Manager.get(this.stateId, {});
103         Ext.apply(this, state);
104         
105         this.defaultFilters = [
106             {field: 'attender', operator: 'in', value: [Ext.apply(Tine.Calendar.Model.Attender.getDefaultData(), {
107                 user_id: Tine.Tinebase.registry.get('currentAccount')
108             })]},
109             {field: 'attender_status', operator: 'notin', value: ['DECLINED']}
110         ];
111         this.filterToolbar = this.getFilterToolbar({
112             onFilterChange: this.refresh.createDelegate(this, [false]),
113             getAllFilterData: this.getAllFilterData.createDelegate(this)
114         });
115         
116         this.filterToolbar.getQuickFilterPlugin().criteriaIgnores.push(
117             {field: 'period'},
118             {field: 'grants'}
119         );
120         
121         this.startDates = [];
122         this.initActions();
123         this.initLayout();
124         
125         // init autoRefresh
126         this.autoRefreshTask = new Ext.util.DelayedTask(this.refresh, this, [{
127             refresh: true,
128             autoRefresh: true
129         }]);
130         
131         Tine.Calendar.MainScreenCenterPanel.superclass.initComponent.call(this);
132     },
133     
134     initActions: function () {
135         this.action_editInNewWindow = new Ext.Action({
136             requiredGrant: 'readGrant',
137             text: this.i18nEditActionText ? this.app.i18n._hidden(this.i18nEditActionText) : String.format(Tine.Tinebase.translation._hidden('Edit {0}'), this.i18nRecordName),
138             disabled: true,
139             handler: this.onEditInNewWindow.createDelegate(this, ["edit"]),
140             iconCls: 'action_edit'
141         });
142         
143         this.action_addInNewWindow = new Ext.Action({
144             requiredGrant: 'addGrant',
145             text: this.i18nAddActionText ? this.app.i18n._hidden(this.i18nAddActionText) : String.format(Tine.Tinebase.translation._hidden('Add {0}'), this.i18nRecordName),
146             handler: this.onEditInNewWindow.createDelegate(this, ["add"]),
147             iconCls: 'action_add'
148         });
149         
150         this.action_cut = new Ext.Action({
151             requiredGrant: 'deleteGrant',
152             text: this.app.i18n._('Cut event'),
153             handler: this.onCutEvent.createDelegate(this),
154             iconCls: 'action_cut'
155         });
156
157         this.action_copy_to = new Ext.Action({
158             requiredGrant: 'deleteGrant',
159             text: this.app.i18n._('Copy Event to clipboard'),
160             handler: this.onCopyToEvent.createDelegate(this),
161             iconCls: 'action_editcopy'
162         });
163         
164         this.action_cancelPasting = new Ext.Action({
165             requiredGrant: 'deleteGrant',
166             text: this.app.i18n._('Stop cut / copy & paste'),
167             handler: this.onCutCancelEvent.createDelegate(this),
168             iconCls: 'action_cut_break'
169         });
170         
171         // note: unprecise plural form here, but this is hard to change
172         this.action_deleteRecord = new Ext.Action({
173             requiredGrant: 'deleteGrant',
174             allowMultiple: true,
175             singularText: this.i18nDeleteActionText ? i18nDeleteActionText[0] : String.format(Tine.Tinebase.translation.n_hidden('Delete {0}', 'Delete {0}', 1), this.i18nRecordName),
176             pluralText: this.i18nDeleteActionText ? i18nDeleteActionText[1] : String.format(Tine.Tinebase.translation.n_hidden('Delete {0}', 'Delete {0}', 1), this.i18nRecordsName),
177             translationObject: this.i18nDeleteActionText ? this.app.i18n : Tine.Tinebase.translation,
178             text: this.i18nDeleteActionText ? this.i18nDeleteActionText[0] : String.format(Tine.Tinebase.translation.n_hidden('Delete {0}', 'Delete {0}', 1), this.i18nRecordName),
179             handler: this.onDeleteRecords,
180             disabled: true,
181             iconCls: 'action_delete',
182             scope: this
183         });
184         
185         this.actions_print = new Ext.Action({
186             requiredGrant: 'readGrant',
187             text: this.app.i18n._('Print Page'),
188             handler: this.onPrint.createDelegate(this, []),
189             iconCls:'action_print',
190             scope: this,
191             listeners: {
192                 arrowclick: this.onPrintMenuClick.createDelegate(this)
193             },
194             menu:{
195                 items:[{
196                     text: this.app.i18n._('Grid'),
197                     iconCls: 'cal-grid-view-type',
198                     handler: this.onPrint.createDelegate(this, ['grid'])
199                 }, {
200                     text: this.app.i18n._('Sheet'),
201                     iconCls: 'cal-week-view',
202                     handler: this.onPrint.createDelegate(this, ['sheet']),
203                     disabled: Ext.isIE || Ext.isNewIE
204                 }]
205             }
206         });
207
208         /**
209          * @type {Ext.Action}
210          */
211         this.actions_exportEvents = new Ext.Action({
212             requiredGrant: 'exportGrant',
213             text: this.app.i18n._('Export Events'),
214             translationObject: this.app.i18n,
215             iconCls: 'action_export',
216             scope: this,
217             allowMultiple: true,
218             menu: {
219                 items: [
220                     new Tine.Calendar.ExportButton({
221                         text: this.app.i18n._('Export as ODS'),
222                         format: 'ods',
223                         iconCls: 'tinebase-action-export-ods',
224                         exportFunction: 'Calendar.exportEvents',
225                         gridPanel: this
226                     }),
227                     new Tine.Calendar.ExportButton({
228                         text: this.app.i18n._('Export as ...'),
229                         iconCls: 'tinebase-action-export-xls',
230                         exportFunction: 'Calendar.exportEvents',
231                         showExportDialog: true,
232                         gridPanel: this
233                     })
234                 ]
235             }
236         });
237
238         this.showSheetView = new Ext.Button({
239             pressed: String(this.activeView).match(/sheet$/i),
240             scale: 'medium',
241             minWidth: 60,
242             rowspan: 2,
243             iconAlign: 'top',
244             requiredGrant: 'readGrant',
245             text: this.app.i18n._('Sheet'),
246             handler: this.changeView.createDelegate(this, ["sheet"]),
247             iconCls:'cal-sheet-view-type',
248             xtype: 'tbbtnlockedtoggle',
249             toggleGroup: 'Calendar_Toolbar_tgViewTypes',
250             scope: this
251         });
252         
253         this.showGridView = new Ext.Button({
254             pressed: String(this.activeView).match(/grid$/i),
255             scale: 'medium',
256             minWidth: 60,
257             rowspan: 2,
258             iconAlign: 'top',
259             requiredGrant: 'readGrant',
260             text: this.app.i18n._('Grid'),
261             handler: this.changeView.createDelegate(this, ["grid"]),
262             iconCls:'cal-grid-view-type',
263             xtype: 'tbbtnlockedtoggle',
264             toggleGroup: 'Calendar_Toolbar_tgViewTypes',
265             scope: this
266         });
267         
268         this.showDayView = new Ext.Toolbar.Button({
269             pressed: String(this.activeView).match(/^day/i),
270             text: this.app.i18n._('Day'),
271             iconCls: 'cal-day-view',
272             xtype: 'tbbtnlockedtoggle',
273             handler: this.changeView.createDelegate(this, ["day"]),
274             enableToggle: true,
275             toggleGroup: 'Calendar_Toolbar_tgViews'
276         });
277         this.showWeekView = new Ext.Toolbar.Button({
278             pressed: String(this.activeView).match(/^week/i),
279             text: this.app.i18n._('Week'),
280             iconCls: 'cal-week-view',
281             xtype: 'tbbtnlockedtoggle',
282             handler: this.changeView.createDelegate(this, ["week"]),
283             enableToggle: true,
284             toggleGroup: 'Calendar_Toolbar_tgViews'
285         });
286         this.showMonthView = new Ext.Toolbar.Button({
287             pressed: String(this.activeView).match(/^month/i),
288             text: this.app.i18n._('Month'),
289             iconCls: 'cal-month-view',
290             xtype: 'tbbtnlockedtoggle',
291             handler: this.changeView.createDelegate(this, ["month"]),
292             enableToggle: true,
293             toggleGroup: 'Calendar_Toolbar_tgViews'
294         });
295         this.showYearView = new Ext.Toolbar.Button({
296             pressed: String(this.activeView).match(/^year/i),
297             text: this.app.i18n._('Year'),
298             iconCls: 'cal-year-view',
299             xtype: 'tbbtnlockedtoggle',
300             handler: this.changeView.createDelegate(this, ["year"]),
301             enableToggle: true,
302             toggleGroup: 'Calendar_Toolbar_tgViews'
303         });
304         
305        this.action_import = new Ext.Action({
306             requiredGrant: 'addGrant',
307             text: this.app.i18n._('Import Events'),
308             disabled: false,
309             handler: this.onImport,
310             scale: 'medium',
311             minWidth: 60,
312             rowspan: 2,
313             iconAlign: 'top',
314             requiredGrant: 'readGrant',
315             iconCls: 'action_import',
316             scope: this,
317             allowMultiple: true
318         });
319
320         this.changeViewActions = [
321             this.showDayView,
322             this.showWeekView,
323             this.showMonthView
324         ];
325
326         if (this.app.featureEnabled('featureYearView')) {
327             this.changeViewActions.push(this.showYearView);
328         }
329
330         this.recordActions = [
331             this.action_import,
332             this.action_editInNewWindow,
333             this.action_deleteRecord
334             
335         ];
336         
337         this.actionUpdater = new  Tine.widgets.ActionUpdater({
338             actions: this.recordActions,
339             grantsProperty: false,
340             containerProperty: false
341         });
342     },
343     
344     /**
345      * returns the paste action
346      * 
347      * @param {Date} datetime
348      * @param {Tine.Calendar.Model.Event} event
349      */
350     getPasteAction: function(datetime, event) {
351         var shortSummary = Ext.util.Format.ellipsis(event.get('summary'), 15);
352         return new Ext.Action({
353             requiredGrant: 'addGrant',
354             text: String.format(this.app.i18n._('Paste event "{0}"'), shortSummary),
355             handler: this.onPasteEvent.createDelegate(this, [datetime]),
356             iconCls: 'action_paste'
357         });
358     },
359         
360     getActionToolbar: Tine.widgets.grid.GridPanel.prototype.getActionToolbar,
361     
362     getActionToolbarItems: function() {
363         return [/*{
364             xtype: 'buttongroup',
365             columns: 1,
366             rows: 2,
367             frame: false,
368             items: [
369                 this.actions_exportEvents
370                 // @TODO move import btn here
371             ]
372         }, */{
373             xtype: 'buttongroup',
374             plugins: [{
375                 ptype: 'ux.itemregistry',
376                 key:   'Calendar-MainScreenPanel-ViewBtnGrp'
377             }],
378             items: [
379                 this.showSheetView,
380                 this.showGridView,
381                 this.action_import
382             ]
383         }];
384     },
385     
386     /**
387      * @private
388      * 
389      * NOTE: Order of items matters! Ext.Layout.Border.SplitRegion.layout() does not
390      *       fence the rendering correctly, as such it's impotant, so have the ftb
391      *       defined after all other layout items
392      */
393     initLayout: function () {
394         this.items = [{
395             region: 'center',
396             layout: 'card',
397             activeItem: 0,
398             border: false,
399             items: [this.getCalendarPanel(this.activeView)]
400         }];
401         
402         // add detail panel
403         if (this.detailsPanel) {
404             this.items.push({
405                 region: 'south',
406                 border: false,
407                 collapsible: true,
408                 collapseMode: 'mini',
409                 header: false,
410                 split: true,
411                 layout: 'fit',
412                 height: this.detailsPanel.defaultHeight ? this.detailsPanel.defaultHeight : 125,
413                 items: this.detailsPanel
414                 
415             });
416             //this.detailsPanel.doBind(this.activeView);
417         }
418         
419         // add filter toolbar
420         if (this.filterToolbar) {
421             this.items.push({
422                 region: 'north',
423                 border: false,
424                 items: this.filterToolbar,
425                 listeners: {
426                     scope: this,
427                     afterlayout: function (ct) {
428                         ct.suspendEvents();
429                         ct.setHeight(this.filterToolbar.getHeight());
430                         ct.ownerCt.layout.layout();
431                         ct.resumeEvents();
432                     }
433                 }
434             });
435         }
436     },
437     
438     /**
439      * import events
440      * 
441      * @param {Button} btn 
442      */
443     onImport: function(btn) {
444         var popupWindow = Tine.Calendar.ImportDialog.openWindow({
445             appName: 'Calendar',
446             modelName: 'Event',
447             defaultImportContainer: this.app.getMainScreen().getWestPanel().getContainerTreePanel().getDefaultContainer('defaultContainer'),
448             
449             ignoreConflicts: true,
450             doTryRun: false,
451             
452             
453             // update grid after import
454             listeners: {
455                 scope: this,
456                 'finish': function() {
457                     this.refresh();
458                 }
459             }
460         });
461     },
462     
463     /**
464      * @private
465      */
466     onRender: function(ct, position) {
467         Tine.Calendar.MainScreenCenterPanel.superclass.onRender.apply(this, arguments);
468         
469         var defaultFavorite = Tine.widgets.persistentfilter.model.PersistentFilter.getDefaultFavorite(this.app.appName, this.recordClass.prototype.modelName),
470             favoritesPanel  = this.app.getMainScreen().getWestPanel().getFavoritesPanel();
471         
472         this.loadMask = new Ext.LoadMask(this.body, {msg: this.loadMaskText});
473         
474         if (defaultFavorite) {
475             favoritesPanel.selectFilter(defaultFavorite);
476         } else {
477             this.refresh();
478         }
479     },
480     
481     getViewParts: function (view) {
482         view = String(view);
483         
484         var activeView = String(this.activeView),
485             periodMatch = view.match(this.periodRe),
486             period = Ext.isArray(periodMatch) ? periodMatch[0] : null,
487             activePeriodMatch = activeView.match(this.periodRe),
488             activePeriod = Ext.isArray(activePeriodMatch) ? activePeriodMatch[0] : 'week',
489             presentationMatch = view.match(this.presentationRe),
490             presentation = Ext.isArray(presentationMatch) ? presentationMatch[0] : null,
491             activePresentationMatch = activeView.match(this.presentationRe),
492             activePresentation = Ext.isArray(activePresentationMatch) ? activePresentationMatch[0] : 'sheet';
493             
494         return {
495             period: period ? period : activePeriod,
496             presentation: presentation ? presentation : activePresentation,
497             toString: function() {return this.period + Ext.util.Format.capitalize(this.presentation);}
498         };
499     },
500     
501     changeView: function (view, startDate) {
502         // autocomplete view
503         var viewParts = this.getViewParts(view);
504         view = viewParts.toString();
505         
506         Tine.log.debug('Tine.Calendar.MainScreenCenterPanel::changeView(' + view + ',' + startDate + ')');
507         
508         // save current startDate
509         this.startDates[this.activeView] = this.startDate.clone();
510         
511         if (startDate && Ext.isDate(startDate)) {
512             this.startDate = startDate.clone();
513         } else {
514             // see if a recent startDate of that view fits
515             var lastStartDate = this.startDates[view],
516                 currentPeriod = this.getCalendarPanel(this.activeView).getView().getPeriod();
517                 
518             if (Ext.isDate(lastStartDate) && lastStartDate.between(currentPeriod.from, currentPeriod.until)) {
519                 this.startDate = this.startDates[view].clone();
520             }
521         }
522         
523         var panel = this.getCalendarPanel(view);
524         var cardPanel = this.items.first();
525         
526         if (panel.rendered) {
527             cardPanel.layout.setActiveItem(panel.id);
528         } else {
529             cardPanel.add(panel);
530             cardPanel.layout.setActiveItem(panel.id);
531             cardPanel.doLayout();
532         }
533         
534         this.activeView = view;
535         
536         // move around changeViewButtons
537         var rightRow = Ext.get(Ext.DomQuery.selectNode('tr[class=x-toolbar-right-row]', panel.tbar.dom));
538         
539         for (var i = this.changeViewActions.length - 1; i >= 0; i--) {
540             rightRow.insertFirst(this.changeViewActions[i].getEl().parent().dom);
541         }
542         this['show' + Ext.util.Format.capitalize(viewParts.period) +  'View'].toggle(true);
543         this['show' + Ext.util.Format.capitalize(viewParts.presentation) +  'View'].toggle(true);
544         
545         // update actions
546         this.updateEventActions();
547         
548         // update data
549         panel.getView().updatePeriod({from: this.startDate});
550         panel.getStore().load({});
551         
552         this.fireEvent('changeview', this, view);
553     },
554     
555     /**
556      * returns all filter data for current view
557      */
558     getAllFilterData: function (options) {
559         var store = this.getCalendarPanel(this.activeView).getStore();
560         
561         options = Ext.apply({
562             refresh: true, // ommit loadMask
563             noPeriodFilter: true
564         }, options || {});
565         this.onStoreBeforeload(store, options);
566         
567         return options.params.filter;
568     },
569     
570     getCustomfieldFilters: Tine.widgets.grid.GridPanel.prototype.getCustomfieldFilters,
571     
572     getFilterToolbar: Tine.widgets.grid.GridPanel.prototype.getFilterToolbar,
573     
574     /**
575      * returns store of currently active view
576      */
577     getStore: function () {
578         return this.getCalendarPanel(this.activeView).getStore();
579     },
580     
581     /**
582      * onContextMenu
583      * 
584      * @param {Event} e
585      */
586     onContextMenu: function (e) {
587         e.stopEvent();
588
589         var view = this.getCalendarPanel(this.activeView).getView();
590         var event = view.getTargetEvent(e);
591         var datetime = view.getTargetDateTime(e);
592         
593         if (event && event.id.match(/new-ext-gen/) ) {
594             // new event, no ctx menu possible atm
595             // @see 0008948: deactivate context menu on new events
596             return;
597         }
598         
599         var addAction, responseAction, copyAction;
600
601         if (datetime || event) {
602             var dtStart = datetime || event.get('dtstart').clone();
603             if (dtStart.format('H:i') === '00:00') {
604                 dtStart = dtStart.add(Date.HOUR, 9);
605             }
606             
607             addAction = {
608                 text: this.i18nAddActionText ? this.app.i18n._hidden(this.i18nAddActionText) : String.format(Tine.Tinebase.translation._hidden('Add {0}'), this.i18nRecordName),
609                 handler: this.onEditInNewWindow.createDelegate(this, ["add", null, null, {dtStart: dtStart, is_all_day_event: datetime && datetime.is_all_day_event}]),
610                 iconCls: 'action_add'
611             };
612             
613             // assemble event actions
614             if (event) {
615                 responseAction = this.getResponseAction(event);
616                 copyAction = this.getCopyAction(event);
617             }
618         } else {
619             addAction = this.action_addInNewWindow;
620         }
621         
622         if (event) {
623             view.getSelectionModel().select(event, e, e.ctrlKey);
624         } else {
625             view.getSelectionModel().clearSelections();
626         }
627
628         var menuitems = this.recordActions.concat(addAction, responseAction || [], copyAction || []);
629         
630         if (event) {
631             this.action_copy_to.setDisabled(event.isRecurInstance() || event.isRecurException() || event.isRecurBase());
632             menuitems = menuitems.concat(['-', this.action_cut, this.action_copy_to, '-']);
633         } else if (Tine.Tinebase.data.Clipboard.has('Calendar', 'Event')) {
634             menuitems = menuitems.concat(['-', this.getPasteAction(datetime, Tine.Tinebase.data.Clipboard.pull('Calendar', 'Event', true)), this.action_cancelPasting, '-']);
635         }
636
637         var ctxMenu = new Ext.menu.Menu({
638             plugins: [{
639                 ptype: 'ux.itemregistry',
640                 key:   'Calendar-MainScreenPanel-ContextMenu',
641                 config: {
642                     event: event,
643                     datetime: datetime
644                 }
645             },
646             // to allow gridpanel hooks (like email compose)
647             {
648                 ptype: 'ux.itemregistry',
649                 key:   'Calendar-GridPanel-ContextMenu'
650             }],
651             items: menuitems
652         });
653         ctxMenu.showAt(e.getXY());
654     },
655     
656     /**
657      * get response action
658      * 
659      * @param {Tine.Calendar.Model.Event} event
660      * @return {Object}
661      */
662     getResponseAction: function(event) {
663         var statusStore = Tine.Tinebase.widgets.keyfield.StoreMgr.get('Calendar', 'attendeeStatus'),
664             myAttenderRecord = event.getMyAttenderRecord(),
665             myAttenderStatus = myAttenderRecord ? myAttenderRecord.get('status') : null,
666             myAttenderStatusRecord = statusStore.getById(myAttenderStatus),
667             responseAction = null;
668         
669         if (myAttenderRecord) {
670             responseAction = {
671                 text: this.app.i18n._('Set my response'),
672                 icon: myAttenderStatusRecord ? myAttenderStatusRecord.get('icon') : false,
673                 menu: []
674             };
675             
676             statusStore.each(function(status) {
677                 var isCurrent = myAttenderRecord.get('status') === status.id;
678                 
679                 // NOTE: we can't use checked items here as we use icons already
680                 responseAction.menu.push({
681                     text: status.get('i18nValue'),
682                     handler: this.setResponseStatus.createDelegate(this, [event, status.id]),
683                     icon: status.get('icon'),
684                     disabled: myAttenderRecord.get('status') === status.id
685                 });
686             }, this);
687         }
688         
689         return responseAction;
690     },
691
692     /**
693      * get copy action
694      * 
695      * @param {Tine.Calendar.Model.Event} event
696      * @return {Object}
697      */
698     getCopyAction: function(event) {
699         var copyAction = {
700             text: String.format(this.app.i18n._('Copy {0}'), this.i18nRecordName),
701             handler: this.onEditInNewWindow.createDelegate(this, ["copy", event]),
702             iconCls: 'action_editcopy',
703             // TODO allow to copy recurring events / exceptions
704             disabled: event.isRecurInstance() || event.isRecurException() || event.isRecurBase()
705         };
706         
707         return copyAction
708     },
709     
710     checkPastEvent: function(event, checkBusyConflicts, actionType) {
711         var start = event.get('dtstart').getTime();
712         var morning = new Date().clearTime().getTime();
713
714         switch (actionType) {
715             case 'update':
716                 var title = this.app.i18n._('Updating event in the past'),
717                     optionYes = this.app.i18n._('Update this event'),
718                     optionNo = this.app.i18n._('Do not update this event');
719                 break;
720             case 'add':
721             default:
722                 var title = this.app.i18n._('Creating event in the past'),
723                     optionYes = this.app.i18n._('Create this event'),
724                     optionNo = this.app.i18n._('Do not create this event');
725         }
726         
727         if(start < morning) {
728             Tine.widgets.dialog.MultiOptionsDialog.openWindow({
729                 title: title,
730                 height: 170,
731                 scope: this,
732                 options: [
733                     {text: optionYes, name: 'yes'},
734                     {text: optionNo, name: 'no'}
735                 ],
736                 
737                 handler: function(option) {
738                     try {
739                         switch (option) {
740                             case 'yes':
741                                 if (actionType == 'update') this.onUpdateEvent(event, true);
742                                 else this.onAddEvent(event, checkBusyConflicts, true);
743                                 break;
744                             case 'no':
745                             default:
746                                 try {
747                                     var panel = this.getCalendarPanel(this.activeView);
748                                     if(panel) {
749                                         var store = panel.getStore(),
750                                             view = panel.getView();
751                                     }
752                                 } catch(e) {
753                                     var panel = null, 
754                                         store = null,
755                                         view = null;
756                                 }
757                                 
758                                 if (actionType == 'add') {
759                                     if(store) store.remove(event);
760                                 } else {
761                                     if (view && view.rendered) {
762                                         this.loadMask.show();
763                                         store.reload();
764 //                                        TODO: restore original event so no reload is needed
765 //                                        var updatedEvent = event;
766 //                                        updatedEvent.dirty = false;
767 //                                        updatedEvent.editing = false;
768 //                                        updatedEvent.modified = null;
769 //                                        
770 //                                        store.replaceRecord(event, updatedEvent);
771 //                                        view.getSelectionModel().select(event);
772                                     }
773                                     this.setLoading(false);
774                                 }
775                         }
776                     } catch (e) {
777                         Tine.log.error('Tine.Calendar.MainScreenCenterPanel::checkPastEvent::handler');
778                         Tine.log.error(e);
779                     }
780                 }             
781             });
782         } else {
783             if (actionType == 'update') this.onUpdateEvent(event, true);
784             else this.onAddEvent(event, checkBusyConflicts, true);
785         }
786     },
787     
788     onAddEvent: function(event, checkBusyConflicts, pastChecked) {
789         if(!pastChecked) {
790             this.checkPastEvent(event, checkBusyConflicts, 'add');
791             return;
792         }
793         
794         this.setLoading(true);
795         
796         // remove temporary id
797         if (event.get('id').match(/new/)) {
798             event.set('id', '');
799         }
800         
801         if (event.isRecurBase()) {
802             if (this.loadMask) {
803                 this.loadMask.show();
804             }
805         }
806         
807         var panel = this.getCalendarPanel(this.activeView),
808             store = event.store,
809             view = panel.getView();
810         
811         Tine.Calendar.backend.saveRecord(event, {
812             scope: this,
813             success: function(createdEvent) {
814                 if (createdEvent.isRecurBase()) {
815                     store.load({refresh: true});
816                 } else {
817                     // store may be lost on conflict or else
818                     if (store) {
819                         store.replaceRecord(event, createdEvent);
820                         this.setLoading(false);
821                     } else {
822                         this.refresh();
823                     }
824                     
825                     if (view && view.rendered) {
826                         view.getSelectionModel().select(createdEvent);
827                     }
828                 }
829             },
830             failure: this.onProxyFail.createDelegate(this, [event], true)
831         }, {
832             checkBusyConflicts: checkBusyConflicts === false ? 0 : 1
833         });
834     },
835     
836     onUpdateEvent: function(event, pastChecked) {
837         this.setLoading(true);
838         
839         if(!pastChecked) {
840             this.checkPastEvent(event, null, 'update');
841             return;
842         }
843         
844         if (event.isRecurBase() && this.loadMask) {
845            this.loadMask.show();
846         }
847         
848         if (event.id && (event.isRecurInstance() || event.isRecurException() || (event.isRecurBase() && ! event.get('rrule').newrule))) {
849             Tine.widgets.dialog.MultiOptionsDialog.openWindow({
850                 title: this.app.i18n._('Update Event'),
851                 height: 170,
852                 scope: this,
853                 options: [
854                     {text: this.app.i18n._('Update this event only'), name: 'this'},
855                     {text: this.app.i18n._('Update this and all future events'), name: (event.isRecurBase() && ! event.get('rrule').newrule) ? 'series' : 'future'},
856                     {text: this.app.i18n._('Update whole series'), name: 'series'},
857                     {text: this.app.i18n._('Update nothing'), name: 'cancel'}
858                     
859                 ],
860                 handler: function(option) {
861                     var store = event.store;
862
863                     if (! store) {
864                         store = this.getStore();
865                     }
866                     
867                     switch (option) {
868                         case 'series':
869                             if (this.loadMask) {
870                                 this.loadMask.show();
871                             }
872                             
873                             var options = {
874                                 scope: this,
875                                 success: function() {
876                                     store.load({refresh: true});
877                                 }
878                             };
879                             options.failure = this.onProxyFail.createDelegate(this, [event, Tine.Calendar.backend.updateRecurSeries.createDelegate(Tine.Calendar.backend, [event, false, options])], true);
880                             
881                             if (event.isRecurException()) {
882                                 Tine.Calendar.backend.saveRecord(event, options, {range: 'ALL', checkBusyConflicts: true});
883                             } else {
884                                 Tine.Calendar.backend.updateRecurSeries(event, true, options);
885                             }
886                             break;
887                             
888                         case 'this':
889                         case 'future':
890                             var options = {
891                                 scope: this,
892                                 success: function(updatedEvent) {
893                                     // NOTE: we also need to refresh for 'this' as otherwise
894                                     //       baseevent is not refreshed -> concurrency failures
895                                     store.load({refresh: true});
896                                 },
897                                 failure: this.onProxyFail.createDelegate(this, [event], true)
898                             };
899                             
900                             
901                             if (event.isRecurException()) {
902                                 var range = (option === 'this' ? 'THIS' : 'THISANDFUTURE');
903                                 options.failure = this.onProxyFail.createDelegate(this, [event, Tine.Calendar.backend.saveRecord.createDelegate(Tine.Calendar.backend, [event, options, {range: range, checkBusyConflicts: false}])], true);
904                                 Tine.Calendar.backend.saveRecord(event, options, {range: range, checkBusyConflicts: true});
905                             } else {
906                                 options.failure = this.onProxyFail.createDelegate(this, [event, Tine.Calendar.backend.createRecurException.createDelegate(Tine.Calendar.backend, [event, false, option == 'future', false, options])], true);
907                                 Tine.Calendar.backend.createRecurException(event, false, option === 'future', true, options);
908                             }
909                             break;
910                             
911                         default:
912                             if(this.loadMask) { //no loadMask called from another app
913                                 this.loadMask.show();
914                                 store.load({refresh: true});
915                             }
916                             break;
917                     }
918
919                 } 
920             });
921         } else {
922             this.onUpdateEventAction(event);
923         }
924     },
925     
926     onUpdateEventAction: function(event) {
927         var panel = this.getCalendarPanel(this.activeView),
928             store = panel.getStore(),
929             view = panel.getView();
930             
931         Tine.Calendar.backend.saveRecord(event, {
932             scope: this,
933             success: function(updatedEvent) {
934                 if (updatedEvent.isRecurBase()) {
935                     store.load({refresh: true});
936                 } else {
937                     this.congruenceFilterCheck(event, updatedEvent);
938                 }
939             },
940             failure: this.onProxyFail.createDelegate(this, [event], true)
941         }, {
942             checkBusyConflicts: 1
943         });
944     },
945
946     /**
947      * checks, if the last filter still matches after update
948      * 
949      * @param {Tine.Calendar.Model.Event} event
950      * @param {Tine.Calendar.Model.Event} updatedEvent
951      */
952     congruenceFilterCheck: function(event, updatedEvent) {
953         if (! (event.ui && event.ui.rendered)) {
954             event.store.replaceRecord(event, updatedEvent);
955             this.setLoading(false);
956             return;
957         }
958         
959         var filterData = this.getAllFilterData(),
960             store = event.store;
961         
962         if (! store) {
963             store = this.getStore();
964         }
965         
966         filterData[0].filters[0].filters.push({field: 'id', operator: 'in', value: [ updatedEvent.get('id') ]});
967         
968         Tine.Calendar.searchEvents(filterData, {}, function(r) {
969             if(r.totalcount == 0) {
970                 updatedEvent.outOfFilter = true;
971             }
972             
973             store.replaceRecord(event, updatedEvent);
974             this.setLoading(false);
975         }, this);
976     },
977     
978     onDeleteRecords: function () {
979         var panel = this.getCalendarPanel(this.activeView);
980         var selection = panel.getSelectionModel().getSelectedEvents();
981         
982         var containsRecurBase = false,
983             containsRecurInstance = false,
984             containsRecurException = false;
985         
986         Ext.each(selection, function (event) {
987             if(event.ui) event.ui.markDirty();
988             if (event.isRecurInstance()) {
989                 containsRecurInstance = true;
990             }
991             if (event.isRecurBase()) {
992                 containsRecurBase = true;
993             }
994             if (event.isRecurException()) {
995                 containsRecurException = true;
996             }
997         });
998         
999         if (selection.length > 1 && (containsRecurBase || containsRecurInstance)) {
1000             Ext.Msg.show({
1001                 title: this.app.i18n._('Please Change Selection'), 
1002                 msg: this.app.i18n._('Your selection contains recurring events. Recuring events must be deleted seperatly!'),
1003                 icon: Ext.MessageBox.INFO,
1004                 buttons: Ext.Msg.OK,
1005                 scope: this,
1006                 fn: function () {
1007                     this.onDeleteRecordsConfirmFail(panel, selection);
1008                 }
1009             });
1010             return;
1011         }
1012         
1013         if (selection.length === 1 && (containsRecurBase || containsRecurInstance || containsRecurException)) {
1014             this.deleteMethodWin = Tine.widgets.dialog.MultiOptionsDialog.openWindow({
1015                 title: this.app.i18n._('Delete Event'),
1016                 scope: this,
1017                 height: 170,
1018                 options: [
1019                     {text: this.app.i18n._('Delete this event only'), name: 'this'},
1020                     {text: this.app.i18n._('Delete this and all future events'), name: containsRecurBase ? 'all' : 'future'},
1021                     {text: this.app.i18n._('Delete whole series'), name: 'all'},
1022                     {text: this.app.i18n._('Delete nothing'), name: 'nothing'}
1023                 ],
1024                 handler: function (option) {
1025                     try {
1026                         switch (option) {
1027                             case 'all':
1028                             case 'this':
1029                             case 'future':
1030                                 panel.getTopToolbar().beforeLoad();
1031                                 if (option !== 'this') {
1032                                     this.loadMask.show();
1033                                 }
1034                                 
1035                                 var options = {
1036                                     scope: this,
1037                                     success: function () {
1038                                         if (option === 'this') {
1039                                             Ext.each(selection, function (event) {
1040                                                 panel.getStore().remove(event);
1041                                             });
1042                                         }
1043                                         this.refresh(true);
1044                                     }
1045                                 };
1046                                 
1047                                 if (containsRecurException) {
1048                                     var range = (option === 'future') ? 'THISANDFUTURE' : Ext.util.Format.uppercase(option);
1049                                     Tine.Calendar.backend.deleteRecords([selection[0]], options, {range: range});
1050                                 } else {
1051                                     if (option === 'all') {
1052                                         Tine.Calendar.backend.deleteRecurSeries(selection[0], options);
1053                                     } else {
1054                                         Tine.Calendar.backend.createRecurException(selection[0], true, option === 'future', false, options);
1055                                     }
1056                                 }
1057                                 break;
1058                             default:
1059                                 this.onDeleteRecordsConfirmFail(panel, selection);
1060                                 break;
1061                     }
1062                     
1063                     } catch (e) {
1064                         Tine.log.error('Tine.Calendar.MainScreenCenterPanel::onDeleteRecords::handle');
1065                         Tine.log.error(e);
1066                     }
1067                 }
1068             });
1069             return;
1070         }
1071         
1072         // else
1073         var i18nQuestion = String.format(this.app.i18n.ngettext('Do you really want to delete this event?', 'Do you really want to delete the {0} selected events?', selection.length), selection.length);
1074         Ext.MessageBox.confirm(Tine.Tinebase.translation._hidden('Confirm'), i18nQuestion, function (btn) {
1075             if (btn === 'yes') {
1076                 this.onDeleteRecordsConfirmNonRecur(panel, selection);
1077             } else {
1078                 this.onDeleteRecordsConfirmFail(panel, selection);
1079             }
1080         }, this);
1081         
1082     },
1083     
1084     onDeleteRecordsConfirmNonRecur: function (panel, selection) {
1085         panel.getTopToolbar().beforeLoad();
1086         
1087         // create a copy of selection so selection changes don't affect this
1088         var sel = Ext.unique(selection);
1089                 
1090         var options = {
1091             scope: this,
1092             success: function () {
1093                 panel.getTopToolbar().onLoad();
1094                 Ext.each(sel, function (event) {
1095                     panel.getStore().remove(event);
1096                 });
1097             },
1098             failure: function () {
1099                 panel.getTopToolbar().onLoad();
1100                 Ext.MessageBox.alert(Tine.Tinebase.translation._hidden('Failed'), String.format(this.app.i18n.n_('Failed to delete event', 'Failed to delete the {0} events', selection.length), selection.length));
1101             }
1102         };
1103         
1104         Tine.Calendar.backend.deleteRecords(selection, options);
1105     },
1106     
1107     onDeleteRecordsConfirmFail: function (panel, selection) {
1108         Ext.each(selection, function (event) {
1109             event.ui.clearDirty();
1110         });
1111     },
1112     
1113     /**
1114      * is called on action cut
1115      * 
1116      * @param {} action
1117      * @param {} event
1118      */
1119     onCutEvent: function(action, event) {
1120         var panel = this.getCalendarPanel(this.activeView);
1121         var selection = panel.getSelectionModel().getSelectedEvents();
1122         if (Ext.isArray(selection) && selection.length === 1) {
1123             event = selection[0];
1124         }
1125         if (event.ui) {
1126             event.ui.markDirty();
1127         }
1128         Tine.Tinebase.data.Clipboard.push(event);
1129     },
1130
1131     /**
1132      * Is called on copy to clipboard
1133      *
1134      * @param action
1135      * @param event
1136      */
1137     onCopyToEvent: function(action, event) {
1138         var panel = this.getCalendarPanel(this.activeView);
1139         var selection = panel.getSelectionModel().getSelectedEvents();
1140         if (Ext.isArray(selection) && selection.length === 1) {
1141             event = selection[0];
1142         }
1143
1144         event.isCopy = true;
1145
1146         Tine.Tinebase.data.Clipboard.push(event);
1147     },
1148     
1149     /**
1150      * is called on cancelling cut & paste
1151      */
1152     onCutCancelEvent: function() {
1153         var store = this.getStore();
1154         var ids = Tine.Tinebase.data.Clipboard.getIds('Calendar', 'Event');
1155         
1156         for (var index = 0; index < ids.length; index++) {
1157             var record = store.getAt(store.findExact('id', ids[index]));
1158             if (record && record.ui) {
1159                 record.ui.clearDirty();
1160             }
1161         }
1162
1163         Tine.Tinebase.data.Clipboard.clear('Calendar', 'Event');
1164     },
1165     
1166     /**
1167      * is called on action paste
1168      * 
1169      * @param {Date} datetime
1170      */
1171     onPasteEvent: function(datetime) {
1172         var record = Tine.Tinebase.data.Clipboard.pull('Calendar', 'Event');
1173         var isCopy = record.isCopy;
1174
1175         if (! record) {
1176             return;
1177         }
1178         
1179         var dtend   = record.get('dtend');
1180         var dtstart = record.get('dtstart');
1181         var eventLength = dtend - dtstart;
1182
1183         if (isCopy != true) {
1184             // remove before update
1185             var store = this.getStore();
1186             var oldRecord = store.getAt(store.findExact('id', record.getId()));
1187             if (oldRecord && oldRecord.hasOwnProperty('ui')) {
1188                 oldRecord.ui.remove();
1189             }
1190         } else {
1191             record = Tine.Calendar.EventEditDialog.superclass.doCopyRecordToReturn.call(this, record);
1192
1193             record.set('editGrant', true);
1194             record.set('id', '');
1195
1196             // remove attender ids
1197             Ext.each(record.data.attendee, function(attender) {
1198                 delete attender.id;
1199             }, this);
1200         }
1201
1202         // Allow to change attendee if in split view
1203         var defaultAttendee = Tine.Calendar.Model.Event.getDefaultData().attendee;
1204         if (record.data.attendee[0].user_id.account_id != defaultAttendee[0].user_id.account_id) {
1205             record.data.attendee[0] = Tine.Calendar.Model.Event.getDefaultData().attendee[0];
1206         }
1207
1208         record.set('dtstart', datetime);
1209         record.set('dtend', new Date(datetime.getTime() + eventLength));
1210
1211         if (isCopy == true) {
1212             record.isCopy = true;
1213             Tine.Tinebase.data.Clipboard.push(record);
1214             if (record.ui) {
1215                 record.ui.clearDirty();
1216             }
1217
1218             this.onAddEvent(record);
1219         } else {
1220             this.onUpdateEvent(record);
1221         }
1222     },
1223     
1224     /**
1225      * open event in new window
1226      * 
1227      * @param {String} action  add|edit|copy
1228      * @param {String} event   edit given event instead of selected event
1229      * @param {Object} plugins event dlg plugins
1230      * @param {Object} default properties for new items
1231      */
1232     onEditInNewWindow: function (action, event, plugins, defaults) {
1233         if (! event) {
1234             event = null;
1235         }
1236         // needed for addToEventPanel
1237         if (Ext.isObject(action)) {
1238             action = action.actionType;
1239         }
1240         
1241         if (action === 'edit' && ! event) {
1242             var panel = this.getCalendarPanel(this.activeView);
1243             var selection = panel.getSelectionModel().getSelectedEvents();
1244             if (Ext.isArray(selection) && selection.length === 1) {
1245                 event = selection[0];
1246             }
1247         }
1248
1249         if (action === 'edit' && (! event || event.dirty)) {
1250             return;
1251         }
1252         
1253         if (! event) {
1254             event = new Tine.Calendar.Model.Event(Ext.apply(Tine.Calendar.Model.Event.getDefaultData(), defaults), 0);
1255             if (defaults && Ext.isDate(defaults.dtStart)) {
1256                 event.set('dtstart', defaults.dtStart);
1257                 event.set('dtend', defaults.dtStart.add(Date.HOUR, 1));
1258             }
1259         }
1260         
1261         Tine.log.debug('Tine.Calendar.MainScreenCenterPanel::onEditInNewWindow() - Opening event edit dialog with action: ' + action);
1262
1263         Tine.Calendar.EventEditDialog.openWindow({
1264             plugins: plugins ? Ext.encode(plugins) : null,
1265             record: Ext.encode(event.data),
1266             recordId: event.data.id,
1267             copyRecord: (action == 'copy'),
1268             listeners: {
1269                 scope: this,
1270                 update: function (eventJson) {
1271                     var updatedEvent = Tine.Calendar.backend.recordReader({responseText: eventJson});
1272                     
1273                     updatedEvent.dirty = true;
1274                     updatedEvent.modified = {};
1275                     event.phantom = (action === 'edit');
1276                     var panel = this.getCalendarPanel(this.activeView);
1277                     var store = panel.getStore();
1278                     event = store.getById(event.id);
1279                     
1280                     if (event && action !== 'copy') {
1281                         store.replaceRecord(event, updatedEvent);
1282                     } else {
1283                         store.add(updatedEvent);
1284                     }
1285                     
1286                     this.onUpdateEvent(updatedEvent, false);
1287                 }
1288             }
1289         });
1290     },
1291     
1292     onKeyDown: function (e) {
1293         if (e.ctrlKey) {
1294             switch (e.getKey()) 
1295             {
1296             case e.A:
1297                 // select only current page
1298                 //this.grid.getSelectionModel().selectAll(true);
1299                 e.preventDefault();
1300                 break;
1301             case e.E:
1302                 if (!this.action_editInNewWindow.isDisabled()) {
1303                     this.onEditInNewWindow('edit');
1304                 }
1305                 e.preventDefault();
1306                 break;
1307             case e.N:
1308                 if (!this.action_addInNewWindow.isDisabled()) {
1309                     this.onEditInNewWindow('add');
1310                 }
1311                 e.preventDefault();
1312                 break;
1313             }
1314         } else if (e.getKey() === e.DELETE) {
1315             if (! this.action_deleteRecord.isDisabled()) {
1316                 this.onDeleteRecords.call(this);
1317             }
1318         }
1319     },
1320     
1321     onPrintMenuClick: function(splitBtn, e) {
1322         if (! String(this.activeView).match(/(day|week)sheet$/i)) {
1323             splitBtn.menu.hide();
1324         }
1325     },
1326     
1327     onPrint: function(printMode) {
1328         var printMode = printMode ? printMode : this.defaultPrintMode,
1329             panel = this.getCalendarPanel(this.activeView),
1330             view = panel ? panel.getView() : null;
1331             
1332         if (view && Ext.isFunction(view.print)) {
1333             view.print(printMode);
1334         } else {
1335             Ext.Msg.alert(this.app.i18n._('Could not Print'), this.app.i18n._('Sorry, your current view does not support printing.'));
1336         }
1337     },
1338     
1339     /**
1340      * called before store queries for data
1341      */
1342     onStoreBeforeload: function (store, options) {
1343         options.params = options.params || {};
1344         
1345         // define a transaction
1346         this.lastStoreTransactionId = options.transactionId = Ext.id();
1347         
1348         // allways start with an empty filter set!
1349         // this is important for paging and sort header!
1350         options.params.filter = [];
1351         
1352         if (! options.refresh && this.rendered) {
1353             // defer to have the loadMask centered in case of rendering actions
1354             this.loadMask.show.defer(50, this.loadMask);
1355         }
1356         
1357         // note, we can't use the 'normal' plugin approach here, cause we have to deal with n stores
1358         //var calendarSelectionPlugin = this.app.getMainScreen().getWestPanel().getContainerTreePanel().getFilterPlugin();
1359         //calendarSelectionPlugin.onBeforeLoad.call(calendarSelectionPlugin, store, options);
1360         
1361         this.filterToolbar.onBeforeLoad.call(this.filterToolbar, store, options);
1362         
1363         // add period filter as last filter to not conflict with first OR filter
1364         if (! options.noPeriodFilter) {
1365             options.params.filter.push({field: 'period', operator: 'within', value: this.getCalendarPanel(this.activeView).getView().getPeriod() });
1366         }
1367     },
1368     
1369     /**
1370      * fence against loading of wrong data set
1371      */
1372     onStoreBeforeLoadRecords: function(o, options, success) {
1373         return this.lastStoreTransactionId === options.transactionId;
1374     },
1375     
1376     /**
1377      * called when store loaded data
1378      */
1379     onStoreLoad: function (store, options) {
1380         if (this.rendered) {
1381             this.loadMask.hide();
1382         }
1383         
1384         // reset autoRefresh
1385         if (window.isMainWindow && this.autoRefreshInterval) {
1386             this.autoRefreshTask.delay(this.autoRefreshInterval * 1000);
1387         }
1388         
1389         // check if store is current store
1390         if (store !== this.getCalendarPanel(this.activeView).getStore()) {
1391             Tine.log.debug('Tine.Calendar.MainScreenCenterPanel::onStoreLoad view is not active anymore');
1392             return;
1393         }
1394         
1395         if (this.rendered) {
1396             // update filtertoolbar
1397             if(this.filterToolbar) {
1398                 this.filterToolbar.setValue(store.proxy.jsonReader.jsonData.filter);
1399             }
1400             // update container tree
1401             Tine.Tinebase.appMgr.get('Calendar').getMainScreen().getWestPanel().getContainerTreePanel().getFilterPlugin().setValue(store.proxy.jsonReader.jsonData.filter);
1402             
1403             // update attendee filter grid
1404             Tine.Tinebase.appMgr.get('Calendar').getMainScreen().getWestPanel().getAttendeeFilter().setFilterValue(store.proxy.jsonReader.jsonData.filter);
1405         }
1406     },
1407     
1408     /**
1409      * on store load exception
1410      * 
1411      * @param {Tine.Tinebase.data.RecordProxy} proxy
1412      * @param {String} type
1413      * @param {Object} error
1414      * @param {Object} options
1415      */
1416     onStoreLoadException: function(proxy, type, error, options) {
1417         // reset autoRefresh
1418         if (window.isMainWindow && this.autoRefreshInterval) {
1419             this.autoRefreshTask.delay(this.autoRefreshInterval * 5000);
1420         }
1421         
1422         this.setLoading(false);
1423         this.loadMask.hide();
1424         
1425         if (! options.autoRefresh) {
1426             this.onProxyFail(error);
1427         }
1428     },
1429     
1430     onProxyFail: function(error, event, ignoreFn) {
1431         this.setLoading(false);
1432         if(this.loadMask) this.loadMask.hide();
1433         
1434         if (error.code == 901) {
1435            
1436             // resort fbInfo to combine all events of a attender
1437             var busyAttendee = [];
1438             var conflictEvents = {};
1439             var attendeeStore = Tine.Calendar.Model.Attender.getAttendeeStore(error.event.attendee);
1440             
1441             Ext.each(error.freebusyinfo, function(fbinfo) {
1442                 attendeeStore.each(function(a) {
1443                     var userType = a.get('user_type');
1444                     userType = userType == 'groupmember' ? 'user' : userType;
1445                     if (userType == fbinfo.user_type && a.getUserId() == fbinfo.user_id) {
1446                         if (busyAttendee.indexOf(a) < 0) {
1447                             busyAttendee.push(a);
1448                             conflictEvents[a.id] = [];
1449                         }
1450                         conflictEvents[a.id].push(fbinfo);
1451                     }
1452                 });
1453             }, this);
1454             
1455             // generate html for each busy attender
1456             var busyAttendeeHTML = '';
1457             Ext.each(busyAttendee, function(busyAttender) {
1458                 // TODO refactore name handling of attendee
1459                 //      -> attender model needs knowlege of how to get names!
1460                 //var attenderName = a.getName();
1461                 var attenderName = Tine.Calendar.AttendeeGridPanel.prototype.renderAttenderName.call(Tine.Calendar.AttendeeGridPanel.prototype, busyAttender.get('user_id'), false, busyAttender);
1462                 busyAttendeeHTML += '<div class="cal-conflict-attendername">' + attenderName + '</div>';
1463                 
1464                 var eventInfos = [];
1465                 Ext.each(conflictEvents[busyAttender.id], function(fbInfo) {
1466                     var format = 'H:i';
1467                     var dateFormat = Ext.form.DateField.prototype.format;
1468                     if (event.get('dtstart').format(dateFormat) != event.get('dtend').format(dateFormat) ||
1469                         Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat) != Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(dateFormat))
1470                     {
1471                         format = dateFormat + ' ' + format;
1472                     }
1473                     
1474                     var eventInfo = Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(format) + ' - ' + Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(format);
1475                     if (fbInfo.event && fbInfo.event.summary) {
1476                         eventInfo += ' : ' + fbInfo.event.summary;
1477                     }
1478                     eventInfos.push(eventInfo);
1479                 }, this);
1480                 busyAttendeeHTML += '<div class="cal-conflict-eventinfos">' + eventInfos.join(', <br />') + '</div>';
1481                 
1482             });
1483             
1484             this.conflictConfirmWin = Tine.widgets.dialog.MultiOptionsDialog.openWindow({
1485                 modal: true,
1486                 allowCancel: false,
1487                 height: 180 + 15*error.freebusyinfo.length,
1488                 title: this.app.i18n._('Scheduling Conflict'),
1489                 questionText: '<div class = "cal-conflict-heading">' +
1490                                    this.app.i18n._('The following attendee are busy at the requested time:') + 
1491                                '</div>' +
1492                                busyAttendeeHTML,
1493                 options: [
1494                     {text: this.app.i18n._('Ignore Conflict'), name: 'ignore'},
1495                     {text: this.app.i18n._('Edit Event'), name: 'edit', checked: true},
1496                     {text: this.app.i18n._('Cancel this action'), name: 'cancel'}
1497                 ],
1498                 scope: this,
1499                 handler: function(option) {
1500                     var panel = this.getCalendarPanel(this.activeView),
1501                         store = panel.getStore();
1502
1503                     switch (option) {
1504                         case 'ignore':
1505                             if (Ext.isFunction(ignoreFn)) {
1506                                 ignoreFn();
1507                             } else {
1508                                 this.onAddEvent(event, false, true);
1509                             }
1510                             this.conflictConfirmWin.close();
1511                             break;
1512                         
1513                         case 'edit':
1514                             
1515                             var presentationMatch = this.activeView.match(this.presentationRe),
1516                                 presentation = Ext.isArray(presentationMatch) ? presentationMatch[0] : null;
1517                             
1518                             if (presentation != 'Grid') {
1519                                 var view = panel.getView();
1520                                 view.getSelectionModel().select(event);
1521                                 // mark event as not dirty to allow edit dlg
1522                                 event.dirty = false;
1523                                 view.fireEvent('dblclick', view, event);
1524                             } else {
1525                                 // add or edit?
1526                                 this.onEditInNewWindow(null, event);
1527                             }
1528                             
1529                             this.conflictConfirmWin.close();
1530                             break;
1531                         case 'cancel':
1532                         default:
1533                             this.conflictConfirmWin.close();
1534                             this.loadMask.show();
1535                             store.load({refresh: true});
1536                             break;
1537                     }
1538                 }
1539             });
1540             
1541         } else {
1542             Tine.Tinebase.ExceptionHandler.handleRequestException(error);
1543         }
1544     },
1545     
1546     refresh: function (options) {
1547         // convert old boolean argument
1548         options = Ext.isObject(options) ? options : {
1549             refresh: !!options
1550         };
1551         Tine.log.debug('Tine.Calendar.MainScreenCenterPanel::refresh(' + options.refresh + ')');
1552         var panel = this.getCalendarPanel(this.activeView);
1553         panel.getStore().load(options);
1554         
1555         // clear favorites
1556         Tine.Tinebase.appMgr.get('Calendar').getMainScreen().getWestPanel().getFavoritesPanel().getSelectionModel().clearSelections();
1557     },
1558     
1559     setLoading: function(bool) {
1560         if (this.rendered) {
1561             var panel = this.getCalendarPanel(this.activeView),
1562                 tbar = panel.getTopToolbar();
1563                 
1564             if (tbar && tbar.loading) {
1565                 tbar.loading[bool ? 'disable' : 'enable']();
1566             }
1567         }
1568     },
1569     
1570     setResponseStatus: function(event, status) {
1571         var myAttenderRecord = event.getMyAttenderRecord();
1572         if (myAttenderRecord) {
1573             myAttenderRecord.set('status', status);
1574             event.dirty = true;
1575             event.modified = {};
1576             
1577             var panel = this.getCalendarPanel(this.activeView);
1578             var store = panel.getStore();
1579             
1580             store.replaceRecord(event, event);
1581             
1582             this.onUpdateEvent(event);
1583         }
1584     },
1585     
1586     updateEventActions: function () {
1587         var panel = this.getCalendarPanel(this.activeView);
1588         var selection = panel.getSelectionModel().getSelectedEvents();
1589         
1590         this.actionUpdater.updateActions(selection);
1591         if (this.detailsPanel) {
1592             this.detailsPanel.onDetailsUpdate(panel.getSelectionModel());
1593         }
1594     },
1595     
1596     updateView: function (which) {
1597         Tine.log.debug('Tine.Calendar.MainScreenCenterPanel::updateView(' + which + ')');
1598         var panel = this.getCalendarPanel(which);
1599         var period = panel.getTopToolbar().getPeriod();
1600         
1601         panel.getView().updatePeriod(period);
1602         panel.getStore().load({});
1603         //this.updateMiniCal();
1604     },
1605     
1606     /**
1607      * returns requested CalendarPanel
1608      * 
1609      * @param {String} which
1610      * @return {Tine.Calendar.CalendarPanel}
1611      */
1612     getCalendarPanel: function (which) {
1613         var whichParts = this.getViewParts(which);
1614         which = whichParts.toString();
1615         
1616         if (! this.calendarPanels[which]) {
1617             Tine.log.debug('Tine.Calendar.MainScreenCenterPanel::getCalendarPanel creating new calender panel for view ' + which);
1618             
1619             var store = new Ext.data.JsonStore({
1620                 //autoLoad: true,
1621                 id: 'id',
1622                 fields: Tine.Calendar.Model.Event,
1623                 proxy: Tine.Calendar.backend,
1624                 reader: new Ext.data.JsonReader({}), //Tine.Calendar.backend.getReader(),
1625                 listeners: {
1626                     scope: this,
1627                     'beforeload': this.onStoreBeforeload,
1628                     'beforeloadrecords' : this.onStoreBeforeLoadRecords,
1629                     'load': this.onStoreLoad,
1630                     'loadexception': this.onStoreLoadException
1631                 },
1632                 replaceRecord: function(o, n) {
1633                     var idx = this.indexOf(o);
1634                     this.remove(o);
1635                     this.insert(idx, n);
1636                 }
1637             });
1638             
1639             var tbar = new Tine.Calendar.PagingToolbar({
1640                 view: whichParts.period,
1641                 store: store,
1642                 dtStart: this.startDate,
1643                 listeners: {
1644                     scope: this,
1645                     // NOTE: only render the button once for the toolbars
1646                     //       the buttons will be moved on chageView later
1647                     render: function (tbar) {
1648                         for (var i = 0; i < this.changeViewActions.length; i += 1) {
1649                             if (! this.changeViewActions[i].rendered) {
1650                                 tbar.addButton(this.changeViewActions[i]);
1651                             }
1652                         }
1653                     }
1654                 }
1655             });
1656             
1657             tbar.on('change', this.updateView.createDelegate(this, [which]), this, {buffer: 200});
1658             tbar.on('refresh', this.refresh.createDelegate(this, [true]), this, {buffer: 200});
1659             
1660             if (whichParts.presentation.match(/sheet/i)) {
1661                 var view;
1662                 switch (which) {
1663                     case 'daySheet':
1664                         view = new Tine.Calendar.DaysView({
1665                             store: store,
1666                             startDate: tbar.getPeriod().from,
1667                             numOfDays: 1
1668                         });
1669                         break;
1670                     case 'monthSheet':
1671                         view = new Tine.Calendar.MonthView({
1672                             store: store,
1673                             period: tbar.getPeriod()
1674                         });
1675                         break;
1676                     case 'yearSheet':
1677                         view = new Tine.Calendar.YearView({
1678                             store: store,
1679                             period: tbar.getPeriod()
1680                         });
1681                         break;
1682                     default:
1683                     case 'weekSheet':
1684                         view = new Tine.Calendar.DaysView({
1685                             store: store,
1686                             startDate: tbar.getPeriod().from,
1687                             numOfDays: 7
1688                         });
1689                         break;
1690                 }
1691                 
1692                 view.on('changeView', this.changeView, this);
1693                 view.on('changePeriod', function (period) {
1694                     this.startDate = period.from;
1695                     this.startDates[which] = this.startDate.clone();
1696                     this.updateMiniCal();
1697                 }, this);
1698                 
1699                 // quick add/update actions
1700                 view.on('addEvent', this.onAddEvent, this);
1701                 view.on('updateEvent', this.onUpdateEvent, this);
1702             
1703                 this.calendarPanels[which] = new Tine.Calendar.CalendarPanel({
1704                     tbar: tbar,
1705                     view: view
1706                 });
1707             } else if (whichParts.presentation.match(/grid/i)) {
1708                 this.calendarPanels[which] = new Tine.Calendar.GridView({
1709                     tbar: tbar,
1710                     store: store
1711                 });
1712             }
1713             
1714             this.calendarPanels[which].on('dblclick', this.onEditInNewWindow.createDelegate(this, ["edit"]));
1715             this.calendarPanels[which].on('contextmenu', this.onContextMenu, this);
1716             this.calendarPanels[which].getSelectionModel().on('selectionchange', this.updateEventActions, this);
1717             this.calendarPanels[which].on('keydown', this.onKeyDown, this);
1718             
1719             this.calendarPanels[which].relayEvents(this, ['show', 'beforehide']);
1720         }
1721         
1722         return this.calendarPanels[which];
1723     },
1724     
1725     updateMiniCal: function () {
1726         var miniCal = Ext.getCmp('cal-mainscreen-minical');
1727         var weekNumbers = null;
1728         var period = this.getCalendarPanel(this.activeView).getView().getPeriod();
1729         
1730         switch (this.activeView) 
1731         {
1732         case 'week' :
1733             weekNumbers = [period.from.add(Date.DAY, 1).getWeekOfYear()];
1734             break;
1735         case 'month' :
1736             weekNumbers = [];
1737             var startWeek = period.from.add(Date.DAY, 1).getWeekOfYear();
1738             var numWeeks = Math.round((period.until.getTime() - period.from.getTime()) / Date.msWEEK);
1739             for (var i = 0; i < numWeeks; i += 1) {
1740                 weekNumbers.push(startWeek + i);
1741             }
1742             break;
1743         }
1744         miniCal.update(this.startDate, true, weekNumbers);
1745     }
1746 });