/*!
 * Tine 2.0 - Events 
 * Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 * http://www.gnu.org/licenses/agpl.html AGPL Version 3
 */
/* 
 * Tine 2.0
 * 
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Philipp Schüle <p.schuele@metaways.de>
 * @copyright   Copyright (c) 2015 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.Events');

// register grants for events containers
Tine.widgets.container.GrantsManager.register('Events_Model_Event', ['read', 'add', 'edit', 'delete']);
/*
 * Tine 2.0
 * 
 * @package     Events
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Philipp Schüle <p.schuele@metaways.de>
 * @copyright   Copyright (c) 2009-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 *
 */
 
Ext.ns('Tine.Events');

/**
 * @namespace Tine.Calendar
 * @class Tine.Events.CalendarEventEditDialog
 * @extends Tine.Calendar.CalendarEventEditDialog
 * Calendar Edit Dialog <br>
 * 
 * @author      Philipp Schüle <p.schuele@metaways.de>
 */
Tine.Events.CalendarEventEditDialog = Ext.extend(Tine.Calendar.EventEditDialog, {

    /**
     * @private
     */
    onRender : function(ct, position){
        Tine.Events.CalendarEventEditDialog.superclass.onRender.call(this, ct, position);

        // TODO add more fields
        Ext.each(['container_id'], function(field) {
            this.getForm().findField(field).setReadOnly(true);
        }, this);
    }
});

/**
 * Opens a new event edit dialog window
 *
 * @return {Ext.ux.Window}
 */
Tine.Events.CalendarEventEditDialog.openWindow = function (config) {
    // record is JSON encoded here...
    var id = config.recordId ? config.recordId : 0;
    var window = Tine.WindowFactory.getWindow({
        width: 800,
        height: 505,
        name: Tine.Events.CalendarEventEditDialog.prototype.windowNamePrefix + id,
        contentPanelConstructor: 'Tine.Events.CalendarEventEditDialog',
        contentPanelConstructorConfig: config
    });
    return window;
};
/*
 * Tine 2.0
 * 
 * @package     Events
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Philipp Schüle <p.schuele@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 *
 */
 
Ext.ns('Tine.Events');

/**
 * Events grid panel
 * 
 * @namespace   Tine.Events
 * @class       Tine.Events.CalendarEventGridPanel
 * @extends     Tine.Calendar.GridView
 * 
 * <p>Calendar Events Grid Panel</p>
 * <p><pre>
 *     this is used in the EventEditDialog as a tab to allow to manage the related calendar events
 * </pre></p>
 * 
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Philipp Schüle <p.schuele@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 * 
 * @param       {Object} config
 * @constructor
 * Create a new Tine.Events.CalendarEventGridPanel
 */
Tine.Events.CalendarEventGridPanel = Ext.extend(Tine.widgets.grid.BbarGridPanel, {

    /**
     * record class
     * @cfg {Tine.Addressbook.Model.Contact} recordClass
     */
    recordClass: Tine.Calendar.Model.Event,
    recordProxy: null,

    editDialogClass: Tine.Events.CalendarEventEditDialog,
    disableDeleteConfirmation: true,

    /**
     * grid specific
     * @private
     */
    defaultSortInfo: {field: 'dtstart', direction: 'ASC'},

    initComponent: function() {
        this.store = new Ext.data.JsonStore({
            // TODO prevent store from LOADing on render/creation (autoLoad = false does not help)
            //autoLoad: false,
            fields: Tine.Calendar.Model.Event
        });

        if (! this.app) {
            // FIXME this should not be needed ...
            this.app = Tine.Tinebase.appMgr.get('Events');
        }

        // TODO make it work: this currently destroys the container selector in the dialog because the container displayfield
        // TODO ... in the details panel is used instead of the selector :((
        // this.initDetailsPanel();

        // TODO use better fitting default columns? custom fields?
        var additionalColumns = [
            {
                id: 'type',
                header: this.app.i18n._("Type"),
                width: 100,
                dataIndex: 'type',
                renderer: function(value, metadata, record) {
                    return this.typeRenderer(record);
                },
                scope: this
            }
        ];
        this.gridConfig.cm = Tine.Calendar.GridView.initCM(Tine.Tinebase.appMgr.get('Calendar'), additionalColumns);

        Tine.Events.CalendarEventGridPanel.superclass.initComponent.call(this);

        this.store.on('add', this.updateContainer, this);
    },

    /**
     * @private
     */
    initDetailsPanel: function() {
        this.detailsPanel = new Tine.Calendar.EventDetailsPanel({
            grid : this,
            app: this.app
        });
    },

    /**
     * TODO is this really needed?
     */
    updateContainer: function(store, records) {

        Ext.each(records, function(record) {
            // TODO use set()? but we need to suspend events ...
            record.data.container_id = Tine.Events.registry.get('defaultEventsCalendar');
        }, this);
    },

    /**
     * get events from record relations and put into store
     */
    fillEventsStore: function(record) {
        this.record = record;

        var calEvents = [],
            calEvent;

        Ext.each(record.get('relations'), function(relation) {
            if (['MAIN', 'ASSEMBLY', 'DISASSEMBLY'].indexOf(relation.type) !== false) {
                // only add "special" events to this grid and set main event here
                calEvent = new Tine.Calendar.Model.Event(relation.related_record, relation.related_id);
                if (relation.type === 'MAIN') {
                    this.mainEvent = calEvent;
                }
                calEvents.push(calEvent);
            }
        }, this);

        if (calEvents.length > 0) {
            this.getStore().suspendEvents();
            this.getStore().removeAll();
            this.getStore().add(calEvents);
            this.getStore().resumeEvents();
        }
    },

    /**
     * fetch events from grid and put into relations
     */
    updateRelationsFromGrid: function(currentRelations) {
        var relations = [];
        // remove all old cal_event relations
        Ext.each(currentRelations, function(relation) {
            if (['MAIN', 'ASSEMBLY', 'DISASSEMBLY'].indexOf(relation.type) === false) {
                relations.push(relation);
            }
        }, this);

        // add cal_event relations from events grid
        this.getStore().each(function(calEvent) {
            relations.push(this.getRelation(calEvent).data);
        }, this);

        return relations;
    },

    /**
     * create new record
     * - overwritten Tine.widgets.grid.GridPanel::createNewRecord
     *
     * @returns {Tine.Tinebase.data.Record}
     */
    createNewRecord: function() {
        var record = Tine.Events.CalendarEventGridPanel.superclass.createNewRecord.call(this);
        record.set('container_id', Tine.Events.registry.get('defaultEventsCalendar'));

        return record;
    },

    /**
     * get relation for cal event
     *
     * @param {Tine.Calendar.Model.Event} calEvent
     * @returns {Tine.Tinebase.Model.Relation}
     */
    getRelation: function(calEvent) {
        var type = this.getRelationType(calEvent);

        // set id to 0 for new events
        var eventId = calEvent.getId();
        if (eventId && eventId.match(/^new-/)) {
            calEvent.data.id = null;
        }

        var relationId = null,
            relatedCalEventId = calEvent.data.id ? calEvent.data.id : null;
        if (this.record && relatedCalEventId) {
            // try to find find existing relation as it is needed to update related record
            Ext.each(this.record.get('relations'), function (relation) {
                if (relation.related_id === relatedCalEventId) {
                    relationId = relation.id;
                }
            });
        }

        return new Tine.Tinebase.Model.Relation({
            related_record: calEvent.data,
            related_id: relatedCalEventId,
            related_model: 'Calendar_Model_Event',
            type: type,
            related_degree: 'parent',
            own_backend: 'Sql',
            related_backend: 'Sql',
            own_id: (this.record) ? this.record.id : null,
            own_model: 'Events_Model_Event',
            id: relationId
        });
    },

    /**
     * determines relation type (MAIN, ASSEMBLY, DISASSEMBLY) depending on dtstart & main event
     *
     * @param calEvent
     * @returns {string}
     */
    getRelationType: function(calEvent) {
        if (! this.mainEvent) {
            this.mainEvent = calEvent;
        }

        // normalize dtstarts
        var mainDtStart = (Ext.isString(this.mainEvent.get('dtstart')))
            ? new Date(this.mainEvent.get('dtstart'))
            : this.mainEvent.get('dtstart'),
            calEventDtStart = (Ext.isString(calEvent.get('dtstart')))
            ? new Date(calEvent.get('dtstart'))
            : calEvent.get('dtstart');
        mainDtStart = mainDtStart.getTime();
        calEventDtStart = calEventDtStart.getTime();

        if (calEventDtStart > mainDtStart) {
            return 'DISASSEMBLY'; // _('DISASSEMBLY')
        } else if (calEventDtStart < mainDtStart) {
            return 'ASSEMBLY'; // _('ASSEMBLY')
        } else if (calEventDtStart == mainDtStart) {
            return 'MAIN'; // _('MAIN')
        }

        return '';
    },

    getMainEvent: function() {
        return this.mainEvent;
    },

    /**
     * @param calEvent
     * @returns {string}
     */
    typeRenderer: function(calEvent) {
        var type = this.getRelationType(calEvent);
        return this.app.i18n._(type);
    },

    /**
     * updates / creates main event from form values
     */
    updateMainEvent: function(dtstart, dtend, summary) {
        if (! this.mainEvent) {
            this.mainEvent = new Tine.Calendar.Model.Event(Tine.Calendar.Model.Event.getDefaultData());
            this.mainEvent.set('container_id', Tine.Events.registry.get('defaultEventsCalendar'));
            this.mainEvent.id = 'new-' + Ext.id();
            this.mainEvent.setId(this.mainEvent.id);
        }

        if (dtstart && dtend) {
            this.mainEvent.set('dtstart', dtstart);
            this.mainEvent.set('dtend', dtend);
            this.mainEvent.set('summary', this.app.i18n._('Main Event') + ': ' + summary);
            // TODO use a better check to detect main event
            if (this.getStore().getCount() === 0) {
                this.getStore().add([this.mainEvent]);
            }
        }
    }
});
/*
 * Tine 2.0
 * 
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Stefanie Stamer <s.stamer@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 */
Ext.ns('Tine.Events');

/**
 * @namespace   Tine.Events
 * @class       Tine.Events.EventEditDialog
 * @extends     Tine.widgets.dialog.EditDialog
 * 
 * <p>Event Compose Dialog</p>
 * <p></p>
 * 
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Stefanie Stamer <s.stamer@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 * 
 * @param       {Object} config
 * @constructor
 * Create a new Tine.Events.EventEditDialog
 */
Tine.Events.EventEditDialog = Ext.extend(Tine.widgets.dialog.EditDialog, {

    /**
     * @cfg {Boolean} checkBusyConflicts
     * do busy conflict check when saving record
     */
    checkBusyConflicts: true,

    /**
     * @private
     */
    windowHeight: 600,
    windowWidth: 800,
    windowNamePrefix: 'EventEventEditWindow_',
    displayNotes: true,

    initComponent: function() {
        this.addEvents(
            /**
             * @event dtStartChange
             * @desc  Fired when dtstart changes in UI
             * @param {Json String} oldValue, newValue
             */
            'dtStartChange'
        );

        this.calendarEventGridPanel = new Tine.Events.CalendarEventGridPanel({
            app: this.app
        });

        Tine.Events.EventEditDialog.superclass.initComponent.call(this);

        this.on('load', this.loadRecord, this);
    },

    onAfterRecordLoad: function () {
        Tine.Events.EventEditDialog.superclass.onAfterRecordLoad.call(this);

        this.showHideOptionalDate();
        this.onContactLoad();
        this.onDepartmentLoad();
    },

    onDtEndChange: function(dtEndField, newValue, oldValue) {
        this.validateDtEnd();
    },

    loadRecord: function() {
        this.calendarEventGridPanel.fillEventsStore(this.record);
        if (this.record.id === 0) {
            var department = Tine.Tinebase.registry.get('userDepartment');
            // set current user as contact
            this.record.set('contact', Tine.Tinebase.registry.get('userContact'));
            if (department) {
                this.record.set('department', department);
                this.record.set('location', (department.customfields && department.customfields.location) ? department.customfields.location : '');
            }
        }
    },

    onRecordUpdate: function() {
        Tine.Events.EventEditDialog.superclass.onRecordUpdate.call(this);

        var relations = this.calendarEventGridPanel.updateRelationsFromGrid(this.record.get('relations'));
        this.record.set('relations', relations);
        
        // TODO update dtstart/dtend from main event
    },

    /**
     * returns additional save params
     *
     * @returns {{checkBusyConflicts: boolean}}
     */
    getAdditionalSaveParams: function() {
        return {
            checkBusyConflicts: this.checkBusyConflicts
        };
    },

    /**
     * generic request exception handler
     *
     * @param {Object} exception
     */
    onRequestFailed: function(exception) {
        this.saving = false;

        if (exception.code == 901) {
            this.onBusyException.apply(this, arguments);
        } else {
            Tine.Events.EventEditDialog.superclass.onRequestFailed.call(this, exception);
        }
        this.loadMask.hide();
    },

    onBusyException: function() {
        Ext.Msg.confirm(this.app.i18n._('Ignore Scheduling Conflict'),
            this.app.i18n._('There is a resource/attendee conflict. You can ignore the conflict and save the record by pressing "yes".'),
            function(btn) {
                if (btn == 'yes') {
                    this.checkBusyConflicts = false;
                    this.onApplyChanges(true);
                }
            }, this);
    },

    /**
     * returns dialog
     * 
     * NOTE: when this method gets called, all initialisation is done.
     * 
     * @return {Object}
     * @private
     */
    getFormItems: function() {
        return {
            xtype: 'tabpanel',
            border: false,
            plain: true,
            activeTab: 0,
            defaults: {
                hideMode: 'offsets'
            },
            items: [{
                //Start first tab
                title: this.app.i18n._('General'),
                border: false,
                frame: true,
                layout: 'border',
                items: [{
                    region: 'center',
                    layout: 'hfit',
                    border: false,
                    items: [{
                        region: 'center',
                        xtype: 'columnform',
                        labelAlign: 'top',
                        formDefaults: {
                            xtype:'textfield',
                            anchor: '100%',
                            labelSeparator: '',
                            columnWidth: .333,
                            disabled: (this.useMultiple) ? true : false
                        },
                        // Start first line
                        items: [
                            [{
                                columnWidth: 1,
                                xtype: 'textfield',
                                fieldLabel: this.app.i18n._('Title'),
                                name: 'title',
                                maxLength: 100,
                                allowBlank: false,
                                listeners: {
                                    change: this.updateMainEvent,
                                    scope: this
                                }
                            }],
                            [new Tine.Tinebase.widgets.keyfield.ComboBox({
                                app: 'Events',
                                keyFieldName: 'actionType',
                                columnWidth: 1,
                                fieldLabel: this.app.i18n._('Action'),
                                name: 'action'
                            })],
                            [new Tine.Tinebase.widgets.keyfield.ComboBox({
                                app: 'Events',
                                keyFieldName: 'projectType',
                                columnWidth: 1,
                                fieldLabel: this.app.i18n._('Project type'),
                                name: 'project_type'
                            })]
                            ,
                            [Tine.widgets.form.RecordPickerManager.get('Addressbook', 'List', {
                                columnWidth: 0.5,
                                fieldLabel: this.app.i18n._('Department'),
                                name: 'department',
                                maxLength: 100,
                                departmentOnly: true,
                                listeners:{
                                    scope: this,
                                    'select': this.onDepartmentLoad
                                }
                            }),
                            {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                fieldLabel: this.app.i18n._('Location'),
                                name: 'location',
                                maxLength: 100,
                                disabled: true
                            }],
                            [
                            Tine.widgets.form.RecordPickerManager.get('Addressbook', 'Contact', {
                                columnWidth: 0.5,
                                userOnly: true,
                                fieldLabel: this.app.i18n._('Contact'),
                                emptyText: _('Add Contact ...'),
                                name: 'contact',
                                allowEmpty: true,
                                listeners:{
                                    scope: this,
                                    'select': this.onContactLoad
                                }
                            }),
                            {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                fieldLabel: this.app.i18n._('Phone'),
                                name: 'phone'
                            }],
                            [{
                                columnWidth: 1,
                                xtype: 'textfield',
                                fieldLabel: this.app.i18n._('Subregion'),
                                name: 'subregion',
                                maxLength: 100
                            }],
                            [{
                                columnWidth: 1,
                                xtype: 'textfield',
                                fieldLabel: this.app.i18n._('Organizer'),
                                name: 'organizer',
                                maxLength: 100
                            }],
                            [new Tine.Tinebase.widgets.keyfield.ComboBox({
                                app: 'Events',
                                keyFieldName: 'targetGroups',
                                columnWidth: 0.5,
                                fieldLabel: this.app.i18n._('Target group'),
                                name: 'target_group'
                            }), {
                                columnWidth: 0.5,
                                xtype: 'numberfield',
                                fieldLabel: this.app.i18n._('Guests'),
                                name: 'guests',
                                value: 0,
                                allowNegative: false,
                                allowDecimals: false
                            }],
                            [
                                new Tine.Tinebase.widgets.keyfield.ComboBox({
                                app: 'Events',
                                keyFieldName: 'plannedStatus',
                                columnWidth: 0.5,
                                fieldLabel: this.app.i18n._('Planned'),
                                name: 'planned',
                                listeners:{
                                    scope: this,
                                    'select': this.showHideOptionalDate
                                }
                            }), {
                                xtype: 'datefield',
                                columnWidth: 0.5,
                                fieldLabel: this.app.i18n._('Optional Date'),
                                name: 'optional_date'
                            }],
                            [{
                                xtype: 'datetimefield',
                                columnWidth: 0.5,
                                fieldLabel: this.app.i18n._('Start'),
                                listeners: {scope: this, change: this.onDtStartChange},
                                defaultTime: '12:00',
                                name: 'event_dtstart',
                                listeners: {
                                    change: this.updateMainEvent,
                                    scope: this
                                }
                            }],
                            [{
                                xtype: 'datetimefield',
                                columnWidth: 0.5,
                                fieldLabel: this.app.i18n._('End'),
                                listeners: {scope: this, change: this.onDtEndChange},
                                defaultTime: '13:00',
                                name: 'event_dtend',
                                listeners: {
                                    change: this.updateMainEvent,
                                    scope: this
                                }

                            }]
                        ]
                    }
                    ]
                    
                },
                    {
                        // activities and tags
                        // TODO make order of accordion items stateful
                        region: 'east',
                        layout: 'accordion',
                        animate: true,
                        width: 210,
                        split: true,
                        collapsible: true,
                        collapseMode: 'mini',
                        header: false,
                        margins: '0 5 0 5',
                        border: true,
                        items: [
                            new Ext.Panel({
                                // @todo generalise!
                                title: this.app.i18n._('Description'),
                                iconCls: 'descriptionIcon',
                                layout: 'form',
                                labelAlign: 'top',
                                border: false,
                                items: [{
                                    style: 'margin-top: -4px; border 0px;',
                                    labelSeparator: '',
                                    xtype: 'textarea',
                                    name: 'description',
                                    hideLabel: true,
                                    grow: false,
                                    preventScrollbars: false,
                                    anchor: '100% 100%',
                                    emptyText: this.app.i18n._('Enter description'),
                                    requiredGrant: 'editGrant'
                                }]
                            }),
                            new Tine.widgets.tags.TagPanel({
                                app: 'Events',
                                border: false,
                                bodyStyle: 'border:1px solid #B5B8C8;'
                            })
                        ]
                    }]
                }, {
                    title: this.app.i18n._('Calendar Entries'),
                    autoScroll: true,
                    border: false,
                    frame: true,
                    layout: 'fit',
                    items: [
                        this.calendarEventGridPanel
                    ]
                },
                new Tine.widgets.activities.ActivitiesTabPanel({
                    app: this.appName,
                    record_id: this.record.id,
                    record_model: this.appName + '_Model_' + this.recordClass.getMeta('modelName')
                })
            ]
        };
    },

    /**
     * updates / creates main event from form values
     */
    updateMainEvent: function() {
        var dtstart = this.getForm().findField('event_dtstart').getValue(),
            dtend = this.getForm().findField('event_dtend').getValue(),
            summary = this.getForm().findField('title').getValue();
        this.calendarEventGridPanel.updateMainEvent(dtstart, dtend, summary);

        // refresh/re-sort grid to update event/relation types
        //this.calendarEventGridPanel.getStore().sort('dtstart', 'DESC');
        this.calendarEventGridPanel.getStore().fireEvent('datachanged', this.calendarEventGridPanel.getStore());
    },

    /**
     * on dt start change
     * 
     * @param {} dtStartField
     * @param {} newValue
     * @param {} oldValue
     */
    onDtStartChange: function(dtStartField, newValue, oldValue) {
        if (this.validateDtStart() == false) {
            return false;
        }
        
        if (Ext.isDate(newValue) && Ext.isDate(oldValue)) {
            var dtEndField = this.getForm().findField('event_dtend'),
                dtEnd = dtEndField.getValue();
                
            if (Ext.isDate(dtEnd)) {
                var duration = dtEnd.getTime() - oldValue.getTime(),
                    newDtEnd = newValue.add(Date.MILLI, duration);
                dtEndField.setValue(newDtEnd);
                this.validateDtEnd();
            }
        }

        this.fireEvent('dtStartChange', Ext.util.JSON.encode({newValue: newValue, oldValue: oldValue}));
    },
    
    validateDtStart: function() {
        var dtStartField = this.getForm().findField('event_dtstart'),
            dtStart = dtStartField.getValue();
        
        if (! Ext.isDate(dtStart)) {
            dtStartField.markInvalid(this.app.i18n._('Start date is not valid'));
            return false;
        } else {
            dtStartField.clearInvalid();
            return true;
        }
    },
    
    validateDtEnd: function() {
        var dtStart = this.getForm().findField('event_dtstart').getValue(),
            dtEndField = this.getForm().findField('event_dtend'),
            dtEnd = dtEndField.getValue();
        
        if (! Ext.isDate(dtEnd)) {
            dtEndField.markInvalid(this.app.i18n._('End date is not valid'));
            return false;
        } else if (Ext.isDate(dtStart) && dtEnd.getTime() - dtStart.getTime() <= 0) {
            dtEndField.markInvalid(this.app.i18n._('End date must be after start date'));
            return false;
        } else {
            dtEndField.clearInvalid();
            return true;
        }
    },
    
    showHideOptionalDate: function() {
        var planned = this.getForm().findField('planned').getValue(),
            optionalDate = this.getForm().findField('optional_date');

        if (planned == 'OPTIONAL') {
            optionalDate.show();
        } else {
            optionalDate.hide();
        }
    },

    onContactLoad: function(combo, record) {
        var contact = !Ext.isEmpty(record) ? record.data : this.record.get('contact'),
            phoneField = this.getForm().findField('phone');
            
        if(!Ext.isEmpty(contact) && !Ext.isEmpty(contact.tel_work)) {
            phoneField.setValue(contact.tel_work);
        }
    },
    
    onDepartmentLoad: function(combo, record) {
        var department = !Ext.isEmpty(record) ? record.data : this.record.get('department'),
            locationField = this.getForm().findField('location');
            
        if(!Ext.isEmpty(department) && !Ext.isEmpty(department.customfields) && !Ext.isEmpty(department.customfields.location)) {
            locationField.setValue(department.customfields.location);
        } else {
            locationField.setValue('');
        }
    }
});
/*
 * Tine 2.0
 * 
 * @package     Events
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Stefanie Stamer <s.stamer@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 *
 */
 
Ext.ns('Tine.Events');

/**
 * Events grid panel
 * 
 * @namespace   Tine.Events
 * @class       Tine.Events.EventGridPanel
 * @extends     Tine.widgets.grid.GridPanel
 * 
 * <p>Events Grid Panel</p>
 * <p><pre>
 * </pre></p>
 * 
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Stefanie Stamer <s.stamer@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 * 
 * @param       {Object} config
 * @constructor
 * Create a new Tine.Events.EventGridPanel
 */
Tine.Events.EventGridPanel = Ext.extend(Tine.widgets.grid.GridPanel, {
    copyEditAction: true,
    initComponent: function() {
        this.initDetailsPanel();
        Tine.Events.EventGridPanel.superclass.initComponent.call(this);
    },
    
    /**
     * @private
     */
    initDetailsPanel: function() {
        this.detailsPanel = new Tine.Events.EventDetailsPanel({
            grid : this,
            app: this.app
        });
    },
    
    /**
     * returns view row class (scope is this.grid.view)
     */
    getViewRowClass: function(record, index, rp, ds) {
        
        var className = Tine.Events.EventGridPanel.superclass.getViewRowClass(record, index, rp, ds),
            color = '',
            actionTypeConfig = Tine.Events.registry.get('config').actionType.value.records,
            config;
       
        if(record.get('action')) {
           for (var i = 0; i < actionTypeConfig.length; i++) {
                if (actionTypeConfig[i].id === record.get('action')) {
                    config = actionTypeConfig[i];
                }
            }
        }
        
        if (config && config.color) {
            rp.tstyle += 'color: ' + config.color + ';';
        }
        return className;
    }
});
/* 
 * Tine 2.0
 * 
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Stefanie Stamer <s.stamer@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 */
 
Ext.ns('Tine.Events');

/**
 * @class     Tine.Events.EventDetailsPanel
 * @namespace Events
 * @extends   Tine.widgets.grid.DetailsPanel
 * @author      Stefanie Stamer <s.stamer@metaways.de>
 * @copyright   Copyright (c) 2007-2015 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Tine.Events.EventDetailsPanel = Ext.extend(Tine.widgets.grid.DetailsPanel, {
    
    app: null,
    
    /**
     * @cfg {Number} defaultHeight
     * default Heights
     */
    defaultHeight: 150,
    
    initComponent: function() {
        this.summaryRecord = new Ext.data.Record({
            count: 0
        }, 0);
        
        Tine.Events.EventDetailsPanel.superclass.initComponent.call(this);
    },
        /**
     * renders datetime
     * 
     * @param {Date} dt
     * @return {String}
     */
    datetimeRenderer: function(dt) {
        if (! dt) {
            return this.app.i18n._('Unknown date');
        }
        
        return String.format(this.app.i18n._("{0} {1} o'clock"), dt.format('l') + ', ' + Tine.Tinebase.common.dateRenderer(dt), dt.format('H:i'));
    },
        /**
     * renders department
     * 
     * @param {List} d
     * @return {String}
     */
    departmentRenderer: function(d) {
        if (! d) {
            return '';
        }
        
        return d.name;
    },
    
    /**
     * default panel w.o. data
     * 
     * @return {Ext.ux.display.DisplayPanel}
     */
    getDefaultInfosPanel: function() {
        return this.getMultiRecordsPanel();
    },
    
    /**
     * get panel for multi selection aggregates/information
     * 
     * @return {Ext.Panel}
     */
    getMultiRecordsPanel: function() {
        if (! this.multiRecordsPanel) {
            this.multiRecordsPanel = new Ext.ux.display.DisplayPanel(
                this.wrapPanel([{
                    xtype: 'ux.displayfield',
                    name: 'count',
                    fieldLabel: this.app.i18n._('Total Events')
                }], 160)
            );
        }
        return this.multiRecordsPanel;
    },
    
    /**
     * main Event record details panel
     * 
     * @return {Ext.ux.display.DisplayPanel}
     */
    getSingleRecordPanel: function() {
        if (! this.singleRecordPanel) {
            this.singleRecordPanel = new Ext.ux.display.DisplayPanel(
                this.wrapPanel([{
                    xtype: 'ux.displayfield',
                    name: 'title',
                    fieldLabel: this.app.i18n._('Title')
                }, {
                    xtype: 'ux.displayfield',
                    name: 'action',
                    fieldLabel: this.app.i18n._('Action'),
                    renderer: Tine.Tinebase.widgets.keyfield.Renderer.get('Events', 'actionType', 'text')
                }, {
                    xtype: 'ux.displayfield',
                    name: 'project_type',
                    fieldLabel: this.app.i18n._('Project type'),
                    renderer: Tine.Tinebase.widgets.keyfield.Renderer.get('Events', 'projectType', 'text')
                }, {
                    xtype: 'ux.displayfield',
                    name: 'department',
                    fieldLabel: this.app.i18n._('Department'),
                    renderer: this.departmentRenderer.createDelegate(this)
                }, {
                    xtype: 'ux.displayfield',
                    name: 'event_dtstart',
                    fieldLabel: this.app.i18n._('Start Time'),
                    renderer: this.datetimeRenderer.createDelegate(this)
                }, {
                    xtype: 'ux.displayfield',
                    name: 'event_dtend',
                    fieldLabel: this.app.i18n._('End Time'),
                    renderer: this.datetimeRenderer.createDelegate(this)
                }, {
                    xtype: 'ux.displayfield',
                    name: 'location',
                    fieldLabel: this.app.i18n._('Location')
                }
                ], 80)
            );
        }
        return this.singleRecordPanel;
    },
    
    /**
     * update Event record details panel
     * 
     * @param {Tine.Tinebase.data.Record} record
     * @param {Mixed} body
     */
    updateDetails: function(record, body) {
        this.getSingleRecordPanel().loadRecord.defer(100, this.getSingleRecordPanel(), [record]);
    },
    
    /**
     * show default template
     * 
     * @param {Mixed} body
     */
    showDefault: function(body) {
        this.showMulti(this.grid.getSelectionModel());
    },
    
    /**
     * show template for multiple rows
     * 
     * @param {Ext.grid.RowSelectionModel} sm
     * @param {Mixed} body
     */
    showMulti: function(sm, body) {
        if (sm.getCount() === 0) {
            var count = this.grid.store.proxy.jsonReader.jsonData.totalcount;
        } else {
            var count = sm.getCount();
        }
        
        this.summaryRecord.set('count', count);
        
        this.getMultiRecordsPanel().loadRecord.defer(100, this.getMultiRecordsPanel(), [this.summaryRecord]);
    }
});
/*
 * Tine 2.0
 * 
 * @package     Events
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Cornelius Weiß <c.weiss@metaways.de>
 * @copyright   Copyright (c) 2015 Metaways Infosystems GmbH (http://www.metaways.de)
 *
 */

Ext.namespace('Tine.Events');

/**
 * admin settings panel
 * 
 * @namespace   Tine.Events
 * @class       Tine.Events.AdminPanel
 * @extends     Ext.TabPanel
 *
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Cornelius Weiß <c.weiss@metaways.de>
 * @copyright   Copyright (c) 2015 Metaways Infosystems GmbH (http://www.metaways.de)
 * 
 * @param       {Object} config
 * @constructor
 * Create a new Tine.Events.AdminPanel
 */
Tine.Events.AdminPanel = Ext.extend(Ext.TabPanel, {

    border: false,
    activeTab: 0,

    /**
     * @private
     */
    initComponent: function() {
        
        this.app = Tine.Tinebase.appMgr.get('Events');
        
        this.items = [
            new Tine.Admin.config.GridPanel({
                configApp: this.app
            })

        ];
        
        Tine.Events.AdminPanel.superclass.initComponent.call(this);
    }
});
    
/**
 * Events Admin Panel Popup
 * 
 * @param   {Object} config
 * @return  {Ext.ux.Window}
 */
Tine.Events.AdminPanel.openWindow = function (config) {
    var window = Tine.WindowFactory.getWindow({
        width: 600,
        height: 470,
        name: 'eventsapp-admin-panel',
        contentPanelConstructor: 'Tine.Events.AdminPanel',
        contentPanelConstructorConfig: config
    });
};
