Ext.define('TP.ComboBoxSum', {
    extend: 'Ext.form.field.ComboBox',

    alias:  'widget.tp_combobox_sum',

    multiSelect:    true,
    queryMode:      'local',
    editable:       false,
    triggerAction:  'all',
    listConfig : {
        getInnerTpl: function(displayField) {
            return '<div class="x-combo-list-item"><img src="' + Ext.BLANK_IMAGE_URL + '" class="chkCombo-default-icon chkCombo" /> {'+displayField+'} <\/div>';
        }
    },
    listeners: {
        'afterrender': function(This, eOpts) {
            if(!This.columns) { return };
            This.getPicker().addListener('beforerender', function(This, eOpts) {
                This.minWidth = 380;
            });
            This.getPicker().addListener('show', function(This, eOpts) {
                var lis = Ext.DomQuery.select('li', This.getEl().dom);
                for(var nr in lis) {
                    var el = Ext.get(lis[nr]);
                    if(nr%2==0) {
                        el.addCls('picker_even');
                    } else {
                        el.addCls('picker_odd');
                    }
                }
            });
        }
    },

    initComponent: function() {
        /* make it possible to set some special display values through
         * sum_values: { '0': 'All' }
         */
        this._getDisplayValue = this.getDisplayValue;
        this.getDisplayValue = function() {
            if(this.sum_values == undefined) {
                return this._getDisplayValue();
            }
            var sum = 0;
            for(var nr in this.displayTplData) {
                sum += this.displayTplData[nr].field1;
            }
            if(this.sum_values[''+sum] != undefined) {
                return this.sum_values[''+sum];
            }
            return this._getDisplayValue();
        };
        this.callParent();
    }
});

// http://www.sencha.com/forum/showthread.php?22661-new-version-DateTime-Field/page83
Ext.define('Ext.ux.form.field.DateTime', {
    extend:'Ext.form.FieldContainer',
    mixins: {
        field: 'Ext.form.field.Field'
    },
    alias: 'widget.datetimefield',
    layout: 'fit',
    timePosition:'right', // valid values:'below', 'right'
    dateCfg:{},
    timeCfg:{},
    allowBlank: true,

    initComponent: function() {
        var me = this;
        me.buildField();
        me.callParent();
        this.dateField = this.down('datefield');
        this.timeField = this.down('timefield');
        me.initField();
    },

    //@private
    buildField: function() {
        var l;
        var d = {};
        if (this.timePosition == 'below') {
            l = {type: 'anchor'};
            d = {anchor: '100%'};
        } else
            l = {type: 'hbox', align: 'middle'};
        this.items = {
            xtype: 'container',
            layout: l,
            defaults: d,
            items: [Ext.apply({
                xtype:      'datefield',
                format:     'Y-m-d',
                width:       this.timePosition != 'below' ? 100 : undefined,
                allowBlank:  this.allowBlank,
                listeners: {
                    specialkey: this.onSpecialKey,
                    scope: this
                },
                isFormField: false // prevent submission
            }, this.dateCfg), Ext.apply({
                xtype:        'timefield',
                format:       'H:i',
                submitFormat: 'H:i:s',
                margin:        this.timePosition != 'below' ? '0 0 0 3' : 0,
                width:         this.timePosition != 'below' ? 80 : undefined,
                allowBlank:    this.allowBlank,
                listeners: {
                    specialkey: this.onSpecialKey,
                    scope: this
                },
                isFormField: false // prevent submission
            }, this.timeCfg)]
        };
    },

    focus: function() {
        this.callParent();
        this.dateField.focus(false, 100);
    },

    // Handle tab events
    onSpecialKey:function(cmp, e) {
        var key = e.getKey();
        if (key === e.TAB) {
            if (cmp == this.dateField) {
                // fire event in container if we are getting out of focus from datefield
                if (e.shiftKey) {
                    this.fireEvent('specialkey', this, e);
                }
            }
            if (cmp == this.timeField) {
                if (!e.shiftKey) {
                    this.fireEvent('specialkey', this, e);
                }
            }
        } else if (this.inEditor) {
            this.fireEvent('specialkey', this, e);
        }
    },

    getValue: function() {
        var value, date = this.dateField.getSubmitValue(), time = this.timeField.getSubmitValue();
        if (date) {
            if (time) {
                var format = this.getFormat();
                value = Ext.Date.parse(date + ' ' + time, format);
            } else {
                value = this.dateField.getValue();
            }
        }
        return value
    },

    setValue: function(value) {
        this.dateField.setValue(value);
        this.timeField.setValue(value);
    },

    getSubmitData: function() {
        var value = this.getValue();
        var format = this.getFormat();
        var v = {};
        v[this.name] = value ? Ext.Date.format(value, format) : null;
        return v;
    },

    getFormat: function() {
        return (this.dateField.submitFormat || this.dateField.format) + " " + (this.timeField.submitFormat || this.timeField.format)
    },

    getErrors: function() {
        return this.dateField.getErrors().concat(this.timeField.getErrors());
    },

    validate: function() {
        if (this.disabled)
            return true;
        else {
            var isDateValid = this.dateField.validate();
            var isTimeValid = this.timeField.validate();
            return isDateValid && isTimeValid;
        }
    },

    reset: function() {
        this.mixins.field.reset();
        this.dateField.reset();
        this.timeField.reset();
    }
});


Ext.define('TP.PagingToolbar', {
    extend:'Ext.toolbar.Paging',

    dock:       'bottom',
    displayInfo: true,
    getPageData: function() {
        var panel  = this.up('panel').up('panel');
        var data   = {
            total:          parseInt(panel.xdata.totalCount),
            currentPage:    parseInt(panel.xdata.currentPage),
            pageCount:      Math.ceil(panel.xdata.totalCount / panel.xdata.pageSize),
            fromRecord:     ((panel.xdata.currentPage - 1) * panel.xdata.pageSize),
            toRecord:       Math.min(panel.xdata.currentPage * panel.xdata.pageSize, panel.xdata.totalCount)
        };
        return(data);
    },
    updateInfo : function(){
        var me = this,
            displayItem = me.child('#displayItem'),
            pageData = me.getPageData(),
            count, msg;
        if (displayItem) {
            msg = Ext.String.format(
                me.displayMsg,
                (pageData.fromRecord+1),
                pageData.toRecord,
                pageData.total
            );
            displayItem.setText(msg);
            me.doComponentLayout();
        }
    },
    onLoad : function(){
        var me = this,
            pageData,
            currPage,
            pageCount,
            afterText;

        if (!me.rendered) {
            return;
        }

        pageData  = me.getPageData();
        currPage  = pageData.currentPage;
        pageCount = pageData.pageCount;
        afterText = Ext.String.format(me.afterPageText, isNaN(pageCount) ? 1 : pageCount);
        me.child('#afterTextItem').setText(afterText);
        me.child('#inputItem').setValue(currPage);
        me.child('#first').setDisabled(currPage === 1);
        me.child('#prev').setDisabled(currPage === 1);
        me.child('#next').setDisabled(currPage === pageCount);
        me.child('#last').setDisabled(currPage === pageCount);
        me.child('#refresh').enable();
        me.updateInfo();
        me.fireEvent('change', me, pageData);
    },
    updateData: function(data) {
        var panel = this.up('panel').up('panel');
        panel.xdata.totalCount  = data.totalCount;
        panel.xdata.currentPage = data.currentPage;
    },
    moveNext: function() {
        var panel = this.up('panel').up('panel');
        panel.xdata.currentPage++;
        panel.refreshHandler();
    },
    moveLast: function() {
        var panel = this.up('panel').up('panel');
        var pageData = this.getPageData();
        panel.xdata.currentPage = pageData.pageCount;
        panel.refreshHandler();
    },
    moveFirst: function() {
        var panel = this.up('panel').up('panel');
        panel.xdata.currentPage = 1;
        panel.refreshHandler();
    },
    movePrevious: function() {
        var panel = this.up('panel').up('panel');
        panel.xdata.currentPage--;
        panel.refreshHandler();
    }
});


TP.Msg = function() {
    var msgCt;

    function createBox(cls, title, s){
        return '<div class="msg '+cls+'"><a class="x-tab-close-btn" title="" href="#"><\/a><h3>' + title + '<\/h3><p>' + s + '<\/p><\/div>';
    }
    return {
        msg : function(s) {
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            var p = s.split('~~', 2);
            var title = 'Success';
            if(p[0] == 'fail_message') {
                title = 'Error';
            }
            var m = Ext.DomHelper.append(msgCt, createBox(p[0], title, p[1]), true);
            var btn = new Ext.Element(m.dom.firstChild);
            btn.on("click", function() {
                m.ghost("t", { remove: true});
            });
            m.show();
            m.hide();
            m.slideIn('t');
            if(p[0] == 'fail_message') {
                debug(title + ': ' + p[1]);
                delay = 30000;
            } else {
                delay = 3000;
            }
            window.setTimeout( function() { if(m && m.dom) { m.ghost("t", { remove: true}) }}, delay );
        }
    };
}();
