Ext.define('TP.Panlet', {
    extend: 'Ext.window.Window',

    x:         0,
    y:         25,
    height:    200,
    width:     400,
    layout:    'fit',
    constrain: true,
    hideMode:  'visibility',
    autoShow:  true,
    stateful:  true,
    resizable: new Ext.Panel({   // make resize snap to grid
        widthIncrement:  TP.snap_x,
        heightIncrement: TP.snap_y
    }),
    initComponent: function() {
        if(this.xdata == undefined) {
            this.xdata = {};
        } else {
            this.xdata = TP.clone(this.xdata);
        }
        this.xdata.refresh  = -1;
        this.xdata.cls      = this.$className;
        this.xdata.pinned   = false;
        this.xdata.backends = [];

        this.gearHandler = function() {
            if(this.gearitem.isHidden()) {
                this.items.getAt(0).hide();
                if(this.gearInitCallback) {
                    this.gearInitCallback(this);
                }
                this.gearitem.down('form').getForm().reset();
                this.gearitem.show();
            } else {
                this.items.getAt(0).show();
                this.gearitem.hide();
            }
        };
        this.tools = [{
            type: 'pin',
            cls: 'pintool',
            handler: function() {
                if(this.xdata.pinned) {
                    this.xdata.pinned = false;
                    /* make sure panelet is now connected to the active tab */
                    this.removeWindowFromPanels();
                    var tabpan = Ext.getCmp('tabpan');
                    tabpan.getActiveTab().window_ids.push(this.id);
                    tabpan.saveState();
                } else {
                    this.xdata.pinned = true;
                }
                this.check_pintool();
            },
            listeners: { afterrender: function() { this.up('panel').pintool = this; }},
            scope: this,
            tooltip: 'make this panlet sticky'
        }];
        if(this.has_search_button != undefined) {
            var This = this;
            this.tools.push({
                type: 'search',
                scope: this,
                tooltip: 'change search filter',
                handler: function() { TP.filterWindow(this.has_search_button, {setValue: function(v) { This.xdata.filter = v; This.refreshHandler() }, getValue: function() { return This.xdata.filter }}); }
            });
        }
        this.tools.push(new Ext.panel.Tool({
            type:    'refresh',
            scope:    this,
            tooltip: 'reload content of this panlet',
            handler:  function() { this.manualRefresh() }
        }));
        this.tools.push({
            type: 'gear',
            scope: this,
            tooltip: 'settings',
            handler: function() { this.gearHandler() }
        });
        this.shadow_id = this.id + '_shadow';
        this.win_shadow = new Ext.create('Ext.Layer', {
            shadow: 'drop',
            id:      this.shadow_id,
            cls:    'window_drop_shadow'
        });
        this.callParent();
        this.gearitem = this.items.getAt(0);

        this.addListener('afterlayout', function() { this.check_pintool(); });
    },
    items: [{
        /* Panlet Settings Panel */
        xtype : 'panel',
        layout: 'fit',
        hidden: true,
        border: 0,
        items: [{
                xtype:           'form',
                bodyPadding:     2,
                border:          0,
                bodyStyle:       'overflow-y: auto;',
                submitEmptyText: false,
                defaults: {
                    anchor: '-12'
                },
                items: [{
                    fieldLabel: 'Title',
                    xtype:      'textfield',
                    name:       'title'
                }, {
                    xtype:      'tp_slider',
                    formConf: {
                        fieldLabel: 'Refresh Rate',
                        value:      60,
                        nameS:      'refresh',
                        nameL:      'refresh_txt'
                    }
                }, {
                    fieldLabel: 'Backends / Sites',
                    xtype:      'combobox',
                    emptyText : 'global settings',
                    name:       'backends',
                    multiSelect: true,
                    queryMode:  'local',
                    valueField: 'key',
                    displayField: 'text',
                    editable:   false,
                    triggerAction: 'all',
                    store:      TP.getBackendsArray(initial_backends),
                    listConfig : {
                        getInnerTpl: function(displayField) {
                            return '<div class="x-combo-list-item"><img src="' + Ext.BLANK_IMAGE_URL + '" class="chkCombo-default-icon chkCombo" /> {'+displayField+'} <\/div>';
                        }
                    }
                }]
        }],
        buttonAlign: 'center',
        fbar: [{ xtype : 'button', text: 'cancel', handler: function() { this.up('window').gearitem.hide() } },
               /* panlet setting save button */
               { xtype : 'button',
                 text:   'save',
                 handler: function() {
                    var win      = this.up('window');
                    var form     = win.gearitem.down('form').getForm();
                    if(form.isValid()) {
                        win.gearitem.hide();
                        win.xdata = TP.storeFormToData(form, win.xdata);
                        win.setTitle(win.xdata.title);
                        win.setFormDefaults();
                        win.startInterval();
                        win.saveState();
                        win.manualRefresh();
                    }
                 }
               },
        ]
    }],
    html:       '',
    onEsc:      function() { return false; },
    startInterval: function() {
        window.clearInterval(this.interval);
        var refresh = this.xdata.refresh;
        if(this.xdata.refresh == -1) {
            var tab = Ext.getCmp('tabpan');
            refresh = tab.xdata.refresh;
        }
        if(refresh > 0) {
            this.interval = window.setInterval(Ext.bind(this.refreshHandler, this, []), refresh * 1000);
        }
    },
    dd_overriden: false,
    getState: function() {
        var state = this.callParent(arguments);
        state.title = this.title;
        state.xdata = this.xdata;
        return state;
    },
    applyState: function(state) {
        this.callParent(arguments);
        if(state) {
            this.xdata = state.xdata;
            this.setTitle(state.title);
        }
    },
    listeners:  {
        /* make shadow snap to grid */
        move: function( This, x, y, eOpts ) {
            var newpos = TP.get_snap(x, y);
            if(newpos[0] != x || newpos[1] != y) {
                This.setPosition( newpos[0], newpos[1], false );
            }
            var shadow = Ext.get(This.id + '_shadow');
            if(shadow != undefined) { shadow.hide(); }
        },
        destroy: function( This, eOpts ) {
            /* remove shadow */
            This.win_shadow.destroy();

            /* remove window from panels window ids */
            this.removeWindowFromPanels();

            /* stop refreshing */
            window.clearInterval(this.interval);
            /* clear state information */
            cp.clear(this.id);
        },
        show: function(This, eOpts) {
            // make move show snap shadow
            if(This.dd_overriden == false) {
                This.dd.onDrag = function(e){
                    // original onDrag function
                    var me = this,
                    comp   = (me.proxy && !me.comp.liveDrag) ? me.proxy : me.comp,
                    offset = me.getOffset(me.constrain || me.constrainDelegate ? 'dragTarget' : null);
                    var x = me.startPosition[0] + offset[0];
                    var y = me.startPosition[1] + offset[1];
                    comp.setPagePosition(x, y);
                    // show shadow
                    var newpos = TP.get_snap(x, y);
                    This.win_shadow.moveTo(newpos[0], newpos[1]);
                    This.win_shadow.setSize(This.getSize());
                    This.win_shadow.show();
                    This.win_shadow.setZIndex(100000);
                };
                This.dd_overriden = true;
            }
        },
        render: function(This, eOpts) {
            /* make title editable */
            var head = Ext.get(This.id + '_header_hd');
            head.on("dblclick", function() {
                Ext.Msg.prompt('Change Title', '', function(btn, text) {
                    if(btn == 'ok') {
                        This.setTitle(text);
                        This.setFormDefaults();
                        This.saveState();
                    }
                }, undefined, undefined, This.title);
            });
            /* make header show on mouseover only */
            var div    = This.getEl();
            var global = Ext.getCmp('tabpan');
            div.on("mouseout", function()  { if(global.xdata.autohideheader) { This.header.hide() }});
            div.on("mouseover", function() { This.header.show() });
        },
        afterrender: function(This, eOpts) {
            /* set initial form values */
            this.setFormDefaults();

            /* start refresh interval */
            this.startInterval();

            /* show all pinned panlets */
            if(this.xdata.pinned) {
                this.show();
            }
            var global = Ext.getCmp('tabpan');
            if(global.xdata.autohideheader) { this.header.hide() }
        }
    },
    setFormDefaults: function() {
        /* set initial form values */
        this.xdata['title'] = this.title;
        TP.applyFormValues(this.gearitem.down('form').getForm(), this.xdata);
        delete this.xdata['title'];
        if(this.formUpdatedCallback) {
            this.formUpdatedCallback(this);
        }
        this.check_pintool();
    },
    check_pintool: function() {
        /* check pin icon and position */
        if(this.xdata.pinned) {
            this.pintool.setType('unpin');
        } else {
            this.pintool.setType('pin');
        }
        /* move pin tool */
        this.pintool.setPosition(0,1);
        var head = Ext.get(this.id + '_header_hd');
        head.setPositioning({left:'20px'});
    },
    removeWindowFromPanels: function() {
        /* remove panel reference */
        var tabpan = Ext.getCmp('tabpan');
        var win_id = this.id;
        tabpan.items.each(function(panel) {
            if(panel.window_ids) {
                panel.window_ids = TP.removeFromList(panel.window_ids, win_id);
                panel.saveState();
            }
        });
    },
    manualRefresh: function() {
        if(this.loader != undefined) { this.loader.loadMask=true; }
        this.refreshHandler();
        if(this.loader != undefined) { this.loader.loadMask=false; }
    },
    getTool: function(name) {
        for(var nr in this.tools) {
            if(this.tools[nr].type == name) {
                return(this.tools[nr]);
            }
        }
        return null;
    }
});
