633109bef4d174b3ee4746a1c335ebbb2e257e38
[tine20] / tine20 / Tinebase / js / widgets / dialog / EditDialog.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 Ext.ns('Tine.widgets.dialog');
9
10 /**
11  * Generic 'Edit Record' dialog
12  * Base class for all 'Edit Record' dialogs
13  * 
14  * @namespace   Tine.widgets.dialog
15  * @class       Tine.widgets.dialog.EditDialog
16  * @extends     Ext.FormPanel
17  * @author      Cornelius Weiss <c.weiss@metaways.de>
18  * @constructor
19  * @param {Object} config The configuration options.
20  */
21
22 Tine.widgets.dialog.EditDialog = Ext.extend(Ext.FormPanel, {
23     /**
24      * @cfg {Tine.Tinebase.Application} app
25      * instance of the app object (required)
26      */
27     app: null,
28     /**
29      * @cfg {String} mode
30      * Set to 'local' if the EditDialog only operates on this.record (defaults to 'remote' which loads and saves using the recordProxy)
31      */
32     mode : 'remote',
33     /**
34      * @cfg {Array} tbarItems
35      * additional toolbar items (defaults to false)
36      */
37     tbarItems: false,
38     /**
39      * internal/untranslated app name (required)
40      * 
41      * @cfg {String} appName
42      */
43     appName: null,
44     /**
45      * the modelName (filled by application starter)
46      * 
47      * @type {String} modelName
48      */
49     modelName: null,
50     
51     /**
52      * record definition class  (required)
53      * 
54      * @cfg {Ext.data.Record} recordClass
55      */
56     recordClass: null,
57     /**
58      * @cfg {Ext.data.DataProxy} recordProxy
59      */
60     recordProxy: null,
61     /**
62      * @cfg {Bool} showContainerSelector
63      * show container selector in bottom area
64      */
65     showContainerSelector: null,
66     /**
67      * @cfg {Bool} evalGrants
68      * should grants of a grant-aware records be evaluated (defaults to true)
69      */
70     evalGrants: true,
71     /**
72      * @cfg {Ext.data.Record} record
73      * record in edit process.
74      */
75     record: null,
76     
77     /**
78      * holds the modelConfig for the handled record (json-encoded object)
79      * will be decoded in initComponent
80      * 
81      * @type 
82      */
83     modelConfig: null,
84     
85     /**
86      * @cfg {String} saveAndCloseButtonText
87      * text of save and close button
88      */
89     saveAndCloseButtonText: '',
90     /**
91      * @cfg {String} cancelButtonText
92      * text of cancel button
93      */
94     cancelButtonText: '',
95     
96     /**
97      * @cfg {Boolean} copyRecord
98      * copy record
99      */
100     copyRecord: false,
101     
102     /**
103      * @cfg {Boolean} doDuplicateCheck
104      * do duplicate check when saving record (mode remote only)
105      */
106     doDuplicateCheck: true,
107     
108     /**
109      * required grant for apply/save
110      * @type String
111      */
112     editGrant: 'editGrant',
113
114     /**
115      * when a record has the relations-property the relations-panel can be disabled here
116      * @cfg {Boolean} hideRelationsPanel
117      */
118     hideRelationsPanel: false,
119     
120     /**
121      * when a record has the attachments-property the attachments-panel can be disabled here
122      * @cfg {Boolean} hideAttachmentsPanel
123      */
124     hideAttachmentsPanel: false,
125     
126     /**
127      * Registry for other relationgridpanels than the generic one,
128      * handling special types of relations the generic one will not.
129      * Panels registered here must have a store with the relation records.
130      * 
131      * @type {Array}
132      */
133     relationPanelRegistry: null,
134     
135     /**
136      * ignore relations to given php-class names in the relation grid
137      * @type {Array}
138      */
139     ignoreRelatedModels: null,
140     
141     /**
142      * dialog is currently saving data
143      * @type Boolean
144      */
145     saving: false,
146     
147     /**
148      * Disable adding cf tab even if model has support for customfields
149      * @type Boolean
150      */
151     disableCfs: false,
152     
153     /**
154      * @property window {Ext.Window|Ext.ux.PopupWindow|Ext.Air.Window}
155      */
156     /**
157      * @property {Number} loadRequest 
158      * transaction id of loadData request
159      */
160     /**
161      * @property loadMask {Ext.LoadMask}
162      */
163     
164     /**
165      * @property containerSelectCombo {Tine.widgets.container.selectionComboBox}
166      */
167     containerSelectCombo: null,
168     
169     /**
170      * If set, these fields are readOnly (when called dependent to related record)
171      * 
172      * @type {Ext.util.MixedCollection}
173      */
174     fixedFields: null,
175
176     /**
177      * Plain Object with additional configuration (JSON-encoded)
178      * 
179      * @type {Object}
180      */
181     additionalConfig: null,
182     
183     // private
184     bodyStyle:'padding:5px',
185     layout: 'fit',
186     border: false,
187     cls: 'tw-editdialog',
188     anchor:'100% 100%',
189     deferredRender: false,
190     buttonAlign: null,
191     bufferResize: 500,
192
193     /**
194      * relations panel
195      * 
196      * @type Tine.widgets.relation.GenericPickerGridPanel
197      */
198     relationsPanel: null,
199     
200     // Array of Relation Pickers
201     relationPickers: null,
202     
203     /**
204      * attachments panel
205      * 
206      * @type Tine.widgets.dialog.AttachmentsGridPanel
207      */
208     attachmentsPanel: null,
209     
210     /**
211      * holds the loadMask
212      * set this to false, if no loadMask should be shown
213      * 
214      * @type {Ext.LoadMask}
215      */
216     loadMask: null,
217
218     /**
219      * hook notes panel into dialog
220      */
221     displayNotes: false,
222
223     //private
224     initComponent: function() {
225         this.relationPanelRegistry = this.relationPanelRegistry ? this.relationPanelRegistry : [];
226         this.addEvents(
227             /**
228              * @event cancel
229              * Fired when user pressed cancel button
230              */
231             'cancel',
232             /**
233              * @event saveAndClose
234              * Fired when user pressed OK button
235              */
236             'saveAndClose',
237             /**
238              * @event update
239              * @desc  Fired when the record got updated
240              * @param {Json String} data data of the entry
241              * @pram  {String} this.mode
242              */
243             'update',
244             /**
245              * @event apply
246              * Fired when user pressed apply button
247              */
248             'apply',
249             /**
250              * @event load
251              * @param {Tine.widgets.dialog.EditDialog} this
252              * @param {Tine.data.Record} record which got loaded
253              * @param {Function} ticket function for async defer
254              * Fired when record is loaded
255              */
256             'load',
257             /**
258              * @event save
259              * @param {Tine.widgets.dialog.EditDialog} this
260              * @param {Tine.data.Record} record which got loaded
261              * @param {Function} ticket function for async defer
262              * Fired when remote record is saving
263              */
264             'save',
265             /**
266              * @event updateDependent
267              * Fired when a subpanel updates the record locally
268              */
269             'updateDependent'
270         );
271
272         if (Ext.isString(this.modelConfig)) {
273             this.modelConfig = Ext.decode(this.modelConfig);
274         }
275         
276         if (Ext.isString(this.additionalConfig)) {
277             Ext.apply(this, Ext.decode(this.additionalConfig));
278         }
279         
280         if (Ext.isString(this.fixedFields)) {
281             var decoded = Ext.decode(this.fixedFields);
282             this.fixedFields = new Ext.util.MixedCollection();
283             this.fixedFields.addAll(decoded);
284         }
285         
286         if (! this.recordClass && this.modelName) {
287             this.recordClass = Tine[this.appName].Model[this.modelName];
288         }
289         
290         if (this.recordClass) {
291             this.appName    = this.appName    ? this.appName    : this.recordClass.getMeta('appName');
292             this.modelName  = this.modelName  ? this.modelName  : this.recordClass.getMeta('modelName');
293         }
294         
295         if (! this.app) {
296             this.app = Tine.Tinebase.appMgr.get(this.appName);
297         }
298         
299         if (! this.windowNamePrefix) {
300             this.windowNamePrefix = this.modelName + 'EditWindow_';
301         }
302         
303         Tine.log.debug('initComponent: appName: ', this.appName);
304         Tine.log.debug('initComponent: modelName: ', this.modelName);
305         Tine.log.debug('initComponent: app: ', this.app);
306         
307         // init some translations
308         if (this.app.i18n && this.recordClass !== null) {
309             this.i18nRecordName = this.app.i18n.n_hidden(this.recordClass.getMeta('recordName'), this.recordClass.getMeta('recordsName'), 1);
310             this.i18nRecordsName = this.app.i18n._hidden(this.recordClass.getMeta('recordsName'));
311         }
312     
313         if (! this.recordProxy && this.recordClass) {
314             Tine.log.debug('no record proxy given, creating a new one...');
315             this.recordProxy = new Tine.Tinebase.data.RecordProxy({
316                 recordClass: this.recordClass
317             });
318         }
319         // init plugins
320         this.plugins = Ext.isString(this.plugins) ? Ext.decode(this.plugins) : Ext.isArray(this.plugins) ? this.plugins.concat(Ext.decode(this.initialConfig.plugins)) : [];
321         
322         this.plugins.push(this.tokenModePlugin = new Tine.widgets.dialog.TokenModeEditDialogPlugin({}));
323         // added possibility to disable using customfield plugin
324         if (this.disableCfs !== true) {
325             this.plugins.push(new Tine.widgets.customfields.EditDialogPlugin({}));
326         }
327         
328         // init actions
329         this.initActions();
330         // init buttons and tbar
331         this.initButtons();
332         // init container selector
333         this.initContainerSelector();
334         // init record 
335         this.initRecord();
336         // get items for this dialog
337         this.items = this.getFormItems();
338
339         // init relations panel if relations are defined
340         this.initRelationsPanel();
341         // init attachments panel
342         this.initAttachmentsPanel();
343         // init notes panel
344         this.initNotesPanel();
345
346         Tine.widgets.dialog.EditDialog.superclass.initComponent.call(this);
347         
348         // set fields readOnly if set
349         this.fixFields();
350         
351         // firefox fix: blur each item before tab changes, so no field  will be focused afterwards
352         if (Ext.isGecko) {
353             this.items.items[0].addListener('beforetabchange', function(tabpanel, newtab, oldtab) {
354                 if (! oldtab) {
355                     return;
356                 }
357                 var form = this.getForm();
358                 
359                 if (form && form.hasOwnProperty('items'))
360                     form.items.each(function(item, index) {
361                         item.blur();
362                     });
363             }, this);
364         }
365
366         this.window.relayEvents(this, ['resize']);
367     },
368
369     /**
370      * generic form layout
371      */
372     getFormItems: function() {
373         return {
374             xtype: 'tabpanel',
375             border: false,
376             plain:true,
377             activeTab: 0,
378             border: false,
379             defaults: {
380                 hideMode: 'offsets'
381             },
382             plugins: [{
383                 ptype : 'ux.tabpanelkeyplugin'
384             }],
385             items:[
386                 {
387                     title: this.i18nRecordName,
388                     autoScroll: true,
389                     border: false,
390                     frame: true,
391                     layout: 'border',
392                     items: [Ext.applyIf(this.getRecordFormItems(), {
393                         region: 'center',
394                         xtype: 'columnform',
395                         labelAlign: 'top',
396                         formDefaults: {
397                             xtype:'textfield',
398                             anchor: '100%',
399                             labelSeparator: '',
400                             columnWidth: 1/2
401                         },
402                     })].concat(this.getEastPanel())
403                 }, new Tine.widgets.activities.ActivitiesTabPanel({
404                     app: this.appName,
405                     record_id: this.record.id,
406                     record_model: this.modelName
407                 })
408             ]
409         };
410     },
411
412     getEastPanel: function() {
413         var items = [];
414         if (this.recordClass.hasField('description')) {
415             items.push(new Ext.Panel({
416                 title: i18n._('Description'),
417                 iconCls: 'descriptionIcon',
418                 layout: 'form',
419                 labelAlign: 'top',
420                 border: false,
421                 items: [{
422                     style: 'margin-top: -4px; border 0px;',
423                     labelSeparator: '',
424                     xtype: 'textarea',
425                     name: 'description',
426                     hideLabel: true,
427                     grow: false,
428                     preventScrollbars: false,
429                     anchor: '100% 100%',
430                     emptyText: i18n._('Enter description'),
431                     requiredGrant: 'editGrant'
432                 }]
433             }));
434         }
435
436         if (this.recordClass.hasField('tags')) {
437             items.push(new Tine.widgets.tags.TagPanel({
438                 app: this.appName,
439                 border: false,
440                 bodyStyle: 'border:1px solid #B5B8C8;'
441             }));
442         }
443
444         return items.length ? {
445             layout: 'accordion',
446             animate: true,
447             region: 'east',
448             width: 210,
449             split: true,
450             collapsible: true,
451             collapseMode: 'mini',
452             header: false,
453             margins: '0 5 0 5',
454             border: true,
455             items: items
456         } : [];
457     },
458
459     getRecordFormItems: function() {
460         return new Tine.widgets.form.RecordForm({
461             recordClass: this.recordClass
462         });
463     },
464
465     /**
466      * fix fields (used for preselecting form fields when called in dependency to another record)
467      * @return {Boolean}
468      */
469     fixFields: function() {
470         if (this.fixedFields && this.fixedFields.getCount() > 0) {
471             if (! this.rendered) {
472                 this.fixFields.defer(100, this);
473                 return false;
474             }
475             
476             this.fixedFields.each(function(value, index) {
477                 var key = this.fixedFields.keys[index]; 
478                 
479                 var field = this.getForm().findField(key);
480                 
481                 if (field) {
482                     if (Ext.isFunction(this.recordClass.getField(key).type)) {
483                         var foreignRecordClass = this.recordClass.getField(key).type;
484                         var record = new foreignRecordClass(value);
485                         field.selectedRecord = record;
486                         field.setValue(value);
487                         field.fireEvent('select');
488                     } else {
489                         field.setValue(value);
490                     }
491                     field.disable();
492                 }
493             }, this);
494         }
495     },
496
497     /**
498      * Get available model for given application
499      *
500      *  @param {Mixed} application
501      *  @param {Boolean} customFieldModel
502      */
503     getApplicationModels: function (application, customFieldModel) {
504         var models      = [],
505             useModel,
506             appName     = Ext.isString(application) ? application : application.get('name'),
507             app         = Tine.Tinebase.appMgr.get(appName),
508             trans       = app && app.i18n ? app.i18n : i18n,
509             appModels   = Tine[appName].Model;
510
511         if (appModels) {
512             for (var model in appModels) {
513                 if (appModels.hasOwnProperty(model) && typeof appModels[model].getMeta === 'function') {
514                     if (customFieldModel && appModels[model].getField('customfields')) {
515                         useModel = appModels[model].getMeta('appName') + '_Model_' + appModels[model].getMeta('modelName');
516
517                         Tine.log.info('Found model with customfields property: ' + useModel);
518                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
519                     } else if (! customFieldModel) {
520                         useModel = 'Tine.' + appModels[model].getMeta('appName') + '.Model.' + appModels[model].getMeta('modelName');
521
522                         Tine.log.info('Found model: ' + useModel);
523                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
524                     }
525                 }
526             }
527         }
528         return models;
529     },
530
531     /**
532      * init actions
533      */
534     initActions: function() {
535         this.action_saveAndClose = new Ext.Action({
536             requiredGrant: this.editGrant,
537             text: (this.saveAndCloseButtonText != '') ? this.app.i18n._(this.saveAndCloseButtonText) : i18n._('Ok'),
538             minWidth: 70,
539             ref: '../btnSaveAndClose',
540             scope: this,
541             // TODO: remove the defer when all subpanels use the deferByTicket mechanism
542             handler: function() { this.onSaveAndClose.defer(500, this); },
543             iconCls: 'action_saveAndClose'
544         });
545     
546         this.action_applyChanges = new Ext.Action({
547             requiredGrant: this.editGrant,
548             text: i18n._('Apply'),
549             minWidth: 70,
550             ref: '../btnApplyChanges',
551             scope: this,
552             handler: this.onApplyChanges,
553             iconCls: 'action_applyChanges'
554         });
555         
556         this.action_cancel = new Ext.Action({
557             text: (this.cancelButtonText != '') ? this.app.i18n._(this.cancelButtonText) : i18n._('Cancel'),
558             minWidth: 70,
559             scope: this,
560             handler: this.onCancel,
561             iconCls: 'action_cancel'
562         });
563         
564         this.action_delete = new Ext.Action({
565             requiredGrant: 'deleteGrant',
566             text: i18n._('delete'),
567             minWidth: 70,
568             scope: this,
569             handler: this.onDelete,
570             iconCls: 'action_delete',
571             disabled: true
572         });
573     },
574     
575     /**
576      * init buttons
577      * 
578      * use button order from preference
579      */
580     initButtons: function () {
581         this.fbar = [
582             '->'
583         ];
584         
585         if (Tine.Tinebase.registry && Tine.Tinebase.registry.get('preferences') && Tine.Tinebase.registry.get('preferences').get('dialogButtonsOrderStyle') === 'Windows') {
586             this.fbar.push(this.action_saveAndClose, this.action_cancel);
587         } else {
588             this.fbar.push(this.action_cancel, this.action_saveAndClose);
589         }
590        
591         if (this.tbarItems) {
592             this.tbar = new Ext.Toolbar({
593                 items: this.tbarItems
594             });
595         }
596     },
597     
598     /**
599      * init container selector
600      */
601     initContainerSelector: function() {
602         if (this.showContainerSelector) {
603             this.containerSelectCombo = new Tine.widgets.container.selectionComboBox({
604                 id: this.app.appName + 'EditDialogContainerSelector-' + Ext.id(),
605                 fieldLabel: i18n._('Saved in'),
606                 width: 300,
607                 listWidth: 300,
608                 name: this.recordClass.getMeta('containerProperty'),
609                 recordClass: this.recordClass,
610                 containerName: this.app.i18n.n_hidden(this.recordClass.getMeta('containerName'), this.recordClass.getMeta('containersName'), 1),
611                 containersName: this.app.i18n._hidden(this.recordClass.getMeta('containersName')),
612                 appName: this.app.appName,
613                 requiredGrant: this.evalGrants ? 'addGrant' : false,
614                 disabled: this.isContainerSelectorDisabled(),
615                 listeners: {
616                     scope: this,
617                     select: function() {    
618                         // enable or disable save button dependent to containers account grants
619                         // on edit: check editGrant, on add: check addGrant
620                         var grants = this.containerSelectCombo.selectedContainer
621                             ? this.containerSelectCombo.selectedContainer.account_grants : {},
622                             grantToCheck = (this.record.data.id) ? 'editGrant' : 'addGrant',
623                             enabled =  grants.hasOwnProperty(grantToCheck) && grants[grantToCheck]
624                                     || grants.hasOwnProperty('adminGrant') && grants.adminGrant ? true : false;
625
626                         this.action_saveAndClose.setDisabled(! enabled);
627                     }
628                 }
629             });
630             this.on('render', function() { this.getForm().add(this.containerSelectCombo); }, this);
631             
632             this.fbar = [
633                 i18n._('Saved in'),
634                 this.containerSelectCombo
635             ].concat(this.fbar);
636         }
637         
638     },
639     
640     /**
641      * checks if the container selector should be disabled (dependent on account grants of the container itself)
642      * @return {}
643      */
644     isContainerSelectorDisabled: function() {
645         if (this.record) {
646             var cp = this.recordClass.getMeta('containerProperty'),
647                 container = this.record.data[cp],
648                 grants = (container && container.hasOwnProperty('account_grants')) ? container.account_grants : null,
649                 cond = false;
650                 
651             // check grants if record already exists and grants should be evaluated
652             if(this.evalGrants && this.record.data.id && grants) {
653                 cond = ! (grants.hasOwnProperty('editGrant') && grants.editGrant);
654             }
655             
656             return cond;
657         } else {
658             return false;
659         }
660     },
661     
662     /**
663      * init record to edit
664      */
665     initRecord: function() {
666         Tine.log.debug('init record with mode: ' + this.mode);
667         if (! this.record) {
668             Tine.log.debug('creating new default data record');
669             this.record = new this.recordClass(this.recordClass.getDefaultData(), 0);
670         }
671         
672         if (this.mode !== 'local') {
673             if (this.record && this.record.id) {
674                 this.loadRemoteRecord();
675             } else {
676                 this.onRecordLoad();
677             }
678         } else {
679             // note: in local mode we expect a valid record
680             if (! Ext.isFunction(this.record.beginEdit)) {
681                 this.record = this.recordProxy.recordReader({responseText: this.record});
682             }
683             this.onRecordLoad();
684         }
685     },
686     
687     /**
688      * load record via record proxy
689      */
690     loadRemoteRecord: function() {
691         Tine.log.info('initiating record load via proxy');
692         this.loadRequest = this.recordProxy.loadRecord(this.record, {
693             scope: this,
694             success: function(record) {
695                 this.record = record;
696                 this.onRecordLoad();
697             }
698         });
699     },
700
701     /**
702      * copy this.record record
703      */
704     doCopyRecord: function() {
705         this.record = this.doCopyRecordToReturn(this.record);
706     },
707
708     /**
709      * Copy record and returns "new record with same settings"
710      *
711      * @param record
712      */
713     doCopyRecordToReturn: function(record) {
714         var omitFields = this.recordClass.getMeta('copyOmitFields') || [];
715         // always omit id + notes + attachments
716         omitFields = omitFields.concat(['id', 'notes', 'attachments', 'relations']);
717
718         var fieldsToCopy = this.recordClass.getFieldNames().diff(omitFields),
719             recordData = Ext.copyTo({}, record.data, fieldsToCopy);
720
721         var resetProperties = {
722             alarms:    ['id', 'record_id', 'sent_time', 'sent_message'],
723             relations: ['id', 'own_id', 'created_by', 'creation_time', 'last_modified_by', 'last_modified_time']
724         };
725
726         var setProperties = {alarms: {sent_status: 'pending'}};
727
728         Ext.iterate(resetProperties, function(property, properties) {
729             if (recordData.hasOwnProperty(property)) {
730                 var r = recordData[property];
731                 for (var index = 0; index < r.length; index++) {
732                     Ext.each(properties,
733                         function(prop) {
734                             r[index][prop] = null;
735                         }
736                     );
737                 }
738             }
739         });
740
741         Ext.iterate(setProperties, function(property, properties) {
742             if (recordData.hasOwnProperty(property)) {
743                 var r = recordData[property];
744                 for (var index = 0; index < r.length; index++) {
745                     Ext.iterate(properties,
746                         function(prop, value) {
747                             r[index][prop] = value;
748                         }
749                     );
750                 }
751             }
752         });
753
754         return new this.recordClass(recordData, 0);
755     },
756
757     
758     /**
759      * executed after record got updated from proxy
760      */
761     onRecordLoad: function() {
762         // interrupt process flow until dialog is rendered
763         if (! this.rendered) {
764             this.onRecordLoad.defer(250, this);
765             return;
766         }
767         Tine.log.debug('Tine.widgets.dialog.EditDialog::onRecordLoad() - Loading of the following record completed:');
768         Tine.log.debug(this.record);
769         
770         if (this.copyRecord) {
771             this.doCopyRecord();
772             this.window.setTitle(String.format(i18n._('Copy {0}'), this.i18nRecordName));
773         } else {
774             if (! this.record.id) {
775                 this.window.setTitle(String.format(i18n._('Add New {0}'), this.i18nRecordName));
776             } else {
777                 this.window.setTitle(String.format(i18n._('Edit {0} "{1}"'), this.i18nRecordName, this.record.getTitle()));
778             }
779         }
780         
781         var ticketFn = this.onAfterRecordLoad.deferByTickets(this),
782             wrapTicket = ticketFn();
783         
784         this.fireEvent('load', this, this.record, ticketFn);
785         wrapTicket();
786     },
787     
788     // finally load the record into the form
789     onAfterRecordLoad: function() {
790         var form = this.getForm();
791         
792         if (form) {
793             form.loadRecord(this.record);
794             form.clearInvalid();
795         }
796         
797         if (this.record && this.record.hasOwnProperty('data') && Ext.isObject(this.record.data[this.recordClass.getMeta('containerProperty')])) {
798             this.updateToolbars(this.record, this.recordClass.getMeta('containerProperty'));
799         }
800         
801         // add current timestamp as id, if this is a dependent record 
802         if (this.modelConfig && this.modelConfig.isDependent == true && this.record.id == 0) {
803             this.record.set('id', (new Date()).getTime());
804         }
805         
806         if (this.loadMask) {
807             this.loadMask.hide();
808         }
809     },
810     
811     /**
812      * executed when record gets updated from form
813      */
814     onRecordUpdate: function() {
815         var form = this.getForm();
816
817         // merge changes from form into record
818         form.updateRecord(this.record);
819     },
820     
821     /**
822      * @private
823      */
824     onRender : function(ct, position){
825         Tine.widgets.dialog.EditDialog.superclass.onRender.call(this, ct, position);
826         
827         // generalized keybord map for edit dlgs
828         new Ext.KeyMap(this.el, [
829             {
830                 key: [10,13], // ctrl + return
831                 ctrl: true,
832                 scope: this,
833                 fn: function() {
834                     if (this.getForm().hasOwnProperty('items')) {
835                         // force set last selected field
836                         this.getForm().items.each(function(item) {
837                             if (item.hasFocus) {
838                                 item.setValue(item.getRawValue());
839                             }
840                         }, this);
841                     }
842                     this.action_saveAndClose.execute();
843                 }
844             }
845         ]);
846         
847         if (this.loadMask !== false && this.i18nRecordName) {
848             this.loadMask = new Ext.LoadMask(ct, {msg: String.format(i18n._('Transferring {0}...'), this.i18nRecordName)});
849             this.loadMask.show();
850         }
851     },
852     
853     /**
854      * update (action updateer) top and bottom toolbars
855      */
856     updateToolbars: function(record, containerField) {
857         if (! this.evalGrants) {
858             return;
859         }
860         
861         var actions = [
862             this.action_saveAndClose,
863             this.action_applyChanges,
864             this.action_delete,
865             this.action_cancel
866         ];
867         Tine.widgets.actionUpdater(record, actions, containerField);
868         Tine.widgets.actionUpdater(record, this.tbarItems, containerField);
869     },
870     
871     /**
872      * get top toolbar
873      */
874     getToolbar: function() {
875         return this.getTopToolbar();
876     },
877     
878     /**
879      * is form valid?
880      * 
881      * @return {Boolean}
882      */
883     isValid: function() {
884         var me = this;
885         return new Promise(function (fulfill, reject) {
886             if (me.getForm().isValid()) {
887                 fulfill(true);
888             } else {
889                 reject(me.getValidationErrorMessage())
890             }
891         });
892     },
893
894     /**
895      * vaidates on multiple edit
896      * 
897      * @return {Boolean}
898      */
899     isMultipleValid: function() {
900         return true;
901     },
902     
903     /**
904      * @private
905      */
906     onCancel : function(){
907         this.fireEvent('cancel');
908         this.purgeListeners();
909         this.window.close();
910     },
911     
912     /**
913      * @private
914      */
915     onSaveAndClose: function() {
916         this.fireEvent('saveAndClose');
917         this.onApplyChanges(true);
918     },
919     
920     /**
921      * generic apply changes handler
922      * @param {Boolean} closeWindow
923      */
924     onApplyChanges: function(closeWindow) {
925         if (this.saving) {
926             return;
927         }
928         this.saving = true;
929
930         this.loadMask.show();
931
932         var ticketFn = this.doApplyChanges.deferByTickets(this, [closeWindow]),
933             wrapTicket = ticketFn();
934
935         this.fireEvent('save', this, this.record, ticketFn);
936         wrapTicket();
937     },
938     
939     /**
940      * is called from onApplyChanges
941      * @param {Boolean} closeWindow
942      */
943     doApplyChanges: function(closeWindow) {
944         // we need to sync record before validating to let (sub) panels have 
945         // current data of other panels
946         this.onRecordUpdate();
947         
948         // quit copy mode
949         this.copyRecord = false;
950
951         var isValid = this.isValid(),
952             vBool = !! isValid,
953             me = this;
954
955         if (Ext.isDefined(isValid) && ! Ext.isFunction(isValid.then)) {
956             // convert legacy isValid into promise
957             isValid = new Promise(function (fulfill, reject) {;
958                 return vBool ? fulfill(true) : reject(me.getValidationErrorMessage());
959             });
960         }
961
962         isValid.then(function () {
963             if (me.mode !== 'local') {
964                 me.recordProxy.saveRecord(me.record, {
965                     scope: me,
966                     success: function (record) {
967                         // override record with returned data
968                         me.record = record;
969                         if (!Ext.isFunction(me.window.cascade)) {
970                             // update form with this new data
971                             // NOTE: We update the form also when window should be closed,
972                             //       cause sometimes security restrictions might prevent
973                             //       closing of native windows
974                             me.onRecordLoad();
975                         }
976                         var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
977                             wrapTicket = ticketFn();
978
979                         me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
980                         wrapTicket();
981                     },
982                     failure: me.onRequestFailed,
983                     timeout: 300000 // 5 minutes
984                 }, me.getAdditionalSaveParams(me));
985             } else {
986                 me.onRecordLoad();
987                 var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
988                     wrapTicket = ticketFn();
989
990                 me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
991                 wrapTicket();
992             }
993         }, function (message) {
994             me.saving = false;
995             me.loadMask.hide();
996             Ext.MessageBox.alert(i18n._('Errors'), message);
997         });
998     },
999
1000     /**
1001      * returns additional save params
1002      *
1003      * @param {EditDialog} me
1004      * @returns {{duplicateCheck: boolean}}
1005      */
1006     getAdditionalSaveParams: function(me) {
1007         return {
1008             duplicateCheck: me.doDuplicateCheck
1009         };
1010     },
1011     
1012     onAfterApplyChanges: function(closeWindow) {
1013         this.window.rename(this.windowNamePrefix + this.record.id);
1014         this.loadMask.hide();
1015         this.saving = false;
1016         
1017         if (closeWindow) {
1018             this.window.fireEvent('saveAndClose');
1019             this.purgeListeners();
1020             this.window.close();
1021         }
1022     },
1023     
1024     /**
1025      * get validation error message
1026      * 
1027      * @return {String}
1028      */
1029     getValidationErrorMessage: function() {
1030         return i18n._('Please fix the errors noted.');
1031     },
1032     
1033     /**
1034      * generic delete handler
1035      */
1036     onDelete: function(btn, e) {
1037         Ext.MessageBox.confirm(i18n._('Confirm'), String.format(i18n._('Do you really want to delete this {0}?'), this.i18nRecordName), function(_button) {
1038             if(btn == 'yes') {
1039                 var deleteMask = new Ext.LoadMask(this.getEl(), {msg: String.format(i18n._('Deleting {0}'), this.i18nRecordName)});
1040                 deleteMask.show();
1041                 
1042                 this.recordProxy.deleteRecords(this.record, {
1043                     scope: this,
1044                     success: function() {
1045                         this.purgeListeners();
1046                         this.window.close();
1047                     },
1048                     failure: function () {
1049                         Ext.MessageBox.alert(i18n._('Failed'), String.format(i18n._('Could not delete {0}.'), this.i18nRecordName));
1050                         Ext.MessageBox.hide();
1051                     }
1052                 });
1053             }
1054         });
1055     },
1056     
1057     /**
1058      * duplicate(s) found exception handler
1059      * 
1060      * @param {Object} exception
1061      */
1062     onDuplicateException: function(exception) {
1063         var resolveGridPanel = new Tine.widgets.dialog.DuplicateResolveGridPanel({
1064             app: this.app,
1065             store: new Tine.widgets.dialog.DuplicateResolveStore({
1066                 app: this.app,
1067                 recordClass: this.recordClass,
1068                 recordProxy: this.recordProxy,
1069                 data: {
1070                     clientRecord: exception.clientRecord,
1071                     duplicates: exception.duplicates
1072                 }
1073             }),
1074             fbar: [
1075                 '->',
1076                 this.action_cancel,
1077                 this.action_saveAndClose
1078             ]
1079         });
1080         
1081         // intercept save handler
1082         resolveGridPanel.btnSaveAndClose.setHandler(function(btn, e) {
1083             var resolveStrategy = resolveGridPanel.store.resolveStrategy;
1084             
1085             // action discard -> close window
1086             if (resolveStrategy == 'discard') {
1087                 return this.onCancel();
1088             }
1089             
1090             this.record = resolveGridPanel.store.getResolvedRecord();
1091             
1092             // quit copy mode before populating form with resolved data
1093             this.copyRecord = false;
1094             this.onRecordLoad();
1095             
1096             mainCardPanel.layout.setActiveItem(this.id);
1097             resolveGridPanel.doLayout();
1098             
1099             this.doDuplicateCheck = false;
1100             this.onSaveAndClose();
1101         }, this);
1102         
1103         // place in viewport
1104         this.window.setTitle(String.format(i18n._('Resolve Duplicate {0} Suspicion'), this.i18nRecordName));
1105         var mainCardPanel = this.findParentBy(function(p) {return p.isWindowMainCardPanel });
1106         mainCardPanel.add(resolveGridPanel);
1107         mainCardPanel.layout.setActiveItem(resolveGridPanel.id);
1108         resolveGridPanel.doLayout();
1109     },
1110     
1111     /**
1112      * generic request exception handler
1113      * 
1114      * @param {Object} exception
1115      */
1116     onRequestFailed: function(exception) {
1117         this.saving = false;
1118
1119         if (this.exceptionHandlingMap && this.exceptionHandlingMap[exception.code] && typeof this.exceptionHandlingMap[exception.code] === 'function') {
1120             this.exceptionHandlingMap[exception.code](exception);
1121
1122         } else if (exception.code == 629) {
1123             this.onDuplicateException.apply(this, arguments);
1124
1125         } else {
1126             Tine.Tinebase.ExceptionHandler.handleRequestException(exception);
1127         }
1128
1129         this.loadMask.hide();
1130     },
1131     
1132     /**
1133      * creates the relations panel, if relations are defined
1134      */
1135     initRelationsPanel: function() {
1136         if (! this.hideRelationsPanel && this.recordClass && this.recordClass.hasField('relations')) {
1137             // init relations panel before onRecordLoad
1138             if (! this.relationsPanel) {
1139                 this.relationsPanel = new Tine.widgets.relation.GenericPickerGridPanel({ anchor: '100% 100%', editDialog: this });
1140             }
1141             // interrupt process flow until dialog is rendered
1142             if (! this.rendered) {
1143                 this.initRelationsPanel.defer(250, this);
1144                 return;
1145             }
1146             // add relations panel if this is rendered
1147             if (this.items.items[0]) {
1148                 this.items.items[0].add(this.relationsPanel);
1149             }
1150             
1151             Tine.log.debug('Tine.widgets.dialog.EditDialog::initRelationsPanel() - Initialized relations panel and added to dialog tab items.');
1152         }
1153     },
1154
1155     /**
1156      * create notes panel
1157      */
1158     initNotesPanel: function() {
1159         // This dialog is pretty generic but for some cases it's used in a differend way
1160         if(this.displayNotes == true) {
1161             this.items.items.push(new Tine.widgets.activities.ActivitiesGridPanel({
1162                 anchor: '100% 100%',
1163                 editDialog: this
1164             }));
1165         }
1166     },
1167
1168     /**
1169      * creates attachments panel
1170      */
1171     initAttachmentsPanel: function() {
1172         if (! this.attachmentsPanel && ! this.hideAttachmentsPanel && this.recordClass && this.recordClass.hasField('attachments') && Tine.Tinebase.registry.get('filesystemAvailable')) {
1173             this.attachmentsPanel = new Tine.widgets.dialog.AttachmentsGridPanel({ anchor: '100% 100%', editDialog: this }); 
1174             this.items.items.push(this.attachmentsPanel);
1175         }
1176     }
1177 });