/*!
 * Tine 2.0 - SimpleFAQ 
 * Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 * http://www.gnu.org/licenses/agpl.html AGPL Version 3
 */
/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ','Tine.SimpleFAQ.Model');

/**
 * @namespace Tine.SimpleFAQ.Model
 * @class Tine.SimpleFAQ.Model.Faq
 * @extends Tine.Tinebase.data.Record
 *
 * Faq Record Definition
 */ 
Tine.SimpleFAQ.Model.Faq = Tine.Tinebase.data.Record.create(Tine.Tinebase.Model.genericFields.concat([
    {name: 'id',            type: 'string'},
    {name: 'faqstatus_id',  type: 'int'},
    {name: 'faqtype_id',    type: 'int'},
    {name: 'question'},
    {name: 'answer'},
    {name: 'notes'},
    {name: 'tags'},
    {name: 'relations'},
    
    {name: 'attachments', omitDuplicateResolving: true}
]), {
    appName: 'SimpleFAQ',
    modelName: 'Faq',
    idProperty: 'id',
    titleProperty: 'question',
    // ngettext('FAQ', 'FAQs', n);
    recordName: 'FAQ',
    recordsName: 'FAQs',
    containerProperty: 'container_id',
    // ngettext('FAQ List', 'FAQ Lists', n); gettext('FAQ Lists');
    containerName: 'FAQ List',
    containersName: 'FAQ Lists'
});

/**
 * get default data for a new Faq
 *
 * @return {Object} default data
 */
Tine.SimpleFAQ.Model.Faq.getDefaultData = function() {

    var defaults = Tine.SimpleFAQ.registry.get('defaults');
    var app = Tine.Tinebase.appMgr.get('SimpleFAQ');

    var data = {
        faqstatus_id: defaults.faqstatus_id,
        faqtype_id: defaults.faqtype_id,
        container_id: app.getMainScreen().getWestPanel().getContainerTreePanel().getSelectedContainer('addGrant', defaults.container_id)
    }
    return data;
};

/**
 * @namespace Tine.Sales.Model
 *
 * get product filter
 *
 * @return {Array} filter objects
 * @static
 */
Tine.SimpleFAQ.Model.Faq.getFilterModel = function() {
    var app = Tine.Tinebase.appMgr.get("SimpleFAQ");
    
    return [
        {label: i18n._('Quick Search'), field: 'query', operators: ['contains']},
        {filtertype: 'tine.widget.container.filtermodel', app: app, recordClass: Tine.SimpleFAQ.Model.Faq},
        {filtertype: 'simplefaq.faqstatus', app: app},
        {filtertype: 'simplefaq.faqtype', app: app},
        {filtertype: 'tinebase.tag', app: app}
    ];
};

/**
 * @namespace Tine.SimpleFAQ.Model
 * @class Tine.SimpleFAQ.Model.Settings
 * @extends Tine.Tinebase.data.Record
 *
 * Settings Record Definition
 * 
 */
Tine.SimpleFAQ.Model.Settings = Tine.Tinebase.data.Record.create([
       {name: 'id'},
       {name: 'defaults'},
       {name: 'faqstatuses'},
       {name: 'faqtypes'},
       {name: 'default_faqstatus_id',   type: 'int'},
       {name: 'default_faqtype_id',     type: 'int'}
    ], {
    appName: 'SimpleFAQ',
    modelName: 'Settings',
    idProperty: 'id',
    titleProperty: 'title',
    recordName: 'Settings',
    recordsName: 'Settings',
    containerProperty: 'container_id',
    containerName: 'Settings',
    containersName: 'Settings',
    getTitle: function() {
        return this.recordName;
    }
});

Tine.SimpleFAQ.Model.getRandomUnusedId = function(store) {
    var result;
    do {
        result = Tine.Tinebase.common.getRandomNumber(0, 21474836);
    } while (store.getById(result) != undefined)

    return result;
};
/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine', 'Tine.SimpleFAQ');

/**
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.Application
 * @extends     Tine.Tinebase.Application
 */
Tine.SimpleFAQ.Application = Ext.extend(Tine.Tinebase.Application, {
    getTitle: function() {
        return this.i18n.gettext('FAQ');
    },
    
    findQuestion: function () {
        var app = Tine.Tinebase.appMgr.get('SimpleFAQ');
        
        var qWin = new Ext.Window({
            title: app.i18n.gettext('Find Question'),
            width: 500,
            height: 300,
            layout: 'form',
            labelAlign: 'top',
            bodyStyle: 'padding: 5px',
            modal: true,
            items: [{
                xtype: 'faqpickercombobox',
                fieldLabel: app.i18n.gettext('Search question'),
                listeners: {
                    scope: this,
                    'select': function (combo, record) {
                        if (record) {
                            qWin.get(1).get(0).setValue(record.get('answer'));
                        }
                    }
                }
            }, {
                xtype: 'fieldset',
                title: app.i18n.gettext('Answer'),
                hideLabels: true,
                bodyStyle: 'padding: 5px',
                items: [{
                    xtype: 'displayfield'
                }]
            }]
        }).show();
    }
})

/**
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.MainScreen
 * @extends     Tine.widgets.MainScreen
 *
 * The mainscreen of the SimpleFAQ App
 */
Tine.SimpleFAQ.MainScreen = Ext.extend(Tine.widgets.MainScreen, {
    activeContentType: 'Faq'
});

Tine.SimpleFAQ.FaqTreePanel = function(config) {
    Ext.apply(this, config);
    
    this.id = 'SimpleFAQTreePanel';
    this.recordClass = Tine.SimpleFAQ.Model.Faq;

    this.filterMode = 'filterToolbar';
    Tine.SimpleFAQ.FaqTreePanel.superclass.constructor.call(this);
};

Ext.extend(Tine.SimpleFAQ.FaqTreePanel , Tine.widgets.container.TreePanel);

Tine.SimpleFAQ.FaqFilterPanel = function(config) {
    Ext.apply(this, config);
    Tine.SimpleFAQ.FaqFilterPanel.superclass.constructor.call(this);
};

Ext.extend(Tine.SimpleFAQ.FaqFilterPanel, Tine.widgets.persistentfilter.PickerPanel, {
    filter: [{field: 'model', operator: 'equals', value: 'SimpleFAQ_Model_FaqFilter'}]
});

/**
 * @namespace Tine.SimpleFAQ
 * @class Tine.SimpleFAQ.faqBackend
 * @extends Tine.Tinebase.data.RecordProxy
 *
 * Faq Backend
 */
Tine.SimpleFAQ.faqBackend = new Tine.Tinebase.data.RecordProxy({
    appName: 'SimpleFAQ',
    modelName: 'Faq',
    recordClass: Tine.SimpleFAQ.Model.Faq
});

/**
 * @namespace Tine.SimpleFAQ
 * @class Tine.SimpleFAQ.settingsBackend
 * @extends Tine.Tinebase.data.RecordProxy
 *
 * Settings Backend
 */
Tine.SimpleFAQ.settingsBackend = new Tine.Tinebase.data.RecordProxy({
   appName: 'SimpleFAQ' ,
   modelName: 'Settings',
   recordClass: Tine.SimpleFAQ.Model.Settings
});/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ');

/**
 * the grid details panel
 */

Tine.SimpleFAQ.FaqGridDetailsPanel = Ext.extend(Tine.widgets.grid.DetailsPanel, {

    border: false,

    /**
     * inits this component
     */
    initComponent: function() {
        this.app = Tine.Tinebase.appMgr.get('SimpleFAQ');

        Tine.SimpleFAQ.FaqGridDetailsPanel.superclass.initComponent.call(this);
        //this.supr().initComponent.call(this);
    },

    /**
     * returns rendered tags with tag-text for grids
     *
     * @param {mixed} tags
     * @return {String} tags as colored text with qtips
     * 
     */
    tagsRenderer: function(tags) {
        var result = '';
        if (tags) {
            for (var i = 0; i < tags.length; i += 1) {
                result += '<div style="float:left; margin:3px; font: 11px arial,tahoma,helvetica,sans-serif;"><div class="tb-grid-tags" style="background-color:' + tags[i].color + ';">&#160;</div> '+ Ext.util.Format.htmlEncode(tags[i].name) +'</div>';
            }
        }
        return result;
    },
    
    htmlRenderer: function(text) {
        var result = '';
        if(text) {
            result +='<div style="float:left; margin:3px; font: 11px arial,tahoma,helvetica,sans-serif;">' + text + '</div>'
        }
        return result;
    },

     /**
     * faq status renderer
     *
     * @param   {Number} id
     * @param   {Store} store
     * @return  {String} label
     */
    dataRenderer: function(id, store, definitionsLabel) {
        record = store.getById(id);
        if (record) {
            return record.data[definitionsLabel];
        } else {
            return 'undefined';
        }
    },


    /**
     * default panel
     *
     * @return {Ext.ux.display.DisplayPanel}
     */
    getDefaultInfosPanel: function() {
        if(!this.defaultInfosPanel){
                this.defaultInfosPanel = new Ext.ux.display.DisplayPanel({
                    layout: 'fit',
                    border: false,
                        items:[{
                            layout: 'hbox',
                            border: false,
                            layoutConfig: {
                                padding: 5,
                                align:'stretch'
                            },
                            defaults:{
                                margins:'0 5 0 0'
                            },
                            items: [{
                                layout: 'ux.display',
                                width: 240,
                                layoutConfig: {
                                    background: 'solid',
                                    declaration: this.app.i18n._('FAQ Infos'),
                                    align:'stretch',
                                    padding: 5
                                }
                            },{
                                layout: 'ux.display',
                                flex: 1,
                                border: false
                            },{
                                layout: 'fit',
                                flex: 1,
                                border: false
                            }]//end of display fields
                    }]//end of main panel
                })
            }
         return this.defaultInfosPanel;
        
    },

    /**
     * single record panel
     *
     * @return {Ext.ux.display.DisplayPanel}
     */
    getSingleRecordPanel: function() {
        if(!this.singleRecordPanel)
            {
                this.singleRecordPanel = new Ext.ux.display.DisplayPanel({
                    layout: 'fit',
                    border: false,
                    items:[{
                        layout: 'vbox',
                        border: false,
                        layoutConfig: {
                            align: 'stretch'
                        },
                        items:[{
                            layout: 'hbox',
                            flex: 0,
                            height: 16,
                            border: false,
                            layoutConfig: {
                                align: 'stretch'
                            },
                            items: [{
                                width: 240,
                                xtype: 'ux.displayfield',
                                cls: 'x-ux-display-header'
                            }, {
                                flex: 1,
                                xtype: 'ux.displayfield',
                                cls: 'x-ux-display-header',
                                style: 'text-align: center;',
                                html: this.app.i18n._('Question')
                            }, {
                                flex: 1,
                                xtype: 'ux.displayfield',
                                cls: 'x-ux-display-header',
                                style: 'text-align: center;',
                                html: this.app.i18n._('Answer')
                            },{
                                width: 150,
                                xtype: 'ux.displayfield',
                                cls: 'x-ux-display-header',
                                style: 'text-align: center;',
                                html: this.app.i18n._('Tags')
                            }]//end of title hbox items
                        },{ //end of title hbox
                            layout: 'hbox',
                            flex: 1,
                            border: false,
                            layoutConfig: {
                                padding: 5,
                                align:'stretch'
                            },
                            defaults:{
                                margins:'0 5 0 0'
                            },
                            items: [{
                                layout: 'ux.display',
                                labelWidth: 85,
                                width: 240,
                                layoutConfig: {
                                    background: 'solid',
                                    declaration: this.app.i18n._('FAQ Infos'),
                                    align:'stretch',
                                    padding: 5
                                },
                                items: [{
                                    xtype: 'ux.displayfield',
                                    name: 'creation_time',
                                    fieldLabel: this.app.i18n._('Creation Time'),
                                    renderer: Tine.Tinebase.common.dateRenderer
                                },{
                                    xtype: 'ux.displayfield',
                                    name: 'created_by',
                                    fieldLabel: this.app.i18n._('Created By'),
                                    renderer: Tine.Tinebase.common.usernameRenderer
                                },{
                                    xtype: 'ux.displayfield',
                                    name: 'faqstatus_id',
                                    fieldLabel: this.app.i18n._('FAQ Status'),
                                    renderer: this.dataRenderer.createDelegate(this, [Tine.SimpleFAQ.FaqStatus.getStore(), 'faqstatus'], true)
                                },{
                                    xtype: 'ux.displayfield',
                                    name: 'faqtype_id',
                                    fieldLabel: this.app.i18n._('FAQ Type'),
                                    renderer: this.dataRenderer.createDelegate(this, [Tine.SimpleFAQ.FaqType.getStore(), 'faqtype'], true)
                                }]
                            },{
                                flex: 1,
                                layout: 'fit',
                                border: false,
                                items: [{
                                    cls: 'x-ux-display-background-border',
                                    xtype: 'ux.displayfield',
                                    name: 'question',
                                    htmlEncode: false,
                                    renderer: this.htmlRenderer
                                }]
                            },{
                                flex: 1,
                                layout: 'fit',
                                border: false,
                                items: [{
                                    cls: 'x-ux-display-background-border',
                                    xtype: 'ux.displayfield',
                                    name: 'answer',
                                    emptyText: this.app.i18n._('No answer yet'),
                                    htmlEncode: false,
                                    renderer: this.htmlRenderer
                                }]
                            },{
                                width: 150,
                                layout: 'fit',
                                border: false,
                                items: [{
                                    cls: 'x-ux-display-background-border',
                                    xtype: 'ux.displayfield',
                                    name: 'tags',
                                    htmlEncode: false,
                                    renderer: this.tagsRenderer 
                                }]
                            }]//end of display fields
                      }
                        //end of content hbox
                    ]//end of hbox
                    }]//end of main panel

                })
            }
         return this.singleRecordPanel;
    },

    /**
     * get panel for multi selection aggregates/information
     *
     * @return {Ext.Panel}
     */
    getMultiRecordsPanel: function() {
        return this.getDefaultInfosPanel();
    },

    /**
     * update lead 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 panel
     *
     * @param {Mixed} body
     */
    showDefault: function(body) {
        //this.getDefaultInfosPanel();
        //this.setPiechartStores.defer(500, this, [true]);
    },

    /**
     * show template for multiple rows
     *
     * @param {Ext.grid.RowSelectionModel} sm
     * @param {Mixed} body
     */
    showMulti: function(sm, body) {
       //this.getDefaultInfosPanel();
    }
});/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ');

/**
 * Create a new Tine.SimpleFAQ.SimpleFAQGridPanel
 */
Tine.SimpleFAQ.FaqGridPanel = Ext.extend(Tine.widgets.grid.GridPanel, {
     /**
      * record class
      * @cfg {Tine.SimpleFAQ.Model.Faq} recordClass
      */
     recordClass: Tine.SimpleFAQ.Model.Faq,

     /**
      * eval grants
      * @cfg {Boolean} evalGrants
      */
     evalGrants: true,
    
     /**
      * grid specific
      * @private
      */
     defaultSortInfo: {field: 'creation_time', direction: 'DESC'},
     gridConfig: {
         loadMask: true,
         enableDragDrop: true,
         ddGroup: 'containerDDGroup',
         autoExpandColumn: 'question'
         
     },

    /**
     * inits this cmp
     * @private
     */
    initComponent: function() {
        this.recordProxy = Tine.SimpleFAQ.faqBackend;
        this.gridConfig.cm = this.getColumnModel();
        
        this.defaultFilters = [{field: 'container_id', operator: 'equals', value: {path: Tine.Tinebase.container.getMyNodePath()}}];

        this.detailsPanel = new Tine.SimpleFAQ.FaqGridDetailsPanel({
            grid: this
        });

        Tine.SimpleFAQ.FaqGridPanel.superclass.initComponent.call(this);
    },

    /**
     * returns cm
     *
     * @return Ext.grid.ColumnModel
     * @private
     */
    getColumnModel: function() {
         return new Ext.grid.ColumnModel({
        defaults: {
            sortable: true,
            resizable: true
        },
        columns: [{
            id: 'id',
            header: this.app.i18n._('FAQ id'),
            width: 30,
            sortable: false,
            dataIndex: 'id',
            hidden: true
        },{
            id: 'tags',
            header: this.app.i18n._('Tags'),
            width: 50,
            sortable: false,
            dataIndex: 'tags',
            renderer: Tine.Tinebase.common.tagsRenderer
        },{
            id: 'faqstatus',
            header: this.app.i18n._("Status"),
            width: 30,
            dataIndex: 'faqstatus_id',
            renderer: Tine.SimpleFAQ.FaqStatus.Renderer
        },{
            id: 'faqtype',
            header: this.app.i18n._("Type"),
            width: 30,
            dataIndex: 'faqtype_id',
            renderer: Tine.SimpleFAQ.FaqType.Renderer
        },{
            id: 'question',
            header: this.app.i18n._("Question"),
            width: 150,            
            dataIndex: 'question',
            renderer: function(value){return value}
            
        },{
            id: 'answer',
            header: this.app.i18n._("Answer"),
            width: 200,
            dataIndex: 'answer',
            renderer: function(value){return value}
        }].concat(this.getModlogColumns())
       });
    },
    
     /**
     * return additional tb items
     * @private
     */ 
    getToolbarItems: function() {
        return [
        ]
    }

});
/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ');

Tine.SimpleFAQ.FaqEditDialog = Ext.extend(Tine.widgets.dialog.EditDialog, {
    /**
     * @private
     */
    windowNamePrefix: 'FaqEditWindow_',
    appName: 'SimpleFAQ',
    recordClass: Tine.SimpleFAQ.Model.Faq,
    recordProxy: Tine.SimpleFAQ.faqBackend,
    showContainerSelector: true,
    displayNotes: true,

    /**
     * overwrite update toolbars function (we don't have record grants yet)
     * @private
     */
    updateToolbars: function() {
    },

    /**
     * executed when a record ist loaded
     * @private
     */
    onRecordLoad: function() {
        if(!this.rendered) {
            this.onRecordLoad.defer(250, this);
            return;
        }

        Tine.SimpleFAQ.FaqEditDialog.superclass.onRecordLoad.apply(this, arguments);
    },

    /**
     * executed when a when a record ist updated
     * 
     */
    onRecordUpdate: function() {
        Tine.SimpleFAQ.FaqEditDialog.superclass.onRecordUpdate.apply(this, arguments);
    },

    /**
     * handling for the completed fields
     *
     */
    handlingCompletedData: function() {
        
    },

    /**
     * returns dialog
     *
     * NOTE: when this method gets called, all initalisation is done.
     *
     * @return {Object}
     * @private
     */
    getFormItems: function(){
        return {
            xtype: 'tabpanel',
            border: false,
            plain: true,
            activeTab: 0,
            defaults: {
                hideMode: 'offsets'
            },
            items:[{
                title: this.app.i18n.n_('FAQ', 'FAQs', 1),
                autoScroll: true,
                border: true,
                frame: true,
                layout: 'border',
                id: 'editCenterPanel',
                items:[{
                    region: 'center',
                    xtype: 'columnform',
                    labelAlign: 'top',
                    formDefaults: {
                        xtype:'htmleditor',
                        anchor: '100%',
                        labelSeparator: '',
                        columnWidth: .5,
                        enableFont: false,
                        enableFontSize: false,
                        enableLinks: false
                    },
                    items: [[{
                            columnWidth: 1,
                            height: 100,
                            fieldLabel: this.app.i18n._('Question'),
                            emptyText: this.app.i18n._('Enter a question...'),
                            name: 'question',
                            allowBlank: false
                        }, {
                            columnWidth: 1,
                            height: 150,
                            fieldLabel: this.app.i18n._('Answer'),
                            emptyText: this.app.i18n._('Enter a answer...'),
                            name: 'answer'
                        }], [{
                            xtype: 'combo',
                            mode: 'local',
                            triggerAction: 'all',
                            editable: false,
                            valueField:'id',
                            fieldLabel: this.app.i18n._('Type'),
                            id:'faqtype',
                            name:'faqtype_id',
                            store: Tine.SimpleFAQ.FaqType.getStore(),
                            value: Tine.SimpleFAQ.FaqType.getStore().getAt(0).id,
                            displayField:'faqtype'
                        }, {
                            xtype: 'combo',
                            mode: 'local',
                            triggerAction: 'all',
                            editable: false,
                            valueField:'id',
                            fieldLabel: this.app.i18n._('Status'),
                            id:'faqstatus',
                            name:'faqstatus_id',
                            store: Tine.SimpleFAQ.FaqStatus.getStore(),
                            value: Tine.SimpleFAQ.FaqStatus.getStore().getAt(0).id,
                            displayField:'faqstatus'
                        }]] //end of center panel items
                    }, {
                        layout: 'accordion',
                        animate: true,
                        region: 'east',
                        width: 210,
                        split: true,
                        collapsible: true,
                        collapseMode: 'mini',
                        header: false,
                        margins: '0 5 0 5',
                        border: true,
                        items: [
                            new Tine.widgets.tags.TagPanel({
                                app: 'SimpleFAQ',
                                border: false,
                                bodyStyle: 'border:1px solid #B5B8C8;'
                            })
                        ]} // end of accordion panel (east)
                ] // end of editCenterPanel
            }, new Tine.widgets.activities.ActivitiesTabPanel({
                    app: this.appName,
                    record_id: this.record.id,
                    record_model: this.appName + '_Model_' + this.recordClass.getMeta('modelName')
               })
           ] //end of main tabpanel
        }
    }
});

Tine.SimpleFAQ.FaqEditDialog.openWindow = function (config) {
    var id = (config.record && config.record.id) ? config.record.id : 0;
    var window = Tine.WindowFactory.getWindow({
        width: 700,
        height: 450,
        name: Tine.SimpleFAQ.FaqEditDialog.prototype.windowNamePrefix + id,
        contentPanelConstructor: 'Tine.SimpleFAQ.FaqEditDialog',
        contentPanelConstructorConfig: config
    });
    return window;
};
/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ');

/**
 * Create a new Tine.SimpleFAQ.AdminPanel
 */
Tine.SimpleFAQ.AdminPanel = Ext.extend(Tine.widgets.dialog.EditDialog, {

    appName: 'SimpleFAQ',
    recordClass: Tine.SimpleFAQ.Model.Settings,
    recordProxy: Tine.SimpleFAQ.settingsBackend,

    /**
     * overwrite update toolbars function (we don't have record grants yet)
     * @private
     */
    updateToolbars: function() {
        
    },

    /**
     * executed after record got updated from proxy
     *
     * @private
     */
    onRecordLoad: function() {
        if(!this.record.get('default_faqstatus_id')) {
            this.record.set('default_faqstatus_id', this.record.data.defaults.faqstatus_id);
            this.record.set('default_faqtype_id', this.record.data.defaults.faqtype_id);
        }
        if (this.fireEvent('load', this) !== false) {
            this.getForm().loadRecord(this.record);
            this.updateToolbars(this.record, this.recordClass.getMeta('containerProperty'));

            this.loadMask.hide();
        }
    },

    /**
     * executed when a record was updated from form
     *
     * @private
     */
    onRecordUpdate: function() {
        Tine.SimpleFAQ.AdminPanel.superclass.onRecordUpdate.call(this);
        var defaults = {
            faqstatus_id: this.record.get('default_faqstatus_id'),
            faqtype_id: this.record.get('default_faqtype_id')
        };

        this.record.set('defaults', defaults);

        this.record.set('faqstatuses', this.getFromStore(this.faqstatusPanel.store));
        this.record.set('faqtypes', this.getFromStore(this.faqtypePanel.store));

    },

     /**
      * get values from store (as array)
      *
      * @param {Ext.data.JsonStore} store
      * @return {Array}
      */
    getFromStore: function(store) {
        var result = [];
        store.each(function(record) {
            result.push(record.data);
        }, this);
        store.commitChanges();

        return result;
    },

    /**
     * returns dialog
     *
     * NOTE: when this method gets called, all initalisation is done
     *
     * @return {Object}
     * @private
     */
    getFormItems: function() {
        
        this.faqstatusPanel = new Tine.SimpleFAQ.FaqStatus.GridPanel({
            title: this.app.i18n._('FAQ Status')
        });
        
        this.faqtypePanel = new Tine.SimpleFAQ.FaqType.GridPanel({
            title: this.app.i18n._('FAQ Type')
        });

        return {
            xtype: 'tabpanel',
            activeTab: 0,
            border: true,
            items: [{
                title: this.app.i18n._('Defaults'),
                autoScroll: true,
                border: false,
                frame: true,
                xtype: 'columnform',
                formDefaults: {
                    xtype:'combo',
                    anchor: '90%',
                    labelSeparator: '',
                    columnWidth: 1,
                    valueField:'id',
                    typeAhead: true,
                    mode: 'local',
                    triggerAction: 'all',
                    editable: false,
                    allowBlank: false,
                    forceSelection: true
                },
                items: [[
                        {
                    fieldLabel: this.app.i18n._('FAQ Status'),
                    name:'default_faqstatus_id',
                    store: Tine.SimpleFAQ.FaqStatus.getStore(),
                    displayField:'faqstatus',
                    lazyInit: false,
                    value: Tine.SimpleFAQ.FaqStatus.getStore().getAt(0).id
                }, {
                    fieldLabel: this.app.i18n._('FAQ Type'),
                    name:'default_faqtype_id',
                    store: Tine.SimpleFAQ.FaqType.getStore(),
                    displayField:'faqtype',
                    lazyInit: false,
                    value: Tine.SimpleFAQ.FaqType.getStore().getAt(0).id
                }
            ]]
            },
                this.faqstatusPanel,
                this.faqtypePanel
            ]
        };
    }
});

/**
 * admin panel on update function
 *
 * TODO         update registry without reloading the mainscreen
 */
Tine.SimpleFAQ.AdminPanel.onUpdate = function() {
    // reload mainscreen to make sure registry gets updated
    Tine.Tinebase.common.reload();
}

/**
 * SimpleFAQ admin settings popup
 *
 * @param   {Object} config
 * @return  {Ext.ux.Window}
 */
Tine.SimpleFAQ.AdminPanel.openWindow = function (config) {
    var id = (config.record && config.record.id) ? config.record.id : 0;
    var window = Tine.WindowFactory.getWindow({
        width: 500,
        height: 400,
        name: Tine.SimpleFAQ.AdminPanel.prototype.windowNamePrefix + id,
        contentPanelConstructor: 'Tine.SimpleFAQ.AdminPanel',
        contentPanelConstructorConfig: config
    });
    return window;
};

Ext.ns('Tine.SimpleFAQ.Admin');

/**
 * @namespace   Tine.SimpleFAQ.Admin
 * @class       Tine.SimpleFAQ.Admin.QuickaddGridPanel
 * @extends     Tine.widgets.grid.QuickaddGridPanel
 *
 * admin config option quickadd grid panel
 */
Tine.SimpleFAQ.Admin.QuickaddGridPanel = Ext.extend(Tine.widgets.grid.QuickaddGridPanel, {
    /**
     * @private
     */
    initComponent: function() {
        this.app = this.app ? this.app : Tine.Tinebase.appMgr.get('SimpleFAQ');

        Tine.SimpleFAQ.Admin.QuickaddGridPanel.superclass.initComponent.call(this);
    }
});
/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ', 'Tine.SimpleFAQ.FaqStatus');

/**
 * @namespace Tine.SimpleFAQ.FaqStatus
 * @class Tine.SimpleFAQ.FaqStatus.Model
 * @extends Ext.data.Record
 *
 * faq status model
 */
Tine.SimpleFAQ.FaqStatus.Model = Tine.Tinebase.data.Record.create([
   {name: 'id', type: 'int'},
   {name: 'faqstatus'}
], {
    appName: 'SimpleFAQ',
    modelName: 'FaqStatus',
    idProperty: 'id',
    // ngettext('FAQ Status', 'FAQ Status', n);
    titleProperty: 'faqstatus',
    recordName: 'FAQ Status',
    recordsName: 'FAQ Status'
});

/**
 * @namespace Tine.SimpleFAQ.FaqStatus
 *
 * get default data for a new faqstatus
 *
 * @return {Object} default data
 * @static
 */
Tine.SimpleFAQ.FaqStatus.Model.getDefaultData = function() {
    var data = {
        id: Tine.SimpleFAQ.Model.getRandomUnusedId(Ext.StoreMgr.get('SimpleFAQFaqStatusStore'))
    };

    return data;
};

/**
 * get faq status store
 * if available, load data from FaqStatus
 *
 * @return {Ext.data.JsonStore}
 */

Tine.SimpleFAQ.FaqStatus.getStore = function() {
    var store = Ext.StoreMgr.get('SimpleFAQFaqStatusStore');
    if(!store)
        {
            store = new Ext.data.JsonStore({
                fields: Tine.SimpleFAQ.FaqStatus.Model,
                baseParams: {
                    method: 'SimpleFAQ.getFaqStatuses',
                    sort: 'FaqStatus',
                    dir: 'ASC'
                },
                root: 'results',
                totalProperty: 'totalcount',
                id: 'id',
                remoteSort: false
            });

            if(Tine.SimpleFAQ.registry.get('faqstatuses')) {
                store.loadData(Tine.SimpleFAQ.registry.get('faqstatuses'));
            }

            Ext.StoreMgr.add('SimpleFAQFaqStatusStore', store);
        }
        return store;
};

/**
 * faq status renderer
 *
 * @param   {Number} _faqstatusId
 * @return  {String} faqstatus
 */
Tine.SimpleFAQ.FaqStatus.Renderer = function(_faqstatusId) {
    store = Tine.SimpleFAQ.FaqStatus.getStore();
    record = store.getById(_faqstatusId);

    if (record) {
       return record.data.faqstatus;
    } else {
        return 'undefined';
    }
};

/**
 * @namespace   Tine.SimpleFAQ.FaqStatus
 * @class       Tine.SimpleFAQ.FaqStatus.GridPanel
 * @extends     Tine.SimpleFAQ.Admin.QuickaddGridPanel
 *
 * faq status grid panel
 */
Tine.SimpleFAQ.FaqStatus.GridPanel = Ext.extend(Tine.SimpleFAQ.Admin.QuickaddGridPanel, {
    /**
     * @private
     */
    autoExpandColumn: 'faqstatus',
    quickaddMandatory: 'faqstatus',

    /**
     * @private
     */
    initComponent: function() {
        this.app = this.app ? this.app : Tine.Tinebase.appMgr.get('SimpleFAQ');

        this.store = Tine.SimpleFAQ.FaqStatus.getStore();
        this.recordClass = Tine.SimpleFAQ.FaqStatus.Model;

        Tine.SimpleFAQ.FaqStatus.GridPanel.superclass.initComponent.call(this);
    },

    getColumnModel: function() {
        return new Ext.grid.ColumnModel([
        {
            id: 'faqstatus_id',
            header: 'Id',
            dataIndex: 'id',
            width: 20,
            hidden: true
        }, {
            id: 'faqstatus',
            header: 'Status',
            dataIndex: 'faqstatus',
            width: 150,
            hideable: false,
            sortable: false,
            editor: new Ext.form.TextField({allowBlank: false}),
            quickaddField: new Ext.form.TextField({
                emptyText: this.app.i18n._('Add a new FAQ Status...')
            })
        }]);
    }
});/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ');

/**
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.FaqStatusFilterModel
 * @extends     Tine.widgets.grid.FilterModel
 *
 */
Tine.SimpleFAQ.FaqStatusFilterModel = Ext.extend(Tine.widgets.grid.FilterModel, {
   
   field: 'faqstatus_id',
   defaultOperator: 'in',

   /**
    * @private
    */
   initComponent: function() {
       this.label = this.app.i18n._('FAQ Status');
       this.operators = ['in', 'notin'];

       //@todo pr: add this.defaultValue ....
       
       Tine.SimpleFAQ.FaqStatusFilterModel.superclass.initComponent.call(this);
   },

   /**
    * value renderer
    *
    * @param {Ext.data.Record} filter line
    * @param {Ext.Element} element to render to
    */
   valueRenderer: function(filter, el){
       var value = new Tine.SimpleFAQ.FaqStatusFilterModelValueField({
           app: this.app,
           filter: filter,
           width: 180,
           id: 'tw-ftb-frow-valuefield-' + filter.id,
           //@todo pr: add default value
           //value: filter.data.value ? filter.data.value : this.defaultValue,
           value: filter.data.value,
           renderTo: el
       });
       value.on('specialkey', function(field, e){
             if(e.getKey() == e.ENTER){
                 this.onFiltertrigger();
             }
        }, this);
        value.on('select', this.onFiltertrigger, this);

        return value;
   }
});

Tine.widgets.grid.FilterToolbar.FILTERS['simplefaq.faqstatus'] = Tine.SimpleFAQ.FaqStatusFilterModel;

/**
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.FaqStatusFilterModelValueField
 * @extends     Ext.ux.form.LayerCombo
 * 
 */
Tine.SimpleFAQ.FaqStatusFilterModelValueField = Ext.extend(Ext.ux.form.LayerCombo, {
   hideButtons: false,
   formConfig: {
       labelAlign: 'left',
       labelWidth: 30
   },
   
   getFormValue: function(){
       var ids = [];
       var statusStore = Tine.SimpleFAQ.FaqStatus.getStore();

       var formValues = this.getInnerForm().getForm().getValues();
       for (var id in formValues){
           if(formValues[id] === 'on' && statusStore.getById(id)){
               ids.push(id);
           }
       }

       return ids;
   },

   getItems: function(){
       var items = [];

       Tine.SimpleFAQ.FaqStatus.getStore().each(function(status){
           items.push({
               xtype: 'checkbox',
               boxLabel: status.get('faqstatus'),
               icon: status.get('status_icon'),
               name: status.get('id')
           });
       }, this);

       return items;
   },

   /**
    * @param {String} value
    * @return {Ext.form.Field} this
    */
   setValue: function(value) {
       value = Ext.isArray(value) ? value : [value];
       
       var statusText = [];
       this.currentValue = [];

       Tine.SimpleFAQ.FaqStatus.getStore().each(function(status){
           var id = status.get('id');
           var name = status.get('faqstatus');

           Ext.each(value, function(valueId){
               if(valueId == id) {
                   statusText.push(name);
                   this.currentValue.push(id);
               }
           }, this);
       }, this);

       this.setRawValue(statusText.join(', '));

       return this;
   },

    /**
     * sets values to innerForm
     */
   setFormValue: function(value) {
        this.getInnerForm().getForm().items.each(function(item) {
            item.setValue(value.indexOf(item.name) >= 0 ? 'on' : 'off');
        }, this);
    }
});/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ', 'Tine.SimpleFAQ.FaqType');

/**
 * @namespace Tine.SimpleFAQ.FaqType
 * @class Tine.SimpleFAQ.FaqType.Model
 * @extends Ext.data.Record
 *
 * faq type model
 */
Tine.SimpleFAQ.FaqType.Model = Tine.Tinebase.data.Record.create([
   {name: 'id', type: 'int'},
   {name: 'faqtype'}
], {
    appName: 'SimpleFAQ',
    modelName: 'FaqType',
    idProperty: 'id',
    // ngettext('FAQ Type', 'FAQ Types', n);
    titleProperty: 'faqtype',
    recordName: 'FAQ Type',
    recordsName: 'FAQ Type'
});

/**
 * @namespace Tine.SimpleFAQ.FaqType
 *
 * get default data for a new faqtype
 *
 * @return {Object} default data
 * @static
 */
Tine.SimpleFAQ.FaqType.Model.getDefaultData = function() {

    var data = {
        id: Tine.SimpleFAQ.Model.getRandomUnusedId(Ext.StoreMgr.get('SimpleFAQFaqTypeStore'))
    };

    return data;
};

/**
 * get faq type store
 * if available, load data from FaqType
 *
 * @return {Ext.data.JsonStore}
 */

Tine.SimpleFAQ.FaqType.getStore = function() {

    var store = Ext.StoreMgr.get('SimpleFAQFaqTypeStore');
    if(!store)
        {
            store = new Ext.data.JsonStore({
                fields: Tine.SimpleFAQ.FaqType.Model,
                baseParams: {
                    method: 'SimpleFAQ.getFaqTypes',
                    sort: 'FaqType',
                    dir: 'ASC'
                },
                root: 'results',
                totalProperty: 'totalcount',
                id: 'id',
                remoteSort: false
            });

            if(Tine.SimpleFAQ.registry.get('faqtypes')) {
                store.loadData(Tine.SimpleFAQ.registry.get('faqtypes'));
            }

            Ext.StoreMgr.add('SimpleFAQFaqTypeStore', store);
        }
        return store;
};

/**
 * faq type renderer
 *
 * @param   {Number} _faqtypeId
 * @return  {String} faqtype
 */
Tine.SimpleFAQ.FaqType.Renderer = function(_faqtypeId) {
    store = Tine.SimpleFAQ.FaqType.getStore();
    record = store.getById(_faqtypeId);

    if (record) {
        return record.data.faqtype;
    } else {
            return 'undefined';
    }
};

/**
 * @namespace   Tine.SimpleFAQ.FaqType
 * @class       Tine.SimpleFAQ.FaqType.GridPanel
 * @extends     Tine.SimpleFAQ.Admin.QuickaddGridPanel
 *
 * faq type grid panel
 */
Tine.SimpleFAQ.FaqType.GridPanel = Ext.extend(Tine.SimpleFAQ.Admin.QuickaddGridPanel, {

    /**
     * @private
     */
    autoExpandColumn: 'faqtype',
    quickaddMandatory: 'faqtype',

    /**
     * @private
     */
    initComponent: function() {
        this.app = this.app ? this.app : Tine.Tinebase.appMgr.get('SimpleFAQ');

        this.store = Tine.SimpleFAQ.FaqType.getStore();
        this.recordClass = Tine.SimpleFAQ.FaqType.Model;

        Tine.SimpleFAQ.FaqType.GridPanel.superclass.initComponent.call(this);
    },

    getColumnModel: function() {
        return new Ext.grid.ColumnModel([
        {
            id: 'faqtype_id',
            header: 'Id',
            dataIndex: 'id',
            width: 20,
            hidden: true
        }, {
            id: 'faqtype',
            header: 'Type',
            dataIndex: 'faqtype',
            width: 150,
            hideable: false,
            sortable: false,
            editor: new Ext.form.TextField({allowBlank: false}),
            quickaddField: new Ext.form.TextField({
                emptyText: this.app.i18n._('Add a new FAQ Type...')
            })
        }]);
    }
});/**
 * Tine 2.0
 * 
 * @package     SimpleFAQ
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Patrick Ryser <patrick.ryser@gmail.com>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (http://www.metaways.de)
 */

Ext.ns('Tine.SimpleFAQ');

/**
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.FaqTypeFilterModel
 * @extends     Tine.widgets.grid.FilterModel
 *
 */
Tine.SimpleFAQ.FaqTypeFilterModel = Ext.extend(Tine.widgets.grid.FilterModel, {
   
   field: 'faqtype_id',
   defaultOperator: 'in',

   /**
    * @private
    */
   initComponent: function() {
       this.label = this.app.i18n._('FAQ Type');
       this.operators = ['in', 'notin'];

       //@todo pr: add this.defaultValue ....
       
       Tine.SimpleFAQ.FaqTypeFilterModel.superclass.initComponent.call(this);
   },

   /**
    * value renderer
    *
    * @param {Ext.data.Record} filter line
    * @param {Ext.Element} element to render to
    */
   valueRenderer: function(filter, el){
       var value = new Tine.SimpleFAQ.FaqTypeFilterModelValueField({
           app: this.app,
           filter: filter,
           width: 180,
           id: 'tw-ftb-frow-valuefield-' + filter.id,
           //@todo pr: add default value
           //value: filter.data.value ? filter.data.value : this.defaultValue,
           value: filter.data.value,
           renderTo: el
       });
       value.on('specialkey', function(field, e){
             if(e.getKey() == e.ENTER){
                 this.onFiltertrigger();
             }
        }, this);
        value.on('select', this.onFiltertrigger, this);

        return value;
   }
});

Tine.widgets.grid.FilterToolbar.FILTERS['simplefaq.faqtype'] = Tine.SimpleFAQ.FaqTypeFilterModel;

/**
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.FaqTypeFilterModelValueField
 * @extends     Ext.ux.form.LayerCombo
 * 
 */
Tine.SimpleFAQ.FaqTypeFilterModelValueField = Ext.extend(Ext.ux.form.LayerCombo, {
   hideButtons: false,
   formConfig: {
       labelAlign: 'left',
       labelWidth: 30
   },
   
   getFormValue: function(){
       var ids = [];
       var typeStore = Tine.SimpleFAQ.FaqType.getStore();

       var formValues = this.getInnerForm().getForm().getValues();
       for (var id in formValues){
           if(formValues[id] === 'on' && typeStore.getById(id)){
               ids.push(id);
           }
       }
       
       return ids;
   },

   getItems: function(){
       var items = [];

       Tine.SimpleFAQ.FaqType.getStore().each(function(type){
           items.push({
               xtype: 'checkbox',
               boxLabel: type.get('faqtype'),
               icon: type.get('type_icon'),
               name: type.get('id')
           });
       }, this);
       
       return items;
   },

   /**
    * @param {String} value
    * @return {Ext.form.Field} this
    */
   setValue: function(value) {
       value = Ext.isArray(value) ? value : [value];
       
       var typeText = [];
       this.currentValue = [];

       Tine.SimpleFAQ.FaqType.getStore().each(function(type){
           var id = type.get('id');
           var name = type.get('faqtype');

           Ext.each(value, function(valueId){
               if(valueId == id) {
                   typeText.push(name);
                   this.currentValue.push(id);
               }
           }, this);
       }, this);

       this.setRawValue(typeText.join(', '));

       return this;
   },

   /**
    * sets values to innerForm
    */
   setFormValue: function(value) {
        this.getInnerForm().getForm().items.each(function(item) {
            item.setValue(value.indexOf(item.name) >= 0 ? 'on' : 'off');
        }, this);
    }

});/*global Ext, Tine*/
Ext.ns('Tine.SimpleFAQ');
/**
 Tine.SimpleFAQ.SearchCombo use for search without switch to SimpleFAQ modul
 Example usage:
 this.actions_searchFAQ = new Ext.Action({
     requiredGrant: 'readGrant',
     text: this.app.i18n._('Search FAQ'),
     disabled: false,
     handler: Tine.Tinebase.appMgr.get('SimpleFAQ').findQuestion,
     iconCls: '.x-btn-large SimpleFAQIconCls',
     scope: this
 });
 */
/**
 * Lead selection combo box
 * 
 * @namespace   Tine.SimpleFAQ
 * @class       Tine.SimpleFAQ.SearchCombo
 * @extends     Tine.Tinebase.widgets.form.RecordPickerComboBox
 * 
 * @param       {Object} config
 * @constructor Create a new Tine.SimpleFAQ.SearchCombo
 */
Tine.SimpleFAQ.SearchCombo = Ext.extend(Tine.Tinebase.widgets.form.RecordPickerComboBox, {
    /**
     * @cfg
     */
    allowBlank: false,
    itemSelector: 'div.search-item',
    minListWidth: 650,
    resizable: true,
    
    //private
    initComponent: function () {
        this.recordClass = Tine.SimpleFAQ.Model.Faq;
        
        this.initTemplate();
        
        Tine.SimpleFAQ.SearchCombo.superclass.initComponent.call(this);
    },
    
    /**
     * init template
     * @private
     */
    initTemplate: function () {
        if (! this.tpl) {
            this.tpl = new Ext.XTemplate(
                '<tpl for="."><div class="search-item">',
                    '<table cellspacing="0" cellpadding="2" border="0" style="font-size: 11px;" width="100%">',
                        '<tr>',
                            '<td valign="top" width="100%">{[this.encode(values.question)]}</td>',
                        '</tr>',
                    '</table>',
                '</div></tpl>', {
                    encode: function (value) {
                        return Ext.util.Format.htmlEncode(value);
                    }
                }
            );
        }
    }
});

Ext.reg('faqpickercombobox', Tine.SimpleFAQ.SearchCombo);
Tine.widgets.form.RecordPickerManager.register('SimpleFAQ', 'Faq', 'faqpickercombobox');