Ext.define('TP.PanletGrid', {
    extend: 'TP.Panlet',

    title:  'grid',
    width:   640,
    height:  260,
    initComponent: function() {
        this.callParent();
        this.xdata.pageSize    = 5;
        this.xdata.currentPage = 1;
        this.xdata.totalCount  = 1;

        this.loader = {
            autoLoad: false,
            renderer: 'data',
            scope:    this,
            url:      '',
            ajaxOptions: { method: 'POST' },
            loading:  false,
            listeners: {
                'beforeload': function(This, options, eOpts) {
                    if(this.loading) {
                        return false;
                    }
                    this.loading = true;
                    return true;
                }
            },
            callback: function(This, success, response, options) {
                This.loading = false;
                var data = TP.getResponse(this, response);
                if(data) {
                    var b    = Ext.get(this.grid.id+"-body");
                    var body;
                    if(b) { body = b.dom.firstChild }
                    if(data.paging) {
                        this.pagingToolbar.show();
                        this.pagingToolbar.items.getAt(9).hide();  // hide seperator
                        this.pagingToolbar.items.getAt(10).hide(); // hide refresh
                        this.pagingToolbar.updateData(data);
                        if(body) {
                            body.style.overflow  = 'inherit';
                            body.style.overflowY = 'hidden';
                        }
                    } else {
                        this.pagingToolbar.hide();
                        if(body) {
                            body.style.overflowY = 'inherit';
                            body.style.overflow  = 'auto';
                        }
                    }
                    var fields = [];
                    var newcolumns = Ext.JSON.encode(data.columns);
                    for(key in data.columns) {
                        fields.push(data.columns[key].dataIndex);
                        for(key2 in data.columns[key]) {
                            /* this is usually a function, so eval it */
                            if(key2 == 'renderer') {
                                eval('data.columns[key][key2]=' + data.columns[key][key2]);
                            }
                        }
                    }
                    this.gridStore = Ext.create('Ext.data.Store', {
                        data:  {'items': data.data },
                        fields: fields,
                        pageSize: this.xdata.pageSize,
                        proxy: {
                            type: 'memory',
                            reader: {
                                type: 'json',
                                root: 'items'
                            }
                        },
                        groupField: data.group
                    });
                    if(this.gridcolumns == undefined || this.gridcolumns != newcolumns) {
                        this.gridcolumns = newcolumns;
                        this.grid.reconfigure(this.gridStore, data.columns);
                    } else {
                        this.grid.reconfigure(this.gridStore);
                    }
                    if(this.xdata.gridstate != undefined) {
                        this.grid.applyState(this.xdata.gridstate);
                    }
                    if(this.initialState != undefined) {
                        /* applyState throws internal error but state gets applied anyway */
                        try {
                            this.grid.applyState(this.initialState);
                        } catch(e) {}
                    }
                    this.pagingToolbar.onLoad();
                    if(data.paging && this.pagingToolbar.getPageData().pageCount == 1) {
                        this.pagingToolbar.hide();
                    }
                }
            }
        };

        var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
            groupHeaderTpl: '{name}'
        });

        this.pagingToolbar = new TP.PagingToolbar();

        this.grid = Ext.create('Ext.grid.Panel', {
            store:        this.gridStore,
            features:    [groupingFeature],
            id:           this.id + '_gridpanel',
            cls:          this.$className.replace('.', '_'),
            stateful:     true,
            stateEvents: ['reconfigure', 'afterlayout', 'columnmove', 'columnresize', 'sortchange', 'groupchange'],
            listeners: {
                beforestatesave: function(This, state, eOpts) {
                    /* only save filled grids state */
                    if(This.columns.length == 0) {
                        return false;
                    }
                    var panlet = This.up('panel');
                    panlet.xdata.gridstate = state;
                    panlet.saveState();
                    return false;
                },
                resize: function(This, adjWidth, adjHeight, eOpts) {
                    this.adjustPageSize();
                },
                beforeselect: function(This, record, index, eOpts) {
                    /* prevent selections */
                    return false;
                }
            },
            adjustPageSize: function() {
                var panlet      = this.up('panel');
                var bodySize    = Ext.get(panlet.id + '_gridpanel-body').getSize();
                if(bodySize.height > 2) {
                    panlet.xdata.pageSize = Math.floor(bodySize.height / 25.5);
                    if(panlet.xdata.pageSize <= 0) { panlet.xdata.pageSize = 1; }
                }
                panlet.refreshHandler();
            },
            columns: [],
            dockedItems: [this.pagingToolbar]
        });
        this.addListener('beforestaterestore', function(This, state, eOpts) {
            if(state.xdata.gridstate != undefined) {
                This.grid.applyState(state.xdata.gridstate);
            }
            return true;
        });
        var state = cp.get(this.id);
        if(state && state.xdata && state.xdata.gridstate) {
            this.initialState = Ext.JSON.decode(Ext.JSON.encode(state.xdata.gridstate));
        }

        this.add(this.grid);

        this.refreshHandler = function() {
            TP.defaultSiteRefreshHandler(this);
        };
        this.addListener('afterrender', function() {
            this.grid.adjustPageSize();
        });

        this.down('form').add({
            fieldLabel: 'URL',
            xtype:      'textfield',
            name:       'url'
        });
    }
});
